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     OutStreamer->EmitDwarfFileDirective(i, "", Filename);
802     ++i;
803   }
804 }
805 
806 static bool isEmptyXXStructor(GlobalVariable *GV) {
807   if (!GV) return true;
808   const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
809   if (!InitList) return true;  // Not an array; we don't know how to parse.
810   return InitList->getNumOperands() == 0;
811 }
812 
813 bool NVPTXAsmPrinter::doInitialization(Module &M) {
814   // Construct a default subtarget off of the TargetMachine defaults. The
815   // rest of NVPTX isn't friendly to change subtargets per function and
816   // so the default TargetMachine will have all of the options.
817   const Triple &TT = TM.getTargetTriple();
818   StringRef CPU = TM.getTargetCPU();
819   StringRef FS = TM.getTargetFeatureString();
820   const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
821   const NVPTXSubtarget STI(TT, CPU, FS, NTM);
822 
823   if (M.alias_size()) {
824     report_fatal_error("Module has aliases, which NVPTX does not support.");
825     return true; // error
826   }
827   if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
828     report_fatal_error(
829         "Module has a nontrivial global ctor, which NVPTX does not support.");
830     return true;  // error
831   }
832   if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
833     report_fatal_error(
834         "Module has a nontrivial global dtor, which NVPTX does not support.");
835     return true;  // error
836   }
837 
838   SmallString<128> Str1;
839   raw_svector_ostream OS1(Str1);
840 
841   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
842 
843   // We need to call the parent's one explicitly.
844   //bool Result = AsmPrinter::doInitialization(M);
845 
846   // Initialize TargetLoweringObjectFile.
847   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
848       .Initialize(OutContext, TM);
849 
850   Mang = new Mangler();
851 
852   // Emit header before any dwarf directives are emitted below.
853   emitHeader(M, OS1, STI);
854   OutStreamer->EmitRawText(OS1.str());
855 
856   // Already commented out
857   //bool Result = AsmPrinter::doInitialization(M);
858 
859   // Emit module-level inline asm if it exists.
860   if (!M.getModuleInlineAsm().empty()) {
861     OutStreamer->AddComment("Start of file scope inline assembly");
862     OutStreamer->AddBlankLine();
863     OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
864     OutStreamer->AddBlankLine();
865     OutStreamer->AddComment("End of file scope inline assembly");
866     OutStreamer->AddBlankLine();
867   }
868 
869   // If we're not NVCL we're CUDA, go ahead and emit filenames.
870   if (TM.getTargetTriple().getOS() != Triple::NVCL)
871     recordAndEmitFilenames(M);
872 
873   GlobalsEmitted = false;
874 
875   return false; // success
876 }
877 
878 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
879   SmallString<128> Str2;
880   raw_svector_ostream OS2(Str2);
881 
882   emitDeclarations(M, OS2);
883 
884   // As ptxas does not support forward references of globals, we need to first
885   // sort the list of module-level globals in def-use order. We visit each
886   // global variable in order, and ensure that we emit it *after* its dependent
887   // globals. We use a little extra memory maintaining both a set and a list to
888   // have fast searches while maintaining a strict ordering.
889   SmallVector<const GlobalVariable *, 8> Globals;
890   DenseSet<const GlobalVariable *> GVVisited;
891   DenseSet<const GlobalVariable *> GVVisiting;
892 
893   // Visit each global variable, in order
894   for (const GlobalVariable &I : M.globals())
895     VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
896 
897   assert(GVVisited.size() == M.getGlobalList().size() &&
898          "Missed a global variable");
899   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
900 
901   // Print out module-level global variables in proper order
902   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
903     printModuleLevelGV(Globals[i], OS2);
904 
905   OS2 << '\n';
906 
907   OutStreamer->EmitRawText(OS2.str());
908 }
909 
910 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
911                                  const NVPTXSubtarget &STI) {
912   O << "//\n";
913   O << "// Generated by LLVM NVPTX Back-End\n";
914   O << "//\n";
915   O << "\n";
916 
917   unsigned PTXVersion = STI.getPTXVersion();
918   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
919 
920   O << ".target ";
921   O << STI.getTargetName();
922 
923   const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
924   if (NTM.getDrvInterface() == NVPTX::NVCL)
925     O << ", texmode_independent";
926   else {
927     if (!STI.hasDouble())
928       O << ", map_f64_to_f32";
929   }
930 
931   if (MAI->doesSupportDebugInformation())
932     O << ", debug";
933 
934   O << "\n";
935 
936   O << ".address_size ";
937   if (NTM.is64Bit())
938     O << "64";
939   else
940     O << "32";
941   O << "\n";
942 
943   O << "\n";
944 }
945 
946 bool NVPTXAsmPrinter::doFinalization(Module &M) {
947   // If we did not emit any functions, then the global declarations have not
948   // yet been emitted.
949   if (!GlobalsEmitted) {
950     emitGlobals(M);
951     GlobalsEmitted = true;
952   }
953 
954   // XXX Temproarily remove global variables so that doFinalization() will not
955   // emit them again (global variables are emitted at beginning).
956 
957   Module::GlobalListType &global_list = M.getGlobalList();
958   int i, n = global_list.size();
959   GlobalVariable **gv_array = new GlobalVariable *[n];
960 
961   // first, back-up GlobalVariable in gv_array
962   i = 0;
963   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
964        I != E; ++I)
965     gv_array[i++] = &*I;
966 
967   // second, empty global_list
968   while (!global_list.empty())
969     global_list.remove(global_list.begin());
970 
971   // call doFinalization
972   bool ret = AsmPrinter::doFinalization(M);
973 
974   // now we restore global variables
975   for (i = 0; i < n; i++)
976     global_list.insert(global_list.end(), gv_array[i]);
977 
978   clearAnnotationCache(&M);
979 
980   delete[] gv_array;
981   return ret;
982 
983   //bool Result = AsmPrinter::doFinalization(M);
984   // Instead of calling the parents doFinalization, we may
985   // clone parents doFinalization and customize here.
986   // Currently, we if NVISA out the EmitGlobals() in
987   // parent's doFinalization, which is too intrusive.
988   //
989   // Same for the doInitialization.
990   //return Result;
991 }
992 
993 // This function emits appropriate linkage directives for
994 // functions and global variables.
995 //
996 // extern function declaration            -> .extern
997 // extern function definition             -> .visible
998 // external global variable with init     -> .visible
999 // external without init                  -> .extern
1000 // appending                              -> not allowed, assert.
1001 // for any linkage other than
1002 // internal, private, linker_private,
1003 // linker_private_weak, linker_private_weak_def_auto,
1004 // we emit                                -> .weak.
1005 
1006 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1007                                            raw_ostream &O) {
1008   if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
1009     if (V->hasExternalLinkage()) {
1010       if (isa<GlobalVariable>(V)) {
1011         const GlobalVariable *GVar = cast<GlobalVariable>(V);
1012         if (GVar) {
1013           if (GVar->hasInitializer())
1014             O << ".visible ";
1015           else
1016             O << ".extern ";
1017         }
1018       } else if (V->isDeclaration())
1019         O << ".extern ";
1020       else
1021         O << ".visible ";
1022     } else if (V->hasAppendingLinkage()) {
1023       std::string msg;
1024       msg.append("Error: ");
1025       msg.append("Symbol ");
1026       if (V->hasName())
1027         msg.append(V->getName());
1028       msg.append("has unsupported appending linkage type");
1029       llvm_unreachable(msg.c_str());
1030     } else if (!V->hasInternalLinkage() &&
1031                !V->hasPrivateLinkage()) {
1032       O << ".weak ";
1033     }
1034   }
1035 }
1036 
1037 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1038                                          raw_ostream &O,
1039                                          bool processDemoted) {
1040 
1041   // Skip meta data
1042   if (GVar->hasSection()) {
1043     if (GVar->getSection() == StringRef("llvm.metadata"))
1044       return;
1045   }
1046 
1047   // Skip LLVM intrinsic global variables
1048   if (GVar->getName().startswith("llvm.") ||
1049       GVar->getName().startswith("nvvm."))
1050     return;
1051 
1052   const DataLayout &DL = getDataLayout();
1053 
1054   // GlobalVariables are always constant pointers themselves.
1055   PointerType *PTy = GVar->getType();
1056   Type *ETy = GVar->getValueType();
1057 
1058   if (GVar->hasExternalLinkage()) {
1059     if (GVar->hasInitializer())
1060       O << ".visible ";
1061     else
1062       O << ".extern ";
1063   } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1064              GVar->hasAvailableExternallyLinkage() ||
1065              GVar->hasCommonLinkage()) {
1066     O << ".weak ";
1067   }
1068 
1069   if (llvm::isTexture(*GVar)) {
1070     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1071     return;
1072   }
1073 
1074   if (llvm::isSurface(*GVar)) {
1075     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1076     return;
1077   }
1078 
1079   if (GVar->isDeclaration()) {
1080     // (extern) declarations, no definition or initializer
1081     // Currently the only known declaration is for an automatic __local
1082     // (.shared) promoted to global.
1083     emitPTXGlobalVariable(GVar, O);
1084     O << ";\n";
1085     return;
1086   }
1087 
1088   if (llvm::isSampler(*GVar)) {
1089     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1090 
1091     const Constant *Initializer = nullptr;
1092     if (GVar->hasInitializer())
1093       Initializer = GVar->getInitializer();
1094     const ConstantInt *CI = nullptr;
1095     if (Initializer)
1096       CI = dyn_cast<ConstantInt>(Initializer);
1097     if (CI) {
1098       unsigned sample = CI->getZExtValue();
1099 
1100       O << " = { ";
1101 
1102       for (int i = 0,
1103                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1104            i < 3; i++) {
1105         O << "addr_mode_" << i << " = ";
1106         switch (addr) {
1107         case 0:
1108           O << "wrap";
1109           break;
1110         case 1:
1111           O << "clamp_to_border";
1112           break;
1113         case 2:
1114           O << "clamp_to_edge";
1115           break;
1116         case 3:
1117           O << "wrap";
1118           break;
1119         case 4:
1120           O << "mirror";
1121           break;
1122         }
1123         O << ", ";
1124       }
1125       O << "filter_mode = ";
1126       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1127       case 0:
1128         O << "nearest";
1129         break;
1130       case 1:
1131         O << "linear";
1132         break;
1133       case 2:
1134         llvm_unreachable("Anisotropic filtering is not supported");
1135       default:
1136         O << "nearest";
1137         break;
1138       }
1139       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1140         O << ", force_unnormalized_coords = 1";
1141       }
1142       O << " }";
1143     }
1144 
1145     O << ";\n";
1146     return;
1147   }
1148 
1149   if (GVar->hasPrivateLinkage()) {
1150 
1151     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1152       return;
1153 
1154     // FIXME - need better way (e.g. Metadata) to avoid generating this global
1155     if (!strncmp(GVar->getName().data(), "filename", 8))
1156       return;
1157     if (GVar->use_empty())
1158       return;
1159   }
1160 
1161   const Function *demotedFunc = nullptr;
1162   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1163     O << "// " << GVar->getName() << " has been demoted\n";
1164     if (localDecls.find(demotedFunc) != localDecls.end())
1165       localDecls[demotedFunc].push_back(GVar);
1166     else {
1167       std::vector<const GlobalVariable *> temp;
1168       temp.push_back(GVar);
1169       localDecls[demotedFunc] = temp;
1170     }
1171     return;
1172   }
1173 
1174   O << ".";
1175   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1176 
1177   if (isManaged(*GVar)) {
1178     O << " .attribute(.managed)";
1179   }
1180 
1181   if (GVar->getAlignment() == 0)
1182     O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1183   else
1184     O << " .align " << GVar->getAlignment();
1185 
1186   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1187     O << " .";
1188     // Special case: ABI requires that we use .u8 for predicates
1189     if (ETy->isIntegerTy(1))
1190       O << "u8";
1191     else
1192       O << getPTXFundamentalTypeStr(ETy, false);
1193     O << " ";
1194     getSymbol(GVar)->print(O, MAI);
1195 
1196     // Ptx allows variable initilization only for constant and global state
1197     // spaces.
1198     if (GVar->hasInitializer()) {
1199       if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1200           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1201         const Constant *Initializer = GVar->getInitializer();
1202         // 'undef' is treated as there is no value specified.
1203         if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1204           O << " = ";
1205           printScalarConstant(Initializer, O);
1206         }
1207       } else {
1208         // The frontend adds zero-initializer to device and constant variables
1209         // that don't have an initial value, and UndefValue to shared
1210         // variables, so skip warning for this case.
1211         if (!GVar->getInitializer()->isNullValue() &&
1212             !isa<UndefValue>(GVar->getInitializer())) {
1213           report_fatal_error("initial value of '" + GVar->getName() +
1214                              "' is not allowed in addrspace(" +
1215                              Twine(PTy->getAddressSpace()) + ")");
1216         }
1217       }
1218     }
1219   } else {
1220     unsigned int ElementSize = 0;
1221 
1222     // Although PTX has direct support for struct type and array type and
1223     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1224     // targets that support these high level field accesses. Structs, arrays
1225     // and vectors are lowered into arrays of bytes.
1226     switch (ETy->getTypeID()) {
1227     case Type::StructTyID:
1228     case Type::ArrayTyID:
1229     case Type::VectorTyID:
1230       ElementSize = DL.getTypeStoreSize(ETy);
1231       // Ptx allows variable initilization only for constant and
1232       // global state spaces.
1233       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1234            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1235           GVar->hasInitializer()) {
1236         const Constant *Initializer = GVar->getInitializer();
1237         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1238           AggBuffer aggBuffer(ElementSize, O, *this);
1239           bufferAggregateConstant(Initializer, &aggBuffer);
1240           if (aggBuffer.numSymbols) {
1241             if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1242               O << " .u64 ";
1243               getSymbol(GVar)->print(O, MAI);
1244               O << "[";
1245               O << ElementSize / 8;
1246             } else {
1247               O << " .u32 ";
1248               getSymbol(GVar)->print(O, MAI);
1249               O << "[";
1250               O << ElementSize / 4;
1251             }
1252             O << "]";
1253           } else {
1254             O << " .b8 ";
1255             getSymbol(GVar)->print(O, MAI);
1256             O << "[";
1257             O << ElementSize;
1258             O << "]";
1259           }
1260           O << " = {";
1261           aggBuffer.print();
1262           O << "}";
1263         } else {
1264           O << " .b8 ";
1265           getSymbol(GVar)->print(O, MAI);
1266           if (ElementSize) {
1267             O << "[";
1268             O << ElementSize;
1269             O << "]";
1270           }
1271         }
1272       } else {
1273         O << " .b8 ";
1274         getSymbol(GVar)->print(O, MAI);
1275         if (ElementSize) {
1276           O << "[";
1277           O << ElementSize;
1278           O << "]";
1279         }
1280       }
1281       break;
1282     default:
1283       llvm_unreachable("type not supported yet");
1284     }
1285 
1286   }
1287   O << ";\n";
1288 }
1289 
1290 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1291   if (localDecls.find(f) == localDecls.end())
1292     return;
1293 
1294   std::vector<const GlobalVariable *> &gvars = localDecls[f];
1295 
1296   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1297     O << "\t// demoted variable\n\t";
1298     printModuleLevelGV(gvars[i], O, true);
1299   }
1300 }
1301 
1302 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1303                                           raw_ostream &O) const {
1304   switch (AddressSpace) {
1305   case llvm::ADDRESS_SPACE_LOCAL:
1306     O << "local";
1307     break;
1308   case llvm::ADDRESS_SPACE_GLOBAL:
1309     O << "global";
1310     break;
1311   case llvm::ADDRESS_SPACE_CONST:
1312     O << "const";
1313     break;
1314   case llvm::ADDRESS_SPACE_SHARED:
1315     O << "shared";
1316     break;
1317   default:
1318     report_fatal_error("Bad address space found while emitting PTX");
1319     break;
1320   }
1321 }
1322 
1323 std::string
1324 NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
1325   switch (Ty->getTypeID()) {
1326   default:
1327     llvm_unreachable("unexpected type");
1328     break;
1329   case Type::IntegerTyID: {
1330     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1331     if (NumBits == 1)
1332       return "pred";
1333     else if (NumBits <= 64) {
1334       std::string name = "u";
1335       return name + utostr(NumBits);
1336     } else {
1337       llvm_unreachable("Integer too large");
1338       break;
1339     }
1340     break;
1341   }
1342   case Type::FloatTyID:
1343     return "f32";
1344   case Type::DoubleTyID:
1345     return "f64";
1346   case Type::PointerTyID:
1347     if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1348       if (useB4PTR)
1349         return "b64";
1350       else
1351         return "u64";
1352     else if (useB4PTR)
1353       return "b32";
1354     else
1355       return "u32";
1356   }
1357   llvm_unreachable("unexpected type");
1358   return nullptr;
1359 }
1360 
1361 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1362                                             raw_ostream &O) {
1363 
1364   const DataLayout &DL = getDataLayout();
1365 
1366   // GlobalVariables are always constant pointers themselves.
1367   Type *ETy = GVar->getValueType();
1368 
1369   O << ".";
1370   emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
1371   if (GVar->getAlignment() == 0)
1372     O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1373   else
1374     O << " .align " << GVar->getAlignment();
1375 
1376   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1377     O << " .";
1378     O << getPTXFundamentalTypeStr(ETy);
1379     O << " ";
1380     getSymbol(GVar)->print(O, MAI);
1381     return;
1382   }
1383 
1384   int64_t ElementSize = 0;
1385 
1386   // Although PTX has direct support for struct type and array type and LLVM IR
1387   // is very similar to PTX, the LLVM CodeGen does not support for targets that
1388   // support these high level field accesses. Structs and arrays are lowered
1389   // into arrays of bytes.
1390   switch (ETy->getTypeID()) {
1391   case Type::StructTyID:
1392   case Type::ArrayTyID:
1393   case Type::VectorTyID:
1394     ElementSize = DL.getTypeStoreSize(ETy);
1395     O << " .b8 ";
1396     getSymbol(GVar)->print(O, MAI);
1397     O << "[";
1398     if (ElementSize) {
1399       O << ElementSize;
1400     }
1401     O << "]";
1402     break;
1403   default:
1404     llvm_unreachable("type not supported yet");
1405   }
1406   return;
1407 }
1408 
1409 static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
1410   if (Ty->isSingleValueType())
1411     return DL.getPrefTypeAlignment(Ty);
1412 
1413   auto *ATy = dyn_cast<ArrayType>(Ty);
1414   if (ATy)
1415     return getOpenCLAlignment(DL, ATy->getElementType());
1416 
1417   auto *STy = dyn_cast<StructType>(Ty);
1418   if (STy) {
1419     unsigned int alignStruct = 1;
1420     // Go through each element of the struct and find the
1421     // largest alignment.
1422     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1423       Type *ETy = STy->getElementType(i);
1424       unsigned int align = getOpenCLAlignment(DL, ETy);
1425       if (align > alignStruct)
1426         alignStruct = align;
1427     }
1428     return alignStruct;
1429   }
1430 
1431   auto *FTy = dyn_cast<FunctionType>(Ty);
1432   if (FTy)
1433     return DL.getPointerPrefAlignment();
1434   return DL.getPrefTypeAlignment(Ty);
1435 }
1436 
1437 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1438                                      int paramIndex, raw_ostream &O) {
1439   getSymbol(I->getParent())->print(O, MAI);
1440   O << "_param_" << paramIndex;
1441 }
1442 
1443 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1444   const DataLayout &DL = getDataLayout();
1445   const AttributeSet &PAL = F->getAttributes();
1446   const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1447   Function::const_arg_iterator I, E;
1448   unsigned paramIndex = 0;
1449   bool first = true;
1450   bool isKernelFunc = llvm::isKernelFunction(*F);
1451   bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1452   MVT thePointerTy = TLI->getPointerTy(DL);
1453 
1454   if (F->arg_empty()) {
1455     O << "()\n";
1456     return;
1457   }
1458 
1459   O << "(\n";
1460 
1461   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1462     Type *Ty = I->getType();
1463 
1464     if (!first)
1465       O << ",\n";
1466 
1467     first = false;
1468 
1469     // Handle image/sampler parameters
1470     if (isKernelFunction(*F)) {
1471       if (isSampler(*I) || isImage(*I)) {
1472         if (isImage(*I)) {
1473           std::string sname = I->getName();
1474           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1475             if (nvptxSubtarget->hasImageHandles())
1476               O << "\t.param .u64 .ptr .surfref ";
1477             else
1478               O << "\t.param .surfref ";
1479             CurrentFnSym->print(O, MAI);
1480             O << "_param_" << paramIndex;
1481           }
1482           else { // Default image is read_only
1483             if (nvptxSubtarget->hasImageHandles())
1484               O << "\t.param .u64 .ptr .texref ";
1485             else
1486               O << "\t.param .texref ";
1487             CurrentFnSym->print(O, MAI);
1488             O << "_param_" << paramIndex;
1489           }
1490         } else {
1491           if (nvptxSubtarget->hasImageHandles())
1492             O << "\t.param .u64 .ptr .samplerref ";
1493           else
1494             O << "\t.param .samplerref ";
1495           CurrentFnSym->print(O, MAI);
1496           O << "_param_" << paramIndex;
1497         }
1498         continue;
1499       }
1500     }
1501 
1502     if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
1503       if (Ty->isAggregateType() || Ty->isVectorTy()) {
1504         // Just print .param .align <a> .b8 .param[size];
1505         // <a> = PAL.getparamalignment
1506         // size = typeallocsize of element type
1507         unsigned align = PAL.getParamAlignment(paramIndex + 1);
1508         if (align == 0)
1509           align = DL.getABITypeAlignment(Ty);
1510 
1511         unsigned sz = DL.getTypeAllocSize(Ty);
1512         O << "\t.param .align " << align << " .b8 ";
1513         printParamName(I, paramIndex, O);
1514         O << "[" << sz << "]";
1515 
1516         continue;
1517       }
1518       // Just a scalar
1519       auto *PTy = dyn_cast<PointerType>(Ty);
1520       if (isKernelFunc) {
1521         if (PTy) {
1522           // Special handling for pointer arguments to kernel
1523           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1524 
1525           if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1526               NVPTX::CUDA) {
1527             Type *ETy = PTy->getElementType();
1528             int addrSpace = PTy->getAddressSpace();
1529             switch (addrSpace) {
1530             default:
1531               O << ".ptr ";
1532               break;
1533             case llvm::ADDRESS_SPACE_CONST:
1534               O << ".ptr .const ";
1535               break;
1536             case llvm::ADDRESS_SPACE_SHARED:
1537               O << ".ptr .shared ";
1538               break;
1539             case llvm::ADDRESS_SPACE_GLOBAL:
1540               O << ".ptr .global ";
1541               break;
1542             }
1543             O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
1544           }
1545           printParamName(I, paramIndex, O);
1546           continue;
1547         }
1548 
1549         // non-pointer scalar to kernel func
1550         O << "\t.param .";
1551         // Special case: predicate operands become .u8 types
1552         if (Ty->isIntegerTy(1))
1553           O << "u8";
1554         else
1555           O << getPTXFundamentalTypeStr(Ty);
1556         O << " ";
1557         printParamName(I, paramIndex, O);
1558         continue;
1559       }
1560       // Non-kernel function, just print .param .b<size> for ABI
1561       // and .reg .b<size> for non-ABI
1562       unsigned sz = 0;
1563       if (isa<IntegerType>(Ty)) {
1564         sz = cast<IntegerType>(Ty)->getBitWidth();
1565         if (sz < 32)
1566           sz = 32;
1567       } else if (isa<PointerType>(Ty))
1568         sz = thePointerTy.getSizeInBits();
1569       else
1570         sz = Ty->getPrimitiveSizeInBits();
1571       if (isABI)
1572         O << "\t.param .b" << sz << " ";
1573       else
1574         O << "\t.reg .b" << sz << " ";
1575       printParamName(I, paramIndex, O);
1576       continue;
1577     }
1578 
1579     // param has byVal attribute. So should be a pointer
1580     auto *PTy = dyn_cast<PointerType>(Ty);
1581     assert(PTy && "Param with byval attribute should be a pointer type");
1582     Type *ETy = PTy->getElementType();
1583 
1584     if (isABI || isKernelFunc) {
1585       // Just print .param .align <a> .b8 .param[size];
1586       // <a> = PAL.getparamalignment
1587       // size = typeallocsize of element type
1588       unsigned align = PAL.getParamAlignment(paramIndex + 1);
1589       if (align == 0)
1590         align = DL.getABITypeAlignment(ETy);
1591 
1592       unsigned sz = DL.getTypeAllocSize(ETy);
1593       O << "\t.param .align " << align << " .b8 ";
1594       printParamName(I, paramIndex, O);
1595       O << "[" << sz << "]";
1596       continue;
1597     } else {
1598       // Split the ETy into constituent parts and
1599       // print .param .b<size> <name> for each part.
1600       // Further, if a part is vector, print the above for
1601       // each vector element.
1602       SmallVector<EVT, 16> vtparts;
1603       ComputeValueVTs(*TLI, DL, ETy, vtparts);
1604       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1605         unsigned elems = 1;
1606         EVT elemtype = vtparts[i];
1607         if (vtparts[i].isVector()) {
1608           elems = vtparts[i].getVectorNumElements();
1609           elemtype = vtparts[i].getVectorElementType();
1610         }
1611 
1612         for (unsigned j = 0, je = elems; j != je; ++j) {
1613           unsigned sz = elemtype.getSizeInBits();
1614           if (elemtype.isInteger() && (sz < 32))
1615             sz = 32;
1616           O << "\t.reg .b" << sz << " ";
1617           printParamName(I, paramIndex, O);
1618           if (j < je - 1)
1619             O << ",\n";
1620           ++paramIndex;
1621         }
1622         if (i < e - 1)
1623           O << ",\n";
1624       }
1625       --paramIndex;
1626       continue;
1627     }
1628   }
1629 
1630   O << "\n)\n";
1631 }
1632 
1633 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1634                                             raw_ostream &O) {
1635   const Function *F = MF.getFunction();
1636   emitFunctionParamList(F, O);
1637 }
1638 
1639 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1640     const MachineFunction &MF) {
1641   SmallString<128> Str;
1642   raw_svector_ostream O(Str);
1643 
1644   // Map the global virtual register number to a register class specific
1645   // virtual register number starting from 1 with that class.
1646   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1647   //unsigned numRegClasses = TRI->getNumRegClasses();
1648 
1649   // Emit the Fake Stack Object
1650   const MachineFrameInfo *MFI = MF.getFrameInfo();
1651   int NumBytes = (int) MFI->getStackSize();
1652   if (NumBytes) {
1653     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1654       << getFunctionNumber() << "[" << NumBytes << "];\n";
1655     if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1656       O << "\t.reg .b64 \t%SP;\n";
1657       O << "\t.reg .b64 \t%SPL;\n";
1658     } else {
1659       O << "\t.reg .b32 \t%SP;\n";
1660       O << "\t.reg .b32 \t%SPL;\n";
1661     }
1662   }
1663 
1664   // Go through all virtual registers to establish the mapping between the
1665   // global virtual
1666   // register number and the per class virtual register number.
1667   // We use the per class virtual register number in the ptx output.
1668   unsigned int numVRs = MRI->getNumVirtRegs();
1669   for (unsigned i = 0; i < numVRs; i++) {
1670     unsigned int vr = TRI->index2VirtReg(i);
1671     const TargetRegisterClass *RC = MRI->getRegClass(vr);
1672     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1673     int n = regmap.size();
1674     regmap.insert(std::make_pair(vr, n + 1));
1675   }
1676 
1677   // Emit register declarations
1678   // @TODO: Extract out the real register usage
1679   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1680   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1681   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1682   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1683   // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1684   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1685   // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1686 
1687   // Emit declaration of the virtual registers or 'physical' registers for
1688   // each register class
1689   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1690     const TargetRegisterClass *RC = TRI->getRegClass(i);
1691     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1692     std::string rcname = getNVPTXRegClassName(RC);
1693     std::string rcStr = getNVPTXRegClassStr(RC);
1694     int n = regmap.size();
1695 
1696     // Only declare those registers that may be used.
1697     if (n) {
1698        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1699          << ">;\n";
1700     }
1701   }
1702 
1703   OutStreamer->EmitRawText(O.str());
1704 }
1705 
1706 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1707   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1708   bool ignored;
1709   unsigned int numHex;
1710   const char *lead;
1711 
1712   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1713     numHex = 8;
1714     lead = "0f";
1715     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1716   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1717     numHex = 16;
1718     lead = "0d";
1719     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1720   } else
1721     llvm_unreachable("unsupported fp type");
1722 
1723   APInt API = APF.bitcastToAPInt();
1724   std::string hexstr(utohexstr(API.getZExtValue()));
1725   O << lead;
1726   if (hexstr.length() < numHex)
1727     O << std::string(numHex - hexstr.length(), '0');
1728   O << utohexstr(API.getZExtValue());
1729 }
1730 
1731 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1732   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1733     O << CI->getValue();
1734     return;
1735   }
1736   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1737     printFPConstant(CFP, O);
1738     return;
1739   }
1740   if (isa<ConstantPointerNull>(CPV)) {
1741     O << "0";
1742     return;
1743   }
1744   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1745     bool IsNonGenericPointer = false;
1746     if (GVar->getType()->getAddressSpace() != 0) {
1747       IsNonGenericPointer = true;
1748     }
1749     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1750       O << "generic(";
1751       getSymbol(GVar)->print(O, MAI);
1752       O << ")";
1753     } else {
1754       getSymbol(GVar)->print(O, MAI);
1755     }
1756     return;
1757   }
1758   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1759     const Value *v = Cexpr->stripPointerCasts();
1760     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1761     bool IsNonGenericPointer = false;
1762     if (PTy && PTy->getAddressSpace() != 0) {
1763       IsNonGenericPointer = true;
1764     }
1765     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1766       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1767         O << "generic(";
1768         getSymbol(GVar)->print(O, MAI);
1769         O << ")";
1770       } else {
1771         getSymbol(GVar)->print(O, MAI);
1772       }
1773       return;
1774     } else {
1775       lowerConstant(CPV)->print(O, MAI);
1776       return;
1777     }
1778   }
1779   llvm_unreachable("Not scalar type found in printScalarConstant()");
1780 }
1781 
1782 // These utility functions assure we get the right sequence of bytes for a given
1783 // type even for big-endian machines
1784 template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1785   int64_t vp = (int64_t)val;
1786   for (unsigned i = 0; i < sizeof(T); ++i) {
1787     p[i] = (unsigned char)vp;
1788     vp >>= 8;
1789   }
1790 }
1791 static void ConvertFloatToBytes(unsigned char *p, float val) {
1792   int32_t *vp = (int32_t *)&val;
1793   for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1794     p[i] = (unsigned char)*vp;
1795     *vp >>= 8;
1796   }
1797 }
1798 static void ConvertDoubleToBytes(unsigned char *p, double val) {
1799   int64_t *vp = (int64_t *)&val;
1800   for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1801     p[i] = (unsigned char)*vp;
1802     *vp >>= 8;
1803   }
1804 }
1805 
1806 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1807                                    AggBuffer *aggBuffer) {
1808 
1809   const DataLayout &DL = getDataLayout();
1810 
1811   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1812     int s = DL.getTypeAllocSize(CPV->getType());
1813     if (s < Bytes)
1814       s = Bytes;
1815     aggBuffer->addZeros(s);
1816     return;
1817   }
1818 
1819   unsigned char ptr[8];
1820   switch (CPV->getType()->getTypeID()) {
1821 
1822   case Type::IntegerTyID: {
1823     Type *ETy = CPV->getType();
1824     if (ETy == Type::getInt8Ty(CPV->getContext())) {
1825       unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1826       ConvertIntToBytes<>(ptr, c);
1827       aggBuffer->addBytes(ptr, 1, Bytes);
1828     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1829       short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1830       ConvertIntToBytes<>(ptr, int16);
1831       aggBuffer->addBytes(ptr, 2, Bytes);
1832     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1833       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1834         int int32 = (int)(constInt->getZExtValue());
1835         ConvertIntToBytes<>(ptr, int32);
1836         aggBuffer->addBytes(ptr, 4, Bytes);
1837         break;
1838       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1839         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1840                 ConstantFoldConstantExpression(Cexpr, DL))) {
1841           int int32 = (int)(constInt->getZExtValue());
1842           ConvertIntToBytes<>(ptr, int32);
1843           aggBuffer->addBytes(ptr, 4, Bytes);
1844           break;
1845         }
1846         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1847           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1848           aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1849           aggBuffer->addZeros(4);
1850           break;
1851         }
1852       }
1853       llvm_unreachable("unsupported integer const type");
1854     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1855       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1856         long long int64 = (long long)(constInt->getZExtValue());
1857         ConvertIntToBytes<>(ptr, int64);
1858         aggBuffer->addBytes(ptr, 8, Bytes);
1859         break;
1860       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1861         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1862                 ConstantFoldConstantExpression(Cexpr, DL))) {
1863           long long int64 = (long long)(constInt->getZExtValue());
1864           ConvertIntToBytes<>(ptr, int64);
1865           aggBuffer->addBytes(ptr, 8, Bytes);
1866           break;
1867         }
1868         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1869           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1870           aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1871           aggBuffer->addZeros(8);
1872           break;
1873         }
1874       }
1875       llvm_unreachable("unsupported integer const type");
1876     } else
1877       llvm_unreachable("unsupported integer const type");
1878     break;
1879   }
1880   case Type::FloatTyID:
1881   case Type::DoubleTyID: {
1882     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1883     Type *Ty = CFP->getType();
1884     if (Ty == Type::getFloatTy(CPV->getContext())) {
1885       float float32 = (float) CFP->getValueAPF().convertToFloat();
1886       ConvertFloatToBytes(ptr, float32);
1887       aggBuffer->addBytes(ptr, 4, Bytes);
1888     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1889       double float64 = CFP->getValueAPF().convertToDouble();
1890       ConvertDoubleToBytes(ptr, float64);
1891       aggBuffer->addBytes(ptr, 8, Bytes);
1892     } else {
1893       llvm_unreachable("unsupported fp const type");
1894     }
1895     break;
1896   }
1897   case Type::PointerTyID: {
1898     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1899       aggBuffer->addSymbol(GVar, GVar);
1900     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1901       const Value *v = Cexpr->stripPointerCasts();
1902       aggBuffer->addSymbol(v, Cexpr);
1903     }
1904     unsigned int s = DL.getTypeAllocSize(CPV->getType());
1905     aggBuffer->addZeros(s);
1906     break;
1907   }
1908 
1909   case Type::ArrayTyID:
1910   case Type::VectorTyID:
1911   case Type::StructTyID: {
1912     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1913         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1914       int ElementSize = DL.getTypeAllocSize(CPV->getType());
1915       bufferAggregateConstant(CPV, aggBuffer);
1916       if (Bytes > ElementSize)
1917         aggBuffer->addZeros(Bytes - ElementSize);
1918     } else if (isa<ConstantAggregateZero>(CPV))
1919       aggBuffer->addZeros(Bytes);
1920     else
1921       llvm_unreachable("Unexpected Constant type");
1922     break;
1923   }
1924 
1925   default:
1926     llvm_unreachable("unsupported type");
1927   }
1928 }
1929 
1930 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1931                                               AggBuffer *aggBuffer) {
1932   const DataLayout &DL = getDataLayout();
1933   int Bytes;
1934 
1935   // Old constants
1936   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1937     if (CPV->getNumOperands())
1938       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1939         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1940     return;
1941   }
1942 
1943   if (const ConstantDataSequential *CDS =
1944           dyn_cast<ConstantDataSequential>(CPV)) {
1945     if (CDS->getNumElements())
1946       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1947         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1948                      aggBuffer);
1949     return;
1950   }
1951 
1952   if (isa<ConstantStruct>(CPV)) {
1953     if (CPV->getNumOperands()) {
1954       StructType *ST = cast<StructType>(CPV->getType());
1955       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1956         if (i == (e - 1))
1957           Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1958                   DL.getTypeAllocSize(ST) -
1959                   DL.getStructLayout(ST)->getElementOffset(i);
1960         else
1961           Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1962                   DL.getStructLayout(ST)->getElementOffset(i);
1963         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1964       }
1965     }
1966     return;
1967   }
1968   llvm_unreachable("unsupported constant type in printAggregateConstant()");
1969 }
1970 
1971 // buildTypeNameMap - Run through symbol table looking for type names.
1972 //
1973 
1974 
1975 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1976   switch (MI.getOpcode()) {
1977   default:
1978     return false;
1979   case NVPTX::CallArgBeginInst:
1980   case NVPTX::CallArgEndInst0:
1981   case NVPTX::CallArgEndInst1:
1982   case NVPTX::CallArgF32:
1983   case NVPTX::CallArgF64:
1984   case NVPTX::CallArgI16:
1985   case NVPTX::CallArgI32:
1986   case NVPTX::CallArgI32imm:
1987   case NVPTX::CallArgI64:
1988   case NVPTX::CallArgParam:
1989   case NVPTX::CallVoidInst:
1990   case NVPTX::CallVoidInstReg:
1991   case NVPTX::Callseq_End:
1992   case NVPTX::CallVoidInstReg64:
1993   case NVPTX::DeclareParamInst:
1994   case NVPTX::DeclareRetMemInst:
1995   case NVPTX::DeclareRetRegInst:
1996   case NVPTX::DeclareRetScalarInst:
1997   case NVPTX::DeclareScalarParamInst:
1998   case NVPTX::DeclareScalarRegInst:
1999   case NVPTX::StoreParamF32:
2000   case NVPTX::StoreParamF64:
2001   case NVPTX::StoreParamI16:
2002   case NVPTX::StoreParamI32:
2003   case NVPTX::StoreParamI64:
2004   case NVPTX::StoreParamI8:
2005   case NVPTX::StoreRetvalF32:
2006   case NVPTX::StoreRetvalF64:
2007   case NVPTX::StoreRetvalI16:
2008   case NVPTX::StoreRetvalI32:
2009   case NVPTX::StoreRetvalI64:
2010   case NVPTX::StoreRetvalI8:
2011   case NVPTX::LastCallArgF32:
2012   case NVPTX::LastCallArgF64:
2013   case NVPTX::LastCallArgI16:
2014   case NVPTX::LastCallArgI32:
2015   case NVPTX::LastCallArgI32imm:
2016   case NVPTX::LastCallArgI64:
2017   case NVPTX::LastCallArgParam:
2018   case NVPTX::LoadParamMemF32:
2019   case NVPTX::LoadParamMemF64:
2020   case NVPTX::LoadParamMemI16:
2021   case NVPTX::LoadParamMemI32:
2022   case NVPTX::LoadParamMemI64:
2023   case NVPTX::LoadParamMemI8:
2024   case NVPTX::PrototypeInst:
2025   case NVPTX::DBG_VALUE:
2026     return true;
2027   }
2028   return false;
2029 }
2030 
2031 /// lowerConstantForGV - Return an MCExpr for the given Constant.  This is mostly
2032 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
2033 /// expressions that are representable in PTX and create
2034 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2035 const MCExpr *
2036 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2037   MCContext &Ctx = OutContext;
2038 
2039   if (CV->isNullValue() || isa<UndefValue>(CV))
2040     return MCConstantExpr::create(0, Ctx);
2041 
2042   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2043     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2044 
2045   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2046     const MCSymbolRefExpr *Expr =
2047       MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2048     if (ProcessingGeneric) {
2049       return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2050     } else {
2051       return Expr;
2052     }
2053   }
2054 
2055   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2056   if (!CE) {
2057     llvm_unreachable("Unknown constant value to lower!");
2058   }
2059 
2060   switch (CE->getOpcode()) {
2061   default:
2062     // If the code isn't optimized, there may be outstanding folding
2063     // opportunities. Attempt to fold the expression using DataLayout as a
2064     // last resort before giving up.
2065     if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
2066       if (C != CE)
2067         return lowerConstantForGV(C, ProcessingGeneric);
2068 
2069     // Otherwise report the problem to the user.
2070     {
2071       std::string S;
2072       raw_string_ostream OS(S);
2073       OS << "Unsupported expression in static initializer: ";
2074       CE->printAsOperand(OS, /*PrintType=*/false,
2075                      !MF ? nullptr : MF->getFunction()->getParent());
2076       report_fatal_error(OS.str());
2077     }
2078 
2079   case Instruction::AddrSpaceCast: {
2080     // Strip the addrspacecast and pass along the operand
2081     PointerType *DstTy = cast<PointerType>(CE->getType());
2082     if (DstTy->getAddressSpace() == 0) {
2083       return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2084     }
2085     std::string S;
2086     raw_string_ostream OS(S);
2087     OS << "Unsupported expression in static initializer: ";
2088     CE->printAsOperand(OS, /*PrintType=*/ false,
2089                        !MF ? 0 : MF->getFunction()->getParent());
2090     report_fatal_error(OS.str());
2091   }
2092 
2093   case Instruction::GetElementPtr: {
2094     const DataLayout &DL = getDataLayout();
2095 
2096     // Generate a symbolic expression for the byte address
2097     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2098     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2099 
2100     const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2101                                             ProcessingGeneric);
2102     if (!OffsetAI)
2103       return Base;
2104 
2105     int64_t Offset = OffsetAI.getSExtValue();
2106     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2107                                    Ctx);
2108   }
2109 
2110   case Instruction::Trunc:
2111     // We emit the value and depend on the assembler to truncate the generated
2112     // expression properly.  This is important for differences between
2113     // blockaddress labels.  Since the two labels are in the same function, it
2114     // is reasonable to treat their delta as a 32-bit value.
2115     // FALL THROUGH.
2116   case Instruction::BitCast:
2117     return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2118 
2119   case Instruction::IntToPtr: {
2120     const DataLayout &DL = getDataLayout();
2121 
2122     // Handle casts to pointers by changing them into casts to the appropriate
2123     // integer type.  This promotes constant folding and simplifies this code.
2124     Constant *Op = CE->getOperand(0);
2125     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2126                                       false/*ZExt*/);
2127     return lowerConstantForGV(Op, ProcessingGeneric);
2128   }
2129 
2130   case Instruction::PtrToInt: {
2131     const DataLayout &DL = getDataLayout();
2132 
2133     // Support only foldable casts to/from pointers that can be eliminated by
2134     // changing the pointer to the appropriately sized integer type.
2135     Constant *Op = CE->getOperand(0);
2136     Type *Ty = CE->getType();
2137 
2138     const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2139 
2140     // We can emit the pointer value into this slot if the slot is an
2141     // integer slot equal to the size of the pointer.
2142     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2143       return OpExpr;
2144 
2145     // Otherwise the pointer is smaller than the resultant integer, mask off
2146     // the high bits so we are sure to get a proper truncation if the input is
2147     // a constant expr.
2148     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2149     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2150     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2151   }
2152 
2153   // The MC library also has a right-shift operator, but it isn't consistently
2154   // signed or unsigned between different targets.
2155   case Instruction::Add: {
2156     const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2157     const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2158     switch (CE->getOpcode()) {
2159     default: llvm_unreachable("Unknown binary operator constant cast expr");
2160     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2161     }
2162   }
2163   }
2164 }
2165 
2166 // Copy of MCExpr::print customized for NVPTX
2167 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2168   switch (Expr.getKind()) {
2169   case MCExpr::Target:
2170     return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
2171   case MCExpr::Constant:
2172     OS << cast<MCConstantExpr>(Expr).getValue();
2173     return;
2174 
2175   case MCExpr::SymbolRef: {
2176     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2177     const MCSymbol &Sym = SRE.getSymbol();
2178     Sym.print(OS, MAI);
2179     return;
2180   }
2181 
2182   case MCExpr::Unary: {
2183     const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2184     switch (UE.getOpcode()) {
2185     case MCUnaryExpr::LNot:  OS << '!'; break;
2186     case MCUnaryExpr::Minus: OS << '-'; break;
2187     case MCUnaryExpr::Not:   OS << '~'; break;
2188     case MCUnaryExpr::Plus:  OS << '+'; break;
2189     }
2190     printMCExpr(*UE.getSubExpr(), OS);
2191     return;
2192   }
2193 
2194   case MCExpr::Binary: {
2195     const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2196 
2197     // Only print parens around the LHS if it is non-trivial.
2198     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2199         isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2200       printMCExpr(*BE.getLHS(), OS);
2201     } else {
2202       OS << '(';
2203       printMCExpr(*BE.getLHS(), OS);
2204       OS<< ')';
2205     }
2206 
2207     switch (BE.getOpcode()) {
2208     case MCBinaryExpr::Add:
2209       // Print "X-42" instead of "X+-42".
2210       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2211         if (RHSC->getValue() < 0) {
2212           OS << RHSC->getValue();
2213           return;
2214         }
2215       }
2216 
2217       OS <<  '+';
2218       break;
2219     default: llvm_unreachable("Unhandled binary operator");
2220     }
2221 
2222     // Only print parens around the LHS if it is non-trivial.
2223     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2224       printMCExpr(*BE.getRHS(), OS);
2225     } else {
2226       OS << '(';
2227       printMCExpr(*BE.getRHS(), OS);
2228       OS << ')';
2229     }
2230     return;
2231   }
2232   }
2233 
2234   llvm_unreachable("Invalid expression kind!");
2235 }
2236 
2237 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2238 ///
2239 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2240                                       unsigned AsmVariant,
2241                                       const char *ExtraCode, raw_ostream &O) {
2242   if (ExtraCode && ExtraCode[0]) {
2243     if (ExtraCode[1] != 0)
2244       return true; // Unknown modifier.
2245 
2246     switch (ExtraCode[0]) {
2247     default:
2248       // See if this is a generic print operand
2249       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2250     case 'r':
2251       break;
2252     }
2253   }
2254 
2255   printOperand(MI, OpNo, O);
2256 
2257   return false;
2258 }
2259 
2260 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2261     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2262     const char *ExtraCode, raw_ostream &O) {
2263   if (ExtraCode && ExtraCode[0])
2264     return true; // Unknown modifier
2265 
2266   O << '[';
2267   printMemOperand(MI, OpNo, O);
2268   O << ']';
2269 
2270   return false;
2271 }
2272 
2273 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2274                                    raw_ostream &O, const char *Modifier) {
2275   const MachineOperand &MO = MI->getOperand(opNum);
2276   switch (MO.getType()) {
2277   case MachineOperand::MO_Register:
2278     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2279       if (MO.getReg() == NVPTX::VRDepot)
2280         O << DEPOTNAME << getFunctionNumber();
2281       else
2282         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2283     } else {
2284       emitVirtualRegister(MO.getReg(), O);
2285     }
2286     return;
2287 
2288   case MachineOperand::MO_Immediate:
2289     if (!Modifier)
2290       O << MO.getImm();
2291     else if (strstr(Modifier, "vec") == Modifier)
2292       printVecModifiedImmediate(MO, Modifier, O);
2293     else
2294       llvm_unreachable(
2295           "Don't know how to handle modifier on immediate operand");
2296     return;
2297 
2298   case MachineOperand::MO_FPImmediate:
2299     printFPConstant(MO.getFPImm(), O);
2300     break;
2301 
2302   case MachineOperand::MO_GlobalAddress:
2303     getSymbol(MO.getGlobal())->print(O, MAI);
2304     break;
2305 
2306   case MachineOperand::MO_MachineBasicBlock:
2307     MO.getMBB()->getSymbol()->print(O, MAI);
2308     return;
2309 
2310   default:
2311     llvm_unreachable("Operand type not supported.");
2312   }
2313 }
2314 
2315 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2316                                       raw_ostream &O, const char *Modifier) {
2317   printOperand(MI, opNum, O);
2318 
2319   if (Modifier && !strcmp(Modifier, "add")) {
2320     O << ", ";
2321     printOperand(MI, opNum + 1, O);
2322   } else {
2323     if (MI->getOperand(opNum + 1).isImm() &&
2324         MI->getOperand(opNum + 1).getImm() == 0)
2325       return; // don't print ',0' or '+0'
2326     O << "+";
2327     printOperand(MI, opNum + 1, O);
2328   }
2329 }
2330 
2331 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2332   std::stringstream temp;
2333   LineReader *reader = this->getReader(filename);
2334   temp << "\n//";
2335   temp << filename.str();
2336   temp << ":";
2337   temp << line;
2338   temp << " ";
2339   temp << reader->readLine(line);
2340   temp << "\n";
2341   this->OutStreamer->EmitRawText(temp.str());
2342 }
2343 
2344 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2345   if (!reader) {
2346     reader = new LineReader(filename);
2347   }
2348 
2349   if (reader->fileName() != filename) {
2350     delete reader;
2351     reader = new LineReader(filename);
2352   }
2353 
2354   return reader;
2355 }
2356 
2357 std::string LineReader::readLine(unsigned lineNum) {
2358   if (lineNum < theCurLine) {
2359     theCurLine = 0;
2360     fstr.seekg(0, std::ios::beg);
2361   }
2362   while (theCurLine < lineNum) {
2363     fstr.getline(buff, 500);
2364     theCurLine++;
2365   }
2366   return buff;
2367 }
2368 
2369 // Force static initialization.
2370 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2371   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2372   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2373 }
2374