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