LLVM API Documentation

NVPTXAsmPrinter.cpp
Go to the documentation of this file.
00001 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains a printer that converts from our internal representation
00011 // of machine-dependent LLVM code to NVPTX assembly language.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "NVPTXAsmPrinter.h"
00016 #include "InstPrinter/NVPTXInstPrinter.h"
00017 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
00018 #include "NVPTX.h"
00019 #include "NVPTXInstrInfo.h"
00020 #include "NVPTXMCExpr.h"
00021 #include "NVPTXMachineFunctionInfo.h"
00022 #include "NVPTXRegisterInfo.h"
00023 #include "NVPTXTargetMachine.h"
00024 #include "NVPTXUtilities.h"
00025 #include "cl_common_defines.h"
00026 #include "llvm/ADT/StringExtras.h"
00027 #include "llvm/Analysis/ConstantFolding.h"
00028 #include "llvm/CodeGen/Analysis.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineLoopInfo.h"
00031 #include "llvm/CodeGen/MachineModuleInfo.h"
00032 #include "llvm/CodeGen/MachineRegisterInfo.h"
00033 #include "llvm/IR/DebugInfo.h"
00034 #include "llvm/IR/DerivedTypes.h"
00035 #include "llvm/IR/Function.h"
00036 #include "llvm/IR/GlobalVariable.h"
00037 #include "llvm/IR/Mangler.h"
00038 #include "llvm/IR/Module.h"
00039 #include "llvm/IR/Operator.h"
00040 #include "llvm/MC/MCStreamer.h"
00041 #include "llvm/MC/MCSymbol.h"
00042 #include "llvm/Support/CommandLine.h"
00043 #include "llvm/Support/ErrorHandling.h"
00044 #include "llvm/Support/FormattedStream.h"
00045 #include "llvm/Support/Path.h"
00046 #include "llvm/Support/TargetRegistry.h"
00047 #include "llvm/Support/TimeValue.h"
00048 #include "llvm/Target/TargetLoweringObjectFile.h"
00049 #include "llvm/Transforms/Utils/UnrollLoop.h"
00050 #include <sstream>
00051 using namespace llvm;
00052 
00053 #define DEPOTNAME "__local_depot"
00054 
00055 static cl::opt<bool>
00056 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
00057                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
00058                 cl::init(true));
00059 
00060 static cl::opt<bool>
00061 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
00062               cl::desc("NVPTX Specific: Emit source line in ptx file"),
00063               cl::init(false));
00064 
00065 namespace {
00066 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
00067 /// depends.
00068 void DiscoverDependentGlobals(const Value *V,
00069                               DenseSet<const GlobalVariable *> &Globals) {
00070   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00071     Globals.insert(GV);
00072   else {
00073     if (const User *U = dyn_cast<User>(V)) {
00074       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
00075         DiscoverDependentGlobals(U->getOperand(i), Globals);
00076       }
00077     }
00078   }
00079 }
00080 
00081 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
00082 /// instances to be emitted, but only after any dependents have been added
00083 /// first.
00084 void VisitGlobalVariableForEmission(
00085     const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
00086     DenseSet<const GlobalVariable *> &Visited,
00087     DenseSet<const GlobalVariable *> &Visiting) {
00088   // Have we already visited this one?
00089   if (Visited.count(GV))
00090     return;
00091 
00092   // Do we have a circular dependency?
00093   if (!Visiting.insert(GV).second)
00094     report_fatal_error("Circular dependency found in global variable set");
00095 
00096   // Make sure we visit all dependents first
00097   DenseSet<const GlobalVariable *> Others;
00098   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
00099     DiscoverDependentGlobals(GV->getOperand(i), Others);
00100 
00101   for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
00102                                                   E = Others.end();
00103        I != E; ++I)
00104     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
00105 
00106   // Now we can visit ourself
00107   Order.push_back(GV);
00108   Visited.insert(GV);
00109   Visiting.erase(GV);
00110 }
00111 }
00112 
00113 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
00114   if (!EmitLineNumbers)
00115     return;
00116   if (ignoreLoc(MI))
00117     return;
00118 
00119   DebugLoc curLoc = MI.getDebugLoc();
00120 
00121   if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
00122     return;
00123 
00124   if (prevDebugLoc == curLoc)
00125     return;
00126 
00127   prevDebugLoc = curLoc;
00128 
00129   if (curLoc.isUnknown())
00130     return;
00131 
00132   const MachineFunction *MF = MI.getParent()->getParent();
00133   //const TargetMachine &TM = MF->getTarget();
00134 
00135   const LLVMContext &ctx = MF->getFunction()->getContext();
00136   DIScope Scope(curLoc.getScope(ctx));
00137 
00138   assert((!Scope || Scope.isScope()) &&
00139     "Scope of a DebugLoc should be null or a DIScope.");
00140   if (!Scope)
00141      return;
00142 
00143   StringRef fileName(Scope.getFilename());
00144   StringRef dirName(Scope.getDirectory());
00145   SmallString<128> FullPathName = dirName;
00146   if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
00147     sys::path::append(FullPathName, fileName);
00148     fileName = FullPathName.str();
00149   }
00150 
00151   if (filenameMap.find(fileName.str()) == filenameMap.end())
00152     return;
00153 
00154   // Emit the line from the source file.
00155   if (InterleaveSrc)
00156     this->emitSrcInText(fileName.str(), curLoc.getLine());
00157 
00158   std::stringstream temp;
00159   temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
00160        << " " << curLoc.getCol();
00161   OutStreamer.EmitRawText(Twine(temp.str().c_str()));
00162 }
00163 
00164 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
00165   SmallString<128> Str;
00166   raw_svector_ostream OS(Str);
00167   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
00168     emitLineNumberAsDotLoc(*MI);
00169 
00170   MCInst Inst;
00171   lowerToMCInst(MI, Inst);
00172   EmitToStreamer(OutStreamer, Inst);
00173 }
00174 
00175 // Handle symbol backtracking for targets that do not support image handles
00176 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
00177                                            unsigned OpNo, MCOperand &MCOp) {
00178   const MachineOperand &MO = MI->getOperand(OpNo);
00179   const MCInstrDesc &MCID = MI->getDesc();
00180 
00181   if (MCID.TSFlags & NVPTXII::IsTexFlag) {
00182     // This is a texture fetch, so operand 4 is a texref and operand 5 is
00183     // a samplerref
00184     if (OpNo == 4 && MO.isImm()) {
00185       lowerImageHandleSymbol(MO.getImm(), MCOp);
00186       return true;
00187     }
00188     if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
00189       lowerImageHandleSymbol(MO.getImm(), MCOp);
00190       return true;
00191     }
00192 
00193     return false;
00194   } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
00195     unsigned VecSize =
00196       1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
00197 
00198     // For a surface load of vector size N, the Nth operand will be the surfref
00199     if (OpNo == VecSize && MO.isImm()) {
00200       lowerImageHandleSymbol(MO.getImm(), MCOp);
00201       return true;
00202     }
00203 
00204     return false;
00205   } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
00206     // This is a surface store, so operand 0 is a surfref
00207     if (OpNo == 0 && MO.isImm()) {
00208       lowerImageHandleSymbol(MO.getImm(), MCOp);
00209       return true;
00210     }
00211 
00212     return false;
00213   } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
00214     // This is a query, so operand 1 is a surfref/texref
00215     if (OpNo == 1 && MO.isImm()) {
00216       lowerImageHandleSymbol(MO.getImm(), MCOp);
00217       return true;
00218     }
00219 
00220     return false;
00221   }
00222 
00223   return false;
00224 }
00225 
00226 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
00227   // Ewwww
00228   TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
00229   NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
00230   const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
00231   const char *Sym = MFI->getImageHandleSymbol(Index);
00232   std::string *SymNamePtr =
00233     nvTM.getManagedStrPool()->getManagedString(Sym);
00234   MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
00235     StringRef(SymNamePtr->c_str())));
00236 }
00237 
00238 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
00239   OutMI.setOpcode(MI->getOpcode());
00240   const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
00241 
00242   // Special: Do not mangle symbol operand of CALL_PROTOTYPE
00243   if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
00244     const MachineOperand &MO = MI->getOperand(0);
00245     OutMI.addOperand(GetSymbolRef(
00246       OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
00247     return;
00248   }
00249 
00250   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00251     const MachineOperand &MO = MI->getOperand(i);
00252 
00253     MCOperand MCOp;
00254     if (!ST.hasImageHandles()) {
00255       if (lowerImageHandleOperand(MI, i, MCOp)) {
00256         OutMI.addOperand(MCOp);
00257         continue;
00258       }
00259     }
00260 
00261     if (lowerOperand(MO, MCOp))
00262       OutMI.addOperand(MCOp);
00263   }
00264 }
00265 
00266 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
00267                                    MCOperand &MCOp) {
00268   switch (MO.getType()) {
00269   default: llvm_unreachable("unknown operand type");
00270   case MachineOperand::MO_Register:
00271     MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
00272     break;
00273   case MachineOperand::MO_Immediate:
00274     MCOp = MCOperand::CreateImm(MO.getImm());
00275     break;
00276   case MachineOperand::MO_MachineBasicBlock:
00277     MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
00278         MO.getMBB()->getSymbol(), OutContext));
00279     break;
00280   case MachineOperand::MO_ExternalSymbol:
00281     MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
00282     break;
00283   case MachineOperand::MO_GlobalAddress:
00284     MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
00285     break;
00286   case MachineOperand::MO_FPImmediate: {
00287     const ConstantFP *Cnt = MO.getFPImm();
00288     APFloat Val = Cnt->getValueAPF();
00289 
00290     switch (Cnt->getType()->getTypeID()) {
00291     default: report_fatal_error("Unsupported FP type"); break;
00292     case Type::FloatTyID:
00293       MCOp = MCOperand::CreateExpr(
00294         NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
00295       break;
00296     case Type::DoubleTyID:
00297       MCOp = MCOperand::CreateExpr(
00298         NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
00299       break;
00300     }
00301     break;
00302   }
00303   }
00304   return true;
00305 }
00306 
00307 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
00308   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00309     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00310 
00311     DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
00312     unsigned RegNum = RegMap[Reg];
00313 
00314     // Encode the register class in the upper 4 bits
00315     // Must be kept in sync with NVPTXInstPrinter::printRegName
00316     unsigned Ret = 0;
00317     if (RC == &NVPTX::Int1RegsRegClass) {
00318       Ret = (1 << 28);
00319     } else if (RC == &NVPTX::Int16RegsRegClass) {
00320       Ret = (2 << 28);
00321     } else if (RC == &NVPTX::Int32RegsRegClass) {
00322       Ret = (3 << 28);
00323     } else if (RC == &NVPTX::Int64RegsRegClass) {
00324       Ret = (4 << 28);
00325     } else if (RC == &NVPTX::Float32RegsRegClass) {
00326       Ret = (5 << 28);
00327     } else if (RC == &NVPTX::Float64RegsRegClass) {
00328       Ret = (6 << 28);
00329     } else {
00330       report_fatal_error("Bad register class");
00331     }
00332 
00333     // Insert the vreg number
00334     Ret |= (RegNum & 0x0FFFFFFF);
00335     return Ret;
00336   } else {
00337     // Some special-use registers are actually physical registers.
00338     // Encode this as the register class ID of 0 and the real register ID.
00339     return Reg & 0x0FFFFFFF;
00340   }
00341 }
00342 
00343 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
00344   const MCExpr *Expr;
00345   Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
00346                                  OutContext);
00347   return MCOperand::CreateExpr(Expr);
00348 }
00349 
00350 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
00351   const DataLayout *TD = TM.getDataLayout();
00352   const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
00353 
00354   Type *Ty = F->getReturnType();
00355 
00356   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
00357 
00358   if (Ty->getTypeID() == Type::VoidTyID)
00359     return;
00360 
00361   O << " (";
00362 
00363   if (isABI) {
00364     if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
00365       unsigned size = 0;
00366       if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
00367         size = ITy->getBitWidth();
00368         if (size < 32)
00369           size = 32;
00370       } else {
00371         assert(Ty->isFloatingPointTy() && "Floating point type expected here");
00372         size = Ty->getPrimitiveSizeInBits();
00373       }
00374 
00375       O << ".param .b" << size << " func_retval0";
00376     } else if (isa<PointerType>(Ty)) {
00377       O << ".param .b" << TLI->getPointerTy().getSizeInBits()
00378         << " func_retval0";
00379     } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
00380        unsigned totalsz = TD->getTypeAllocSize(Ty);
00381        unsigned retAlignment = 0;
00382        if (!llvm::getAlign(*F, 0, retAlignment))
00383          retAlignment = TD->getABITypeAlignment(Ty);
00384        O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
00385          << "]";
00386     } else
00387       llvm_unreachable("Unknown return type");
00388   } else {
00389     SmallVector<EVT, 16> vtparts;
00390     ComputeValueVTs(*TLI, Ty, vtparts);
00391     unsigned idx = 0;
00392     for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
00393       unsigned elems = 1;
00394       EVT elemtype = vtparts[i];
00395       if (vtparts[i].isVector()) {
00396         elems = vtparts[i].getVectorNumElements();
00397         elemtype = vtparts[i].getVectorElementType();
00398       }
00399 
00400       for (unsigned j = 0, je = elems; j != je; ++j) {
00401         unsigned sz = elemtype.getSizeInBits();
00402         if (elemtype.isInteger() && (sz < 32))
00403           sz = 32;
00404         O << ".reg .b" << sz << " func_retval" << idx;
00405         if (j < je - 1)
00406           O << ", ";
00407         ++idx;
00408       }
00409       if (i < e - 1)
00410         O << ", ";
00411     }
00412   }
00413   O << ") ";
00414   return;
00415 }
00416 
00417 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
00418                                         raw_ostream &O) {
00419   const Function *F = MF.getFunction();
00420   printReturnValStr(F, O);
00421 }
00422 
00423 // Return true if MBB is the header of a loop marked with
00424 // llvm.loop.unroll.disable.
00425 // TODO(jingyue): consider "#pragma unroll 1" which is equivalent to "#pragma
00426 // nounroll".
00427 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
00428     const MachineBasicBlock &MBB) const {
00429   MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
00430   // TODO(jingyue): isLoopHeader() should take "const MachineBasicBlock *".
00431   // We insert .pragma "nounroll" only to the loop header.
00432   if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
00433     return false;
00434 
00435   // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
00436   // we iterate through each back edge of the loop with header MBB, and check
00437   // whether its metadata contains llvm.loop.unroll.disable.
00438   for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
00439     const MachineBasicBlock *PMBB = *I;
00440     if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
00441       // Edges from other loops to MBB are not back edges.
00442       continue;
00443     }
00444     if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
00445       if (const MDNode *LoopID =
00446               PBB->getTerminator()->getMetadata("llvm.loop")) {
00447         if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
00448           return true;
00449       }
00450     }
00451   }
00452   return false;
00453 }
00454 
00455 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
00456   AsmPrinter::EmitBasicBlockStart(MBB);
00457   if (isLoopHeaderOfNoUnroll(MBB))
00458     OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
00459 }
00460 
00461 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
00462   SmallString<128> Str;
00463   raw_svector_ostream O(Str);
00464 
00465   if (!GlobalsEmitted) {
00466     emitGlobals(*MF->getFunction()->getParent());
00467     GlobalsEmitted = true;
00468   }
00469   
00470   // Set up
00471   MRI = &MF->getRegInfo();
00472   F = MF->getFunction();
00473   emitLinkageDirective(F, O);
00474   if (llvm::isKernelFunction(*F))
00475     O << ".entry ";
00476   else {
00477     O << ".func ";
00478     printReturnValStr(*MF, O);
00479   }
00480 
00481   O << *CurrentFnSym;
00482 
00483   emitFunctionParamList(*MF, O);
00484 
00485   if (llvm::isKernelFunction(*F))
00486     emitKernelFunctionDirectives(*F, O);
00487 
00488   OutStreamer.EmitRawText(O.str());
00489 
00490   prevDebugLoc = DebugLoc();
00491 }
00492 
00493 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
00494   VRegMapping.clear();
00495   OutStreamer.EmitRawText(StringRef("{\n"));
00496   setAndEmitFunctionVirtualRegisters(*MF);
00497 
00498   SmallString<128> Str;
00499   raw_svector_ostream O(Str);
00500   emitDemotedVars(MF->getFunction(), O);
00501   OutStreamer.EmitRawText(O.str());
00502 }
00503 
00504 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
00505   OutStreamer.EmitRawText(StringRef("}\n"));
00506   VRegMapping.clear();
00507 }
00508 
00509 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00510   unsigned RegNo = MI->getOperand(0).getReg();
00511   const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
00512   if (TRI->isVirtualRegister(RegNo)) {
00513     OutStreamer.AddComment(Twine("implicit-def: ") +
00514                            getVirtualRegisterName(RegNo));
00515   } else {
00516     OutStreamer.AddComment(
00517         Twine("implicit-def: ") +
00518         TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
00519   }
00520   OutStreamer.AddBlankLine();
00521 }
00522 
00523 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
00524                                                    raw_ostream &O) const {
00525   // If the NVVM IR has some of reqntid* specified, then output
00526   // the reqntid directive, and set the unspecified ones to 1.
00527   // If none of reqntid* is specified, don't output reqntid directive.
00528   unsigned reqntidx, reqntidy, reqntidz;
00529   bool specified = false;
00530   if (llvm::getReqNTIDx(F, reqntidx) == false)
00531     reqntidx = 1;
00532   else
00533     specified = true;
00534   if (llvm::getReqNTIDy(F, reqntidy) == false)
00535     reqntidy = 1;
00536   else
00537     specified = true;
00538   if (llvm::getReqNTIDz(F, reqntidz) == false)
00539     reqntidz = 1;
00540   else
00541     specified = true;
00542 
00543   if (specified)
00544     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
00545       << "\n";
00546 
00547   // If the NVVM IR has some of maxntid* specified, then output
00548   // the maxntid directive, and set the unspecified ones to 1.
00549   // If none of maxntid* is specified, don't output maxntid directive.
00550   unsigned maxntidx, maxntidy, maxntidz;
00551   specified = false;
00552   if (llvm::getMaxNTIDx(F, maxntidx) == false)
00553     maxntidx = 1;
00554   else
00555     specified = true;
00556   if (llvm::getMaxNTIDy(F, maxntidy) == false)
00557     maxntidy = 1;
00558   else
00559     specified = true;
00560   if (llvm::getMaxNTIDz(F, maxntidz) == false)
00561     maxntidz = 1;
00562   else
00563     specified = true;
00564 
00565   if (specified)
00566     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
00567       << "\n";
00568 
00569   unsigned mincta;
00570   if (llvm::getMinCTASm(F, mincta))
00571     O << ".minnctapersm " << mincta << "\n";
00572 }
00573 
00574 std::string
00575 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
00576   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00577 
00578   std::string Name;
00579   raw_string_ostream NameStr(Name);
00580 
00581   VRegRCMap::const_iterator I = VRegMapping.find(RC);
00582   assert(I != VRegMapping.end() && "Bad register class");
00583   const DenseMap<unsigned, unsigned> &RegMap = I->second;
00584 
00585   VRegMap::const_iterator VI = RegMap.find(Reg);
00586   assert(VI != RegMap.end() && "Bad virtual register");
00587   unsigned MappedVR = VI->second;
00588 
00589   NameStr << getNVPTXRegClassStr(RC) << MappedVR;
00590 
00591   NameStr.flush();
00592   return Name;
00593 }
00594 
00595 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
00596                                           raw_ostream &O) {
00597   O << getVirtualRegisterName(vr);
00598 }
00599 
00600 void NVPTXAsmPrinter::printVecModifiedImmediate(
00601     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
00602   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
00603   int Imm = (int) MO.getImm();
00604   if (0 == strcmp(Modifier, "vecelem"))
00605     O << "_" << vecelem[Imm];
00606   else if (0 == strcmp(Modifier, "vecv4comm1")) {
00607     if ((Imm < 0) || (Imm > 3))
00608       O << "//";
00609   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
00610     if ((Imm < 4) || (Imm > 7))
00611       O << "//";
00612   } else if (0 == strcmp(Modifier, "vecv4pos")) {
00613     if (Imm < 0)
00614       Imm = 0;
00615     O << "_" << vecelem[Imm % 4];
00616   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
00617     if ((Imm < 0) || (Imm > 1))
00618       O << "//";
00619   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
00620     if ((Imm < 2) || (Imm > 3))
00621       O << "//";
00622   } else if (0 == strcmp(Modifier, "vecv2pos")) {
00623     if (Imm < 0)
00624       Imm = 0;
00625     O << "_" << vecelem[Imm % 2];
00626   } else
00627     llvm_unreachable("Unknown Modifier on immediate operand");
00628 }
00629 
00630 
00631 
00632 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
00633 
00634   emitLinkageDirective(F, O);
00635   if (llvm::isKernelFunction(*F))
00636     O << ".entry ";
00637   else
00638     O << ".func ";
00639   printReturnValStr(F, O);
00640   O << *getSymbol(F) << "\n";
00641   emitFunctionParamList(F, O);
00642   O << ";\n";
00643 }
00644 
00645 static bool usedInGlobalVarDef(const Constant *C) {
00646   if (!C)
00647     return false;
00648 
00649   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00650     if (GV->getName().str() == "llvm.used")
00651       return false;
00652     return true;
00653   }
00654 
00655   for (const User *U : C->users())
00656     if (const Constant *C = dyn_cast<Constant>(U))
00657       if (usedInGlobalVarDef(C))
00658         return true;
00659 
00660   return false;
00661 }
00662 
00663 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
00664   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
00665     if (othergv->getName().str() == "llvm.used")
00666       return true;
00667   }
00668 
00669   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
00670     if (instr->getParent() && instr->getParent()->getParent()) {
00671       const Function *curFunc = instr->getParent()->getParent();
00672       if (oneFunc && (curFunc != oneFunc))
00673         return false;
00674       oneFunc = curFunc;
00675       return true;
00676     } else
00677       return false;
00678   }
00679 
00680   for (const User *UU : U->users())
00681     if (usedInOneFunc(UU, oneFunc) == false)
00682       return false;
00683 
00684   return true;
00685 }
00686 
00687 /* Find out if a global variable can be demoted to local scope.
00688  * Currently, this is valid for CUDA shared variables, which have local
00689  * scope and global lifetime. So the conditions to check are :
00690  * 1. Is the global variable in shared address space?
00691  * 2. Does it have internal linkage?
00692  * 3. Is the global variable referenced only in one function?
00693  */
00694 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
00695   if (gv->hasInternalLinkage() == false)
00696     return false;
00697   const PointerType *Pty = gv->getType();
00698   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
00699     return false;
00700 
00701   const Function *oneFunc = nullptr;
00702 
00703   bool flag = usedInOneFunc(gv, oneFunc);
00704   if (flag == false)
00705     return false;
00706   if (!oneFunc)
00707     return false;
00708   f = oneFunc;
00709   return true;
00710 }
00711 
00712 static bool useFuncSeen(const Constant *C,
00713                         llvm::DenseMap<const Function *, bool> &seenMap) {
00714   for (const User *U : C->users()) {
00715     if (const Constant *cu = dyn_cast<Constant>(U)) {
00716       if (useFuncSeen(cu, seenMap))
00717         return true;
00718     } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
00719       const BasicBlock *bb = I->getParent();
00720       if (!bb)
00721         continue;
00722       const Function *caller = bb->getParent();
00723       if (!caller)
00724         continue;
00725       if (seenMap.find(caller) != seenMap.end())
00726         return true;
00727     }
00728   }
00729   return false;
00730 }
00731 
00732 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
00733   llvm::DenseMap<const Function *, bool> seenMap;
00734   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
00735     const Function *F = FI;
00736 
00737     if (F->isDeclaration()) {
00738       if (F->use_empty())
00739         continue;
00740       if (F->getIntrinsicID())
00741         continue;
00742       emitDeclaration(F, O);
00743       continue;
00744     }
00745     for (const User *U : F->users()) {
00746       if (const Constant *C = dyn_cast<Constant>(U)) {
00747         if (usedInGlobalVarDef(C)) {
00748           // The use is in the initialization of a global variable
00749           // that is a function pointer, so print a declaration
00750           // for the original function
00751           emitDeclaration(F, O);
00752           break;
00753         }
00754         // Emit a declaration of this function if the function that
00755         // uses this constant expr has already been seen.
00756         if (useFuncSeen(C, seenMap)) {
00757           emitDeclaration(F, O);
00758           break;
00759         }
00760       }
00761 
00762       if (!isa<Instruction>(U))
00763         continue;
00764       const Instruction *instr = cast<Instruction>(U);
00765       const BasicBlock *bb = instr->getParent();
00766       if (!bb)
00767         continue;
00768       const Function *caller = bb->getParent();
00769       if (!caller)
00770         continue;
00771 
00772       // If a caller has already been seen, then the caller is
00773       // appearing in the module before the callee. so print out
00774       // a declaration for the callee.
00775       if (seenMap.find(caller) != seenMap.end()) {
00776         emitDeclaration(F, O);
00777         break;
00778       }
00779     }
00780     seenMap[F] = true;
00781   }
00782 }
00783 
00784 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
00785   DebugInfoFinder DbgFinder;
00786   DbgFinder.processModule(M);
00787 
00788   unsigned i = 1;
00789   for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
00790     StringRef Filename(DIUnit.getFilename());
00791     StringRef Dirname(DIUnit.getDirectory());
00792     SmallString<128> FullPathName = Dirname;
00793     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
00794       sys::path::append(FullPathName, Filename);
00795       Filename = FullPathName.str();
00796     }
00797     if (filenameMap.find(Filename.str()) != filenameMap.end())
00798       continue;
00799     filenameMap[Filename.str()] = i;
00800     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
00801     ++i;
00802   }
00803 
00804   for (DISubprogram SP : DbgFinder.subprograms()) {
00805     StringRef Filename(SP.getFilename());
00806     StringRef Dirname(SP.getDirectory());
00807     SmallString<128> FullPathName = Dirname;
00808     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
00809       sys::path::append(FullPathName, Filename);
00810       Filename = FullPathName.str();
00811     }
00812     if (filenameMap.find(Filename.str()) != filenameMap.end())
00813       continue;
00814     filenameMap[Filename.str()] = i;
00815     ++i;
00816   }
00817 }
00818 
00819 bool NVPTXAsmPrinter::doInitialization(Module &M) {
00820 
00821   SmallString<128> Str1;
00822   raw_svector_ostream OS1(Str1);
00823 
00824   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
00825   MMI->AnalyzeModule(M);
00826 
00827   // We need to call the parent's one explicitly.
00828   //bool Result = AsmPrinter::doInitialization(M);
00829 
00830   // Initialize TargetLoweringObjectFile.
00831   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
00832       .Initialize(OutContext, TM);
00833 
00834   Mang = new Mangler(TM.getDataLayout());
00835 
00836   // Emit header before any dwarf directives are emitted below.
00837   emitHeader(M, OS1);
00838   OutStreamer.EmitRawText(OS1.str());
00839 
00840   // Already commented out
00841   //bool Result = AsmPrinter::doInitialization(M);
00842 
00843   // Emit module-level inline asm if it exists.
00844   if (!M.getModuleInlineAsm().empty()) {
00845     OutStreamer.AddComment("Start of file scope inline assembly");
00846     OutStreamer.AddBlankLine();
00847     OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
00848     OutStreamer.AddBlankLine();
00849     OutStreamer.AddComment("End of file scope inline assembly");
00850     OutStreamer.AddBlankLine();
00851   }
00852 
00853   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
00854     recordAndEmitFilenames(M);
00855 
00856   GlobalsEmitted = false;
00857     
00858   return false; // success
00859 }
00860 
00861 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
00862   SmallString<128> Str2;
00863   raw_svector_ostream OS2(Str2);
00864 
00865   emitDeclarations(M, OS2);
00866 
00867   // As ptxas does not support forward references of globals, we need to first
00868   // sort the list of module-level globals in def-use order. We visit each
00869   // global variable in order, and ensure that we emit it *after* its dependent
00870   // globals. We use a little extra memory maintaining both a set and a list to
00871   // have fast searches while maintaining a strict ordering.
00872   SmallVector<const GlobalVariable *, 8> Globals;
00873   DenseSet<const GlobalVariable *> GVVisited;
00874   DenseSet<const GlobalVariable *> GVVisiting;
00875 
00876   // Visit each global variable, in order
00877   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00878        I != E; ++I)
00879     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
00880 
00881   assert(GVVisited.size() == M.getGlobalList().size() &&
00882          "Missed a global variable");
00883   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
00884 
00885   // Print out module-level global variables in proper order
00886   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
00887     printModuleLevelGV(Globals[i], OS2);
00888 
00889   OS2 << '\n';
00890 
00891   OutStreamer.EmitRawText(OS2.str());
00892 }
00893 
00894 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
00895   O << "//\n";
00896   O << "// Generated by LLVM NVPTX Back-End\n";
00897   O << "//\n";
00898   O << "\n";
00899 
00900   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
00901   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
00902 
00903   O << ".target ";
00904   O << nvptxSubtarget.getTargetName();
00905 
00906   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
00907     O << ", texmode_independent";
00908   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
00909     if (!nvptxSubtarget.hasDouble())
00910       O << ", map_f64_to_f32";
00911   }
00912 
00913   if (MAI->doesSupportDebugInformation())
00914     O << ", debug";
00915 
00916   O << "\n";
00917 
00918   O << ".address_size ";
00919   if (nvptxSubtarget.is64Bit())
00920     O << "64";
00921   else
00922     O << "32";
00923   O << "\n";
00924 
00925   O << "\n";
00926 }
00927 
00928 bool NVPTXAsmPrinter::doFinalization(Module &M) {
00929 
00930   // If we did not emit any functions, then the global declarations have not
00931   // yet been emitted.
00932   if (!GlobalsEmitted) {
00933     emitGlobals(M);
00934     GlobalsEmitted = true;
00935   }
00936 
00937   // XXX Temproarily remove global variables so that doFinalization() will not
00938   // emit them again (global variables are emitted at beginning).
00939 
00940   Module::GlobalListType &global_list = M.getGlobalList();
00941   int i, n = global_list.size();
00942   GlobalVariable **gv_array = new GlobalVariable *[n];
00943 
00944   // first, back-up GlobalVariable in gv_array
00945   i = 0;
00946   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
00947        I != E; ++I)
00948     gv_array[i++] = &*I;
00949 
00950   // second, empty global_list
00951   while (!global_list.empty())
00952     global_list.remove(global_list.begin());
00953 
00954   // call doFinalization
00955   bool ret = AsmPrinter::doFinalization(M);
00956 
00957   // now we restore global variables
00958   for (i = 0; i < n; i++)
00959     global_list.insert(global_list.end(), gv_array[i]);
00960 
00961   clearAnnotationCache(&M);
00962 
00963   delete[] gv_array;
00964   return ret;
00965 
00966   //bool Result = AsmPrinter::doFinalization(M);
00967   // Instead of calling the parents doFinalization, we may
00968   // clone parents doFinalization and customize here.
00969   // Currently, we if NVISA out the EmitGlobals() in
00970   // parent's doFinalization, which is too intrusive.
00971   //
00972   // Same for the doInitialization.
00973   //return Result;
00974 }
00975 
00976 // This function emits appropriate linkage directives for
00977 // functions and global variables.
00978 //
00979 // extern function declaration            -> .extern
00980 // extern function definition             -> .visible
00981 // external global variable with init     -> .visible
00982 // external without init                  -> .extern
00983 // appending                              -> not allowed, assert.
00984 // for any linkage other than
00985 // internal, private, linker_private,
00986 // linker_private_weak, linker_private_weak_def_auto,
00987 // we emit                                -> .weak.
00988 
00989 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
00990                                            raw_ostream &O) {
00991   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
00992     if (V->hasExternalLinkage()) {
00993       if (isa<GlobalVariable>(V)) {
00994         const GlobalVariable *GVar = cast<GlobalVariable>(V);
00995         if (GVar) {
00996           if (GVar->hasInitializer())
00997             O << ".visible ";
00998           else
00999             O << ".extern ";
01000         }
01001       } else if (V->isDeclaration())
01002         O << ".extern ";
01003       else
01004         O << ".visible ";
01005     } else if (V->hasAppendingLinkage()) {
01006       std::string msg;
01007       msg.append("Error: ");
01008       msg.append("Symbol ");
01009       if (V->hasName())
01010         msg.append(V->getName().str());
01011       msg.append("has unsupported appending linkage type");
01012       llvm_unreachable(msg.c_str());
01013     } else if (!V->hasInternalLinkage() &&
01014                !V->hasPrivateLinkage()) {
01015       O << ".weak ";
01016     }
01017   }
01018 }
01019 
01020 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
01021                                          raw_ostream &O,
01022                                          bool processDemoted) {
01023 
01024   // Skip meta data
01025   if (GVar->hasSection()) {
01026     if (GVar->getSection() == StringRef("llvm.metadata"))
01027       return;
01028   }
01029 
01030   // Skip LLVM intrinsic global variables
01031   if (GVar->getName().startswith("llvm.") ||
01032       GVar->getName().startswith("nvvm."))
01033     return;
01034 
01035   const DataLayout *TD = TM.getDataLayout();
01036 
01037   // GlobalVariables are always constant pointers themselves.
01038   const PointerType *PTy = GVar->getType();
01039   Type *ETy = PTy->getElementType();
01040 
01041   if (GVar->hasExternalLinkage()) {
01042     if (GVar->hasInitializer())
01043       O << ".visible ";
01044     else
01045       O << ".extern ";
01046   } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
01047              GVar->hasAvailableExternallyLinkage() ||
01048              GVar->hasCommonLinkage()) {
01049     O << ".weak ";
01050   }
01051 
01052   if (llvm::isTexture(*GVar)) {
01053     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
01054     return;
01055   }
01056 
01057   if (llvm::isSurface(*GVar)) {
01058     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
01059     return;
01060   }
01061 
01062   if (GVar->isDeclaration()) {
01063     // (extern) declarations, no definition or initializer
01064     // Currently the only known declaration is for an automatic __local
01065     // (.shared) promoted to global.
01066     emitPTXGlobalVariable(GVar, O);
01067     O << ";\n";
01068     return;
01069   }
01070 
01071   if (llvm::isSampler(*GVar)) {
01072     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
01073 
01074     const Constant *Initializer = nullptr;
01075     if (GVar->hasInitializer())
01076       Initializer = GVar->getInitializer();
01077     const ConstantInt *CI = nullptr;
01078     if (Initializer)
01079       CI = dyn_cast<ConstantInt>(Initializer);
01080     if (CI) {
01081       unsigned sample = CI->getZExtValue();
01082 
01083       O << " = { ";
01084 
01085       for (int i = 0,
01086                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
01087            i < 3; i++) {
01088         O << "addr_mode_" << i << " = ";
01089         switch (addr) {
01090         case 0:
01091           O << "wrap";
01092           break;
01093         case 1:
01094           O << "clamp_to_border";
01095           break;
01096         case 2:
01097           O << "clamp_to_edge";
01098           break;
01099         case 3:
01100           O << "wrap";
01101           break;
01102         case 4:
01103           O << "mirror";
01104           break;
01105         }
01106         O << ", ";
01107       }
01108       O << "filter_mode = ";
01109       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
01110       case 0:
01111         O << "nearest";
01112         break;
01113       case 1:
01114         O << "linear";
01115         break;
01116       case 2:
01117         llvm_unreachable("Anisotropic filtering is not supported");
01118       default:
01119         O << "nearest";
01120         break;
01121       }
01122       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
01123         O << ", force_unnormalized_coords = 1";
01124       }
01125       O << " }";
01126     }
01127 
01128     O << ";\n";
01129     return;
01130   }
01131 
01132   if (GVar->hasPrivateLinkage()) {
01133 
01134     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
01135       return;
01136 
01137     // FIXME - need better way (e.g. Metadata) to avoid generating this global
01138     if (!strncmp(GVar->getName().data(), "filename", 8))
01139       return;
01140     if (GVar->use_empty())
01141       return;
01142   }
01143 
01144   const Function *demotedFunc = nullptr;
01145   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
01146     O << "// " << GVar->getName().str() << " has been demoted\n";
01147     if (localDecls.find(demotedFunc) != localDecls.end())
01148       localDecls[demotedFunc].push_back(GVar);
01149     else {
01150       std::vector<const GlobalVariable *> temp;
01151       temp.push_back(GVar);
01152       localDecls[demotedFunc] = temp;
01153     }
01154     return;
01155   }
01156 
01157   O << ".";
01158   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01159 
01160   if (isManaged(*GVar)) {
01161     O << " .attribute(.managed)";
01162   }
01163 
01164   if (GVar->getAlignment() == 0)
01165     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01166   else
01167     O << " .align " << GVar->getAlignment();
01168 
01169   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
01170     O << " .";
01171     // Special case: ABI requires that we use .u8 for predicates
01172     if (ETy->isIntegerTy(1))
01173       O << "u8";
01174     else
01175       O << getPTXFundamentalTypeStr(ETy, false);
01176     O << " ";
01177     O << *getSymbol(GVar);
01178 
01179     // Ptx allows variable initilization only for constant and global state
01180     // spaces.
01181     if (GVar->hasInitializer()) {
01182       if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01183           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
01184         const Constant *Initializer = GVar->getInitializer();
01185         // 'undef' is treated as there is no value spefied.
01186         if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
01187           O << " = ";
01188           printScalarConstant(Initializer, O);
01189         }
01190       } else {
01191         // The frontend adds zero-initializer to variables that don't have an
01192         // initial value, so skip warning for this case.
01193         if (!GVar->getInitializer()->isNullValue()) {
01194           std::string warnMsg = "initial value of '" + GVar->getName().str() +
01195               "' is not allowed in addrspace(" +
01196               llvm::utostr_32(PTy->getAddressSpace()) + ")";
01197           report_fatal_error(warnMsg.c_str());
01198         }
01199       }
01200     }
01201   } else {
01202     unsigned int ElementSize = 0;
01203 
01204     // Although PTX has direct support for struct type and array type and
01205     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
01206     // targets that support these high level field accesses. Structs, arrays
01207     // and vectors are lowered into arrays of bytes.
01208     switch (ETy->getTypeID()) {
01209     case Type::StructTyID:
01210     case Type::ArrayTyID:
01211     case Type::VectorTyID:
01212       ElementSize = TD->getTypeStoreSize(ETy);
01213       // Ptx allows variable initilization only for constant and
01214       // global state spaces.
01215       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01216            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
01217           GVar->hasInitializer()) {
01218         const Constant *Initializer = GVar->getInitializer();
01219         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
01220           AggBuffer aggBuffer(ElementSize, O, *this);
01221           bufferAggregateConstant(Initializer, &aggBuffer);
01222           if (aggBuffer.numSymbols) {
01223             if (nvptxSubtarget.is64Bit()) {
01224               O << " .u64 " << *getSymbol(GVar) << "[";
01225               O << ElementSize / 8;
01226             } else {
01227               O << " .u32 " << *getSymbol(GVar) << "[";
01228               O << ElementSize / 4;
01229             }
01230             O << "]";
01231           } else {
01232             O << " .b8 " << *getSymbol(GVar) << "[";
01233             O << ElementSize;
01234             O << "]";
01235           }
01236           O << " = {";
01237           aggBuffer.print();
01238           O << "}";
01239         } else {
01240           O << " .b8 " << *getSymbol(GVar);
01241           if (ElementSize) {
01242             O << "[";
01243             O << ElementSize;
01244             O << "]";
01245           }
01246         }
01247       } else {
01248         O << " .b8 " << *getSymbol(GVar);
01249         if (ElementSize) {
01250           O << "[";
01251           O << ElementSize;
01252           O << "]";
01253         }
01254       }
01255       break;
01256     default:
01257       llvm_unreachable("type not supported yet");
01258     }
01259 
01260   }
01261   O << ";\n";
01262 }
01263 
01264 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
01265   if (localDecls.find(f) == localDecls.end())
01266     return;
01267 
01268   std::vector<const GlobalVariable *> &gvars = localDecls[f];
01269 
01270   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
01271     O << "\t// demoted variable\n\t";
01272     printModuleLevelGV(gvars[i], O, true);
01273   }
01274 }
01275 
01276 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
01277                                           raw_ostream &O) const {
01278   switch (AddressSpace) {
01279   case llvm::ADDRESS_SPACE_LOCAL:
01280     O << "local";
01281     break;
01282   case llvm::ADDRESS_SPACE_GLOBAL:
01283     O << "global";
01284     break;
01285   case llvm::ADDRESS_SPACE_CONST:
01286     O << "const";
01287     break;
01288   case llvm::ADDRESS_SPACE_SHARED:
01289     O << "shared";
01290     break;
01291   default:
01292     report_fatal_error("Bad address space found while emitting PTX");
01293     break;
01294   }
01295 }
01296 
01297 std::string
01298 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
01299   switch (Ty->getTypeID()) {
01300   default:
01301     llvm_unreachable("unexpected type");
01302     break;
01303   case Type::IntegerTyID: {
01304     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
01305     if (NumBits == 1)
01306       return "pred";
01307     else if (NumBits <= 64) {
01308       std::string name = "u";
01309       return name + utostr(NumBits);
01310     } else {
01311       llvm_unreachable("Integer too large");
01312       break;
01313     }
01314     break;
01315   }
01316   case Type::FloatTyID:
01317     return "f32";
01318   case Type::DoubleTyID:
01319     return "f64";
01320   case Type::PointerTyID:
01321     if (nvptxSubtarget.is64Bit())
01322       if (useB4PTR)
01323         return "b64";
01324       else
01325         return "u64";
01326     else if (useB4PTR)
01327       return "b32";
01328     else
01329       return "u32";
01330   }
01331   llvm_unreachable("unexpected type");
01332   return nullptr;
01333 }
01334 
01335 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
01336                                             raw_ostream &O) {
01337 
01338   const DataLayout *TD = TM.getDataLayout();
01339 
01340   // GlobalVariables are always constant pointers themselves.
01341   const PointerType *PTy = GVar->getType();
01342   Type *ETy = PTy->getElementType();
01343 
01344   O << ".";
01345   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01346   if (GVar->getAlignment() == 0)
01347     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01348   else
01349     O << " .align " << GVar->getAlignment();
01350 
01351   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
01352     O << " .";
01353     O << getPTXFundamentalTypeStr(ETy);
01354     O << " ";
01355     O << *getSymbol(GVar);
01356     return;
01357   }
01358 
01359   int64_t ElementSize = 0;
01360 
01361   // Although PTX has direct support for struct type and array type and LLVM IR
01362   // is very similar to PTX, the LLVM CodeGen does not support for targets that
01363   // support these high level field accesses. Structs and arrays are lowered
01364   // into arrays of bytes.
01365   switch (ETy->getTypeID()) {
01366   case Type::StructTyID:
01367   case Type::ArrayTyID:
01368   case Type::VectorTyID:
01369     ElementSize = TD->getTypeStoreSize(ETy);
01370     O << " .b8 " << *getSymbol(GVar) << "[";
01371     if (ElementSize) {
01372       O << itostr(ElementSize);
01373     }
01374     O << "]";
01375     break;
01376   default:
01377     llvm_unreachable("type not supported yet");
01378   }
01379   return;
01380 }
01381 
01382 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
01383   if (Ty->isSingleValueType())
01384     return TD->getPrefTypeAlignment(Ty);
01385 
01386   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
01387   if (ATy)
01388     return getOpenCLAlignment(TD, ATy->getElementType());
01389 
01390   const StructType *STy = dyn_cast<StructType>(Ty);
01391   if (STy) {
01392     unsigned int alignStruct = 1;
01393     // Go through each element of the struct and find the
01394     // largest alignment.
01395     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
01396       Type *ETy = STy->getElementType(i);
01397       unsigned int align = getOpenCLAlignment(TD, ETy);
01398       if (align > alignStruct)
01399         alignStruct = align;
01400     }
01401     return alignStruct;
01402   }
01403 
01404   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
01405   if (FTy)
01406     return TD->getPointerPrefAlignment();
01407   return TD->getPrefTypeAlignment(Ty);
01408 }
01409 
01410 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
01411                                      int paramIndex, raw_ostream &O) {
01412   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
01413       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
01414     O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
01415   else {
01416     std::string argName = I->getName();
01417     const char *p = argName.c_str();
01418     while (*p) {
01419       if (*p == '.')
01420         O << "_";
01421       else
01422         O << *p;
01423       p++;
01424     }
01425   }
01426 }
01427 
01428 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
01429   Function::const_arg_iterator I, E;
01430   int i = 0;
01431 
01432   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
01433       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
01434     O << *CurrentFnSym << "_param_" << paramIndex;
01435     return;
01436   }
01437 
01438   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
01439     if (i == paramIndex) {
01440       printParamName(I, paramIndex, O);
01441       return;
01442     }
01443   }
01444   llvm_unreachable("paramIndex out of bound");
01445 }
01446 
01447 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
01448   const DataLayout *TD = TM.getDataLayout();
01449   const AttributeSet &PAL = F->getAttributes();
01450   const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
01451   Function::const_arg_iterator I, E;
01452   unsigned paramIndex = 0;
01453   bool first = true;
01454   bool isKernelFunc = llvm::isKernelFunction(*F);
01455   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
01456   MVT thePointerTy = TLI->getPointerTy();
01457 
01458   O << "(\n";
01459 
01460   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
01461     Type *Ty = I->getType();
01462 
01463     if (!first)
01464       O << ",\n";
01465 
01466     first = false;
01467 
01468     // Handle image/sampler parameters
01469     if (isKernelFunction(*F)) {
01470       if (isSampler(*I) || isImage(*I)) {
01471         if (isImage(*I)) {
01472           std::string sname = I->getName();
01473           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
01474             if (nvptxSubtarget.hasImageHandles())
01475               O << "\t.param .u64 .ptr .surfref ";
01476             else
01477               O << "\t.param .surfref ";
01478             O << *CurrentFnSym << "_param_" << paramIndex;
01479           }
01480           else { // Default image is read_only
01481             if (nvptxSubtarget.hasImageHandles())
01482               O << "\t.param .u64 .ptr .texref ";
01483             else
01484               O << "\t.param .texref ";
01485             O << *CurrentFnSym << "_param_" << paramIndex;
01486           }
01487         } else {
01488           if (nvptxSubtarget.hasImageHandles())
01489             O << "\t.param .u64 .ptr .samplerref ";
01490           else
01491             O << "\t.param .samplerref ";
01492           O << *CurrentFnSym << "_param_" << paramIndex;
01493         }
01494         continue;
01495       }
01496     }
01497 
01498     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
01499       if (Ty->isAggregateType() || Ty->isVectorTy()) {
01500         // Just print .param .align <a> .b8 .param[size];
01501         // <a> = PAL.getparamalignment
01502         // size = typeallocsize of element type
01503         unsigned align = PAL.getParamAlignment(paramIndex + 1);
01504         if (align == 0)
01505           align = TD->getABITypeAlignment(Ty);
01506 
01507         unsigned sz = TD->getTypeAllocSize(Ty);
01508         O << "\t.param .align " << align << " .b8 ";
01509         printParamName(I, paramIndex, O);
01510         O << "[" << sz << "]";
01511 
01512         continue;
01513       }
01514       // Just a scalar
01515       const PointerType *PTy = dyn_cast<PointerType>(Ty);
01516       if (isKernelFunc) {
01517         if (PTy) {
01518           // Special handling for pointer arguments to kernel
01519           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
01520 
01521           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
01522             Type *ETy = PTy->getElementType();
01523             int addrSpace = PTy->getAddressSpace();
01524             switch (addrSpace) {
01525             default:
01526               O << ".ptr ";
01527               break;
01528             case llvm::ADDRESS_SPACE_CONST:
01529               O << ".ptr .const ";
01530               break;
01531             case llvm::ADDRESS_SPACE_SHARED:
01532               O << ".ptr .shared ";
01533               break;
01534             case llvm::ADDRESS_SPACE_GLOBAL:
01535               O << ".ptr .global ";
01536               break;
01537             }
01538             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
01539           }
01540           printParamName(I, paramIndex, O);
01541           continue;
01542         }
01543 
01544         // non-pointer scalar to kernel func
01545         O << "\t.param .";
01546         // Special case: predicate operands become .u8 types
01547         if (Ty->isIntegerTy(1))
01548           O << "u8";
01549         else
01550           O << getPTXFundamentalTypeStr(Ty);
01551         O << " ";
01552         printParamName(I, paramIndex, O);
01553         continue;
01554       }
01555       // Non-kernel function, just print .param .b<size> for ABI
01556       // and .reg .b<size> for non-ABI
01557       unsigned sz = 0;
01558       if (isa<IntegerType>(Ty)) {
01559         sz = cast<IntegerType>(Ty)->getBitWidth();
01560         if (sz < 32)
01561           sz = 32;
01562       } else if (isa<PointerType>(Ty))
01563         sz = thePointerTy.getSizeInBits();
01564       else
01565         sz = Ty->getPrimitiveSizeInBits();
01566       if (isABI)
01567         O << "\t.param .b" << sz << " ";
01568       else
01569         O << "\t.reg .b" << sz << " ";
01570       printParamName(I, paramIndex, O);
01571       continue;
01572     }
01573 
01574     // param has byVal attribute. So should be a pointer
01575     const PointerType *PTy = dyn_cast<PointerType>(Ty);
01576     assert(PTy && "Param with byval attribute should be a pointer type");
01577     Type *ETy = PTy->getElementType();
01578 
01579     if (isABI || isKernelFunc) {
01580       // Just print .param .align <a> .b8 .param[size];
01581       // <a> = PAL.getparamalignment
01582       // size = typeallocsize of element type
01583       unsigned align = PAL.getParamAlignment(paramIndex + 1);
01584       if (align == 0)
01585         align = TD->getABITypeAlignment(ETy);
01586 
01587       unsigned sz = TD->getTypeAllocSize(ETy);
01588       O << "\t.param .align " << align << " .b8 ";
01589       printParamName(I, paramIndex, O);
01590       O << "[" << sz << "]";
01591       continue;
01592     } else {
01593       // Split the ETy into constituent parts and
01594       // print .param .b<size> <name> for each part.
01595       // Further, if a part is vector, print the above for
01596       // each vector element.
01597       SmallVector<EVT, 16> vtparts;
01598       ComputeValueVTs(*TLI, ETy, vtparts);
01599       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
01600         unsigned elems = 1;
01601         EVT elemtype = vtparts[i];
01602         if (vtparts[i].isVector()) {
01603           elems = vtparts[i].getVectorNumElements();
01604           elemtype = vtparts[i].getVectorElementType();
01605         }
01606 
01607         for (unsigned j = 0, je = elems; j != je; ++j) {
01608           unsigned sz = elemtype.getSizeInBits();
01609           if (elemtype.isInteger() && (sz < 32))
01610             sz = 32;
01611           O << "\t.reg .b" << sz << " ";
01612           printParamName(I, paramIndex, O);
01613           if (j < je - 1)
01614             O << ",\n";
01615           ++paramIndex;
01616         }
01617         if (i < e - 1)
01618           O << ",\n";
01619       }
01620       --paramIndex;
01621       continue;
01622     }
01623   }
01624 
01625   O << "\n)\n";
01626 }
01627 
01628 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
01629                                             raw_ostream &O) {
01630   const Function *F = MF.getFunction();
01631   emitFunctionParamList(F, O);
01632 }
01633 
01634 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
01635     const MachineFunction &MF) {
01636   SmallString<128> Str;
01637   raw_svector_ostream O(Str);
01638 
01639   // Map the global virtual register number to a register class specific
01640   // virtual register number starting from 1 with that class.
01641   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
01642   //unsigned numRegClasses = TRI->getNumRegClasses();
01643 
01644   // Emit the Fake Stack Object
01645   const MachineFrameInfo *MFI = MF.getFrameInfo();
01646   int NumBytes = (int) MFI->getStackSize();
01647   if (NumBytes) {
01648     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
01649       << getFunctionNumber() << "[" << NumBytes << "];\n";
01650     if (nvptxSubtarget.is64Bit()) {
01651       O << "\t.reg .b64 \t%SP;\n";
01652       O << "\t.reg .b64 \t%SPL;\n";
01653     } else {
01654       O << "\t.reg .b32 \t%SP;\n";
01655       O << "\t.reg .b32 \t%SPL;\n";
01656     }
01657   }
01658 
01659   // Go through all virtual registers to establish the mapping between the
01660   // global virtual
01661   // register number and the per class virtual register number.
01662   // We use the per class virtual register number in the ptx output.
01663   unsigned int numVRs = MRI->getNumVirtRegs();
01664   for (unsigned i = 0; i < numVRs; i++) {
01665     unsigned int vr = TRI->index2VirtReg(i);
01666     const TargetRegisterClass *RC = MRI->getRegClass(vr);
01667     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01668     int n = regmap.size();
01669     regmap.insert(std::make_pair(vr, n + 1));
01670   }
01671 
01672   // Emit register declarations
01673   // @TODO: Extract out the real register usage
01674   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
01675   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
01676   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
01677   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
01678   // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
01679   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
01680   // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
01681 
01682   // Emit declaration of the virtual registers or 'physical' registers for
01683   // each register class
01684   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
01685     const TargetRegisterClass *RC = TRI->getRegClass(i);
01686     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01687     std::string rcname = getNVPTXRegClassName(RC);
01688     std::string rcStr = getNVPTXRegClassStr(RC);
01689     int n = regmap.size();
01690 
01691     // Only declare those registers that may be used.
01692     if (n) {
01693        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
01694          << ">;\n";
01695     }
01696   }
01697 
01698   OutStreamer.EmitRawText(O.str());
01699 }
01700 
01701 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
01702   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
01703   bool ignored;
01704   unsigned int numHex;
01705   const char *lead;
01706 
01707   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
01708     numHex = 8;
01709     lead = "0f";
01710     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
01711   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
01712     numHex = 16;
01713     lead = "0d";
01714     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
01715   } else
01716     llvm_unreachable("unsupported fp type");
01717 
01718   APInt API = APF.bitcastToAPInt();
01719   std::string hexstr(utohexstr(API.getZExtValue()));
01720   O << lead;
01721   if (hexstr.length() < numHex)
01722     O << std::string(numHex - hexstr.length(), '0');
01723   O << utohexstr(API.getZExtValue());
01724 }
01725 
01726 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
01727   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
01728     O << CI->getValue();
01729     return;
01730   }
01731   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
01732     printFPConstant(CFP, O);
01733     return;
01734   }
01735   if (isa<ConstantPointerNull>(CPV)) {
01736     O << "0";
01737     return;
01738   }
01739   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
01740     PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
01741     bool IsNonGenericPointer = false;
01742     if (PTy && PTy->getAddressSpace() != 0) {
01743       IsNonGenericPointer = true;
01744     }
01745     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
01746       O << "generic(";
01747       O << *getSymbol(GVar);
01748       O << ")";
01749     } else {
01750       O << *getSymbol(GVar);
01751     }
01752     return;
01753   }
01754   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01755     const Value *v = Cexpr->stripPointerCasts();
01756     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
01757     bool IsNonGenericPointer = false;
01758     if (PTy && PTy->getAddressSpace() != 0) {
01759       IsNonGenericPointer = true;
01760     }
01761     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
01762       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
01763         O << "generic(";
01764         O << *getSymbol(GVar);
01765         O << ")";
01766       } else {
01767         O << *getSymbol(GVar);
01768       }
01769       return;
01770     } else {
01771       O << *lowerConstant(CPV);
01772       return;
01773     }
01774   }
01775   llvm_unreachable("Not scalar type found in printScalarConstant()");
01776 }
01777 
01778 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
01779                                    AggBuffer *aggBuffer) {
01780 
01781   const DataLayout *TD = TM.getDataLayout();
01782 
01783   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
01784     int s = TD->getTypeAllocSize(CPV->getType());
01785     if (s < Bytes)
01786       s = Bytes;
01787     aggBuffer->addZeros(s);
01788     return;
01789   }
01790 
01791   unsigned char *ptr;
01792   switch (CPV->getType()->getTypeID()) {
01793 
01794   case Type::IntegerTyID: {
01795     const Type *ETy = CPV->getType();
01796     if (ETy == Type::getInt8Ty(CPV->getContext())) {
01797       unsigned char c =
01798           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
01799       ptr = &c;
01800       aggBuffer->addBytes(ptr, 1, Bytes);
01801     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
01802       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
01803       ptr = (unsigned char *)&int16;
01804       aggBuffer->addBytes(ptr, 2, Bytes);
01805     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
01806       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
01807         int int32 = (int)(constInt->getZExtValue());
01808         ptr = (unsigned char *)&int32;
01809         aggBuffer->addBytes(ptr, 4, Bytes);
01810         break;
01811       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01812         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
01813                 ConstantFoldConstantExpression(Cexpr, TD))) {
01814           int int32 = (int)(constInt->getZExtValue());
01815           ptr = (unsigned char *)&int32;
01816           aggBuffer->addBytes(ptr, 4, Bytes);
01817           break;
01818         }
01819         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
01820           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
01821           aggBuffer->addSymbol(v);
01822           aggBuffer->addZeros(4);
01823           break;
01824         }
01825       }
01826       llvm_unreachable("unsupported integer const type");
01827     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
01828       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
01829         long long int64 = (long long)(constInt->getZExtValue());
01830         ptr = (unsigned char *)&int64;
01831         aggBuffer->addBytes(ptr, 8, Bytes);
01832         break;
01833       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01834         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
01835                 ConstantFoldConstantExpression(Cexpr, TD))) {
01836           long long int64 = (long long)(constInt->getZExtValue());
01837           ptr = (unsigned char *)&int64;
01838           aggBuffer->addBytes(ptr, 8, Bytes);
01839           break;
01840         }
01841         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
01842           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
01843           aggBuffer->addSymbol(v);
01844           aggBuffer->addZeros(8);
01845           break;
01846         }
01847       }
01848       llvm_unreachable("unsupported integer const type");
01849     } else
01850       llvm_unreachable("unsupported integer const type");
01851     break;
01852   }
01853   case Type::FloatTyID:
01854   case Type::DoubleTyID: {
01855     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
01856     const Type *Ty = CFP->getType();
01857     if (Ty == Type::getFloatTy(CPV->getContext())) {
01858       float float32 = (float) CFP->getValueAPF().convertToFloat();
01859       ptr = (unsigned char *)&float32;
01860       aggBuffer->addBytes(ptr, 4, Bytes);
01861     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
01862       double float64 = CFP->getValueAPF().convertToDouble();
01863       ptr = (unsigned char *)&float64;
01864       aggBuffer->addBytes(ptr, 8, Bytes);
01865     } else {
01866       llvm_unreachable("unsupported fp const type");
01867     }
01868     break;
01869   }
01870   case Type::PointerTyID: {
01871     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
01872       aggBuffer->addSymbol(GVar);
01873     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01874       const Value *v = Cexpr->stripPointerCasts();
01875       aggBuffer->addSymbol(v);
01876     }
01877     unsigned int s = TD->getTypeAllocSize(CPV->getType());
01878     aggBuffer->addZeros(s);
01879     break;
01880   }
01881 
01882   case Type::ArrayTyID:
01883   case Type::VectorTyID:
01884   case Type::StructTyID: {
01885     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
01886         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
01887       int ElementSize = TD->getTypeAllocSize(CPV->getType());
01888       bufferAggregateConstant(CPV, aggBuffer);
01889       if (Bytes > ElementSize)
01890         aggBuffer->addZeros(Bytes - ElementSize);
01891     } else if (isa<ConstantAggregateZero>(CPV))
01892       aggBuffer->addZeros(Bytes);
01893     else
01894       llvm_unreachable("Unexpected Constant type");
01895     break;
01896   }
01897 
01898   default:
01899     llvm_unreachable("unsupported type");
01900   }
01901 }
01902 
01903 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
01904                                               AggBuffer *aggBuffer) {
01905   const DataLayout *TD = TM.getDataLayout();
01906   int Bytes;
01907 
01908   // Old constants
01909   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
01910     if (CPV->getNumOperands())
01911       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
01912         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
01913     return;
01914   }
01915 
01916   if (const ConstantDataSequential *CDS =
01917           dyn_cast<ConstantDataSequential>(CPV)) {
01918     if (CDS->getNumElements())
01919       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
01920         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
01921                      aggBuffer);
01922     return;
01923   }
01924 
01925   if (isa<ConstantStruct>(CPV)) {
01926     if (CPV->getNumOperands()) {
01927       StructType *ST = cast<StructType>(CPV->getType());
01928       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
01929         if (i == (e - 1))
01930           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
01931                   TD->getTypeAllocSize(ST) -
01932                   TD->getStructLayout(ST)->getElementOffset(i);
01933         else
01934           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
01935                   TD->getStructLayout(ST)->getElementOffset(i);
01936         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
01937       }
01938     }
01939     return;
01940   }
01941   llvm_unreachable("unsupported constant type in printAggregateConstant()");
01942 }
01943 
01944 // buildTypeNameMap - Run through symbol table looking for type names.
01945 //
01946 
01947 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
01948 
01949   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
01950 
01951   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
01952                                   !PI->second.compare("struct._image2d_t") ||
01953                                   !PI->second.compare("struct._image3d_t")))
01954     return true;
01955 
01956   return false;
01957 }
01958 
01959 
01960 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
01961   switch (MI.getOpcode()) {
01962   default:
01963     return false;
01964   case NVPTX::CallArgBeginInst:
01965   case NVPTX::CallArgEndInst0:
01966   case NVPTX::CallArgEndInst1:
01967   case NVPTX::CallArgF32:
01968   case NVPTX::CallArgF64:
01969   case NVPTX::CallArgI16:
01970   case NVPTX::CallArgI32:
01971   case NVPTX::CallArgI32imm:
01972   case NVPTX::CallArgI64:
01973   case NVPTX::CallArgParam:
01974   case NVPTX::CallVoidInst:
01975   case NVPTX::CallVoidInstReg:
01976   case NVPTX::Callseq_End:
01977   case NVPTX::CallVoidInstReg64:
01978   case NVPTX::DeclareParamInst:
01979   case NVPTX::DeclareRetMemInst:
01980   case NVPTX::DeclareRetRegInst:
01981   case NVPTX::DeclareRetScalarInst:
01982   case NVPTX::DeclareScalarParamInst:
01983   case NVPTX::DeclareScalarRegInst:
01984   case NVPTX::StoreParamF32:
01985   case NVPTX::StoreParamF64:
01986   case NVPTX::StoreParamI16:
01987   case NVPTX::StoreParamI32:
01988   case NVPTX::StoreParamI64:
01989   case NVPTX::StoreParamI8:
01990   case NVPTX::StoreRetvalF32:
01991   case NVPTX::StoreRetvalF64:
01992   case NVPTX::StoreRetvalI16:
01993   case NVPTX::StoreRetvalI32:
01994   case NVPTX::StoreRetvalI64:
01995   case NVPTX::StoreRetvalI8:
01996   case NVPTX::LastCallArgF32:
01997   case NVPTX::LastCallArgF64:
01998   case NVPTX::LastCallArgI16:
01999   case NVPTX::LastCallArgI32:
02000   case NVPTX::LastCallArgI32imm:
02001   case NVPTX::LastCallArgI64:
02002   case NVPTX::LastCallArgParam:
02003   case NVPTX::LoadParamMemF32:
02004   case NVPTX::LoadParamMemF64:
02005   case NVPTX::LoadParamMemI16:
02006   case NVPTX::LoadParamMemI32:
02007   case NVPTX::LoadParamMemI64:
02008   case NVPTX::LoadParamMemI8:
02009   case NVPTX::PrototypeInst:
02010   case NVPTX::DBG_VALUE:
02011     return true;
02012   }
02013   return false;
02014 }
02015 
02016 /// PrintAsmOperand - Print out an operand for an inline asm expression.
02017 ///
02018 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
02019                                       unsigned AsmVariant,
02020                                       const char *ExtraCode, raw_ostream &O) {
02021   if (ExtraCode && ExtraCode[0]) {
02022     if (ExtraCode[1] != 0)
02023       return true; // Unknown modifier.
02024 
02025     switch (ExtraCode[0]) {
02026     default:
02027       // See if this is a generic print operand
02028       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
02029     case 'r':
02030       break;
02031     }
02032   }
02033 
02034   printOperand(MI, OpNo, O);
02035 
02036   return false;
02037 }
02038 
02039 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
02040     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
02041     const char *ExtraCode, raw_ostream &O) {
02042   if (ExtraCode && ExtraCode[0])
02043     return true; // Unknown modifier
02044 
02045   O << '[';
02046   printMemOperand(MI, OpNo, O);
02047   O << ']';
02048 
02049   return false;
02050 }
02051 
02052 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
02053                                    raw_ostream &O, const char *Modifier) {
02054   const MachineOperand &MO = MI->getOperand(opNum);
02055   switch (MO.getType()) {
02056   case MachineOperand::MO_Register:
02057     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
02058       if (MO.getReg() == NVPTX::VRDepot)
02059         O << DEPOTNAME << getFunctionNumber();
02060       else
02061         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
02062     } else {
02063       emitVirtualRegister(MO.getReg(), O);
02064     }
02065     return;
02066 
02067   case MachineOperand::MO_Immediate:
02068     if (!Modifier)
02069       O << MO.getImm();
02070     else if (strstr(Modifier, "vec") == Modifier)
02071       printVecModifiedImmediate(MO, Modifier, O);
02072     else
02073       llvm_unreachable(
02074           "Don't know how to handle modifier on immediate operand");
02075     return;
02076 
02077   case MachineOperand::MO_FPImmediate:
02078     printFPConstant(MO.getFPImm(), O);
02079     break;
02080 
02081   case MachineOperand::MO_GlobalAddress:
02082     O << *getSymbol(MO.getGlobal());
02083     break;
02084 
02085   case MachineOperand::MO_MachineBasicBlock:
02086     O << *MO.getMBB()->getSymbol();
02087     return;
02088 
02089   default:
02090     llvm_unreachable("Operand type not supported.");
02091   }
02092 }
02093 
02094 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
02095                                       raw_ostream &O, const char *Modifier) {
02096   printOperand(MI, opNum, O);
02097 
02098   if (Modifier && !strcmp(Modifier, "add")) {
02099     O << ", ";
02100     printOperand(MI, opNum + 1, O);
02101   } else {
02102     if (MI->getOperand(opNum + 1).isImm() &&
02103         MI->getOperand(opNum + 1).getImm() == 0)
02104       return; // don't print ',0' or '+0'
02105     O << "+";
02106     printOperand(MI, opNum + 1, O);
02107   }
02108 }
02109 
02110 
02111 // Force static initialization.
02112 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
02113   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02114   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02115 }
02116 
02117 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
02118   std::stringstream temp;
02119   LineReader *reader = this->getReader(filename.str());
02120   temp << "\n//";
02121   temp << filename.str();
02122   temp << ":";
02123   temp << line;
02124   temp << " ";
02125   temp << reader->readLine(line);
02126   temp << "\n";
02127   this->OutStreamer.EmitRawText(Twine(temp.str()));
02128 }
02129 
02130 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
02131   if (!reader) {
02132     reader = new LineReader(filename);
02133   }
02134 
02135   if (reader->fileName() != filename) {
02136     delete reader;
02137     reader = new LineReader(filename);
02138   }
02139 
02140   return reader;
02141 }
02142 
02143 std::string LineReader::readLine(unsigned lineNum) {
02144   if (lineNum < theCurLine) {
02145     theCurLine = 0;
02146     fstr.seekg(0, std::ios::beg);
02147   }
02148   while (theCurLine < lineNum) {
02149     fstr.getline(buff, 500);
02150     theCurLine++;
02151   }
02152   return buff;
02153 }
02154 
02155 // Force static initialization.
02156 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
02157   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02158   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02159 }