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