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