[NVPTX] Fix bug in stack code generation causes by MC conversion
[oota-llvm.git] / lib / Target / NVPTX / NVPTXAsmPrinter.cpp
1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "NVPTXAsmPrinter.h"
16 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
17 #include "NVPTX.h"
18 #include "NVPTXInstrInfo.h"
19 #include "NVPTXMCExpr.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "cl_common_defines.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TimeValue.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include <sstream>
48 using namespace llvm;
49
50 bool RegAllocNilUsed = true;
51
52 #define DEPOTNAME "__local_depot"
53
54 static cl::opt<bool>
55 EmitLineNumbers("nvptx-emit-line-numbers",
56                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
57                 cl::init(true));
58
59 namespace llvm { bool InterleaveSrcInPtx = false; }
60
61 static cl::opt<bool, true>
62 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
63               cl::desc("NVPTX Specific: Emit source line in ptx file"),
64               cl::location(llvm::InterleaveSrcInPtx));
65
66 namespace {
67 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
68 /// depends.
69 void DiscoverDependentGlobals(const Value *V,
70                               DenseSet<const GlobalVariable *> &Globals) {
71   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
72     Globals.insert(GV);
73   else {
74     if (const User *U = dyn_cast<User>(V)) {
75       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76         DiscoverDependentGlobals(U->getOperand(i), Globals);
77       }
78     }
79   }
80 }
81
82 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83 /// instances to be emitted, but only after any dependents have been added
84 /// first.
85 void VisitGlobalVariableForEmission(
86     const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87     DenseSet<const GlobalVariable *> &Visited,
88     DenseSet<const GlobalVariable *> &Visiting) {
89   // Have we already visited this one?
90   if (Visited.count(GV))
91     return;
92
93   // Do we have a circular dependency?
94   if (Visiting.count(GV))
95     report_fatal_error("Circular dependency found in global variable set");
96
97   // Start visiting this global
98   Visiting.insert(GV);
99
100   // Make sure we visit all dependents first
101   DenseSet<const GlobalVariable *> Others;
102   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
103     DiscoverDependentGlobals(GV->getOperand(i), Others);
104
105   for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
106                                                   E = Others.end();
107        I != E; ++I)
108     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
109
110   // Now we can visit ourself
111   Order.push_back(GV);
112   Visited.insert(GV);
113   Visiting.erase(GV);
114 }
115 }
116
117 // @TODO: This is a copy from AsmPrinter.cpp.  The function is static, so we
118 // cannot just link to the existing version.
119 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
120 ///
121 using namespace nvptx;
122 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
123   MCContext &Ctx = AP.OutContext;
124
125   if (CV->isNullValue() || isa<UndefValue>(CV))
126     return MCConstantExpr::Create(0, Ctx);
127
128   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
129     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
130
131   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
132     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
133
134   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
135     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
136
137   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
138   if (CE == 0)
139     llvm_unreachable("Unknown constant value to lower!");
140
141   switch (CE->getOpcode()) {
142   default:
143     // If the code isn't optimized, there may be outstanding folding
144     // opportunities. Attempt to fold the expression using DataLayout as a
145     // last resort before giving up.
146     if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
147       if (C != CE)
148         return LowerConstant(C, AP);
149
150     // Otherwise report the problem to the user.
151     {
152       std::string S;
153       raw_string_ostream OS(S);
154       OS << "Unsupported expression in static initializer: ";
155       WriteAsOperand(OS, CE, /*PrintType=*/ false,
156                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
157       report_fatal_error(OS.str());
158     }
159   case Instruction::GetElementPtr: {
160     const DataLayout &TD = *AP.TM.getDataLayout();
161     // Generate a symbolic expression for the byte address
162     APInt OffsetAI(TD.getPointerSizeInBits(), 0);
163     cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
164
165     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
166     if (!OffsetAI)
167       return Base;
168
169     int64_t Offset = OffsetAI.getSExtValue();
170     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
171                                    Ctx);
172   }
173
174   case Instruction::Trunc:
175     // We emit the value and depend on the assembler to truncate the generated
176     // expression properly.  This is important for differences between
177     // blockaddress labels.  Since the two labels are in the same function, it
178     // is reasonable to treat their delta as a 32-bit value.
179   // FALL THROUGH.
180   case Instruction::BitCast:
181     return LowerConstant(CE->getOperand(0), AP);
182
183   case Instruction::IntToPtr: {
184     const DataLayout &TD = *AP.TM.getDataLayout();
185     // Handle casts to pointers by changing them into casts to the appropriate
186     // integer type.  This promotes constant folding and simplifies this code.
187     Constant *Op = CE->getOperand(0);
188     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
189                                       false /*ZExt*/);
190     return LowerConstant(Op, AP);
191   }
192
193   case Instruction::PtrToInt: {
194     const DataLayout &TD = *AP.TM.getDataLayout();
195     // Support only foldable casts to/from pointers that can be eliminated by
196     // changing the pointer to the appropriately sized integer type.
197     Constant *Op = CE->getOperand(0);
198     Type *Ty = CE->getType();
199
200     const MCExpr *OpExpr = LowerConstant(Op, AP);
201
202     // We can emit the pointer value into this slot if the slot is an
203     // integer slot equal to the size of the pointer.
204     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
205       return OpExpr;
206
207     // Otherwise the pointer is smaller than the resultant integer, mask off
208     // the high bits so we are sure to get a proper truncation if the input is
209     // a constant expr.
210     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
211     const MCExpr *MaskExpr =
212         MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
213     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
214   }
215
216     // The MC library also has a right-shift operator, but it isn't consistently
217   // signed or unsigned between different targets.
218   case Instruction::Add:
219   case Instruction::Sub:
220   case Instruction::Mul:
221   case Instruction::SDiv:
222   case Instruction::SRem:
223   case Instruction::Shl:
224   case Instruction::And:
225   case Instruction::Or:
226   case Instruction::Xor: {
227     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
228     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
229     switch (CE->getOpcode()) {
230     default:
231       llvm_unreachable("Unknown binary operator constant cast expr");
232     case Instruction::Add:
233       return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
234     case Instruction::Sub:
235       return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
236     case Instruction::Mul:
237       return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
238     case Instruction::SDiv:
239       return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
240     case Instruction::SRem:
241       return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
242     case Instruction::Shl:
243       return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
244     case Instruction::And:
245       return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
246     case Instruction::Or:
247       return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
248     case Instruction::Xor:
249       return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
250     }
251   }
252   }
253 }
254
255 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
256   if (!EmitLineNumbers)
257     return;
258   if (ignoreLoc(MI))
259     return;
260
261   DebugLoc curLoc = MI.getDebugLoc();
262
263   if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
264     return;
265
266   if (prevDebugLoc == curLoc)
267     return;
268
269   prevDebugLoc = curLoc;
270
271   if (curLoc.isUnknown())
272     return;
273
274   const MachineFunction *MF = MI.getParent()->getParent();
275   //const TargetMachine &TM = MF->getTarget();
276
277   const LLVMContext &ctx = MF->getFunction()->getContext();
278   DIScope Scope(curLoc.getScope(ctx));
279
280   assert((!Scope || Scope.isScope()) &&
281     "Scope of a DebugLoc should be null or a DIScope.");
282   if (!Scope)
283      return;
284
285   StringRef fileName(Scope.getFilename());
286   StringRef dirName(Scope.getDirectory());
287   SmallString<128> FullPathName = dirName;
288   if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
289     sys::path::append(FullPathName, fileName);
290     fileName = FullPathName.str();
291   }
292
293   if (filenameMap.find(fileName.str()) == filenameMap.end())
294     return;
295
296   // Emit the line from the source file.
297   if (llvm::InterleaveSrcInPtx)
298     this->emitSrcInText(fileName.str(), curLoc.getLine());
299
300   std::stringstream temp;
301   temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
302        << " " << curLoc.getCol();
303   OutStreamer.EmitRawText(Twine(temp.str().c_str()));
304 }
305
306 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
307   SmallString<128> Str;
308   raw_svector_ostream OS(Str);
309   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
310     emitLineNumberAsDotLoc(*MI);
311
312   MCInst Inst;
313   lowerToMCInst(MI, Inst);
314   OutStreamer.EmitInstruction(Inst);
315 }
316
317 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
318   OutMI.setOpcode(MI->getOpcode());
319
320   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
321     const MachineOperand &MO = MI->getOperand(i);
322
323     MCOperand MCOp;
324     if (lowerOperand(MO, MCOp))
325       OutMI.addOperand(MCOp);
326   }
327 }
328
329 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
330                                    MCOperand &MCOp) {
331   switch (MO.getType()) {
332   default: llvm_unreachable("unknown operand type");
333   case MachineOperand::MO_Register:
334     MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
335     break;
336   case MachineOperand::MO_Immediate:
337     MCOp = MCOperand::CreateImm(MO.getImm());
338     break;
339   case MachineOperand::MO_MachineBasicBlock:
340     MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
341         MO.getMBB()->getSymbol(), OutContext));
342     break;
343   case MachineOperand::MO_ExternalSymbol:
344     MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
345     break;
346   case MachineOperand::MO_GlobalAddress:
347     MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
348     break;
349   case MachineOperand::MO_FPImmediate: {
350     const ConstantFP *Cnt = MO.getFPImm();
351     APFloat Val = Cnt->getValueAPF();
352
353     switch (Cnt->getType()->getTypeID()) {
354     default: report_fatal_error("Unsupported FP type"); break;
355     case Type::FloatTyID:
356       MCOp = MCOperand::CreateExpr(
357         NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
358       break;
359     case Type::DoubleTyID:
360       MCOp = MCOperand::CreateExpr(
361         NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
362       break;
363     }
364     break;
365   }
366   }
367   return true;
368 }
369
370 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
371   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
372     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
373
374     DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
375     unsigned RegNum = RegMap[Reg];
376
377     // Encode the register class in the upper 4 bits
378     // Must be kept in sync with NVPTXInstPrinter::printRegName
379     unsigned Ret = 0;
380     if (RC == &NVPTX::Int1RegsRegClass) {
381       Ret = (1 << 28);
382     } else if (RC == &NVPTX::Int16RegsRegClass) {
383       Ret = (2 << 28);
384     } else if (RC == &NVPTX::Int32RegsRegClass) {
385       Ret = (3 << 28);
386     } else if (RC == &NVPTX::Int64RegsRegClass) {
387       Ret = (4 << 28);
388     } else if (RC == &NVPTX::Float32RegsRegClass) {
389       Ret = (5 << 28);
390     } else if (RC == &NVPTX::Float64RegsRegClass) {
391       Ret = (6 << 28);
392     } else {
393       report_fatal_error("Bad register class");
394     }
395
396     // Insert the vreg number
397     Ret |= (RegNum & 0x0FFFFFFF);
398     return Ret;
399   } else {
400     // Some special-use registers are actually physical registers.
401     // Encode this as the register class ID of 0 and the real register ID.
402     return Reg & 0x0FFFFFFF;
403   }
404 }
405
406 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
407                                         const MCSymbol *Symbol) {
408   const MCExpr *Expr;
409   switch (MO.getTargetFlags()) {
410   default: {
411     Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
412                                    OutContext);
413     break;
414   }
415   }
416   return MCOperand::CreateExpr(Expr);
417 }
418
419 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
420   const DataLayout *TD = TM.getDataLayout();
421   const TargetLowering *TLI = TM.getTargetLowering();
422
423   Type *Ty = F->getReturnType();
424
425   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
426
427   if (Ty->getTypeID() == Type::VoidTyID)
428     return;
429
430   O << " (";
431
432   if (isABI) {
433     if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
434       unsigned size = 0;
435       if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
436         size = ITy->getBitWidth();
437         if (size < 32)
438           size = 32;
439       } else {
440         assert(Ty->isFloatingPointTy() && "Floating point type expected here");
441         size = Ty->getPrimitiveSizeInBits();
442       }
443
444       O << ".param .b" << size << " func_retval0";
445     } else if (isa<PointerType>(Ty)) {
446       O << ".param .b" << TLI->getPointerTy().getSizeInBits()
447         << " func_retval0";
448     } else {
449       if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
450         SmallVector<EVT, 16> vtparts;
451         ComputeValueVTs(*TLI, Ty, vtparts);
452         unsigned totalsz = 0;
453         for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
454           unsigned elems = 1;
455           EVT elemtype = vtparts[i];
456           if (vtparts[i].isVector()) {
457             elems = vtparts[i].getVectorNumElements();
458             elemtype = vtparts[i].getVectorElementType();
459           }
460           for (unsigned j = 0, je = elems; j != je; ++j) {
461             unsigned sz = elemtype.getSizeInBits();
462             if (elemtype.isInteger() && (sz < 8))
463               sz = 8;
464             totalsz += sz / 8;
465           }
466         }
467         unsigned retAlignment = 0;
468         if (!llvm::getAlign(*F, 0, retAlignment))
469           retAlignment = TD->getABITypeAlignment(Ty);
470         O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
471           << "]";
472       } else
473         assert(false && "Unknown return type");
474     }
475   } else {
476     SmallVector<EVT, 16> vtparts;
477     ComputeValueVTs(*TLI, Ty, vtparts);
478     unsigned idx = 0;
479     for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
480       unsigned elems = 1;
481       EVT elemtype = vtparts[i];
482       if (vtparts[i].isVector()) {
483         elems = vtparts[i].getVectorNumElements();
484         elemtype = vtparts[i].getVectorElementType();
485       }
486
487       for (unsigned j = 0, je = elems; j != je; ++j) {
488         unsigned sz = elemtype.getSizeInBits();
489         if (elemtype.isInteger() && (sz < 32))
490           sz = 32;
491         O << ".reg .b" << sz << " func_retval" << idx;
492         if (j < je - 1)
493           O << ", ";
494         ++idx;
495       }
496       if (i < e - 1)
497         O << ", ";
498     }
499   }
500   O << ") ";
501   return;
502 }
503
504 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
505                                         raw_ostream &O) {
506   const Function *F = MF.getFunction();
507   printReturnValStr(F, O);
508 }
509
510 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
511   SmallString<128> Str;
512   raw_svector_ostream O(Str);
513
514   if (!GlobalsEmitted) {
515     emitGlobals(*MF->getFunction()->getParent());
516     GlobalsEmitted = true;
517   }
518   
519   // Set up
520   MRI = &MF->getRegInfo();
521   F = MF->getFunction();
522   emitLinkageDirective(F, O);
523   if (llvm::isKernelFunction(*F))
524     O << ".entry ";
525   else {
526     O << ".func ";
527     printReturnValStr(*MF, O);
528   }
529
530   O << *CurrentFnSym;
531
532   emitFunctionParamList(*MF, O);
533
534   if (llvm::isKernelFunction(*F))
535     emitKernelFunctionDirectives(*F, O);
536
537   OutStreamer.EmitRawText(O.str());
538
539   prevDebugLoc = DebugLoc();
540 }
541
542 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
543   VRegMapping.clear();
544   OutStreamer.EmitRawText(StringRef("{\n"));
545   setAndEmitFunctionVirtualRegisters(*MF);
546
547   SmallString<128> Str;
548   raw_svector_ostream O(Str);
549   emitDemotedVars(MF->getFunction(), O);
550   OutStreamer.EmitRawText(O.str());
551 }
552
553 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
554   OutStreamer.EmitRawText(StringRef("}\n"));
555   VRegMapping.clear();
556 }
557
558 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
559                                                    raw_ostream &O) const {
560   // If the NVVM IR has some of reqntid* specified, then output
561   // the reqntid directive, and set the unspecified ones to 1.
562   // If none of reqntid* is specified, don't output reqntid directive.
563   unsigned reqntidx, reqntidy, reqntidz;
564   bool specified = false;
565   if (llvm::getReqNTIDx(F, reqntidx) == false)
566     reqntidx = 1;
567   else
568     specified = true;
569   if (llvm::getReqNTIDy(F, reqntidy) == false)
570     reqntidy = 1;
571   else
572     specified = true;
573   if (llvm::getReqNTIDz(F, reqntidz) == false)
574     reqntidz = 1;
575   else
576     specified = true;
577
578   if (specified)
579     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
580       << "\n";
581
582   // If the NVVM IR has some of maxntid* specified, then output
583   // the maxntid directive, and set the unspecified ones to 1.
584   // If none of maxntid* is specified, don't output maxntid directive.
585   unsigned maxntidx, maxntidy, maxntidz;
586   specified = false;
587   if (llvm::getMaxNTIDx(F, maxntidx) == false)
588     maxntidx = 1;
589   else
590     specified = true;
591   if (llvm::getMaxNTIDy(F, maxntidy) == false)
592     maxntidy = 1;
593   else
594     specified = true;
595   if (llvm::getMaxNTIDz(F, maxntidz) == false)
596     maxntidz = 1;
597   else
598     specified = true;
599
600   if (specified)
601     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
602       << "\n";
603
604   unsigned mincta;
605   if (llvm::getMinCTASm(F, mincta))
606     O << ".minnctapersm " << mincta << "\n";
607 }
608
609 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
610                                              raw_ostream &O) {
611   const TargetRegisterClass *RC = MRI->getRegClass(vr);
612
613   DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
614   unsigned mapped_vr = regmap[vr];
615
616   if (!isVec) {
617     O << getNVPTXRegClassStr(RC) << mapped_vr;
618     return;
619   }
620   report_fatal_error("Bad register!");
621 }
622
623 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
624                                           raw_ostream &O) {
625   getVirtualRegisterName(vr, isVec, O);
626 }
627
628 void NVPTXAsmPrinter::printVecModifiedImmediate(
629     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
630   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
631   int Imm = (int) MO.getImm();
632   if (0 == strcmp(Modifier, "vecelem"))
633     O << "_" << vecelem[Imm];
634   else if (0 == strcmp(Modifier, "vecv4comm1")) {
635     if ((Imm < 0) || (Imm > 3))
636       O << "//";
637   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
638     if ((Imm < 4) || (Imm > 7))
639       O << "//";
640   } else if (0 == strcmp(Modifier, "vecv4pos")) {
641     if (Imm < 0)
642       Imm = 0;
643     O << "_" << vecelem[Imm % 4];
644   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
645     if ((Imm < 0) || (Imm > 1))
646       O << "//";
647   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
648     if ((Imm < 2) || (Imm > 3))
649       O << "//";
650   } else if (0 == strcmp(Modifier, "vecv2pos")) {
651     if (Imm < 0)
652       Imm = 0;
653     O << "_" << vecelem[Imm % 2];
654   } else
655     llvm_unreachable("Unknown Modifier on immediate operand");
656 }
657
658
659
660 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
661
662   emitLinkageDirective(F, O);
663   if (llvm::isKernelFunction(*F))
664     O << ".entry ";
665   else
666     O << ".func ";
667   printReturnValStr(F, O);
668   O << *Mang->getSymbol(F) << "\n";
669   emitFunctionParamList(F, O);
670   O << ";\n";
671 }
672
673 static bool usedInGlobalVarDef(const Constant *C) {
674   if (!C)
675     return false;
676
677   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
678     if (GV->getName().str() == "llvm.used")
679       return false;
680     return true;
681   }
682
683   for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
684        ui != ue; ++ui) {
685     const Constant *C = dyn_cast<Constant>(*ui);
686     if (usedInGlobalVarDef(C))
687       return true;
688   }
689   return false;
690 }
691
692 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
693   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
694     if (othergv->getName().str() == "llvm.used")
695       return true;
696   }
697
698   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
699     if (instr->getParent() && instr->getParent()->getParent()) {
700       const Function *curFunc = instr->getParent()->getParent();
701       if (oneFunc && (curFunc != oneFunc))
702         return false;
703       oneFunc = curFunc;
704       return true;
705     } else
706       return false;
707   }
708
709   if (const MDNode *md = dyn_cast<MDNode>(U))
710     if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
711                           (md->getName().str() == "llvm.dbg.sp")))
712       return true;
713
714   for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
715        ui != ue; ++ui) {
716     if (usedInOneFunc(*ui, oneFunc) == false)
717       return false;
718   }
719   return true;
720 }
721
722 /* Find out if a global variable can be demoted to local scope.
723  * Currently, this is valid for CUDA shared variables, which have local
724  * scope and global lifetime. So the conditions to check are :
725  * 1. Is the global variable in shared address space?
726  * 2. Does it have internal linkage?
727  * 3. Is the global variable referenced only in one function?
728  */
729 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
730   if (gv->hasInternalLinkage() == false)
731     return false;
732   const PointerType *Pty = gv->getType();
733   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
734     return false;
735
736   const Function *oneFunc = 0;
737
738   bool flag = usedInOneFunc(gv, oneFunc);
739   if (flag == false)
740     return false;
741   if (!oneFunc)
742     return false;
743   f = oneFunc;
744   return true;
745 }
746
747 static bool useFuncSeen(const Constant *C,
748                         llvm::DenseMap<const Function *, bool> &seenMap) {
749   for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
750        ui != ue; ++ui) {
751     if (const Constant *cu = dyn_cast<Constant>(*ui)) {
752       if (useFuncSeen(cu, seenMap))
753         return true;
754     } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
755       const BasicBlock *bb = I->getParent();
756       if (!bb)
757         continue;
758       const Function *caller = bb->getParent();
759       if (!caller)
760         continue;
761       if (seenMap.find(caller) != seenMap.end())
762         return true;
763     }
764   }
765   return false;
766 }
767
768 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
769   llvm::DenseMap<const Function *, bool> seenMap;
770   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
771     const Function *F = FI;
772
773     if (F->isDeclaration()) {
774       if (F->use_empty())
775         continue;
776       if (F->getIntrinsicID())
777         continue;
778       emitDeclaration(F, O);
779       continue;
780     }
781     for (Value::const_use_iterator iter = F->use_begin(),
782                                    iterEnd = F->use_end();
783          iter != iterEnd; ++iter) {
784       if (const Constant *C = dyn_cast<Constant>(*iter)) {
785         if (usedInGlobalVarDef(C)) {
786           // The use is in the initialization of a global variable
787           // that is a function pointer, so print a declaration
788           // for the original function
789           emitDeclaration(F, O);
790           break;
791         }
792         // Emit a declaration of this function if the function that
793         // uses this constant expr has already been seen.
794         if (useFuncSeen(C, seenMap)) {
795           emitDeclaration(F, O);
796           break;
797         }
798       }
799
800       if (!isa<Instruction>(*iter))
801         continue;
802       const Instruction *instr = cast<Instruction>(*iter);
803       const BasicBlock *bb = instr->getParent();
804       if (!bb)
805         continue;
806       const Function *caller = bb->getParent();
807       if (!caller)
808         continue;
809
810       // If a caller has already been seen, then the caller is
811       // appearing in the module before the callee. so print out
812       // a declaration for the callee.
813       if (seenMap.find(caller) != seenMap.end()) {
814         emitDeclaration(F, O);
815         break;
816       }
817     }
818     seenMap[F] = true;
819   }
820 }
821
822 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
823   DebugInfoFinder DbgFinder;
824   DbgFinder.processModule(M);
825
826   unsigned i = 1;
827   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
828                                  E = DbgFinder.compile_unit_end();
829        I != E; ++I) {
830     DICompileUnit DIUnit(*I);
831     StringRef Filename(DIUnit.getFilename());
832     StringRef Dirname(DIUnit.getDirectory());
833     SmallString<128> FullPathName = Dirname;
834     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
835       sys::path::append(FullPathName, Filename);
836       Filename = FullPathName.str();
837     }
838     if (filenameMap.find(Filename.str()) != filenameMap.end())
839       continue;
840     filenameMap[Filename.str()] = i;
841     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
842     ++i;
843   }
844
845   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
846                                  E = DbgFinder.subprogram_end();
847        I != E; ++I) {
848     DISubprogram SP(*I);
849     StringRef Filename(SP.getFilename());
850     StringRef Dirname(SP.getDirectory());
851     SmallString<128> FullPathName = Dirname;
852     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
853       sys::path::append(FullPathName, Filename);
854       Filename = FullPathName.str();
855     }
856     if (filenameMap.find(Filename.str()) != filenameMap.end())
857       continue;
858     filenameMap[Filename.str()] = i;
859     ++i;
860   }
861 }
862
863 bool NVPTXAsmPrinter::doInitialization(Module &M) {
864
865   SmallString<128> Str1;
866   raw_svector_ostream OS1(Str1);
867
868   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
869   MMI->AnalyzeModule(M);
870
871   // We need to call the parent's one explicitly.
872   //bool Result = AsmPrinter::doInitialization(M);
873
874   // Initialize TargetLoweringObjectFile.
875   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
876       .Initialize(OutContext, TM);
877
878   Mang = new Mangler(OutContext, &TM);
879
880   // Emit header before any dwarf directives are emitted below.
881   emitHeader(M, OS1);
882   OutStreamer.EmitRawText(OS1.str());
883
884   // Already commented out
885   //bool Result = AsmPrinter::doInitialization(M);
886
887   // Emit module-level inline asm if it exists.
888   if (!M.getModuleInlineAsm().empty()) {
889     OutStreamer.AddComment("Start of file scope inline assembly");
890     OutStreamer.AddBlankLine();
891     OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
892     OutStreamer.AddBlankLine();
893     OutStreamer.AddComment("End of file scope inline assembly");
894     OutStreamer.AddBlankLine();
895   }
896
897   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
898     recordAndEmitFilenames(M);
899
900   GlobalsEmitted = false;
901     
902   return false; // success
903 }
904
905 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
906   SmallString<128> Str2;
907   raw_svector_ostream OS2(Str2);
908
909   emitDeclarations(M, OS2);
910
911   // As ptxas does not support forward references of globals, we need to first
912   // sort the list of module-level globals in def-use order. We visit each
913   // global variable in order, and ensure that we emit it *after* its dependent
914   // globals. We use a little extra memory maintaining both a set and a list to
915   // have fast searches while maintaining a strict ordering.
916   SmallVector<const GlobalVariable *, 8> Globals;
917   DenseSet<const GlobalVariable *> GVVisited;
918   DenseSet<const GlobalVariable *> GVVisiting;
919
920   // Visit each global variable, in order
921   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
922        I != E; ++I)
923     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
924
925   assert(GVVisited.size() == M.getGlobalList().size() &&
926          "Missed a global variable");
927   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
928
929   // Print out module-level global variables in proper order
930   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
931     printModuleLevelGV(Globals[i], OS2);
932
933   OS2 << '\n';
934
935   OutStreamer.EmitRawText(OS2.str());
936 }
937
938 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
939   O << "//\n";
940   O << "// Generated by LLVM NVPTX Back-End\n";
941   O << "//\n";
942   O << "\n";
943
944   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
945   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
946
947   O << ".target ";
948   O << nvptxSubtarget.getTargetName();
949
950   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
951     O << ", texmode_independent";
952   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
953     if (!nvptxSubtarget.hasDouble())
954       O << ", map_f64_to_f32";
955   }
956
957   if (MAI->doesSupportDebugInformation())
958     O << ", debug";
959
960   O << "\n";
961
962   O << ".address_size ";
963   if (nvptxSubtarget.is64Bit())
964     O << "64";
965   else
966     O << "32";
967   O << "\n";
968
969   O << "\n";
970 }
971
972 bool NVPTXAsmPrinter::doFinalization(Module &M) {
973
974   // If we did not emit any functions, then the global declarations have not
975   // yet been emitted.
976   if (!GlobalsEmitted) {
977     emitGlobals(M);
978     GlobalsEmitted = true;
979   }
980
981   // XXX Temproarily remove global variables so that doFinalization() will not
982   // emit them again (global variables are emitted at beginning).
983
984   Module::GlobalListType &global_list = M.getGlobalList();
985   int i, n = global_list.size();
986   GlobalVariable **gv_array = new GlobalVariable *[n];
987
988   // first, back-up GlobalVariable in gv_array
989   i = 0;
990   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
991        I != E; ++I)
992     gv_array[i++] = &*I;
993
994   // second, empty global_list
995   while (!global_list.empty())
996     global_list.remove(global_list.begin());
997
998   // call doFinalization
999   bool ret = AsmPrinter::doFinalization(M);
1000
1001   // now we restore global variables
1002   for (i = 0; i < n; i++)
1003     global_list.insert(global_list.end(), gv_array[i]);
1004
1005   delete[] gv_array;
1006   return ret;
1007
1008   //bool Result = AsmPrinter::doFinalization(M);
1009   // Instead of calling the parents doFinalization, we may
1010   // clone parents doFinalization and customize here.
1011   // Currently, we if NVISA out the EmitGlobals() in
1012   // parent's doFinalization, which is too intrusive.
1013   //
1014   // Same for the doInitialization.
1015   //return Result;
1016 }
1017
1018 // This function emits appropriate linkage directives for
1019 // functions and global variables.
1020 //
1021 // extern function declaration            -> .extern
1022 // extern function definition             -> .visible
1023 // external global variable with init     -> .visible
1024 // external without init                  -> .extern
1025 // appending                              -> not allowed, assert.
1026
1027 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1028                                            raw_ostream &O) {
1029   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1030     if (V->hasExternalLinkage()) {
1031       if (isa<GlobalVariable>(V)) {
1032         const GlobalVariable *GVar = cast<GlobalVariable>(V);
1033         if (GVar) {
1034           if (GVar->hasInitializer())
1035             O << ".visible ";
1036           else
1037             O << ".extern ";
1038         }
1039       } else if (V->isDeclaration())
1040         O << ".extern ";
1041       else
1042         O << ".visible ";
1043     } else if (V->hasAppendingLinkage()) {
1044       std::string msg;
1045       msg.append("Error: ");
1046       msg.append("Symbol ");
1047       if (V->hasName())
1048         msg.append(V->getName().str());
1049       msg.append("has unsupported appending linkage type");
1050       llvm_unreachable(msg.c_str());
1051     }
1052   }
1053 }
1054
1055 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1056                                          raw_ostream &O,
1057                                          bool processDemoted) {
1058
1059   // Skip meta data
1060   if (GVar->hasSection()) {
1061     if (GVar->getSection() == "llvm.metadata")
1062       return;
1063   }
1064
1065   const DataLayout *TD = TM.getDataLayout();
1066
1067   // GlobalVariables are always constant pointers themselves.
1068   const PointerType *PTy = GVar->getType();
1069   Type *ETy = PTy->getElementType();
1070
1071   if (GVar->hasExternalLinkage()) {
1072     if (GVar->hasInitializer())
1073       O << ".visible ";
1074     else
1075       O << ".extern ";
1076   }
1077
1078   if (llvm::isTexture(*GVar)) {
1079     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1080     return;
1081   }
1082
1083   if (llvm::isSurface(*GVar)) {
1084     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1085     return;
1086   }
1087
1088   if (GVar->isDeclaration()) {
1089     // (extern) declarations, no definition or initializer
1090     // Currently the only known declaration is for an automatic __local
1091     // (.shared) promoted to global.
1092     emitPTXGlobalVariable(GVar, O);
1093     O << ";\n";
1094     return;
1095   }
1096
1097   if (llvm::isSampler(*GVar)) {
1098     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1099
1100     const Constant *Initializer = NULL;
1101     if (GVar->hasInitializer())
1102       Initializer = GVar->getInitializer();
1103     const ConstantInt *CI = NULL;
1104     if (Initializer)
1105       CI = dyn_cast<ConstantInt>(Initializer);
1106     if (CI) {
1107       unsigned sample = CI->getZExtValue();
1108
1109       O << " = { ";
1110
1111       for (int i = 0,
1112                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1113            i < 3; i++) {
1114         O << "addr_mode_" << i << " = ";
1115         switch (addr) {
1116         case 0:
1117           O << "wrap";
1118           break;
1119         case 1:
1120           O << "clamp_to_border";
1121           break;
1122         case 2:
1123           O << "clamp_to_edge";
1124           break;
1125         case 3:
1126           O << "wrap";
1127           break;
1128         case 4:
1129           O << "mirror";
1130           break;
1131         }
1132         O << ", ";
1133       }
1134       O << "filter_mode = ";
1135       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1136       case 0:
1137         O << "nearest";
1138         break;
1139       case 1:
1140         O << "linear";
1141         break;
1142       case 2:
1143         assert(0 && "Anisotropic filtering is not supported");
1144       default:
1145         O << "nearest";
1146         break;
1147       }
1148       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1149         O << ", force_unnormalized_coords = 1";
1150       }
1151       O << " }";
1152     }
1153
1154     O << ";\n";
1155     return;
1156   }
1157
1158   if (GVar->hasPrivateLinkage()) {
1159
1160     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1161       return;
1162
1163     // FIXME - need better way (e.g. Metadata) to avoid generating this global
1164     if (!strncmp(GVar->getName().data(), "filename", 8))
1165       return;
1166     if (GVar->use_empty())
1167       return;
1168   }
1169
1170   const Function *demotedFunc = 0;
1171   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1172     O << "// " << GVar->getName().str() << " has been demoted\n";
1173     if (localDecls.find(demotedFunc) != localDecls.end())
1174       localDecls[demotedFunc].push_back(GVar);
1175     else {
1176       std::vector<const GlobalVariable *> temp;
1177       temp.push_back(GVar);
1178       localDecls[demotedFunc] = temp;
1179     }
1180     return;
1181   }
1182
1183   O << ".";
1184   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1185   if (GVar->getAlignment() == 0)
1186     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1187   else
1188     O << " .align " << GVar->getAlignment();
1189
1190   if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1191     O << " .";
1192     // Special case: ABI requires that we use .u8 for predicates
1193     if (ETy->isIntegerTy(1))
1194       O << "u8";
1195     else
1196       O << getPTXFundamentalTypeStr(ETy, false);
1197     O << " ";
1198     O << *Mang->getSymbol(GVar);
1199
1200     // Ptx allows variable initilization only for constant and global state
1201     // spaces.
1202     if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1203          (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1204         GVar->hasInitializer()) {
1205       const Constant *Initializer = GVar->getInitializer();
1206       if (!Initializer->isNullValue()) {
1207         O << " = ";
1208         printScalarConstant(Initializer, O);
1209       }
1210     }
1211   } else {
1212     unsigned int ElementSize = 0;
1213
1214     // Although PTX has direct support for struct type and array type and
1215     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1216     // targets that support these high level field accesses. Structs, arrays
1217     // and vectors are lowered into arrays of bytes.
1218     switch (ETy->getTypeID()) {
1219     case Type::StructTyID:
1220     case Type::ArrayTyID:
1221     case Type::VectorTyID:
1222       ElementSize = TD->getTypeStoreSize(ETy);
1223       // Ptx allows variable initilization only for constant and
1224       // global state spaces.
1225       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1226            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1227           GVar->hasInitializer()) {
1228         const Constant *Initializer = GVar->getInitializer();
1229         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1230           AggBuffer aggBuffer(ElementSize, O, *this);
1231           bufferAggregateConstant(Initializer, &aggBuffer);
1232           if (aggBuffer.numSymbols) {
1233             if (nvptxSubtarget.is64Bit()) {
1234               O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1235               O << ElementSize / 8;
1236             } else {
1237               O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1238               O << ElementSize / 4;
1239             }
1240             O << "]";
1241           } else {
1242             O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1243             O << ElementSize;
1244             O << "]";
1245           }
1246           O << " = {";
1247           aggBuffer.print();
1248           O << "}";
1249         } else {
1250           O << " .b8 " << *Mang->getSymbol(GVar);
1251           if (ElementSize) {
1252             O << "[";
1253             O << ElementSize;
1254             O << "]";
1255           }
1256         }
1257       } else {
1258         O << " .b8 " << *Mang->getSymbol(GVar);
1259         if (ElementSize) {
1260           O << "[";
1261           O << ElementSize;
1262           O << "]";
1263         }
1264       }
1265       break;
1266     default:
1267       assert(0 && "type not supported yet");
1268     }
1269
1270   }
1271   O << ";\n";
1272 }
1273
1274 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1275   if (localDecls.find(f) == localDecls.end())
1276     return;
1277
1278   std::vector<const GlobalVariable *> &gvars = localDecls[f];
1279
1280   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1281     O << "\t// demoted variable\n\t";
1282     printModuleLevelGV(gvars[i], O, true);
1283   }
1284 }
1285
1286 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1287                                           raw_ostream &O) const {
1288   switch (AddressSpace) {
1289   case llvm::ADDRESS_SPACE_LOCAL:
1290     O << "local";
1291     break;
1292   case llvm::ADDRESS_SPACE_GLOBAL:
1293     O << "global";
1294     break;
1295   case llvm::ADDRESS_SPACE_CONST:
1296     O << "const";
1297     break;
1298   case llvm::ADDRESS_SPACE_SHARED:
1299     O << "shared";
1300     break;
1301   default:
1302     report_fatal_error("Bad address space found while emitting PTX");
1303     break;
1304   }
1305 }
1306
1307 std::string
1308 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1309   switch (Ty->getTypeID()) {
1310   default:
1311     llvm_unreachable("unexpected type");
1312     break;
1313   case Type::IntegerTyID: {
1314     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1315     if (NumBits == 1)
1316       return "pred";
1317     else if (NumBits <= 64) {
1318       std::string name = "u";
1319       return name + utostr(NumBits);
1320     } else {
1321       llvm_unreachable("Integer too large");
1322       break;
1323     }
1324     break;
1325   }
1326   case Type::FloatTyID:
1327     return "f32";
1328   case Type::DoubleTyID:
1329     return "f64";
1330   case Type::PointerTyID:
1331     if (nvptxSubtarget.is64Bit())
1332       if (useB4PTR)
1333         return "b64";
1334       else
1335         return "u64";
1336     else if (useB4PTR)
1337       return "b32";
1338     else
1339       return "u32";
1340   }
1341   llvm_unreachable("unexpected type");
1342   return NULL;
1343 }
1344
1345 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1346                                             raw_ostream &O) {
1347
1348   const DataLayout *TD = TM.getDataLayout();
1349
1350   // GlobalVariables are always constant pointers themselves.
1351   const PointerType *PTy = GVar->getType();
1352   Type *ETy = PTy->getElementType();
1353
1354   O << ".";
1355   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1356   if (GVar->getAlignment() == 0)
1357     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1358   else
1359     O << " .align " << GVar->getAlignment();
1360
1361   if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1362     O << " .";
1363     O << getPTXFundamentalTypeStr(ETy);
1364     O << " ";
1365     O << *Mang->getSymbol(GVar);
1366     return;
1367   }
1368
1369   int64_t ElementSize = 0;
1370
1371   // Although PTX has direct support for struct type and array type and LLVM IR
1372   // is very similar to PTX, the LLVM CodeGen does not support for targets that
1373   // support these high level field accesses. Structs and arrays are lowered
1374   // into arrays of bytes.
1375   switch (ETy->getTypeID()) {
1376   case Type::StructTyID:
1377   case Type::ArrayTyID:
1378   case Type::VectorTyID:
1379     ElementSize = TD->getTypeStoreSize(ETy);
1380     O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1381     if (ElementSize) {
1382       O << itostr(ElementSize);
1383     }
1384     O << "]";
1385     break;
1386   default:
1387     assert(0 && "type not supported yet");
1388   }
1389   return;
1390 }
1391
1392 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1393   if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1394     return TD->getPrefTypeAlignment(Ty);
1395
1396   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1397   if (ATy)
1398     return getOpenCLAlignment(TD, ATy->getElementType());
1399
1400   const VectorType *VTy = dyn_cast<VectorType>(Ty);
1401   if (VTy) {
1402     Type *ETy = VTy->getElementType();
1403     unsigned int numE = VTy->getNumElements();
1404     unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1405     if (numE == 3)
1406       return 4 * alignE;
1407     else
1408       return numE * alignE;
1409   }
1410
1411   const StructType *STy = dyn_cast<StructType>(Ty);
1412   if (STy) {
1413     unsigned int alignStruct = 1;
1414     // Go through each element of the struct and find the
1415     // largest alignment.
1416     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1417       Type *ETy = STy->getElementType(i);
1418       unsigned int align = getOpenCLAlignment(TD, ETy);
1419       if (align > alignStruct)
1420         alignStruct = align;
1421     }
1422     return alignStruct;
1423   }
1424
1425   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1426   if (FTy)
1427     return TD->getPointerPrefAlignment();
1428   return TD->getPrefTypeAlignment(Ty);
1429 }
1430
1431 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1432                                      int paramIndex, raw_ostream &O) {
1433   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1434       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1435     O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1436   else {
1437     std::string argName = I->getName();
1438     const char *p = argName.c_str();
1439     while (*p) {
1440       if (*p == '.')
1441         O << "_";
1442       else
1443         O << *p;
1444       p++;
1445     }
1446   }
1447 }
1448
1449 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1450   Function::const_arg_iterator I, E;
1451   int i = 0;
1452
1453   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1454       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1455     O << *CurrentFnSym << "_param_" << paramIndex;
1456     return;
1457   }
1458
1459   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1460     if (i == paramIndex) {
1461       printParamName(I, paramIndex, O);
1462       return;
1463     }
1464   }
1465   llvm_unreachable("paramIndex out of bound");
1466 }
1467
1468 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1469   const DataLayout *TD = TM.getDataLayout();
1470   const AttributeSet &PAL = F->getAttributes();
1471   const TargetLowering *TLI = TM.getTargetLowering();
1472   Function::const_arg_iterator I, E;
1473   unsigned paramIndex = 0;
1474   bool first = true;
1475   bool isKernelFunc = llvm::isKernelFunction(*F);
1476   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1477   MVT thePointerTy = TLI->getPointerTy();
1478
1479   O << "(\n";
1480
1481   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1482     Type *Ty = I->getType();
1483
1484     if (!first)
1485       O << ",\n";
1486
1487     first = false;
1488
1489     // Handle image/sampler parameters
1490     if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1491       if (llvm::isImage(*I)) {
1492         std::string sname = I->getName();
1493         if (llvm::isImageWriteOnly(*I))
1494           O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1495             << paramIndex;
1496         else // Default image is read_only
1497           O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1498             << paramIndex;
1499       } else // Should be llvm::isSampler(*I)
1500         O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1501           << paramIndex;
1502       continue;
1503     }
1504
1505     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1506       if (Ty->isVectorTy()) {
1507         // Just print .param .b8 .align <a> .param[size];
1508         // <a> = PAL.getparamalignment
1509         // size = typeallocsize of element type
1510         unsigned align = PAL.getParamAlignment(paramIndex + 1);
1511         if (align == 0)
1512           align = TD->getABITypeAlignment(Ty);
1513
1514         unsigned sz = TD->getTypeAllocSize(Ty);
1515         O << "\t.param .align " << align << " .b8 ";
1516         printParamName(I, paramIndex, O);
1517         O << "[" << sz << "]";
1518
1519         continue;
1520       }
1521       // Just a scalar
1522       const PointerType *PTy = dyn_cast<PointerType>(Ty);
1523       if (isKernelFunc) {
1524         if (PTy) {
1525           // Special handling for pointer arguments to kernel
1526           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1527
1528           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1529             Type *ETy = PTy->getElementType();
1530             int addrSpace = PTy->getAddressSpace();
1531             switch (addrSpace) {
1532             default:
1533               O << ".ptr ";
1534               break;
1535             case llvm::ADDRESS_SPACE_CONST:
1536               O << ".ptr .const ";
1537               break;
1538             case llvm::ADDRESS_SPACE_SHARED:
1539               O << ".ptr .shared ";
1540               break;
1541             case llvm::ADDRESS_SPACE_GLOBAL:
1542               O << ".ptr .global ";
1543               break;
1544             }
1545             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1546           }
1547           printParamName(I, paramIndex, O);
1548           continue;
1549         }
1550
1551         // non-pointer scalar to kernel func
1552         O << "\t.param .";
1553         // Special case: predicate operands become .u8 types
1554         if (Ty->isIntegerTy(1))
1555           O << "u8";
1556         else
1557           O << getPTXFundamentalTypeStr(Ty);
1558         O << " ";
1559         printParamName(I, paramIndex, O);
1560         continue;
1561       }
1562       // Non-kernel function, just print .param .b<size> for ABI
1563       // and .reg .b<size> for non ABY
1564       unsigned sz = 0;
1565       if (isa<IntegerType>(Ty)) {
1566         sz = cast<IntegerType>(Ty)->getBitWidth();
1567         if (sz < 32)
1568           sz = 32;
1569       } else if (isa<PointerType>(Ty))
1570         sz = thePointerTy.getSizeInBits();
1571       else
1572         sz = Ty->getPrimitiveSizeInBits();
1573       if (isABI)
1574         O << "\t.param .b" << sz << " ";
1575       else
1576         O << "\t.reg .b" << sz << " ";
1577       printParamName(I, paramIndex, O);
1578       continue;
1579     }
1580
1581     // param has byVal attribute. So should be a pointer
1582     const PointerType *PTy = dyn_cast<PointerType>(Ty);
1583     assert(PTy && "Param with byval attribute should be a pointer type");
1584     Type *ETy = PTy->getElementType();
1585
1586     if (isABI || isKernelFunc) {
1587       // Just print .param .b8 .align <a> .param[size];
1588       // <a> = PAL.getparamalignment
1589       // size = typeallocsize of element type
1590       unsigned align = PAL.getParamAlignment(paramIndex + 1);
1591       if (align == 0)
1592         align = TD->getABITypeAlignment(ETy);
1593
1594       unsigned sz = TD->getTypeAllocSize(ETy);
1595       O << "\t.param .align " << align << " .b8 ";
1596       printParamName(I, paramIndex, O);
1597       O << "[" << sz << "]";
1598       continue;
1599     } else {
1600       // Split the ETy into constituent parts and
1601       // print .param .b<size> <name> for each part.
1602       // Further, if a part is vector, print the above for
1603       // each vector element.
1604       SmallVector<EVT, 16> vtparts;
1605       ComputeValueVTs(*TLI, ETy, vtparts);
1606       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1607         unsigned elems = 1;
1608         EVT elemtype = vtparts[i];
1609         if (vtparts[i].isVector()) {
1610           elems = vtparts[i].getVectorNumElements();
1611           elemtype = vtparts[i].getVectorElementType();
1612         }
1613
1614         for (unsigned j = 0, je = elems; j != je; ++j) {
1615           unsigned sz = elemtype.getSizeInBits();
1616           if (elemtype.isInteger() && (sz < 32))
1617             sz = 32;
1618           O << "\t.reg .b" << sz << " ";
1619           printParamName(I, paramIndex, O);
1620           if (j < je - 1)
1621             O << ",\n";
1622           ++paramIndex;
1623         }
1624         if (i < e - 1)
1625           O << ",\n";
1626       }
1627       --paramIndex;
1628       continue;
1629     }
1630   }
1631
1632   O << "\n)\n";
1633 }
1634
1635 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1636                                             raw_ostream &O) {
1637   const Function *F = MF.getFunction();
1638   emitFunctionParamList(F, O);
1639 }
1640
1641 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1642     const MachineFunction &MF) {
1643   SmallString<128> Str;
1644   raw_svector_ostream O(Str);
1645
1646   // Map the global virtual register number to a register class specific
1647   // virtual register number starting from 1 with that class.
1648   const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1649   //unsigned numRegClasses = TRI->getNumRegClasses();
1650
1651   // Emit the Fake Stack Object
1652   const MachineFrameInfo *MFI = MF.getFrameInfo();
1653   int NumBytes = (int) MFI->getStackSize();
1654   if (NumBytes) {
1655     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1656       << getFunctionNumber() << "[" << NumBytes << "];\n";
1657     if (nvptxSubtarget.is64Bit()) {
1658       O << "\t.reg .b64 \t%SP;\n";
1659       O << "\t.reg .b64 \t%SPL;\n";
1660     } else {
1661       O << "\t.reg .b32 \t%SP;\n";
1662       O << "\t.reg .b32 \t%SPL;\n";
1663     }
1664   }
1665
1666   // Go through all virtual registers to establish the mapping between the
1667   // global virtual
1668   // register number and the per class virtual register number.
1669   // We use the per class virtual register number in the ptx output.
1670   unsigned int numVRs = MRI->getNumVirtRegs();
1671   for (unsigned i = 0; i < numVRs; i++) {
1672     unsigned int vr = TRI->index2VirtReg(i);
1673     const TargetRegisterClass *RC = MRI->getRegClass(vr);
1674     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1675     int n = regmap.size();
1676     regmap.insert(std::make_pair(vr, n + 1));
1677   }
1678
1679   // Emit register declarations
1680   // @TODO: Extract out the real register usage
1681   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1682   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1683   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1684   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1685   // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1686   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1687   // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1688
1689   // Emit declaration of the virtual registers or 'physical' registers for
1690   // each register class
1691   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1692     const TargetRegisterClass *RC = TRI->getRegClass(i);
1693     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1694     std::string rcname = getNVPTXRegClassName(RC);
1695     std::string rcStr = getNVPTXRegClassStr(RC);
1696     int n = regmap.size();
1697
1698     // Only declare those registers that may be used.
1699     if (n) {
1700        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1701          << ">;\n";
1702     }
1703   }
1704
1705   OutStreamer.EmitRawText(O.str());
1706 }
1707
1708 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1709   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1710   bool ignored;
1711   unsigned int numHex;
1712   const char *lead;
1713
1714   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1715     numHex = 8;
1716     lead = "0f";
1717     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1718   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1719     numHex = 16;
1720     lead = "0d";
1721     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1722   } else
1723     llvm_unreachable("unsupported fp type");
1724
1725   APInt API = APF.bitcastToAPInt();
1726   std::string hexstr(utohexstr(API.getZExtValue()));
1727   O << lead;
1728   if (hexstr.length() < numHex)
1729     O << std::string(numHex - hexstr.length(), '0');
1730   O << utohexstr(API.getZExtValue());
1731 }
1732
1733 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1734   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1735     O << CI->getValue();
1736     return;
1737   }
1738   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1739     printFPConstant(CFP, O);
1740     return;
1741   }
1742   if (isa<ConstantPointerNull>(CPV)) {
1743     O << "0";
1744     return;
1745   }
1746   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1747     O << *Mang->getSymbol(GVar);
1748     return;
1749   }
1750   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1751     const Value *v = Cexpr->stripPointerCasts();
1752     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1753       O << *Mang->getSymbol(GVar);
1754       return;
1755     } else {
1756       O << *LowerConstant(CPV, *this);
1757       return;
1758     }
1759   }
1760   llvm_unreachable("Not scalar type found in printScalarConstant()");
1761 }
1762
1763 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1764                                    AggBuffer *aggBuffer) {
1765
1766   const DataLayout *TD = TM.getDataLayout();
1767
1768   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1769     int s = TD->getTypeAllocSize(CPV->getType());
1770     if (s < Bytes)
1771       s = Bytes;
1772     aggBuffer->addZeros(s);
1773     return;
1774   }
1775
1776   unsigned char *ptr;
1777   switch (CPV->getType()->getTypeID()) {
1778
1779   case Type::IntegerTyID: {
1780     const Type *ETy = CPV->getType();
1781     if (ETy == Type::getInt8Ty(CPV->getContext())) {
1782       unsigned char c =
1783           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1784       ptr = &c;
1785       aggBuffer->addBytes(ptr, 1, Bytes);
1786     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1787       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1788       ptr = (unsigned char *)&int16;
1789       aggBuffer->addBytes(ptr, 2, Bytes);
1790     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1791       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1792         int int32 = (int)(constInt->getZExtValue());
1793         ptr = (unsigned char *)&int32;
1794         aggBuffer->addBytes(ptr, 4, Bytes);
1795         break;
1796       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1797         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1798                 ConstantFoldConstantExpression(Cexpr, TD))) {
1799           int int32 = (int)(constInt->getZExtValue());
1800           ptr = (unsigned char *)&int32;
1801           aggBuffer->addBytes(ptr, 4, Bytes);
1802           break;
1803         }
1804         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1805           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1806           aggBuffer->addSymbol(v);
1807           aggBuffer->addZeros(4);
1808           break;
1809         }
1810       }
1811       llvm_unreachable("unsupported integer const type");
1812     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1813       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1814         long long int64 = (long long)(constInt->getZExtValue());
1815         ptr = (unsigned char *)&int64;
1816         aggBuffer->addBytes(ptr, 8, Bytes);
1817         break;
1818       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1819         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1820                 ConstantFoldConstantExpression(Cexpr, TD))) {
1821           long long int64 = (long long)(constInt->getZExtValue());
1822           ptr = (unsigned char *)&int64;
1823           aggBuffer->addBytes(ptr, 8, Bytes);
1824           break;
1825         }
1826         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1827           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1828           aggBuffer->addSymbol(v);
1829           aggBuffer->addZeros(8);
1830           break;
1831         }
1832       }
1833       llvm_unreachable("unsupported integer const type");
1834     } else
1835       llvm_unreachable("unsupported integer const type");
1836     break;
1837   }
1838   case Type::FloatTyID:
1839   case Type::DoubleTyID: {
1840     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1841     const Type *Ty = CFP->getType();
1842     if (Ty == Type::getFloatTy(CPV->getContext())) {
1843       float float32 = (float) CFP->getValueAPF().convertToFloat();
1844       ptr = (unsigned char *)&float32;
1845       aggBuffer->addBytes(ptr, 4, Bytes);
1846     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1847       double float64 = CFP->getValueAPF().convertToDouble();
1848       ptr = (unsigned char *)&float64;
1849       aggBuffer->addBytes(ptr, 8, Bytes);
1850     } else {
1851       llvm_unreachable("unsupported fp const type");
1852     }
1853     break;
1854   }
1855   case Type::PointerTyID: {
1856     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1857       aggBuffer->addSymbol(GVar);
1858     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1859       const Value *v = Cexpr->stripPointerCasts();
1860       aggBuffer->addSymbol(v);
1861     }
1862     unsigned int s = TD->getTypeAllocSize(CPV->getType());
1863     aggBuffer->addZeros(s);
1864     break;
1865   }
1866
1867   case Type::ArrayTyID:
1868   case Type::VectorTyID:
1869   case Type::StructTyID: {
1870     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1871         isa<ConstantStruct>(CPV)) {
1872       int ElementSize = TD->getTypeAllocSize(CPV->getType());
1873       bufferAggregateConstant(CPV, aggBuffer);
1874       if (Bytes > ElementSize)
1875         aggBuffer->addZeros(Bytes - ElementSize);
1876     } else if (isa<ConstantAggregateZero>(CPV))
1877       aggBuffer->addZeros(Bytes);
1878     else
1879       llvm_unreachable("Unexpected Constant type");
1880     break;
1881   }
1882
1883   default:
1884     llvm_unreachable("unsupported type");
1885   }
1886 }
1887
1888 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1889                                               AggBuffer *aggBuffer) {
1890   const DataLayout *TD = TM.getDataLayout();
1891   int Bytes;
1892
1893   // Old constants
1894   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1895     if (CPV->getNumOperands())
1896       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1897         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1898     return;
1899   }
1900
1901   if (const ConstantDataSequential *CDS =
1902           dyn_cast<ConstantDataSequential>(CPV)) {
1903     if (CDS->getNumElements())
1904       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1905         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1906                      aggBuffer);
1907     return;
1908   }
1909
1910   if (isa<ConstantStruct>(CPV)) {
1911     if (CPV->getNumOperands()) {
1912       StructType *ST = cast<StructType>(CPV->getType());
1913       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1914         if (i == (e - 1))
1915           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1916                   TD->getTypeAllocSize(ST) -
1917                   TD->getStructLayout(ST)->getElementOffset(i);
1918         else
1919           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1920                   TD->getStructLayout(ST)->getElementOffset(i);
1921         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1922       }
1923     }
1924     return;
1925   }
1926   llvm_unreachable("unsupported constant type in printAggregateConstant()");
1927 }
1928
1929 // buildTypeNameMap - Run through symbol table looking for type names.
1930 //
1931
1932 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1933
1934   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1935
1936   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1937                                   !PI->second.compare("struct._image2d_t") ||
1938                                   !PI->second.compare("struct._image3d_t")))
1939     return true;
1940
1941   return false;
1942 }
1943
1944
1945 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1946   switch (MI.getOpcode()) {
1947   default:
1948     return false;
1949   case NVPTX::CallArgBeginInst:
1950   case NVPTX::CallArgEndInst0:
1951   case NVPTX::CallArgEndInst1:
1952   case NVPTX::CallArgF32:
1953   case NVPTX::CallArgF64:
1954   case NVPTX::CallArgI16:
1955   case NVPTX::CallArgI32:
1956   case NVPTX::CallArgI32imm:
1957   case NVPTX::CallArgI64:
1958   case NVPTX::CallArgParam:
1959   case NVPTX::CallVoidInst:
1960   case NVPTX::CallVoidInstReg:
1961   case NVPTX::Callseq_End:
1962   case NVPTX::CallVoidInstReg64:
1963   case NVPTX::DeclareParamInst:
1964   case NVPTX::DeclareRetMemInst:
1965   case NVPTX::DeclareRetRegInst:
1966   case NVPTX::DeclareRetScalarInst:
1967   case NVPTX::DeclareScalarParamInst:
1968   case NVPTX::DeclareScalarRegInst:
1969   case NVPTX::StoreParamF32:
1970   case NVPTX::StoreParamF64:
1971   case NVPTX::StoreParamI16:
1972   case NVPTX::StoreParamI32:
1973   case NVPTX::StoreParamI64:
1974   case NVPTX::StoreParamI8:
1975   case NVPTX::StoreRetvalF32:
1976   case NVPTX::StoreRetvalF64:
1977   case NVPTX::StoreRetvalI16:
1978   case NVPTX::StoreRetvalI32:
1979   case NVPTX::StoreRetvalI64:
1980   case NVPTX::StoreRetvalI8:
1981   case NVPTX::LastCallArgF32:
1982   case NVPTX::LastCallArgF64:
1983   case NVPTX::LastCallArgI16:
1984   case NVPTX::LastCallArgI32:
1985   case NVPTX::LastCallArgI32imm:
1986   case NVPTX::LastCallArgI64:
1987   case NVPTX::LastCallArgParam:
1988   case NVPTX::LoadParamMemF32:
1989   case NVPTX::LoadParamMemF64:
1990   case NVPTX::LoadParamMemI16:
1991   case NVPTX::LoadParamMemI32:
1992   case NVPTX::LoadParamMemI64:
1993   case NVPTX::LoadParamMemI8:
1994   case NVPTX::PrototypeInst:
1995   case NVPTX::DBG_VALUE:
1996     return true;
1997   }
1998   return false;
1999 }
2000
2001 // Force static initialization.
2002 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2003   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2004   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2005 }
2006
2007 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2008   std::stringstream temp;
2009   LineReader *reader = this->getReader(filename.str());
2010   temp << "\n//";
2011   temp << filename.str();
2012   temp << ":";
2013   temp << line;
2014   temp << " ";
2015   temp << reader->readLine(line);
2016   temp << "\n";
2017   this->OutStreamer.EmitRawText(Twine(temp.str()));
2018 }
2019
2020 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2021   if (reader == NULL) {
2022     reader = new LineReader(filename);
2023   }
2024
2025   if (reader->fileName() != filename) {
2026     delete reader;
2027     reader = new LineReader(filename);
2028   }
2029
2030   return reader;
2031 }
2032
2033 std::string LineReader::readLine(unsigned lineNum) {
2034   if (lineNum < theCurLine) {
2035     theCurLine = 0;
2036     fstr.seekg(0, std::ios::beg);
2037   }
2038   while (theCurLine < lineNum) {
2039     fstr.getline(buff, 500);
2040     theCurLine++;
2041   }
2042   return buff;
2043 }
2044
2045 // Force static initialization.
2046 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2047   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2048   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2049 }