Remove usernames from TODOs, NFC
[oota-llvm.git] / lib / Target / NVPTX / NVPTXAsmPrinter.cpp
1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
18 #include "NVPTX.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMCExpr.h"
21 #include "NVPTXMachineFunctionInfo.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Mangler.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TimeValue.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Transforms/Utils/UnrollLoop.h"
50 #include <sstream>
51 using namespace llvm;
52
53 #define DEPOTNAME "__local_depot"
54
55 static cl::opt<bool>
56 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
57                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
58                 cl::init(true));
59
60 static cl::opt<bool>
61 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
62               cl::desc("NVPTX Specific: Emit source line in ptx file"),
63               cl::init(false));
64
65 namespace {
66 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
67 /// depends.
68 void DiscoverDependentGlobals(const Value *V,
69                               DenseSet<const GlobalVariable *> &Globals) {
70   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
71     Globals.insert(GV);
72   else {
73     if (const User *U = dyn_cast<User>(V)) {
74       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
75         DiscoverDependentGlobals(U->getOperand(i), Globals);
76       }
77     }
78   }
79 }
80
81 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
82 /// instances to be emitted, but only after any dependents have been added
83 /// first.
84 void VisitGlobalVariableForEmission(
85     const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
86     DenseSet<const GlobalVariable *> &Visited,
87     DenseSet<const GlobalVariable *> &Visiting) {
88   // Have we already visited this one?
89   if (Visited.count(GV))
90     return;
91
92   // Do we have a circular dependency?
93   if (!Visiting.insert(GV).second)
94     report_fatal_error("Circular dependency found in global variable set");
95
96   // Make sure we visit all dependents first
97   DenseSet<const GlobalVariable *> Others;
98   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99     DiscoverDependentGlobals(GV->getOperand(i), Others);
100
101   for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
102                                                   E = Others.end();
103        I != E; ++I)
104     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
105
106   // Now we can visit ourself
107   Order.push_back(GV);
108   Visited.insert(GV);
109   Visiting.erase(GV);
110 }
111 }
112
113 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
114   if (!EmitLineNumbers)
115     return;
116   if (ignoreLoc(MI))
117     return;
118
119   DebugLoc curLoc = MI.getDebugLoc();
120
121   if (prevDebugLoc.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: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
426 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
427     const MachineBasicBlock &MBB) const {
428   MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
429   // TODO: isLoopHeader() should take "const MachineBasicBlock *".
430   // We insert .pragma "nounroll" only to the loop header.
431   if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
432     return false;
433
434   // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
435   // we iterate through each back edge of the loop with header MBB, and check
436   // whether its metadata contains llvm.loop.unroll.disable.
437   for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
438     const MachineBasicBlock *PMBB = *I;
439     if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
440       // Edges from other loops to MBB are not back edges.
441       continue;
442     }
443     if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
444       if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
445         if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
446           return true;
447       }
448     }
449   }
450   return false;
451 }
452
453 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
454   AsmPrinter::EmitBasicBlockStart(MBB);
455   if (isLoopHeaderOfNoUnroll(MBB))
456     OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
457 }
458
459 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
460   SmallString<128> Str;
461   raw_svector_ostream O(Str);
462
463   if (!GlobalsEmitted) {
464     emitGlobals(*MF->getFunction()->getParent());
465     GlobalsEmitted = true;
466   }
467   
468   // Set up
469   MRI = &MF->getRegInfo();
470   F = MF->getFunction();
471   emitLinkageDirective(F, O);
472   if (llvm::isKernelFunction(*F))
473     O << ".entry ";
474   else {
475     O << ".func ";
476     printReturnValStr(*MF, O);
477   }
478
479   O << *CurrentFnSym;
480
481   emitFunctionParamList(*MF, O);
482
483   if (llvm::isKernelFunction(*F))
484     emitKernelFunctionDirectives(*F, O);
485
486   OutStreamer.EmitRawText(O.str());
487
488   prevDebugLoc = DebugLoc();
489 }
490
491 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
492   VRegMapping.clear();
493   OutStreamer.EmitRawText(StringRef("{\n"));
494   setAndEmitFunctionVirtualRegisters(*MF);
495
496   SmallString<128> Str;
497   raw_svector_ostream O(Str);
498   emitDemotedVars(MF->getFunction(), O);
499   OutStreamer.EmitRawText(O.str());
500 }
501
502 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
503   OutStreamer.EmitRawText(StringRef("}\n"));
504   VRegMapping.clear();
505 }
506
507 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
508   unsigned RegNo = MI->getOperand(0).getReg();
509   const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
510   if (TRI->isVirtualRegister(RegNo)) {
511     OutStreamer.AddComment(Twine("implicit-def: ") +
512                            getVirtualRegisterName(RegNo));
513   } else {
514     OutStreamer.AddComment(
515         Twine("implicit-def: ") +
516         TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
517   }
518   OutStreamer.AddBlankLine();
519 }
520
521 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
522                                                    raw_ostream &O) const {
523   // If the NVVM IR has some of reqntid* specified, then output
524   // the reqntid directive, and set the unspecified ones to 1.
525   // If none of reqntid* is specified, don't output reqntid directive.
526   unsigned reqntidx, reqntidy, reqntidz;
527   bool specified = false;
528   if (llvm::getReqNTIDx(F, reqntidx) == false)
529     reqntidx = 1;
530   else
531     specified = true;
532   if (llvm::getReqNTIDy(F, reqntidy) == false)
533     reqntidy = 1;
534   else
535     specified = true;
536   if (llvm::getReqNTIDz(F, reqntidz) == false)
537     reqntidz = 1;
538   else
539     specified = true;
540
541   if (specified)
542     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
543       << "\n";
544
545   // If the NVVM IR has some of maxntid* specified, then output
546   // the maxntid directive, and set the unspecified ones to 1.
547   // If none of maxntid* is specified, don't output maxntid directive.
548   unsigned maxntidx, maxntidy, maxntidz;
549   specified = false;
550   if (llvm::getMaxNTIDx(F, maxntidx) == false)
551     maxntidx = 1;
552   else
553     specified = true;
554   if (llvm::getMaxNTIDy(F, maxntidy) == false)
555     maxntidy = 1;
556   else
557     specified = true;
558   if (llvm::getMaxNTIDz(F, maxntidz) == false)
559     maxntidz = 1;
560   else
561     specified = true;
562
563   if (specified)
564     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
565       << "\n";
566
567   unsigned mincta;
568   if (llvm::getMinCTASm(F, mincta))
569     O << ".minnctapersm " << mincta << "\n";
570 }
571
572 std::string
573 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
574   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
575
576   std::string Name;
577   raw_string_ostream NameStr(Name);
578
579   VRegRCMap::const_iterator I = VRegMapping.find(RC);
580   assert(I != VRegMapping.end() && "Bad register class");
581   const DenseMap<unsigned, unsigned> &RegMap = I->second;
582
583   VRegMap::const_iterator VI = RegMap.find(Reg);
584   assert(VI != RegMap.end() && "Bad virtual register");
585   unsigned MappedVR = VI->second;
586
587   NameStr << getNVPTXRegClassStr(RC) << MappedVR;
588
589   NameStr.flush();
590   return Name;
591 }
592
593 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
594                                           raw_ostream &O) {
595   O << getVirtualRegisterName(vr);
596 }
597
598 void NVPTXAsmPrinter::printVecModifiedImmediate(
599     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
600   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
601   int Imm = (int) MO.getImm();
602   if (0 == strcmp(Modifier, "vecelem"))
603     O << "_" << vecelem[Imm];
604   else if (0 == strcmp(Modifier, "vecv4comm1")) {
605     if ((Imm < 0) || (Imm > 3))
606       O << "//";
607   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
608     if ((Imm < 4) || (Imm > 7))
609       O << "//";
610   } else if (0 == strcmp(Modifier, "vecv4pos")) {
611     if (Imm < 0)
612       Imm = 0;
613     O << "_" << vecelem[Imm % 4];
614   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
615     if ((Imm < 0) || (Imm > 1))
616       O << "//";
617   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
618     if ((Imm < 2) || (Imm > 3))
619       O << "//";
620   } else if (0 == strcmp(Modifier, "vecv2pos")) {
621     if (Imm < 0)
622       Imm = 0;
623     O << "_" << vecelem[Imm % 2];
624   } else
625     llvm_unreachable("Unknown Modifier on immediate operand");
626 }
627
628
629
630 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
631
632   emitLinkageDirective(F, O);
633   if (llvm::isKernelFunction(*F))
634     O << ".entry ";
635   else
636     O << ".func ";
637   printReturnValStr(F, O);
638   O << *getSymbol(F) << "\n";
639   emitFunctionParamList(F, O);
640   O << ";\n";
641 }
642
643 static bool usedInGlobalVarDef(const Constant *C) {
644   if (!C)
645     return false;
646
647   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
648     if (GV->getName().str() == "llvm.used")
649       return false;
650     return true;
651   }
652
653   for (const User *U : C->users())
654     if (const Constant *C = dyn_cast<Constant>(U))
655       if (usedInGlobalVarDef(C))
656         return true;
657
658   return false;
659 }
660
661 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
662   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
663     if (othergv->getName().str() == "llvm.used")
664       return true;
665   }
666
667   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
668     if (instr->getParent() && instr->getParent()->getParent()) {
669       const Function *curFunc = instr->getParent()->getParent();
670       if (oneFunc && (curFunc != oneFunc))
671         return false;
672       oneFunc = curFunc;
673       return true;
674     } else
675       return false;
676   }
677
678   for (const User *UU : U->users())
679     if (usedInOneFunc(UU, oneFunc) == false)
680       return false;
681
682   return true;
683 }
684
685 /* Find out if a global variable can be demoted to local scope.
686  * Currently, this is valid for CUDA shared variables, which have local
687  * scope and global lifetime. So the conditions to check are :
688  * 1. Is the global variable in shared address space?
689  * 2. Does it have internal linkage?
690  * 3. Is the global variable referenced only in one function?
691  */
692 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
693   if (gv->hasInternalLinkage() == false)
694     return false;
695   const PointerType *Pty = gv->getType();
696   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
697     return false;
698
699   const Function *oneFunc = nullptr;
700
701   bool flag = usedInOneFunc(gv, oneFunc);
702   if (flag == false)
703     return false;
704   if (!oneFunc)
705     return false;
706   f = oneFunc;
707   return true;
708 }
709
710 static bool useFuncSeen(const Constant *C,
711                         llvm::DenseMap<const Function *, bool> &seenMap) {
712   for (const User *U : C->users()) {
713     if (const Constant *cu = dyn_cast<Constant>(U)) {
714       if (useFuncSeen(cu, seenMap))
715         return true;
716     } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
717       const BasicBlock *bb = I->getParent();
718       if (!bb)
719         continue;
720       const Function *caller = bb->getParent();
721       if (!caller)
722         continue;
723       if (seenMap.find(caller) != seenMap.end())
724         return true;
725     }
726   }
727   return false;
728 }
729
730 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
731   llvm::DenseMap<const Function *, bool> seenMap;
732   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
733     const Function *F = FI;
734
735     if (F->isDeclaration()) {
736       if (F->use_empty())
737         continue;
738       if (F->getIntrinsicID())
739         continue;
740       emitDeclaration(F, O);
741       continue;
742     }
743     for (const User *U : F->users()) {
744       if (const Constant *C = dyn_cast<Constant>(U)) {
745         if (usedInGlobalVarDef(C)) {
746           // The use is in the initialization of a global variable
747           // that is a function pointer, so print a declaration
748           // for the original function
749           emitDeclaration(F, O);
750           break;
751         }
752         // Emit a declaration of this function if the function that
753         // uses this constant expr has already been seen.
754         if (useFuncSeen(C, seenMap)) {
755           emitDeclaration(F, O);
756           break;
757         }
758       }
759
760       if (!isa<Instruction>(U))
761         continue;
762       const Instruction *instr = cast<Instruction>(U);
763       const BasicBlock *bb = instr->getParent();
764       if (!bb)
765         continue;
766       const Function *caller = bb->getParent();
767       if (!caller)
768         continue;
769
770       // If a caller has already been seen, then the caller is
771       // appearing in the module before the callee. so print out
772       // a declaration for the callee.
773       if (seenMap.find(caller) != seenMap.end()) {
774         emitDeclaration(F, O);
775         break;
776       }
777     }
778     seenMap[F] = true;
779   }
780 }
781
782 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
783   DebugInfoFinder DbgFinder;
784   DbgFinder.processModule(M);
785
786   unsigned i = 1;
787   for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
788     StringRef Filename(DIUnit.getFilename());
789     StringRef Dirname(DIUnit.getDirectory());
790     SmallString<128> FullPathName = Dirname;
791     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
792       sys::path::append(FullPathName, Filename);
793       Filename = FullPathName.str();
794     }
795     if (filenameMap.find(Filename.str()) != filenameMap.end())
796       continue;
797     filenameMap[Filename.str()] = i;
798     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
799     ++i;
800   }
801
802   for (DISubprogram SP : DbgFinder.subprograms()) {
803     StringRef Filename(SP.getFilename());
804     StringRef Dirname(SP.getDirectory());
805     SmallString<128> FullPathName = Dirname;
806     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
807       sys::path::append(FullPathName, Filename);
808       Filename = FullPathName.str();
809     }
810     if (filenameMap.find(Filename.str()) != filenameMap.end())
811       continue;
812     filenameMap[Filename.str()] = i;
813     ++i;
814   }
815 }
816
817 bool NVPTXAsmPrinter::doInitialization(Module &M) {
818
819   SmallString<128> Str1;
820   raw_svector_ostream OS1(Str1);
821
822   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
823   MMI->AnalyzeModule(M);
824
825   // We need to call the parent's one explicitly.
826   //bool Result = AsmPrinter::doInitialization(M);
827
828   // Initialize TargetLoweringObjectFile.
829   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
830       .Initialize(OutContext, TM);
831
832   Mang = new Mangler(TM.getDataLayout());
833
834   // Emit header before any dwarf directives are emitted below.
835   emitHeader(M, OS1);
836   OutStreamer.EmitRawText(OS1.str());
837
838   // Already commented out
839   //bool Result = AsmPrinter::doInitialization(M);
840
841   // Emit module-level inline asm if it exists.
842   if (!M.getModuleInlineAsm().empty()) {
843     OutStreamer.AddComment("Start of file scope inline assembly");
844     OutStreamer.AddBlankLine();
845     OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
846     OutStreamer.AddBlankLine();
847     OutStreamer.AddComment("End of file scope inline assembly");
848     OutStreamer.AddBlankLine();
849   }
850
851   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
852     recordAndEmitFilenames(M);
853
854   GlobalsEmitted = false;
855     
856   return false; // success
857 }
858
859 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
860   SmallString<128> Str2;
861   raw_svector_ostream OS2(Str2);
862
863   emitDeclarations(M, OS2);
864
865   // As ptxas does not support forward references of globals, we need to first
866   // sort the list of module-level globals in def-use order. We visit each
867   // global variable in order, and ensure that we emit it *after* its dependent
868   // globals. We use a little extra memory maintaining both a set and a list to
869   // have fast searches while maintaining a strict ordering.
870   SmallVector<const GlobalVariable *, 8> Globals;
871   DenseSet<const GlobalVariable *> GVVisited;
872   DenseSet<const GlobalVariable *> GVVisiting;
873
874   // Visit each global variable, in order
875   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
876        I != E; ++I)
877     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
878
879   assert(GVVisited.size() == M.getGlobalList().size() &&
880          "Missed a global variable");
881   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
882
883   // Print out module-level global variables in proper order
884   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
885     printModuleLevelGV(Globals[i], OS2);
886
887   OS2 << '\n';
888
889   OutStreamer.EmitRawText(OS2.str());
890 }
891
892 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
893   O << "//\n";
894   O << "// Generated by LLVM NVPTX Back-End\n";
895   O << "//\n";
896   O << "\n";
897
898   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
899   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
900
901   O << ".target ";
902   O << nvptxSubtarget.getTargetName();
903
904   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
905     O << ", texmode_independent";
906   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
907     if (!nvptxSubtarget.hasDouble())
908       O << ", map_f64_to_f32";
909   }
910
911   if (MAI->doesSupportDebugInformation())
912     O << ", debug";
913
914   O << "\n";
915
916   O << ".address_size ";
917   if (nvptxSubtarget.is64Bit())
918     O << "64";
919   else
920     O << "32";
921   O << "\n";
922
923   O << "\n";
924 }
925
926 bool NVPTXAsmPrinter::doFinalization(Module &M) {
927
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 (nvptxSubtarget.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().str());
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().str() << " 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 spefied.
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           std::string warnMsg = "initial value of '" + GVar->getName().str() +
1193               "' is not allowed in addrspace(" +
1194               llvm::utostr_32(PTy->getAddressSpace()) + ")";
1195           report_fatal_error(warnMsg.c_str());
1196         }
1197       }
1198     }
1199   } else {
1200     unsigned int ElementSize = 0;
1201
1202     // Although PTX has direct support for struct type and array type and
1203     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1204     // targets that support these high level field accesses. Structs, arrays
1205     // and vectors are lowered into arrays of bytes.
1206     switch (ETy->getTypeID()) {
1207     case Type::StructTyID:
1208     case Type::ArrayTyID:
1209     case Type::VectorTyID:
1210       ElementSize = TD->getTypeStoreSize(ETy);
1211       // Ptx allows variable initilization only for constant and
1212       // global state spaces.
1213       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1214            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1215           GVar->hasInitializer()) {
1216         const Constant *Initializer = GVar->getInitializer();
1217         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1218           AggBuffer aggBuffer(ElementSize, O, *this);
1219           bufferAggregateConstant(Initializer, &aggBuffer);
1220           if (aggBuffer.numSymbols) {
1221             if (nvptxSubtarget.is64Bit()) {
1222               O << " .u64 " << *getSymbol(GVar) << "[";
1223               O << ElementSize / 8;
1224             } else {
1225               O << " .u32 " << *getSymbol(GVar) << "[";
1226               O << ElementSize / 4;
1227             }
1228             O << "]";
1229           } else {
1230             O << " .b8 " << *getSymbol(GVar) << "[";
1231             O << ElementSize;
1232             O << "]";
1233           }
1234           O << " = {";
1235           aggBuffer.print();
1236           O << "}";
1237         } else {
1238           O << " .b8 " << *getSymbol(GVar);
1239           if (ElementSize) {
1240             O << "[";
1241             O << ElementSize;
1242             O << "]";
1243           }
1244         }
1245       } else {
1246         O << " .b8 " << *getSymbol(GVar);
1247         if (ElementSize) {
1248           O << "[";
1249           O << ElementSize;
1250           O << "]";
1251         }
1252       }
1253       break;
1254     default:
1255       llvm_unreachable("type not supported yet");
1256     }
1257
1258   }
1259   O << ";\n";
1260 }
1261
1262 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1263   if (localDecls.find(f) == localDecls.end())
1264     return;
1265
1266   std::vector<const GlobalVariable *> &gvars = localDecls[f];
1267
1268   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1269     O << "\t// demoted variable\n\t";
1270     printModuleLevelGV(gvars[i], O, true);
1271   }
1272 }
1273
1274 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1275                                           raw_ostream &O) const {
1276   switch (AddressSpace) {
1277   case llvm::ADDRESS_SPACE_LOCAL:
1278     O << "local";
1279     break;
1280   case llvm::ADDRESS_SPACE_GLOBAL:
1281     O << "global";
1282     break;
1283   case llvm::ADDRESS_SPACE_CONST:
1284     O << "const";
1285     break;
1286   case llvm::ADDRESS_SPACE_SHARED:
1287     O << "shared";
1288     break;
1289   default:
1290     report_fatal_error("Bad address space found while emitting PTX");
1291     break;
1292   }
1293 }
1294
1295 std::string
1296 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1297   switch (Ty->getTypeID()) {
1298   default:
1299     llvm_unreachable("unexpected type");
1300     break;
1301   case Type::IntegerTyID: {
1302     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1303     if (NumBits == 1)
1304       return "pred";
1305     else if (NumBits <= 64) {
1306       std::string name = "u";
1307       return name + utostr(NumBits);
1308     } else {
1309       llvm_unreachable("Integer too large");
1310       break;
1311     }
1312     break;
1313   }
1314   case Type::FloatTyID:
1315     return "f32";
1316   case Type::DoubleTyID:
1317     return "f64";
1318   case Type::PointerTyID:
1319     if (nvptxSubtarget.is64Bit())
1320       if (useB4PTR)
1321         return "b64";
1322       else
1323         return "u64";
1324     else if (useB4PTR)
1325       return "b32";
1326     else
1327       return "u32";
1328   }
1329   llvm_unreachable("unexpected type");
1330   return nullptr;
1331 }
1332
1333 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1334                                             raw_ostream &O) {
1335
1336   const DataLayout *TD = TM.getDataLayout();
1337
1338   // GlobalVariables are always constant pointers themselves.
1339   const PointerType *PTy = GVar->getType();
1340   Type *ETy = PTy->getElementType();
1341
1342   O << ".";
1343   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1344   if (GVar->getAlignment() == 0)
1345     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1346   else
1347     O << " .align " << GVar->getAlignment();
1348
1349   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1350     O << " .";
1351     O << getPTXFundamentalTypeStr(ETy);
1352     O << " ";
1353     O << *getSymbol(GVar);
1354     return;
1355   }
1356
1357   int64_t ElementSize = 0;
1358
1359   // Although PTX has direct support for struct type and array type and LLVM IR
1360   // is very similar to PTX, the LLVM CodeGen does not support for targets that
1361   // support these high level field accesses. Structs and arrays are lowered
1362   // into arrays of bytes.
1363   switch (ETy->getTypeID()) {
1364   case Type::StructTyID:
1365   case Type::ArrayTyID:
1366   case Type::VectorTyID:
1367     ElementSize = TD->getTypeStoreSize(ETy);
1368     O << " .b8 " << *getSymbol(GVar) << "[";
1369     if (ElementSize) {
1370       O << itostr(ElementSize);
1371     }
1372     O << "]";
1373     break;
1374   default:
1375     llvm_unreachable("type not supported yet");
1376   }
1377   return;
1378 }
1379
1380 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1381   if (Ty->isSingleValueType())
1382     return TD->getPrefTypeAlignment(Ty);
1383
1384   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1385   if (ATy)
1386     return getOpenCLAlignment(TD, ATy->getElementType());
1387
1388   const StructType *STy = dyn_cast<StructType>(Ty);
1389   if (STy) {
1390     unsigned int alignStruct = 1;
1391     // Go through each element of the struct and find the
1392     // largest alignment.
1393     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1394       Type *ETy = STy->getElementType(i);
1395       unsigned int align = getOpenCLAlignment(TD, ETy);
1396       if (align > alignStruct)
1397         alignStruct = align;
1398     }
1399     return alignStruct;
1400   }
1401
1402   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1403   if (FTy)
1404     return TD->getPointerPrefAlignment();
1405   return TD->getPrefTypeAlignment(Ty);
1406 }
1407
1408 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1409                                      int paramIndex, raw_ostream &O) {
1410   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1411       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1412     O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1413   else {
1414     std::string argName = I->getName();
1415     const char *p = argName.c_str();
1416     while (*p) {
1417       if (*p == '.')
1418         O << "_";
1419       else
1420         O << *p;
1421       p++;
1422     }
1423   }
1424 }
1425
1426 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1427   Function::const_arg_iterator I, E;
1428   int i = 0;
1429
1430   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1431       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1432     O << *CurrentFnSym << "_param_" << paramIndex;
1433     return;
1434   }
1435
1436   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1437     if (i == paramIndex) {
1438       printParamName(I, paramIndex, O);
1439       return;
1440     }
1441   }
1442   llvm_unreachable("paramIndex out of bound");
1443 }
1444
1445 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1446   const DataLayout *TD = TM.getDataLayout();
1447   const AttributeSet &PAL = F->getAttributes();
1448   const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1449   Function::const_arg_iterator I, E;
1450   unsigned paramIndex = 0;
1451   bool first = true;
1452   bool isKernelFunc = llvm::isKernelFunction(*F);
1453   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1454   MVT thePointerTy = TLI->getPointerTy();
1455
1456   O << "(\n";
1457
1458   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1459     Type *Ty = I->getType();
1460
1461     if (!first)
1462       O << ",\n";
1463
1464     first = false;
1465
1466     // Handle image/sampler parameters
1467     if (isKernelFunction(*F)) {
1468       if (isSampler(*I) || isImage(*I)) {
1469         if (isImage(*I)) {
1470           std::string sname = I->getName();
1471           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1472             if (nvptxSubtarget.hasImageHandles())
1473               O << "\t.param .u64 .ptr .surfref ";
1474             else
1475               O << "\t.param .surfref ";
1476             O << *CurrentFnSym << "_param_" << paramIndex;
1477           }
1478           else { // Default image is read_only
1479             if (nvptxSubtarget.hasImageHandles())
1480               O << "\t.param .u64 .ptr .texref ";
1481             else
1482               O << "\t.param .texref ";
1483             O << *CurrentFnSym << "_param_" << paramIndex;
1484           }
1485         } else {
1486           if (nvptxSubtarget.hasImageHandles())
1487             O << "\t.param .u64 .ptr .samplerref ";
1488           else
1489             O << "\t.param .samplerref ";
1490           O << *CurrentFnSym << "_param_" << paramIndex;
1491         }
1492         continue;
1493       }
1494     }
1495
1496     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1497       if (Ty->isAggregateType() || Ty->isVectorTy()) {
1498         // Just print .param .align <a> .b8 .param[size];
1499         // <a> = PAL.getparamalignment
1500         // size = typeallocsize of element type
1501         unsigned align = PAL.getParamAlignment(paramIndex + 1);
1502         if (align == 0)
1503           align = TD->getABITypeAlignment(Ty);
1504
1505         unsigned sz = TD->getTypeAllocSize(Ty);
1506         O << "\t.param .align " << align << " .b8 ";
1507         printParamName(I, paramIndex, O);
1508         O << "[" << sz << "]";
1509
1510         continue;
1511       }
1512       // Just a scalar
1513       const PointerType *PTy = dyn_cast<PointerType>(Ty);
1514       if (isKernelFunc) {
1515         if (PTy) {
1516           // Special handling for pointer arguments to kernel
1517           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1518
1519           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1520             Type *ETy = PTy->getElementType();
1521             int addrSpace = PTy->getAddressSpace();
1522             switch (addrSpace) {
1523             default:
1524               O << ".ptr ";
1525               break;
1526             case llvm::ADDRESS_SPACE_CONST:
1527               O << ".ptr .const ";
1528               break;
1529             case llvm::ADDRESS_SPACE_SHARED:
1530               O << ".ptr .shared ";
1531               break;
1532             case llvm::ADDRESS_SPACE_GLOBAL:
1533               O << ".ptr .global ";
1534               break;
1535             }
1536             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1537           }
1538           printParamName(I, paramIndex, O);
1539           continue;
1540         }
1541
1542         // non-pointer scalar to kernel func
1543         O << "\t.param .";
1544         // Special case: predicate operands become .u8 types
1545         if (Ty->isIntegerTy(1))
1546           O << "u8";
1547         else
1548           O << getPTXFundamentalTypeStr(Ty);
1549         O << " ";
1550         printParamName(I, paramIndex, O);
1551         continue;
1552       }
1553       // Non-kernel function, just print .param .b<size> for ABI
1554       // and .reg .b<size> for non-ABI
1555       unsigned sz = 0;
1556       if (isa<IntegerType>(Ty)) {
1557         sz = cast<IntegerType>(Ty)->getBitWidth();
1558         if (sz < 32)
1559           sz = 32;
1560       } else if (isa<PointerType>(Ty))
1561         sz = thePointerTy.getSizeInBits();
1562       else
1563         sz = Ty->getPrimitiveSizeInBits();
1564       if (isABI)
1565         O << "\t.param .b" << sz << " ";
1566       else
1567         O << "\t.reg .b" << sz << " ";
1568       printParamName(I, paramIndex, O);
1569       continue;
1570     }
1571
1572     // param has byVal attribute. So should be a pointer
1573     const PointerType *PTy = dyn_cast<PointerType>(Ty);
1574     assert(PTy && "Param with byval attribute should be a pointer type");
1575     Type *ETy = PTy->getElementType();
1576
1577     if (isABI || isKernelFunc) {
1578       // Just print .param .align <a> .b8 .param[size];
1579       // <a> = PAL.getparamalignment
1580       // size = typeallocsize of element type
1581       unsigned align = PAL.getParamAlignment(paramIndex + 1);
1582       if (align == 0)
1583         align = TD->getABITypeAlignment(ETy);
1584
1585       unsigned sz = TD->getTypeAllocSize(ETy);
1586       O << "\t.param .align " << align << " .b8 ";
1587       printParamName(I, paramIndex, O);
1588       O << "[" << sz << "]";
1589       continue;
1590     } else {
1591       // Split the ETy into constituent parts and
1592       // print .param .b<size> <name> for each part.
1593       // Further, if a part is vector, print the above for
1594       // each vector element.
1595       SmallVector<EVT, 16> vtparts;
1596       ComputeValueVTs(*TLI, ETy, vtparts);
1597       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1598         unsigned elems = 1;
1599         EVT elemtype = vtparts[i];
1600         if (vtparts[i].isVector()) {
1601           elems = vtparts[i].getVectorNumElements();
1602           elemtype = vtparts[i].getVectorElementType();
1603         }
1604
1605         for (unsigned j = 0, je = elems; j != je; ++j) {
1606           unsigned sz = elemtype.getSizeInBits();
1607           if (elemtype.isInteger() && (sz < 32))
1608             sz = 32;
1609           O << "\t.reg .b" << sz << " ";
1610           printParamName(I, paramIndex, O);
1611           if (j < je - 1)
1612             O << ",\n";
1613           ++paramIndex;
1614         }
1615         if (i < e - 1)
1616           O << ",\n";
1617       }
1618       --paramIndex;
1619       continue;
1620     }
1621   }
1622
1623   O << "\n)\n";
1624 }
1625
1626 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1627                                             raw_ostream &O) {
1628   const Function *F = MF.getFunction();
1629   emitFunctionParamList(F, O);
1630 }
1631
1632 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1633     const MachineFunction &MF) {
1634   SmallString<128> Str;
1635   raw_svector_ostream O(Str);
1636
1637   // Map the global virtual register number to a register class specific
1638   // virtual register number starting from 1 with that class.
1639   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1640   //unsigned numRegClasses = TRI->getNumRegClasses();
1641
1642   // Emit the Fake Stack Object
1643   const MachineFrameInfo *MFI = MF.getFrameInfo();
1644   int NumBytes = (int) MFI->getStackSize();
1645   if (NumBytes) {
1646     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1647       << getFunctionNumber() << "[" << NumBytes << "];\n";
1648     if (nvptxSubtarget.is64Bit()) {
1649       O << "\t.reg .b64 \t%SP;\n";
1650       O << "\t.reg .b64 \t%SPL;\n";
1651     } else {
1652       O << "\t.reg .b32 \t%SP;\n";
1653       O << "\t.reg .b32 \t%SPL;\n";
1654     }
1655   }
1656
1657   // Go through all virtual registers to establish the mapping between the
1658   // global virtual
1659   // register number and the per class virtual register number.
1660   // We use the per class virtual register number in the ptx output.
1661   unsigned int numVRs = MRI->getNumVirtRegs();
1662   for (unsigned i = 0; i < numVRs; i++) {
1663     unsigned int vr = TRI->index2VirtReg(i);
1664     const TargetRegisterClass *RC = MRI->getRegClass(vr);
1665     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1666     int n = regmap.size();
1667     regmap.insert(std::make_pair(vr, n + 1));
1668   }
1669
1670   // Emit register declarations
1671   // @TODO: Extract out the real register usage
1672   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1673   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1674   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1675   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1676   // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1677   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1678   // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1679
1680   // Emit declaration of the virtual registers or 'physical' registers for
1681   // each register class
1682   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1683     const TargetRegisterClass *RC = TRI->getRegClass(i);
1684     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1685     std::string rcname = getNVPTXRegClassName(RC);
1686     std::string rcStr = getNVPTXRegClassStr(RC);
1687     int n = regmap.size();
1688
1689     // Only declare those registers that may be used.
1690     if (n) {
1691        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1692          << ">;\n";
1693     }
1694   }
1695
1696   OutStreamer.EmitRawText(O.str());
1697 }
1698
1699 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1700   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1701   bool ignored;
1702   unsigned int numHex;
1703   const char *lead;
1704
1705   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1706     numHex = 8;
1707     lead = "0f";
1708     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1709   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1710     numHex = 16;
1711     lead = "0d";
1712     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1713   } else
1714     llvm_unreachable("unsupported fp type");
1715
1716   APInt API = APF.bitcastToAPInt();
1717   std::string hexstr(utohexstr(API.getZExtValue()));
1718   O << lead;
1719   if (hexstr.length() < numHex)
1720     O << std::string(numHex - hexstr.length(), '0');
1721   O << utohexstr(API.getZExtValue());
1722 }
1723
1724 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1725   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1726     O << CI->getValue();
1727     return;
1728   }
1729   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1730     printFPConstant(CFP, O);
1731     return;
1732   }
1733   if (isa<ConstantPointerNull>(CPV)) {
1734     O << "0";
1735     return;
1736   }
1737   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1738     PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1739     bool IsNonGenericPointer = false;
1740     if (PTy && PTy->getAddressSpace() != 0) {
1741       IsNonGenericPointer = true;
1742     }
1743     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1744       O << "generic(";
1745       O << *getSymbol(GVar);
1746       O << ")";
1747     } else {
1748       O << *getSymbol(GVar);
1749     }
1750     return;
1751   }
1752   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1753     const Value *v = Cexpr->stripPointerCasts();
1754     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1755     bool IsNonGenericPointer = false;
1756     if (PTy && PTy->getAddressSpace() != 0) {
1757       IsNonGenericPointer = true;
1758     }
1759     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1760       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1761         O << "generic(";
1762         O << *getSymbol(GVar);
1763         O << ")";
1764       } else {
1765         O << *getSymbol(GVar);
1766       }
1767       return;
1768     } else {
1769       O << *lowerConstant(CPV);
1770       return;
1771     }
1772   }
1773   llvm_unreachable("Not scalar type found in printScalarConstant()");
1774 }
1775
1776 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1777                                    AggBuffer *aggBuffer) {
1778
1779   const DataLayout *TD = TM.getDataLayout();
1780
1781   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1782     int s = TD->getTypeAllocSize(CPV->getType());
1783     if (s < Bytes)
1784       s = Bytes;
1785     aggBuffer->addZeros(s);
1786     return;
1787   }
1788
1789   unsigned char *ptr;
1790   switch (CPV->getType()->getTypeID()) {
1791
1792   case Type::IntegerTyID: {
1793     const Type *ETy = CPV->getType();
1794     if (ETy == Type::getInt8Ty(CPV->getContext())) {
1795       unsigned char c =
1796           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1797       ptr = &c;
1798       aggBuffer->addBytes(ptr, 1, Bytes);
1799     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1800       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1801       ptr = (unsigned char *)&int16;
1802       aggBuffer->addBytes(ptr, 2, Bytes);
1803     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1804       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1805         int int32 = (int)(constInt->getZExtValue());
1806         ptr = (unsigned char *)&int32;
1807         aggBuffer->addBytes(ptr, 4, Bytes);
1808         break;
1809       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1810         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1811                 ConstantFoldConstantExpression(Cexpr, TD))) {
1812           int int32 = (int)(constInt->getZExtValue());
1813           ptr = (unsigned char *)&int32;
1814           aggBuffer->addBytes(ptr, 4, Bytes);
1815           break;
1816         }
1817         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1818           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1819           aggBuffer->addSymbol(v);
1820           aggBuffer->addZeros(4);
1821           break;
1822         }
1823       }
1824       llvm_unreachable("unsupported integer const type");
1825     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1826       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1827         long long int64 = (long long)(constInt->getZExtValue());
1828         ptr = (unsigned char *)&int64;
1829         aggBuffer->addBytes(ptr, 8, Bytes);
1830         break;
1831       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1832         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1833                 ConstantFoldConstantExpression(Cexpr, TD))) {
1834           long long int64 = (long long)(constInt->getZExtValue());
1835           ptr = (unsigned char *)&int64;
1836           aggBuffer->addBytes(ptr, 8, Bytes);
1837           break;
1838         }
1839         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1840           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1841           aggBuffer->addSymbol(v);
1842           aggBuffer->addZeros(8);
1843           break;
1844         }
1845       }
1846       llvm_unreachable("unsupported integer const type");
1847     } else
1848       llvm_unreachable("unsupported integer const type");
1849     break;
1850   }
1851   case Type::FloatTyID:
1852   case Type::DoubleTyID: {
1853     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1854     const Type *Ty = CFP->getType();
1855     if (Ty == Type::getFloatTy(CPV->getContext())) {
1856       float float32 = (float) CFP->getValueAPF().convertToFloat();
1857       ptr = (unsigned char *)&float32;
1858       aggBuffer->addBytes(ptr, 4, Bytes);
1859     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1860       double float64 = CFP->getValueAPF().convertToDouble();
1861       ptr = (unsigned char *)&float64;
1862       aggBuffer->addBytes(ptr, 8, Bytes);
1863     } else {
1864       llvm_unreachable("unsupported fp const type");
1865     }
1866     break;
1867   }
1868   case Type::PointerTyID: {
1869     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1870       aggBuffer->addSymbol(GVar);
1871     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1872       const Value *v = Cexpr->stripPointerCasts();
1873       aggBuffer->addSymbol(v);
1874     }
1875     unsigned int s = TD->getTypeAllocSize(CPV->getType());
1876     aggBuffer->addZeros(s);
1877     break;
1878   }
1879
1880   case Type::ArrayTyID:
1881   case Type::VectorTyID:
1882   case Type::StructTyID: {
1883     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1884         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1885       int ElementSize = TD->getTypeAllocSize(CPV->getType());
1886       bufferAggregateConstant(CPV, aggBuffer);
1887       if (Bytes > ElementSize)
1888         aggBuffer->addZeros(Bytes - ElementSize);
1889     } else if (isa<ConstantAggregateZero>(CPV))
1890       aggBuffer->addZeros(Bytes);
1891     else
1892       llvm_unreachable("Unexpected Constant type");
1893     break;
1894   }
1895
1896   default:
1897     llvm_unreachable("unsupported type");
1898   }
1899 }
1900
1901 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1902                                               AggBuffer *aggBuffer) {
1903   const DataLayout *TD = TM.getDataLayout();
1904   int Bytes;
1905
1906   // Old constants
1907   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1908     if (CPV->getNumOperands())
1909       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1910         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1911     return;
1912   }
1913
1914   if (const ConstantDataSequential *CDS =
1915           dyn_cast<ConstantDataSequential>(CPV)) {
1916     if (CDS->getNumElements())
1917       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1918         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1919                      aggBuffer);
1920     return;
1921   }
1922
1923   if (isa<ConstantStruct>(CPV)) {
1924     if (CPV->getNumOperands()) {
1925       StructType *ST = cast<StructType>(CPV->getType());
1926       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1927         if (i == (e - 1))
1928           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1929                   TD->getTypeAllocSize(ST) -
1930                   TD->getStructLayout(ST)->getElementOffset(i);
1931         else
1932           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1933                   TD->getStructLayout(ST)->getElementOffset(i);
1934         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1935       }
1936     }
1937     return;
1938   }
1939   llvm_unreachable("unsupported constant type in printAggregateConstant()");
1940 }
1941
1942 // buildTypeNameMap - Run through symbol table looking for type names.
1943 //
1944
1945 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1946
1947   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1948
1949   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1950                                   !PI->second.compare("struct._image2d_t") ||
1951                                   !PI->second.compare("struct._image3d_t")))
1952     return true;
1953
1954   return false;
1955 }
1956
1957
1958 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1959   switch (MI.getOpcode()) {
1960   default:
1961     return false;
1962   case NVPTX::CallArgBeginInst:
1963   case NVPTX::CallArgEndInst0:
1964   case NVPTX::CallArgEndInst1:
1965   case NVPTX::CallArgF32:
1966   case NVPTX::CallArgF64:
1967   case NVPTX::CallArgI16:
1968   case NVPTX::CallArgI32:
1969   case NVPTX::CallArgI32imm:
1970   case NVPTX::CallArgI64:
1971   case NVPTX::CallArgParam:
1972   case NVPTX::CallVoidInst:
1973   case NVPTX::CallVoidInstReg:
1974   case NVPTX::Callseq_End:
1975   case NVPTX::CallVoidInstReg64:
1976   case NVPTX::DeclareParamInst:
1977   case NVPTX::DeclareRetMemInst:
1978   case NVPTX::DeclareRetRegInst:
1979   case NVPTX::DeclareRetScalarInst:
1980   case NVPTX::DeclareScalarParamInst:
1981   case NVPTX::DeclareScalarRegInst:
1982   case NVPTX::StoreParamF32:
1983   case NVPTX::StoreParamF64:
1984   case NVPTX::StoreParamI16:
1985   case NVPTX::StoreParamI32:
1986   case NVPTX::StoreParamI64:
1987   case NVPTX::StoreParamI8:
1988   case NVPTX::StoreRetvalF32:
1989   case NVPTX::StoreRetvalF64:
1990   case NVPTX::StoreRetvalI16:
1991   case NVPTX::StoreRetvalI32:
1992   case NVPTX::StoreRetvalI64:
1993   case NVPTX::StoreRetvalI8:
1994   case NVPTX::LastCallArgF32:
1995   case NVPTX::LastCallArgF64:
1996   case NVPTX::LastCallArgI16:
1997   case NVPTX::LastCallArgI32:
1998   case NVPTX::LastCallArgI32imm:
1999   case NVPTX::LastCallArgI64:
2000   case NVPTX::LastCallArgParam:
2001   case NVPTX::LoadParamMemF32:
2002   case NVPTX::LoadParamMemF64:
2003   case NVPTX::LoadParamMemI16:
2004   case NVPTX::LoadParamMemI32:
2005   case NVPTX::LoadParamMemI64:
2006   case NVPTX::LoadParamMemI8:
2007   case NVPTX::PrototypeInst:
2008   case NVPTX::DBG_VALUE:
2009     return true;
2010   }
2011   return false;
2012 }
2013
2014 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2015 ///
2016 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2017                                       unsigned AsmVariant,
2018                                       const char *ExtraCode, raw_ostream &O) {
2019   if (ExtraCode && ExtraCode[0]) {
2020     if (ExtraCode[1] != 0)
2021       return true; // Unknown modifier.
2022
2023     switch (ExtraCode[0]) {
2024     default:
2025       // See if this is a generic print operand
2026       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2027     case 'r':
2028       break;
2029     }
2030   }
2031
2032   printOperand(MI, OpNo, O);
2033
2034   return false;
2035 }
2036
2037 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2038     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2039     const char *ExtraCode, raw_ostream &O) {
2040   if (ExtraCode && ExtraCode[0])
2041     return true; // Unknown modifier
2042
2043   O << '[';
2044   printMemOperand(MI, OpNo, O);
2045   O << ']';
2046
2047   return false;
2048 }
2049
2050 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2051                                    raw_ostream &O, const char *Modifier) {
2052   const MachineOperand &MO = MI->getOperand(opNum);
2053   switch (MO.getType()) {
2054   case MachineOperand::MO_Register:
2055     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2056       if (MO.getReg() == NVPTX::VRDepot)
2057         O << DEPOTNAME << getFunctionNumber();
2058       else
2059         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2060     } else {
2061       emitVirtualRegister(MO.getReg(), O);
2062     }
2063     return;
2064
2065   case MachineOperand::MO_Immediate:
2066     if (!Modifier)
2067       O << MO.getImm();
2068     else if (strstr(Modifier, "vec") == Modifier)
2069       printVecModifiedImmediate(MO, Modifier, O);
2070     else
2071       llvm_unreachable(
2072           "Don't know how to handle modifier on immediate operand");
2073     return;
2074
2075   case MachineOperand::MO_FPImmediate:
2076     printFPConstant(MO.getFPImm(), O);
2077     break;
2078
2079   case MachineOperand::MO_GlobalAddress:
2080     O << *getSymbol(MO.getGlobal());
2081     break;
2082
2083   case MachineOperand::MO_MachineBasicBlock:
2084     O << *MO.getMBB()->getSymbol();
2085     return;
2086
2087   default:
2088     llvm_unreachable("Operand type not supported.");
2089   }
2090 }
2091
2092 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2093                                       raw_ostream &O, const char *Modifier) {
2094   printOperand(MI, opNum, O);
2095
2096   if (Modifier && !strcmp(Modifier, "add")) {
2097     O << ", ";
2098     printOperand(MI, opNum + 1, O);
2099   } else {
2100     if (MI->getOperand(opNum + 1).isImm() &&
2101         MI->getOperand(opNum + 1).getImm() == 0)
2102       return; // don't print ',0' or '+0'
2103     O << "+";
2104     printOperand(MI, opNum + 1, O);
2105   }
2106 }
2107
2108
2109 // Force static initialization.
2110 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2111   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2112   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2113 }
2114
2115 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2116   std::stringstream temp;
2117   LineReader *reader = this->getReader(filename.str());
2118   temp << "\n//";
2119   temp << filename.str();
2120   temp << ":";
2121   temp << line;
2122   temp << " ";
2123   temp << reader->readLine(line);
2124   temp << "\n";
2125   this->OutStreamer.EmitRawText(Twine(temp.str()));
2126 }
2127
2128 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2129   if (!reader) {
2130     reader = new LineReader(filename);
2131   }
2132
2133   if (reader->fileName() != filename) {
2134     delete reader;
2135     reader = new LineReader(filename);
2136   }
2137
2138   return reader;
2139 }
2140
2141 std::string LineReader::readLine(unsigned lineNum) {
2142   if (lineNum < theCurLine) {
2143     theCurLine = 0;
2144     fstr.seekg(0, std::ios::beg);
2145   }
2146   while (theCurLine < lineNum) {
2147     fstr.getline(buff, 500);
2148     theCurLine++;
2149   }
2150   return buff;
2151 }
2152
2153 // Force static initialization.
2154 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2155   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2156   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2157 }