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