[NVPTX] Clean up comparison/select/convert patterns and factor out PTX instructions...
[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::printCvtMode(const MachineInstr *MI, int OpNum,
697                                    raw_ostream &O, const char *Modifier) {
698   const MachineOperand &MO = MI->getOperand(OpNum);
699   int64_t Imm = MO.getImm();
700
701   if (strcmp(Modifier, "ftz") == 0) {
702     // FTZ flag
703     if (Imm & NVPTX::PTXCvtMode::FTZ_FLAG)
704       O << ".ftz";
705   } else if (strcmp(Modifier, "sat") == 0) {
706     // SAT flag
707     if (Imm & NVPTX::PTXCvtMode::SAT_FLAG)
708       O << ".sat";
709   } else if (strcmp(Modifier, "base") == 0) {
710     // Default operand
711     switch (Imm & NVPTX::PTXCvtMode::BASE_MASK) {
712     default:
713       return;
714     case NVPTX::PTXCvtMode::NONE:
715       break;
716     case NVPTX::PTXCvtMode::RNI:
717       O << ".rni";
718       break;
719     case NVPTX::PTXCvtMode::RZI:
720       O << ".rzi";
721       break;
722     case NVPTX::PTXCvtMode::RMI:
723       O << ".rmi";
724       break;
725     case NVPTX::PTXCvtMode::RPI:
726       O << ".rpi";
727       break;
728     case NVPTX::PTXCvtMode::RN:
729       O << ".rn";
730       break;
731     case NVPTX::PTXCvtMode::RZ:
732       O << ".rz";
733       break;
734     case NVPTX::PTXCvtMode::RM:
735       O << ".rm";
736       break;
737     case NVPTX::PTXCvtMode::RP:
738       O << ".rp";
739       break;
740     }
741   } else {
742     llvm_unreachable("Invalid conversion modifier");
743   }
744 }
745
746 void NVPTXAsmPrinter::printCmpMode(const MachineInstr *MI, int OpNum,
747                                    raw_ostream &O, const char *Modifier) {
748   const MachineOperand &MO = MI->getOperand(OpNum);
749   int64_t Imm = MO.getImm();
750
751   if (strcmp(Modifier, "ftz") == 0) {
752     // FTZ flag
753     if (Imm & NVPTX::PTXCmpMode::FTZ_FLAG)
754       O << ".ftz";
755   } else if (strcmp(Modifier, "base") == 0) {
756     switch (Imm & NVPTX::PTXCmpMode::BASE_MASK) {
757     default:
758       return;
759     case NVPTX::PTXCmpMode::EQ:
760       O << ".eq";
761       break;
762     case NVPTX::PTXCmpMode::NE:
763       O << ".ne";
764       break;
765     case NVPTX::PTXCmpMode::LT:
766       O << ".lt";
767       break;
768     case NVPTX::PTXCmpMode::LE:
769       O << ".le";
770       break;
771     case NVPTX::PTXCmpMode::GT:
772       O << ".gt";
773       break;
774     case NVPTX::PTXCmpMode::GE:
775       O << ".ge";
776       break;
777     case NVPTX::PTXCmpMode::LO:
778       O << ".lo";
779       break;
780     case NVPTX::PTXCmpMode::LS:
781       O << ".ls";
782       break;
783     case NVPTX::PTXCmpMode::HI:
784       O << ".hi";
785       break;
786     case NVPTX::PTXCmpMode::HS:
787       O << ".hs";
788       break;
789     case NVPTX::PTXCmpMode::EQU:
790       O << ".equ";
791       break;
792     case NVPTX::PTXCmpMode::NEU:
793       O << ".neu";
794       break;
795     case NVPTX::PTXCmpMode::LTU:
796       O << ".ltu";
797       break;
798     case NVPTX::PTXCmpMode::LEU:
799       O << ".leu";
800       break;
801     case NVPTX::PTXCmpMode::GTU:
802       O << ".gtu";
803       break;
804     case NVPTX::PTXCmpMode::GEU:
805       O << ".geu";
806       break;
807     case NVPTX::PTXCmpMode::NUM:
808       O << ".num";
809       break;
810     case NVPTX::PTXCmpMode::NotANumber:
811       O << ".nan";
812       break;
813     }
814   } else {
815     llvm_unreachable("Empty Modifier");
816   }
817 }
818
819
820 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
821
822   emitLinkageDirective(F, O);
823   if (llvm::isKernelFunction(*F))
824     O << ".entry ";
825   else
826     O << ".func ";
827   printReturnValStr(F, O);
828   O << *Mang->getSymbol(F) << "\n";
829   emitFunctionParamList(F, O);
830   O << ";\n";
831 }
832
833 static bool usedInGlobalVarDef(const Constant *C) {
834   if (!C)
835     return false;
836
837   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
838     if (GV->getName().str() == "llvm.used")
839       return false;
840     return true;
841   }
842
843   for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
844        ui != ue; ++ui) {
845     const Constant *C = dyn_cast<Constant>(*ui);
846     if (usedInGlobalVarDef(C))
847       return true;
848   }
849   return false;
850 }
851
852 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
853   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
854     if (othergv->getName().str() == "llvm.used")
855       return true;
856   }
857
858   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
859     if (instr->getParent() && instr->getParent()->getParent()) {
860       const Function *curFunc = instr->getParent()->getParent();
861       if (oneFunc && (curFunc != oneFunc))
862         return false;
863       oneFunc = curFunc;
864       return true;
865     } else
866       return false;
867   }
868
869   if (const MDNode *md = dyn_cast<MDNode>(U))
870     if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
871                           (md->getName().str() == "llvm.dbg.sp")))
872       return true;
873
874   for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
875        ui != ue; ++ui) {
876     if (usedInOneFunc(*ui, oneFunc) == false)
877       return false;
878   }
879   return true;
880 }
881
882 /* Find out if a global variable can be demoted to local scope.
883  * Currently, this is valid for CUDA shared variables, which have local
884  * scope and global lifetime. So the conditions to check are :
885  * 1. Is the global variable in shared address space?
886  * 2. Does it have internal linkage?
887  * 3. Is the global variable referenced only in one function?
888  */
889 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
890   if (gv->hasInternalLinkage() == false)
891     return false;
892   const PointerType *Pty = gv->getType();
893   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
894     return false;
895
896   const Function *oneFunc = 0;
897
898   bool flag = usedInOneFunc(gv, oneFunc);
899   if (flag == false)
900     return false;
901   if (!oneFunc)
902     return false;
903   f = oneFunc;
904   return true;
905 }
906
907 static bool useFuncSeen(const Constant *C,
908                         llvm::DenseMap<const Function *, bool> &seenMap) {
909   for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
910        ui != ue; ++ui) {
911     if (const Constant *cu = dyn_cast<Constant>(*ui)) {
912       if (useFuncSeen(cu, seenMap))
913         return true;
914     } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
915       const BasicBlock *bb = I->getParent();
916       if (!bb)
917         continue;
918       const Function *caller = bb->getParent();
919       if (!caller)
920         continue;
921       if (seenMap.find(caller) != seenMap.end())
922         return true;
923     }
924   }
925   return false;
926 }
927
928 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
929   llvm::DenseMap<const Function *, bool> seenMap;
930   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
931     const Function *F = FI;
932
933     if (F->isDeclaration()) {
934       if (F->use_empty())
935         continue;
936       if (F->getIntrinsicID())
937         continue;
938       emitDeclaration(F, O);
939       continue;
940     }
941     for (Value::const_use_iterator iter = F->use_begin(),
942                                    iterEnd = F->use_end();
943          iter != iterEnd; ++iter) {
944       if (const Constant *C = dyn_cast<Constant>(*iter)) {
945         if (usedInGlobalVarDef(C)) {
946           // The use is in the initialization of a global variable
947           // that is a function pointer, so print a declaration
948           // for the original function
949           emitDeclaration(F, O);
950           break;
951         }
952         // Emit a declaration of this function if the function that
953         // uses this constant expr has already been seen.
954         if (useFuncSeen(C, seenMap)) {
955           emitDeclaration(F, O);
956           break;
957         }
958       }
959
960       if (!isa<Instruction>(*iter))
961         continue;
962       const Instruction *instr = cast<Instruction>(*iter);
963       const BasicBlock *bb = instr->getParent();
964       if (!bb)
965         continue;
966       const Function *caller = bb->getParent();
967       if (!caller)
968         continue;
969
970       // If a caller has already been seen, then the caller is
971       // appearing in the module before the callee. so print out
972       // a declaration for the callee.
973       if (seenMap.find(caller) != seenMap.end()) {
974         emitDeclaration(F, O);
975         break;
976       }
977     }
978     seenMap[F] = true;
979   }
980 }
981
982 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
983   DebugInfoFinder DbgFinder;
984   DbgFinder.processModule(M);
985
986   unsigned i = 1;
987   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
988                                  E = DbgFinder.compile_unit_end();
989        I != E; ++I) {
990     DICompileUnit DIUnit(*I);
991     StringRef Filename(DIUnit.getFilename());
992     StringRef Dirname(DIUnit.getDirectory());
993     SmallString<128> FullPathName = Dirname;
994     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
995       sys::path::append(FullPathName, Filename);
996       Filename = FullPathName.str();
997     }
998     if (filenameMap.find(Filename.str()) != filenameMap.end())
999       continue;
1000     filenameMap[Filename.str()] = i;
1001     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
1002     ++i;
1003   }
1004
1005   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1006                                  E = DbgFinder.subprogram_end();
1007        I != E; ++I) {
1008     DISubprogram SP(*I);
1009     StringRef Filename(SP.getFilename());
1010     StringRef Dirname(SP.getDirectory());
1011     SmallString<128> FullPathName = Dirname;
1012     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1013       sys::path::append(FullPathName, Filename);
1014       Filename = FullPathName.str();
1015     }
1016     if (filenameMap.find(Filename.str()) != filenameMap.end())
1017       continue;
1018     filenameMap[Filename.str()] = i;
1019     ++i;
1020   }
1021 }
1022
1023 bool NVPTXAsmPrinter::doInitialization(Module &M) {
1024
1025   SmallString<128> Str1;
1026   raw_svector_ostream OS1(Str1);
1027
1028   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
1029   MMI->AnalyzeModule(M);
1030
1031   // We need to call the parent's one explicitly.
1032   //bool Result = AsmPrinter::doInitialization(M);
1033
1034   // Initialize TargetLoweringObjectFile.
1035   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
1036       .Initialize(OutContext, TM);
1037
1038   Mang = new Mangler(OutContext, &TM);
1039
1040   // Emit header before any dwarf directives are emitted below.
1041   emitHeader(M, OS1);
1042   OutStreamer.EmitRawText(OS1.str());
1043
1044   // Already commented out
1045   //bool Result = AsmPrinter::doInitialization(M);
1046
1047   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
1048     recordAndEmitFilenames(M);
1049
1050   GlobalsEmitted = false;
1051     
1052   return false; // success
1053 }
1054
1055 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
1056   SmallString<128> Str2;
1057   raw_svector_ostream OS2(Str2);
1058
1059   emitDeclarations(M, OS2);
1060
1061   // As ptxas does not support forward references of globals, we need to first
1062   // sort the list of module-level globals in def-use order. We visit each
1063   // global variable in order, and ensure that we emit it *after* its dependent
1064   // globals. We use a little extra memory maintaining both a set and a list to
1065   // have fast searches while maintaining a strict ordering.
1066   SmallVector<const GlobalVariable *, 8> Globals;
1067   DenseSet<const GlobalVariable *> GVVisited;
1068   DenseSet<const GlobalVariable *> GVVisiting;
1069
1070   // Visit each global variable, in order
1071   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1072        I != E; ++I)
1073     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1074
1075   assert(GVVisited.size() == M.getGlobalList().size() &&
1076          "Missed a global variable");
1077   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1078
1079   // Print out module-level global variables in proper order
1080   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1081     printModuleLevelGV(Globals[i], OS2);
1082
1083   OS2 << '\n';
1084
1085   OutStreamer.EmitRawText(OS2.str());
1086 }
1087
1088 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1089   O << "//\n";
1090   O << "// Generated by LLVM NVPTX Back-End\n";
1091   O << "//\n";
1092   O << "\n";
1093
1094   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1095   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1096
1097   O << ".target ";
1098   O << nvptxSubtarget.getTargetName();
1099
1100   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1101     O << ", texmode_independent";
1102   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1103     if (!nvptxSubtarget.hasDouble())
1104       O << ", map_f64_to_f32";
1105   }
1106
1107   if (MAI->doesSupportDebugInformation())
1108     O << ", debug";
1109
1110   O << "\n";
1111
1112   O << ".address_size ";
1113   if (nvptxSubtarget.is64Bit())
1114     O << "64";
1115   else
1116     O << "32";
1117   O << "\n";
1118
1119   O << "\n";
1120 }
1121
1122 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1123
1124   // If we did not emit any functions, then the global declarations have not
1125   // yet been emitted.
1126   if (!GlobalsEmitted) {
1127     emitGlobals(M);
1128     GlobalsEmitted = true;
1129   }
1130
1131   // XXX Temproarily remove global variables so that doFinalization() will not
1132   // emit them again (global variables are emitted at beginning).
1133
1134   Module::GlobalListType &global_list = M.getGlobalList();
1135   int i, n = global_list.size();
1136   GlobalVariable **gv_array = new GlobalVariable *[n];
1137
1138   // first, back-up GlobalVariable in gv_array
1139   i = 0;
1140   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1141        I != E; ++I)
1142     gv_array[i++] = &*I;
1143
1144   // second, empty global_list
1145   while (!global_list.empty())
1146     global_list.remove(global_list.begin());
1147
1148   // call doFinalization
1149   bool ret = AsmPrinter::doFinalization(M);
1150
1151   // now we restore global variables
1152   for (i = 0; i < n; i++)
1153     global_list.insert(global_list.end(), gv_array[i]);
1154
1155   delete[] gv_array;
1156   return ret;
1157
1158   //bool Result = AsmPrinter::doFinalization(M);
1159   // Instead of calling the parents doFinalization, we may
1160   // clone parents doFinalization and customize here.
1161   // Currently, we if NVISA out the EmitGlobals() in
1162   // parent's doFinalization, which is too intrusive.
1163   //
1164   // Same for the doInitialization.
1165   //return Result;
1166 }
1167
1168 // This function emits appropriate linkage directives for
1169 // functions and global variables.
1170 //
1171 // extern function declaration            -> .extern
1172 // extern function definition             -> .visible
1173 // external global variable with init     -> .visible
1174 // external without init                  -> .extern
1175 // appending                              -> not allowed, assert.
1176
1177 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1178                                            raw_ostream &O) {
1179   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1180     if (V->hasExternalLinkage()) {
1181       if (isa<GlobalVariable>(V)) {
1182         const GlobalVariable *GVar = cast<GlobalVariable>(V);
1183         if (GVar) {
1184           if (GVar->hasInitializer())
1185             O << ".visible ";
1186           else
1187             O << ".extern ";
1188         }
1189       } else if (V->isDeclaration())
1190         O << ".extern ";
1191       else
1192         O << ".visible ";
1193     } else if (V->hasAppendingLinkage()) {
1194       std::string msg;
1195       msg.append("Error: ");
1196       msg.append("Symbol ");
1197       if (V->hasName())
1198         msg.append(V->getName().str());
1199       msg.append("has unsupported appending linkage type");
1200       llvm_unreachable(msg.c_str());
1201     }
1202   }
1203 }
1204
1205 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1206                                          raw_ostream &O,
1207                                          bool processDemoted) {
1208
1209   // Skip meta data
1210   if (GVar->hasSection()) {
1211     if (GVar->getSection() == "llvm.metadata")
1212       return;
1213   }
1214
1215   const DataLayout *TD = TM.getDataLayout();
1216
1217   // GlobalVariables are always constant pointers themselves.
1218   const PointerType *PTy = GVar->getType();
1219   Type *ETy = PTy->getElementType();
1220
1221   if (GVar->hasExternalLinkage()) {
1222     if (GVar->hasInitializer())
1223       O << ".visible ";
1224     else
1225       O << ".extern ";
1226   }
1227
1228   if (llvm::isTexture(*GVar)) {
1229     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1230     return;
1231   }
1232
1233   if (llvm::isSurface(*GVar)) {
1234     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1235     return;
1236   }
1237
1238   if (GVar->isDeclaration()) {
1239     // (extern) declarations, no definition or initializer
1240     // Currently the only known declaration is for an automatic __local
1241     // (.shared) promoted to global.
1242     emitPTXGlobalVariable(GVar, O);
1243     O << ";\n";
1244     return;
1245   }
1246
1247   if (llvm::isSampler(*GVar)) {
1248     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1249
1250     const Constant *Initializer = NULL;
1251     if (GVar->hasInitializer())
1252       Initializer = GVar->getInitializer();
1253     const ConstantInt *CI = NULL;
1254     if (Initializer)
1255       CI = dyn_cast<ConstantInt>(Initializer);
1256     if (CI) {
1257       unsigned sample = CI->getZExtValue();
1258
1259       O << " = { ";
1260
1261       for (int i = 0,
1262                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1263            i < 3; i++) {
1264         O << "addr_mode_" << i << " = ";
1265         switch (addr) {
1266         case 0:
1267           O << "wrap";
1268           break;
1269         case 1:
1270           O << "clamp_to_border";
1271           break;
1272         case 2:
1273           O << "clamp_to_edge";
1274           break;
1275         case 3:
1276           O << "wrap";
1277           break;
1278         case 4:
1279           O << "mirror";
1280           break;
1281         }
1282         O << ", ";
1283       }
1284       O << "filter_mode = ";
1285       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1286       case 0:
1287         O << "nearest";
1288         break;
1289       case 1:
1290         O << "linear";
1291         break;
1292       case 2:
1293         assert(0 && "Anisotropic filtering is not supported");
1294       default:
1295         O << "nearest";
1296         break;
1297       }
1298       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1299         O << ", force_unnormalized_coords = 1";
1300       }
1301       O << " }";
1302     }
1303
1304     O << ";\n";
1305     return;
1306   }
1307
1308   if (GVar->hasPrivateLinkage()) {
1309
1310     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1311       return;
1312
1313     // FIXME - need better way (e.g. Metadata) to avoid generating this global
1314     if (!strncmp(GVar->getName().data(), "filename", 8))
1315       return;
1316     if (GVar->use_empty())
1317       return;
1318   }
1319
1320   const Function *demotedFunc = 0;
1321   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1322     O << "// " << GVar->getName().str() << " has been demoted\n";
1323     if (localDecls.find(demotedFunc) != localDecls.end())
1324       localDecls[demotedFunc].push_back(GVar);
1325     else {
1326       std::vector<const GlobalVariable *> temp;
1327       temp.push_back(GVar);
1328       localDecls[demotedFunc] = temp;
1329     }
1330     return;
1331   }
1332
1333   O << ".";
1334   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1335   if (GVar->getAlignment() == 0)
1336     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1337   else
1338     O << " .align " << GVar->getAlignment();
1339
1340   if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1341     O << " .";
1342     // Special case: ABI requires that we use .u8 for predicates
1343     if (ETy->isIntegerTy(1))
1344       O << "u8";
1345     else
1346       O << getPTXFundamentalTypeStr(ETy, false);
1347     O << " ";
1348     O << *Mang->getSymbol(GVar);
1349
1350     // Ptx allows variable initilization only for constant and global state
1351     // spaces.
1352     if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1353          (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1354         GVar->hasInitializer()) {
1355       const Constant *Initializer = GVar->getInitializer();
1356       if (!Initializer->isNullValue()) {
1357         O << " = ";
1358         printScalarConstant(Initializer, O);
1359       }
1360     }
1361   } else {
1362     unsigned int ElementSize = 0;
1363
1364     // Although PTX has direct support for struct type and array type and
1365     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1366     // targets that support these high level field accesses. Structs, arrays
1367     // and vectors are lowered into arrays of bytes.
1368     switch (ETy->getTypeID()) {
1369     case Type::StructTyID:
1370     case Type::ArrayTyID:
1371     case Type::VectorTyID:
1372       ElementSize = TD->getTypeStoreSize(ETy);
1373       // Ptx allows variable initilization only for constant and
1374       // global state spaces.
1375       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1376            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1377           GVar->hasInitializer()) {
1378         const Constant *Initializer = GVar->getInitializer();
1379         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1380           AggBuffer aggBuffer(ElementSize, O, *this);
1381           bufferAggregateConstant(Initializer, &aggBuffer);
1382           if (aggBuffer.numSymbols) {
1383             if (nvptxSubtarget.is64Bit()) {
1384               O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1385               O << ElementSize / 8;
1386             } else {
1387               O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1388               O << ElementSize / 4;
1389             }
1390             O << "]";
1391           } else {
1392             O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1393             O << ElementSize;
1394             O << "]";
1395           }
1396           O << " = {";
1397           aggBuffer.print();
1398           O << "}";
1399         } else {
1400           O << " .b8 " << *Mang->getSymbol(GVar);
1401           if (ElementSize) {
1402             O << "[";
1403             O << ElementSize;
1404             O << "]";
1405           }
1406         }
1407       } else {
1408         O << " .b8 " << *Mang->getSymbol(GVar);
1409         if (ElementSize) {
1410           O << "[";
1411           O << ElementSize;
1412           O << "]";
1413         }
1414       }
1415       break;
1416     default:
1417       assert(0 && "type not supported yet");
1418     }
1419
1420   }
1421   O << ";\n";
1422 }
1423
1424 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1425   if (localDecls.find(f) == localDecls.end())
1426     return;
1427
1428   std::vector<const GlobalVariable *> &gvars = localDecls[f];
1429
1430   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1431     O << "\t// demoted variable\n\t";
1432     printModuleLevelGV(gvars[i], O, true);
1433   }
1434 }
1435
1436 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1437                                           raw_ostream &O) const {
1438   switch (AddressSpace) {
1439   case llvm::ADDRESS_SPACE_LOCAL:
1440     O << "local";
1441     break;
1442   case llvm::ADDRESS_SPACE_GLOBAL:
1443     O << "global";
1444     break;
1445   case llvm::ADDRESS_SPACE_CONST:
1446     O << "const";
1447     break;
1448   case llvm::ADDRESS_SPACE_SHARED:
1449     O << "shared";
1450     break;
1451   default:
1452     report_fatal_error("Bad address space found while emitting PTX");
1453     break;
1454   }
1455 }
1456
1457 std::string
1458 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1459   switch (Ty->getTypeID()) {
1460   default:
1461     llvm_unreachable("unexpected type");
1462     break;
1463   case Type::IntegerTyID: {
1464     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1465     if (NumBits == 1)
1466       return "pred";
1467     else if (NumBits <= 64) {
1468       std::string name = "u";
1469       return name + utostr(NumBits);
1470     } else {
1471       llvm_unreachable("Integer too large");
1472       break;
1473     }
1474     break;
1475   }
1476   case Type::FloatTyID:
1477     return "f32";
1478   case Type::DoubleTyID:
1479     return "f64";
1480   case Type::PointerTyID:
1481     if (nvptxSubtarget.is64Bit())
1482       if (useB4PTR)
1483         return "b64";
1484       else
1485         return "u64";
1486     else if (useB4PTR)
1487       return "b32";
1488     else
1489       return "u32";
1490   }
1491   llvm_unreachable("unexpected type");
1492   return NULL;
1493 }
1494
1495 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1496                                             raw_ostream &O) {
1497
1498   const DataLayout *TD = TM.getDataLayout();
1499
1500   // GlobalVariables are always constant pointers themselves.
1501   const PointerType *PTy = GVar->getType();
1502   Type *ETy = PTy->getElementType();
1503
1504   O << ".";
1505   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1506   if (GVar->getAlignment() == 0)
1507     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1508   else
1509     O << " .align " << GVar->getAlignment();
1510
1511   if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1512     O << " .";
1513     O << getPTXFundamentalTypeStr(ETy);
1514     O << " ";
1515     O << *Mang->getSymbol(GVar);
1516     return;
1517   }
1518
1519   int64_t ElementSize = 0;
1520
1521   // Although PTX has direct support for struct type and array type and LLVM IR
1522   // is very similar to PTX, the LLVM CodeGen does not support for targets that
1523   // support these high level field accesses. Structs and arrays are lowered
1524   // into arrays of bytes.
1525   switch (ETy->getTypeID()) {
1526   case Type::StructTyID:
1527   case Type::ArrayTyID:
1528   case Type::VectorTyID:
1529     ElementSize = TD->getTypeStoreSize(ETy);
1530     O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1531     if (ElementSize) {
1532       O << itostr(ElementSize);
1533     }
1534     O << "]";
1535     break;
1536   default:
1537     assert(0 && "type not supported yet");
1538   }
1539   return;
1540 }
1541
1542 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1543   if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1544     return TD->getPrefTypeAlignment(Ty);
1545
1546   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1547   if (ATy)
1548     return getOpenCLAlignment(TD, ATy->getElementType());
1549
1550   const VectorType *VTy = dyn_cast<VectorType>(Ty);
1551   if (VTy) {
1552     Type *ETy = VTy->getElementType();
1553     unsigned int numE = VTy->getNumElements();
1554     unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1555     if (numE == 3)
1556       return 4 * alignE;
1557     else
1558       return numE * alignE;
1559   }
1560
1561   const StructType *STy = dyn_cast<StructType>(Ty);
1562   if (STy) {
1563     unsigned int alignStruct = 1;
1564     // Go through each element of the struct and find the
1565     // largest alignment.
1566     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1567       Type *ETy = STy->getElementType(i);
1568       unsigned int align = getOpenCLAlignment(TD, ETy);
1569       if (align > alignStruct)
1570         alignStruct = align;
1571     }
1572     return alignStruct;
1573   }
1574
1575   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1576   if (FTy)
1577     return TD->getPointerPrefAlignment();
1578   return TD->getPrefTypeAlignment(Ty);
1579 }
1580
1581 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1582                                      int paramIndex, raw_ostream &O) {
1583   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1584       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1585     O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1586   else {
1587     std::string argName = I->getName();
1588     const char *p = argName.c_str();
1589     while (*p) {
1590       if (*p == '.')
1591         O << "_";
1592       else
1593         O << *p;
1594       p++;
1595     }
1596   }
1597 }
1598
1599 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1600   Function::const_arg_iterator I, E;
1601   int i = 0;
1602
1603   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1604       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1605     O << *CurrentFnSym << "_param_" << paramIndex;
1606     return;
1607   }
1608
1609   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1610     if (i == paramIndex) {
1611       printParamName(I, paramIndex, O);
1612       return;
1613     }
1614   }
1615   llvm_unreachable("paramIndex out of bound");
1616 }
1617
1618 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1619   const DataLayout *TD = TM.getDataLayout();
1620   const AttributeSet &PAL = F->getAttributes();
1621   const TargetLowering *TLI = TM.getTargetLowering();
1622   Function::const_arg_iterator I, E;
1623   unsigned paramIndex = 0;
1624   bool first = true;
1625   bool isKernelFunc = llvm::isKernelFunction(*F);
1626   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1627   MVT thePointerTy = TLI->getPointerTy();
1628
1629   O << "(\n";
1630
1631   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1632     Type *Ty = I->getType();
1633
1634     if (!first)
1635       O << ",\n";
1636
1637     first = false;
1638
1639     // Handle image/sampler parameters
1640     if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1641       if (llvm::isImage(*I)) {
1642         std::string sname = I->getName();
1643         if (llvm::isImageWriteOnly(*I))
1644           O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1645             << paramIndex;
1646         else // Default image is read_only
1647           O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1648             << paramIndex;
1649       } else // Should be llvm::isSampler(*I)
1650         O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1651           << paramIndex;
1652       continue;
1653     }
1654
1655     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1656       if (Ty->isVectorTy()) {
1657         // Just print .param .b8 .align <a> .param[size];
1658         // <a> = PAL.getparamalignment
1659         // size = typeallocsize of element type
1660         unsigned align = PAL.getParamAlignment(paramIndex + 1);
1661         if (align == 0)
1662           align = TD->getABITypeAlignment(Ty);
1663
1664         unsigned sz = TD->getTypeAllocSize(Ty);
1665         O << "\t.param .align " << align << " .b8 ";
1666         printParamName(I, paramIndex, O);
1667         O << "[" << sz << "]";
1668
1669         continue;
1670       }
1671       // Just a scalar
1672       const PointerType *PTy = dyn_cast<PointerType>(Ty);
1673       if (isKernelFunc) {
1674         if (PTy) {
1675           // Special handling for pointer arguments to kernel
1676           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1677
1678           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1679             Type *ETy = PTy->getElementType();
1680             int addrSpace = PTy->getAddressSpace();
1681             switch (addrSpace) {
1682             default:
1683               O << ".ptr ";
1684               break;
1685             case llvm::ADDRESS_SPACE_CONST:
1686               O << ".ptr .const ";
1687               break;
1688             case llvm::ADDRESS_SPACE_SHARED:
1689               O << ".ptr .shared ";
1690               break;
1691             case llvm::ADDRESS_SPACE_GLOBAL:
1692               O << ".ptr .global ";
1693               break;
1694             }
1695             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1696           }
1697           printParamName(I, paramIndex, O);
1698           continue;
1699         }
1700
1701         // non-pointer scalar to kernel func
1702         O << "\t.param .";
1703         // Special case: predicate operands become .u8 types
1704         if (Ty->isIntegerTy(1))
1705           O << "u8";
1706         else
1707           O << getPTXFundamentalTypeStr(Ty);
1708         O << " ";
1709         printParamName(I, paramIndex, O);
1710         continue;
1711       }
1712       // Non-kernel function, just print .param .b<size> for ABI
1713       // and .reg .b<size> for non ABY
1714       unsigned sz = 0;
1715       if (isa<IntegerType>(Ty)) {
1716         sz = cast<IntegerType>(Ty)->getBitWidth();
1717         if (sz < 32)
1718           sz = 32;
1719       } else if (isa<PointerType>(Ty))
1720         sz = thePointerTy.getSizeInBits();
1721       else
1722         sz = Ty->getPrimitiveSizeInBits();
1723       if (isABI)
1724         O << "\t.param .b" << sz << " ";
1725       else
1726         O << "\t.reg .b" << sz << " ";
1727       printParamName(I, paramIndex, O);
1728       continue;
1729     }
1730
1731     // param has byVal attribute. So should be a pointer
1732     const PointerType *PTy = dyn_cast<PointerType>(Ty);
1733     assert(PTy && "Param with byval attribute should be a pointer type");
1734     Type *ETy = PTy->getElementType();
1735
1736     if (isABI || isKernelFunc) {
1737       // Just print .param .b8 .align <a> .param[size];
1738       // <a> = PAL.getparamalignment
1739       // size = typeallocsize of element type
1740       unsigned align = PAL.getParamAlignment(paramIndex + 1);
1741       if (align == 0)
1742         align = TD->getABITypeAlignment(ETy);
1743
1744       unsigned sz = TD->getTypeAllocSize(ETy);
1745       O << "\t.param .align " << align << " .b8 ";
1746       printParamName(I, paramIndex, O);
1747       O << "[" << sz << "]";
1748       continue;
1749     } else {
1750       // Split the ETy into constituent parts and
1751       // print .param .b<size> <name> for each part.
1752       // Further, if a part is vector, print the above for
1753       // each vector element.
1754       SmallVector<EVT, 16> vtparts;
1755       ComputeValueVTs(*TLI, ETy, vtparts);
1756       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1757         unsigned elems = 1;
1758         EVT elemtype = vtparts[i];
1759         if (vtparts[i].isVector()) {
1760           elems = vtparts[i].getVectorNumElements();
1761           elemtype = vtparts[i].getVectorElementType();
1762         }
1763
1764         for (unsigned j = 0, je = elems; j != je; ++j) {
1765           unsigned sz = elemtype.getSizeInBits();
1766           if (elemtype.isInteger() && (sz < 32))
1767             sz = 32;
1768           O << "\t.reg .b" << sz << " ";
1769           printParamName(I, paramIndex, O);
1770           if (j < je - 1)
1771             O << ",\n";
1772           ++paramIndex;
1773         }
1774         if (i < e - 1)
1775           O << ",\n";
1776       }
1777       --paramIndex;
1778       continue;
1779     }
1780   }
1781
1782   O << "\n)\n";
1783 }
1784
1785 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1786                                             raw_ostream &O) {
1787   const Function *F = MF.getFunction();
1788   emitFunctionParamList(F, O);
1789 }
1790
1791 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1792     const MachineFunction &MF) {
1793   SmallString<128> Str;
1794   raw_svector_ostream O(Str);
1795
1796   // Map the global virtual register number to a register class specific
1797   // virtual register number starting from 1 with that class.
1798   const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1799   //unsigned numRegClasses = TRI->getNumRegClasses();
1800
1801   // Emit the Fake Stack Object
1802   const MachineFrameInfo *MFI = MF.getFrameInfo();
1803   int NumBytes = (int) MFI->getStackSize();
1804   if (NumBytes) {
1805     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1806       << getFunctionNumber() << "[" << NumBytes << "];\n";
1807     if (nvptxSubtarget.is64Bit()) {
1808       O << "\t.reg .b64 \t%SP;\n";
1809       O << "\t.reg .b64 \t%SPL;\n";
1810     } else {
1811       O << "\t.reg .b32 \t%SP;\n";
1812       O << "\t.reg .b32 \t%SPL;\n";
1813     }
1814   }
1815
1816   // Go through all virtual registers to establish the mapping between the
1817   // global virtual
1818   // register number and the per class virtual register number.
1819   // We use the per class virtual register number in the ptx output.
1820   unsigned int numVRs = MRI->getNumVirtRegs();
1821   for (unsigned i = 0; i < numVRs; i++) {
1822     unsigned int vr = TRI->index2VirtReg(i);
1823     const TargetRegisterClass *RC = MRI->getRegClass(vr);
1824     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1825     int n = regmap.size();
1826     regmap.insert(std::make_pair(vr, n + 1));
1827   }
1828
1829   // Emit register declarations
1830   // @TODO: Extract out the real register usage
1831   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1832   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1833   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1834   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1835   // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1836   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1837   // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1838
1839   // Emit declaration of the virtual registers or 'physical' registers for
1840   // each register class
1841   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1842     const TargetRegisterClass *RC = TRI->getRegClass(i);
1843     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1844     std::string rcname = getNVPTXRegClassName(RC);
1845     std::string rcStr = getNVPTXRegClassStr(RC);
1846     int n = regmap.size();
1847
1848     // Only declare those registers that may be used.
1849     if (n) {
1850        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1851          << ">;\n";
1852     }
1853   }
1854
1855   OutStreamer.EmitRawText(O.str());
1856 }
1857
1858 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1859   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1860   bool ignored;
1861   unsigned int numHex;
1862   const char *lead;
1863
1864   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1865     numHex = 8;
1866     lead = "0f";
1867     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1868   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1869     numHex = 16;
1870     lead = "0d";
1871     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1872   } else
1873     llvm_unreachable("unsupported fp type");
1874
1875   APInt API = APF.bitcastToAPInt();
1876   std::string hexstr(utohexstr(API.getZExtValue()));
1877   O << lead;
1878   if (hexstr.length() < numHex)
1879     O << std::string(numHex - hexstr.length(), '0');
1880   O << utohexstr(API.getZExtValue());
1881 }
1882
1883 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1884   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1885     O << CI->getValue();
1886     return;
1887   }
1888   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1889     printFPConstant(CFP, O);
1890     return;
1891   }
1892   if (isa<ConstantPointerNull>(CPV)) {
1893     O << "0";
1894     return;
1895   }
1896   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1897     O << *Mang->getSymbol(GVar);
1898     return;
1899   }
1900   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1901     const Value *v = Cexpr->stripPointerCasts();
1902     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1903       O << *Mang->getSymbol(GVar);
1904       return;
1905     } else {
1906       O << *LowerConstant(CPV, *this);
1907       return;
1908     }
1909   }
1910   llvm_unreachable("Not scalar type found in printScalarConstant()");
1911 }
1912
1913 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1914                                    AggBuffer *aggBuffer) {
1915
1916   const DataLayout *TD = TM.getDataLayout();
1917
1918   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1919     int s = TD->getTypeAllocSize(CPV->getType());
1920     if (s < Bytes)
1921       s = Bytes;
1922     aggBuffer->addZeros(s);
1923     return;
1924   }
1925
1926   unsigned char *ptr;
1927   switch (CPV->getType()->getTypeID()) {
1928
1929   case Type::IntegerTyID: {
1930     const Type *ETy = CPV->getType();
1931     if (ETy == Type::getInt8Ty(CPV->getContext())) {
1932       unsigned char c =
1933           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1934       ptr = &c;
1935       aggBuffer->addBytes(ptr, 1, Bytes);
1936     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1937       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1938       ptr = (unsigned char *)&int16;
1939       aggBuffer->addBytes(ptr, 2, Bytes);
1940     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1941       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1942         int int32 = (int)(constInt->getZExtValue());
1943         ptr = (unsigned char *)&int32;
1944         aggBuffer->addBytes(ptr, 4, Bytes);
1945         break;
1946       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1947         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1948                 ConstantFoldConstantExpression(Cexpr, TD))) {
1949           int int32 = (int)(constInt->getZExtValue());
1950           ptr = (unsigned char *)&int32;
1951           aggBuffer->addBytes(ptr, 4, Bytes);
1952           break;
1953         }
1954         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1955           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1956           aggBuffer->addSymbol(v);
1957           aggBuffer->addZeros(4);
1958           break;
1959         }
1960       }
1961       llvm_unreachable("unsupported integer const type");
1962     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1963       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1964         long long int64 = (long long)(constInt->getZExtValue());
1965         ptr = (unsigned char *)&int64;
1966         aggBuffer->addBytes(ptr, 8, Bytes);
1967         break;
1968       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1969         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1970                 ConstantFoldConstantExpression(Cexpr, TD))) {
1971           long long int64 = (long long)(constInt->getZExtValue());
1972           ptr = (unsigned char *)&int64;
1973           aggBuffer->addBytes(ptr, 8, Bytes);
1974           break;
1975         }
1976         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1977           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1978           aggBuffer->addSymbol(v);
1979           aggBuffer->addZeros(8);
1980           break;
1981         }
1982       }
1983       llvm_unreachable("unsupported integer const type");
1984     } else
1985       llvm_unreachable("unsupported integer const type");
1986     break;
1987   }
1988   case Type::FloatTyID:
1989   case Type::DoubleTyID: {
1990     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1991     const Type *Ty = CFP->getType();
1992     if (Ty == Type::getFloatTy(CPV->getContext())) {
1993       float float32 = (float) CFP->getValueAPF().convertToFloat();
1994       ptr = (unsigned char *)&float32;
1995       aggBuffer->addBytes(ptr, 4, Bytes);
1996     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1997       double float64 = CFP->getValueAPF().convertToDouble();
1998       ptr = (unsigned char *)&float64;
1999       aggBuffer->addBytes(ptr, 8, Bytes);
2000     } else {
2001       llvm_unreachable("unsupported fp const type");
2002     }
2003     break;
2004   }
2005   case Type::PointerTyID: {
2006     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2007       aggBuffer->addSymbol(GVar);
2008     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2009       const Value *v = Cexpr->stripPointerCasts();
2010       aggBuffer->addSymbol(v);
2011     }
2012     unsigned int s = TD->getTypeAllocSize(CPV->getType());
2013     aggBuffer->addZeros(s);
2014     break;
2015   }
2016
2017   case Type::ArrayTyID:
2018   case Type::VectorTyID:
2019   case Type::StructTyID: {
2020     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2021         isa<ConstantStruct>(CPV)) {
2022       int ElementSize = TD->getTypeAllocSize(CPV->getType());
2023       bufferAggregateConstant(CPV, aggBuffer);
2024       if (Bytes > ElementSize)
2025         aggBuffer->addZeros(Bytes - ElementSize);
2026     } else if (isa<ConstantAggregateZero>(CPV))
2027       aggBuffer->addZeros(Bytes);
2028     else
2029       llvm_unreachable("Unexpected Constant type");
2030     break;
2031   }
2032
2033   default:
2034     llvm_unreachable("unsupported type");
2035   }
2036 }
2037
2038 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2039                                               AggBuffer *aggBuffer) {
2040   const DataLayout *TD = TM.getDataLayout();
2041   int Bytes;
2042
2043   // Old constants
2044   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2045     if (CPV->getNumOperands())
2046       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2047         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2048     return;
2049   }
2050
2051   if (const ConstantDataSequential *CDS =
2052           dyn_cast<ConstantDataSequential>(CPV)) {
2053     if (CDS->getNumElements())
2054       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2055         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2056                      aggBuffer);
2057     return;
2058   }
2059
2060   if (isa<ConstantStruct>(CPV)) {
2061     if (CPV->getNumOperands()) {
2062       StructType *ST = cast<StructType>(CPV->getType());
2063       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2064         if (i == (e - 1))
2065           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2066                   TD->getTypeAllocSize(ST) -
2067                   TD->getStructLayout(ST)->getElementOffset(i);
2068         else
2069           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2070                   TD->getStructLayout(ST)->getElementOffset(i);
2071         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2072       }
2073     }
2074     return;
2075   }
2076   llvm_unreachable("unsupported constant type in printAggregateConstant()");
2077 }
2078
2079 // buildTypeNameMap - Run through symbol table looking for type names.
2080 //
2081
2082 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2083
2084   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2085
2086   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2087                                   !PI->second.compare("struct._image2d_t") ||
2088                                   !PI->second.compare("struct._image3d_t")))
2089     return true;
2090
2091   return false;
2092 }
2093
2094 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2095 ///
2096 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2097                                       unsigned AsmVariant,
2098                                       const char *ExtraCode, raw_ostream &O) {
2099   if (ExtraCode && ExtraCode[0]) {
2100     if (ExtraCode[1] != 0)
2101       return true; // Unknown modifier.
2102
2103     switch (ExtraCode[0]) {
2104     default:
2105       // See if this is a generic print operand
2106       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2107     case 'r':
2108       break;
2109     }
2110   }
2111
2112   printOperand(MI, OpNo, O);
2113
2114   return false;
2115 }
2116
2117 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2118     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2119     const char *ExtraCode, raw_ostream &O) {
2120   if (ExtraCode && ExtraCode[0])
2121     return true; // Unknown modifier
2122
2123   O << '[';
2124   printMemOperand(MI, OpNo, O);
2125   O << ']';
2126
2127   return false;
2128 }
2129
2130 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2131   switch (MI.getOpcode()) {
2132   default:
2133     return false;
2134   case NVPTX::CallArgBeginInst:
2135   case NVPTX::CallArgEndInst0:
2136   case NVPTX::CallArgEndInst1:
2137   case NVPTX::CallArgF32:
2138   case NVPTX::CallArgF64:
2139   case NVPTX::CallArgI16:
2140   case NVPTX::CallArgI32:
2141   case NVPTX::CallArgI32imm:
2142   case NVPTX::CallArgI64:
2143   case NVPTX::CallArgParam:
2144   case NVPTX::CallVoidInst:
2145   case NVPTX::CallVoidInstReg:
2146   case NVPTX::Callseq_End:
2147   case NVPTX::CallVoidInstReg64:
2148   case NVPTX::DeclareParamInst:
2149   case NVPTX::DeclareRetMemInst:
2150   case NVPTX::DeclareRetRegInst:
2151   case NVPTX::DeclareRetScalarInst:
2152   case NVPTX::DeclareScalarParamInst:
2153   case NVPTX::DeclareScalarRegInst:
2154   case NVPTX::StoreParamF32:
2155   case NVPTX::StoreParamF64:
2156   case NVPTX::StoreParamI16:
2157   case NVPTX::StoreParamI32:
2158   case NVPTX::StoreParamI64:
2159   case NVPTX::StoreParamI8:
2160   case NVPTX::StoreRetvalF32:
2161   case NVPTX::StoreRetvalF64:
2162   case NVPTX::StoreRetvalI16:
2163   case NVPTX::StoreRetvalI32:
2164   case NVPTX::StoreRetvalI64:
2165   case NVPTX::StoreRetvalI8:
2166   case NVPTX::LastCallArgF32:
2167   case NVPTX::LastCallArgF64:
2168   case NVPTX::LastCallArgI16:
2169   case NVPTX::LastCallArgI32:
2170   case NVPTX::LastCallArgI32imm:
2171   case NVPTX::LastCallArgI64:
2172   case NVPTX::LastCallArgParam:
2173   case NVPTX::LoadParamMemF32:
2174   case NVPTX::LoadParamMemF64:
2175   case NVPTX::LoadParamMemI16:
2176   case NVPTX::LoadParamMemI32:
2177   case NVPTX::LoadParamMemI64:
2178   case NVPTX::LoadParamMemI8:
2179   case NVPTX::PrototypeInst:
2180   case NVPTX::DBG_VALUE:
2181     return true;
2182   }
2183   return false;
2184 }
2185
2186 // Force static initialization.
2187 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2188   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2189   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2190 }
2191
2192 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2193   std::stringstream temp;
2194   LineReader *reader = this->getReader(filename.str());
2195   temp << "\n//";
2196   temp << filename.str();
2197   temp << ":";
2198   temp << line;
2199   temp << " ";
2200   temp << reader->readLine(line);
2201   temp << "\n";
2202   this->OutStreamer.EmitRawText(Twine(temp.str()));
2203 }
2204
2205 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2206   if (reader == NULL) {
2207     reader = new LineReader(filename);
2208   }
2209
2210   if (reader->fileName() != filename) {
2211     delete reader;
2212     reader = new LineReader(filename);
2213   }
2214
2215   return reader;
2216 }
2217
2218 std::string LineReader::readLine(unsigned lineNum) {
2219   if (lineNum < theCurLine) {
2220     theCurLine = 0;
2221     fstr.seekg(0, std::ios::beg);
2222   }
2223   while (theCurLine < lineNum) {
2224     fstr.getline(buff, 500);
2225     theCurLine++;
2226   }
2227   return buff;
2228 }
2229
2230 // Force static initialization.
2231 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2232   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2233   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2234 }