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