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