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