39ae9bbf6405f97a7d646b84439beb92f34abb92
[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   std::vector<GlobalVariable *> gv_array(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   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.getSubtargetImpl()->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.getSubtargetImpl()->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.getSubtargetImpl()->getDataLayout();
1582   const AttributeSet &PAL = F->getAttributes();
1583   const TargetLowering *TLI = TM.getSubtargetImpl()->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.getSubtarget().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.getSubtargetImpl()->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.getSubtargetImpl()->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 }