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