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