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