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