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