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