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