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   // TODO: isLoopHeader() should take "const MachineBasicBlock *".
00422   // We insert .pragma "nounroll" only to the loop header.
00423   if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
00424     return false;
00425 
00426   // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
00427   // we iterate through each back edge of the loop with header MBB, and check
00428   // whether its metadata contains llvm.loop.unroll.disable.
00429   for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
00430     const MachineBasicBlock *PMBB = *I;
00431     if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
00432       // Edges from other loops to MBB are not back edges.
00433       continue;
00434     }
00435     if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
00436       if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
00437         if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
00438           return true;
00439       }
00440     }
00441   }
00442   return false;
00443 }
00444 
00445 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
00446   AsmPrinter::EmitBasicBlockStart(MBB);
00447   if (isLoopHeaderOfNoUnroll(MBB))
00448     OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
00449 }
00450 
00451 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
00452   SmallString<128> Str;
00453   raw_svector_ostream O(Str);
00454 
00455   if (!GlobalsEmitted) {
00456     emitGlobals(*MF->getFunction()->getParent());
00457     GlobalsEmitted = true;
00458   }
00459   
00460   // Set up
00461   MRI = &MF->getRegInfo();
00462   F = MF->getFunction();
00463   emitLinkageDirective(F, O);
00464   if (llvm::isKernelFunction(*F))
00465     O << ".entry ";
00466   else {
00467     O << ".func ";
00468     printReturnValStr(*MF, O);
00469   }
00470 
00471   O << *CurrentFnSym;
00472 
00473   emitFunctionParamList(*MF, O);
00474 
00475   if (llvm::isKernelFunction(*F))
00476     emitKernelFunctionDirectives(*F, O);
00477 
00478   OutStreamer->EmitRawText(O.str());
00479 
00480   prevDebugLoc = DebugLoc();
00481 }
00482 
00483 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
00484   VRegMapping.clear();
00485   OutStreamer->EmitRawText(StringRef("{\n"));
00486   setAndEmitFunctionVirtualRegisters(*MF);
00487 
00488   SmallString<128> Str;
00489   raw_svector_ostream O(Str);
00490   emitDemotedVars(MF->getFunction(), O);
00491   OutStreamer->EmitRawText(O.str());
00492 }
00493 
00494 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
00495   OutStreamer->EmitRawText(StringRef("}\n"));
00496   VRegMapping.clear();
00497 }
00498 
00499 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00500   unsigned RegNo = MI->getOperand(0).getReg();
00501   if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
00502     OutStreamer->AddComment(Twine("implicit-def: ") +
00503                             getVirtualRegisterName(RegNo));
00504   } else {
00505     OutStreamer->AddComment(Twine("implicit-def: ") +
00506                             nvptxSubtarget->getRegisterInfo()->getName(RegNo));
00507   }
00508   OutStreamer->AddBlankLine();
00509 }
00510 
00511 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
00512                                                    raw_ostream &O) const {
00513   // If the NVVM IR has some of reqntid* specified, then output
00514   // the reqntid directive, and set the unspecified ones to 1.
00515   // If none of reqntid* is specified, don't output reqntid directive.
00516   unsigned reqntidx, reqntidy, reqntidz;
00517   bool specified = false;
00518   if (!llvm::getReqNTIDx(F, reqntidx))
00519     reqntidx = 1;
00520   else
00521     specified = true;
00522   if (!llvm::getReqNTIDy(F, reqntidy))
00523     reqntidy = 1;
00524   else
00525     specified = true;
00526   if (!llvm::getReqNTIDz(F, reqntidz))
00527     reqntidz = 1;
00528   else
00529     specified = true;
00530 
00531   if (specified)
00532     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
00533       << "\n";
00534 
00535   // If the NVVM IR has some of maxntid* specified, then output
00536   // the maxntid directive, and set the unspecified ones to 1.
00537   // If none of maxntid* is specified, don't output maxntid directive.
00538   unsigned maxntidx, maxntidy, maxntidz;
00539   specified = false;
00540   if (!llvm::getMaxNTIDx(F, maxntidx))
00541     maxntidx = 1;
00542   else
00543     specified = true;
00544   if (!llvm::getMaxNTIDy(F, maxntidy))
00545     maxntidy = 1;
00546   else
00547     specified = true;
00548   if (!llvm::getMaxNTIDz(F, maxntidz))
00549     maxntidz = 1;
00550   else
00551     specified = true;
00552 
00553   if (specified)
00554     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
00555       << "\n";
00556 
00557   unsigned mincta;
00558   if (llvm::getMinCTASm(F, mincta))
00559     O << ".minnctapersm " << mincta << "\n";
00560 }
00561 
00562 std::string
00563 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
00564   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00565 
00566   std::string Name;
00567   raw_string_ostream NameStr(Name);
00568 
00569   VRegRCMap::const_iterator I = VRegMapping.find(RC);
00570   assert(I != VRegMapping.end() && "Bad register class");
00571   const DenseMap<unsigned, unsigned> &RegMap = I->second;
00572 
00573   VRegMap::const_iterator VI = RegMap.find(Reg);
00574   assert(VI != RegMap.end() && "Bad virtual register");
00575   unsigned MappedVR = VI->second;
00576 
00577   NameStr << getNVPTXRegClassStr(RC) << MappedVR;
00578 
00579   NameStr.flush();
00580   return Name;
00581 }
00582 
00583 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
00584                                           raw_ostream &O) {
00585   O << getVirtualRegisterName(vr);
00586 }
00587 
00588 void NVPTXAsmPrinter::printVecModifiedImmediate(
00589     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
00590   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
00591   int Imm = (int) MO.getImm();
00592   if (0 == strcmp(Modifier, "vecelem"))
00593     O << "_" << vecelem[Imm];
00594   else if (0 == strcmp(Modifier, "vecv4comm1")) {
00595     if ((Imm < 0) || (Imm > 3))
00596       O << "//";
00597   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
00598     if ((Imm < 4) || (Imm > 7))
00599       O << "//";
00600   } else if (0 == strcmp(Modifier, "vecv4pos")) {
00601     if (Imm < 0)
00602       Imm = 0;
00603     O << "_" << vecelem[Imm % 4];
00604   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
00605     if ((Imm < 0) || (Imm > 1))
00606       O << "//";
00607   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
00608     if ((Imm < 2) || (Imm > 3))
00609       O << "//";
00610   } else if (0 == strcmp(Modifier, "vecv2pos")) {
00611     if (Imm < 0)
00612       Imm = 0;
00613     O << "_" << vecelem[Imm % 2];
00614   } else
00615     llvm_unreachable("Unknown Modifier on immediate operand");
00616 }
00617 
00618 
00619 
00620 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
00621 
00622   emitLinkageDirective(F, O);
00623   if (llvm::isKernelFunction(*F))
00624     O << ".entry ";
00625   else
00626     O << ".func ";
00627   printReturnValStr(F, O);
00628   O << *getSymbol(F) << "\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   StringRef 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   MMI->AnalyzeModule(M);
00822 
00823   // We need to call the parent's one explicitly.
00824   //bool Result = AsmPrinter::doInitialization(M);
00825 
00826   // Initialize TargetLoweringObjectFile.
00827   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
00828       .Initialize(OutContext, TM);
00829 
00830   Mang = new Mangler(TM.getDataLayout());
00831 
00832   // Emit header before any dwarf directives are emitted below.
00833   emitHeader(M, OS1, STI);
00834   OutStreamer->EmitRawText(OS1.str());
00835 
00836   // Already commented out
00837   //bool Result = AsmPrinter::doInitialization(M);
00838 
00839   // Emit module-level inline asm if it exists.
00840   if (!M.getModuleInlineAsm().empty()) {
00841     OutStreamer->AddComment("Start of file scope inline assembly");
00842     OutStreamer->AddBlankLine();
00843     OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
00844     OutStreamer->AddBlankLine();
00845     OutStreamer->AddComment("End of file scope inline assembly");
00846     OutStreamer->AddBlankLine();
00847   }
00848 
00849   // If we're not NVCL we're CUDA, go ahead and emit filenames.
00850   if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
00851     recordAndEmitFilenames(M);
00852 
00853   GlobalsEmitted = false;
00854     
00855   return false; // success
00856 }
00857 
00858 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
00859   SmallString<128> Str2;
00860   raw_svector_ostream OS2(Str2);
00861 
00862   emitDeclarations(M, OS2);
00863 
00864   // As ptxas does not support forward references of globals, we need to first
00865   // sort the list of module-level globals in def-use order. We visit each
00866   // global variable in order, and ensure that we emit it *after* its dependent
00867   // globals. We use a little extra memory maintaining both a set and a list to
00868   // have fast searches while maintaining a strict ordering.
00869   SmallVector<const GlobalVariable *, 8> Globals;
00870   DenseSet<const GlobalVariable *> GVVisited;
00871   DenseSet<const GlobalVariable *> GVVisiting;
00872 
00873   // Visit each global variable, in order
00874   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00875        I != E; ++I)
00876     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
00877 
00878   assert(GVVisited.size() == M.getGlobalList().size() &&
00879          "Missed a global variable");
00880   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
00881 
00882   // Print out module-level global variables in proper order
00883   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
00884     printModuleLevelGV(Globals[i], OS2);
00885 
00886   OS2 << '\n';
00887 
00888   OutStreamer->EmitRawText(OS2.str());
00889 }
00890 
00891 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
00892                                  const NVPTXSubtarget &STI) {
00893   O << "//\n";
00894   O << "// Generated by LLVM NVPTX Back-End\n";
00895   O << "//\n";
00896   O << "\n";
00897 
00898   unsigned PTXVersion = STI.getPTXVersion();
00899   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
00900 
00901   O << ".target ";
00902   O << STI.getTargetName();
00903 
00904   const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
00905   if (NTM.getDrvInterface() == NVPTX::NVCL)
00906     O << ", texmode_independent";
00907   else {
00908     if (!STI.hasDouble())
00909       O << ", map_f64_to_f32";
00910   }
00911 
00912   if (MAI->doesSupportDebugInformation())
00913     O << ", debug";
00914 
00915   O << "\n";
00916 
00917   O << ".address_size ";
00918   if (NTM.is64Bit())
00919     O << "64";
00920   else
00921     O << "32";
00922   O << "\n";
00923 
00924   O << "\n";
00925 }
00926 
00927 bool NVPTXAsmPrinter::doFinalization(Module &M) {
00928   // If we did not emit any functions, then the global declarations have not
00929   // yet been emitted.
00930   if (!GlobalsEmitted) {
00931     emitGlobals(M);
00932     GlobalsEmitted = true;
00933   }
00934 
00935   // XXX Temproarily remove global variables so that doFinalization() will not
00936   // emit them again (global variables are emitted at beginning).
00937 
00938   Module::GlobalListType &global_list = M.getGlobalList();
00939   int i, n = global_list.size();
00940   GlobalVariable **gv_array = new GlobalVariable *[n];
00941 
00942   // first, back-up GlobalVariable in gv_array
00943   i = 0;
00944   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
00945        I != E; ++I)
00946     gv_array[i++] = &*I;
00947 
00948   // second, empty global_list
00949   while (!global_list.empty())
00950     global_list.remove(global_list.begin());
00951 
00952   // call doFinalization
00953   bool ret = AsmPrinter::doFinalization(M);
00954 
00955   // now we restore global variables
00956   for (i = 0; i < n; i++)
00957     global_list.insert(global_list.end(), gv_array[i]);
00958 
00959   clearAnnotationCache(&M);
00960 
00961   delete[] gv_array;
00962   return ret;
00963 
00964   //bool Result = AsmPrinter::doFinalization(M);
00965   // Instead of calling the parents doFinalization, we may
00966   // clone parents doFinalization and customize here.
00967   // Currently, we if NVISA out the EmitGlobals() in
00968   // parent's doFinalization, which is too intrusive.
00969   //
00970   // Same for the doInitialization.
00971   //return Result;
00972 }
00973 
00974 // This function emits appropriate linkage directives for
00975 // functions and global variables.
00976 //
00977 // extern function declaration            -> .extern
00978 // extern function definition             -> .visible
00979 // external global variable with init     -> .visible
00980 // external without init                  -> .extern
00981 // appending                              -> not allowed, assert.
00982 // for any linkage other than
00983 // internal, private, linker_private,
00984 // linker_private_weak, linker_private_weak_def_auto,
00985 // we emit                                -> .weak.
00986 
00987 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
00988                                            raw_ostream &O) {
00989   if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
00990     if (V->hasExternalLinkage()) {
00991       if (isa<GlobalVariable>(V)) {
00992         const GlobalVariable *GVar = cast<GlobalVariable>(V);
00993         if (GVar) {
00994           if (GVar->hasInitializer())
00995             O << ".visible ";
00996           else
00997             O << ".extern ";
00998         }
00999       } else if (V->isDeclaration())
01000         O << ".extern ";
01001       else
01002         O << ".visible ";
01003     } else if (V->hasAppendingLinkage()) {
01004       std::string msg;
01005       msg.append("Error: ");
01006       msg.append("Symbol ");
01007       if (V->hasName())
01008         msg.append(V->getName());
01009       msg.append("has unsupported appending linkage type");
01010       llvm_unreachable(msg.c_str());
01011     } else if (!V->hasInternalLinkage() &&
01012                !V->hasPrivateLinkage()) {
01013       O << ".weak ";
01014     }
01015   }
01016 }
01017 
01018 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
01019                                          raw_ostream &O,
01020                                          bool processDemoted) {
01021 
01022   // Skip meta data
01023   if (GVar->hasSection()) {
01024     if (GVar->getSection() == StringRef("llvm.metadata"))
01025       return;
01026   }
01027 
01028   // Skip LLVM intrinsic global variables
01029   if (GVar->getName().startswith("llvm.") ||
01030       GVar->getName().startswith("nvvm."))
01031     return;
01032 
01033   const DataLayout *TD = TM.getDataLayout();
01034 
01035   // GlobalVariables are always constant pointers themselves.
01036   const PointerType *PTy = GVar->getType();
01037   Type *ETy = PTy->getElementType();
01038 
01039   if (GVar->hasExternalLinkage()) {
01040     if (GVar->hasInitializer())
01041       O << ".visible ";
01042     else
01043       O << ".extern ";
01044   } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
01045              GVar->hasAvailableExternallyLinkage() ||
01046              GVar->hasCommonLinkage()) {
01047     O << ".weak ";
01048   }
01049 
01050   if (llvm::isTexture(*GVar)) {
01051     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
01052     return;
01053   }
01054 
01055   if (llvm::isSurface(*GVar)) {
01056     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
01057     return;
01058   }
01059 
01060   if (GVar->isDeclaration()) {
01061     // (extern) declarations, no definition or initializer
01062     // Currently the only known declaration is for an automatic __local
01063     // (.shared) promoted to global.
01064     emitPTXGlobalVariable(GVar, O);
01065     O << ";\n";
01066     return;
01067   }
01068 
01069   if (llvm::isSampler(*GVar)) {
01070     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
01071 
01072     const Constant *Initializer = nullptr;
01073     if (GVar->hasInitializer())
01074       Initializer = GVar->getInitializer();
01075     const ConstantInt *CI = nullptr;
01076     if (Initializer)
01077       CI = dyn_cast<ConstantInt>(Initializer);
01078     if (CI) {
01079       unsigned sample = CI->getZExtValue();
01080 
01081       O << " = { ";
01082 
01083       for (int i = 0,
01084                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
01085            i < 3; i++) {
01086         O << "addr_mode_" << i << " = ";
01087         switch (addr) {
01088         case 0:
01089           O << "wrap";
01090           break;
01091         case 1:
01092           O << "clamp_to_border";
01093           break;
01094         case 2:
01095           O << "clamp_to_edge";
01096           break;
01097         case 3:
01098           O << "wrap";
01099           break;
01100         case 4:
01101           O << "mirror";
01102           break;
01103         }
01104         O << ", ";
01105       }
01106       O << "filter_mode = ";
01107       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
01108       case 0:
01109         O << "nearest";
01110         break;
01111       case 1:
01112         O << "linear";
01113         break;
01114       case 2:
01115         llvm_unreachable("Anisotropic filtering is not supported");
01116       default:
01117         O << "nearest";
01118         break;
01119       }
01120       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
01121         O << ", force_unnormalized_coords = 1";
01122       }
01123       O << " }";
01124     }
01125 
01126     O << ";\n";
01127     return;
01128   }
01129 
01130   if (GVar->hasPrivateLinkage()) {
01131 
01132     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
01133       return;
01134 
01135     // FIXME - need better way (e.g. Metadata) to avoid generating this global
01136     if (!strncmp(GVar->getName().data(), "filename", 8))
01137       return;
01138     if (GVar->use_empty())
01139       return;
01140   }
01141 
01142   const Function *demotedFunc = nullptr;
01143   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
01144     O << "// " << GVar->getName() << " has been demoted\n";
01145     if (localDecls.find(demotedFunc) != localDecls.end())
01146       localDecls[demotedFunc].push_back(GVar);
01147     else {
01148       std::vector<const GlobalVariable *> temp;
01149       temp.push_back(GVar);
01150       localDecls[demotedFunc] = temp;
01151     }
01152     return;
01153   }
01154 
01155   O << ".";
01156   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01157 
01158   if (isManaged(*GVar)) {
01159     O << " .attribute(.managed)";
01160   }
01161 
01162   if (GVar->getAlignment() == 0)
01163     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01164   else
01165     O << " .align " << GVar->getAlignment();
01166 
01167   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
01168     O << " .";
01169     // Special case: ABI requires that we use .u8 for predicates
01170     if (ETy->isIntegerTy(1))
01171       O << "u8";
01172     else
01173       O << getPTXFundamentalTypeStr(ETy, false);
01174     O << " ";
01175     O << *getSymbol(GVar);
01176 
01177     // Ptx allows variable initilization only for constant and global state
01178     // spaces.
01179     if (GVar->hasInitializer()) {
01180       if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01181           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
01182         const Constant *Initializer = GVar->getInitializer();
01183         // 'undef' is treated as there is no value specified.
01184         if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
01185           O << " = ";
01186           printScalarConstant(Initializer, O);
01187         }
01188       } else {
01189         // The frontend adds zero-initializer to variables that don't have an
01190         // initial value, so skip warning for this case.
01191         if (!GVar->getInitializer()->isNullValue()) {
01192           report_fatal_error("initial value of '" + GVar->getName() +
01193                              "' is not allowed in addrspace(" +
01194                              Twine(PTy->getAddressSpace()) + ")");
01195         }
01196       }
01197     }
01198   } else {
01199     unsigned int ElementSize = 0;
01200 
01201     // Although PTX has direct support for struct type and array type and
01202     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
01203     // targets that support these high level field accesses. Structs, arrays
01204     // and vectors are lowered into arrays of bytes.
01205     switch (ETy->getTypeID()) {
01206     case Type::StructTyID:
01207     case Type::ArrayTyID:
01208     case Type::VectorTyID:
01209       ElementSize = TD->getTypeStoreSize(ETy);
01210       // Ptx allows variable initilization only for constant and
01211       // global state spaces.
01212       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01213            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
01214           GVar->hasInitializer()) {
01215         const Constant *Initializer = GVar->getInitializer();
01216         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
01217           AggBuffer aggBuffer(ElementSize, O, *this);
01218           bufferAggregateConstant(Initializer, &aggBuffer);
01219           if (aggBuffer.numSymbols) {
01220             if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
01221               O << " .u64 " << *getSymbol(GVar) << "[";
01222               O << ElementSize / 8;
01223             } else {
01224               O << " .u32 " << *getSymbol(GVar) << "[";
01225               O << ElementSize / 4;
01226             }
01227             O << "]";
01228           } else {
01229             O << " .b8 " << *getSymbol(GVar) << "[";
01230             O << ElementSize;
01231             O << "]";
01232           }
01233           O << " = {";
01234           aggBuffer.print();
01235           O << "}";
01236         } else {
01237           O << " .b8 " << *getSymbol(GVar);
01238           if (ElementSize) {
01239             O << "[";
01240             O << ElementSize;
01241             O << "]";
01242           }
01243         }
01244       } else {
01245         O << " .b8 " << *getSymbol(GVar);
01246         if (ElementSize) {
01247           O << "[";
01248           O << ElementSize;
01249           O << "]";
01250         }
01251       }
01252       break;
01253     default:
01254       llvm_unreachable("type not supported yet");
01255     }
01256 
01257   }
01258   O << ";\n";
01259 }
01260 
01261 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
01262   if (localDecls.find(f) == localDecls.end())
01263     return;
01264 
01265   std::vector<const GlobalVariable *> &gvars = localDecls[f];
01266 
01267   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
01268     O << "\t// demoted variable\n\t";
01269     printModuleLevelGV(gvars[i], O, true);
01270   }
01271 }
01272 
01273 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
01274                                           raw_ostream &O) const {
01275   switch (AddressSpace) {
01276   case llvm::ADDRESS_SPACE_LOCAL:
01277     O << "local";
01278     break;
01279   case llvm::ADDRESS_SPACE_GLOBAL:
01280     O << "global";
01281     break;
01282   case llvm::ADDRESS_SPACE_CONST:
01283     O << "const";
01284     break;
01285   case llvm::ADDRESS_SPACE_SHARED:
01286     O << "shared";
01287     break;
01288   default:
01289     report_fatal_error("Bad address space found while emitting PTX");
01290     break;
01291   }
01292 }
01293 
01294 std::string
01295 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
01296   switch (Ty->getTypeID()) {
01297   default:
01298     llvm_unreachable("unexpected type");
01299     break;
01300   case Type::IntegerTyID: {
01301     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
01302     if (NumBits == 1)
01303       return "pred";
01304     else if (NumBits <= 64) {
01305       std::string name = "u";
01306       return name + utostr(NumBits);
01307     } else {
01308       llvm_unreachable("Integer too large");
01309       break;
01310     }
01311     break;
01312   }
01313   case Type::FloatTyID:
01314     return "f32";
01315   case Type::DoubleTyID:
01316     return "f64";
01317   case Type::PointerTyID:
01318     if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
01319       if (useB4PTR)
01320         return "b64";
01321       else
01322         return "u64";
01323     else if (useB4PTR)
01324       return "b32";
01325     else
01326       return "u32";
01327   }
01328   llvm_unreachable("unexpected type");
01329   return nullptr;
01330 }
01331 
01332 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
01333                                             raw_ostream &O) {
01334 
01335   const DataLayout *TD = TM.getDataLayout();
01336 
01337   // GlobalVariables are always constant pointers themselves.
01338   const PointerType *PTy = GVar->getType();
01339   Type *ETy = PTy->getElementType();
01340 
01341   O << ".";
01342   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01343   if (GVar->getAlignment() == 0)
01344     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01345   else
01346     O << " .align " << GVar->getAlignment();
01347 
01348   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
01349     O << " .";
01350     O << getPTXFundamentalTypeStr(ETy);
01351     O << " ";
01352     O << *getSymbol(GVar);
01353     return;
01354   }
01355 
01356   int64_t ElementSize = 0;
01357 
01358   // Although PTX has direct support for struct type and array type and LLVM IR
01359   // is very similar to PTX, the LLVM CodeGen does not support for targets that
01360   // support these high level field accesses. Structs and arrays are lowered
01361   // into arrays of bytes.
01362   switch (ETy->getTypeID()) {
01363   case Type::StructTyID:
01364   case Type::ArrayTyID:
01365   case Type::VectorTyID:
01366     ElementSize = TD->getTypeStoreSize(ETy);
01367     O << " .b8 " << *getSymbol(GVar) << "[";
01368     if (ElementSize) {
01369       O << ElementSize;
01370     }
01371     O << "]";
01372     break;
01373   default:
01374     llvm_unreachable("type not supported yet");
01375   }
01376   return;
01377 }
01378 
01379 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
01380   if (Ty->isSingleValueType())
01381     return TD->getPrefTypeAlignment(Ty);
01382 
01383   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
01384   if (ATy)
01385     return getOpenCLAlignment(TD, ATy->getElementType());
01386 
01387   const StructType *STy = dyn_cast<StructType>(Ty);
01388   if (STy) {
01389     unsigned int alignStruct = 1;
01390     // Go through each element of the struct and find the
01391     // largest alignment.
01392     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
01393       Type *ETy = STy->getElementType(i);
01394       unsigned int align = getOpenCLAlignment(TD, ETy);
01395       if (align > alignStruct)
01396         alignStruct = align;
01397     }
01398     return alignStruct;
01399   }
01400 
01401   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
01402   if (FTy)
01403     return TD->getPointerPrefAlignment();
01404   return TD->getPrefTypeAlignment(Ty);
01405 }
01406 
01407 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
01408                                      int paramIndex, raw_ostream &O) {
01409   O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
01410 }
01411 
01412 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
01413   O << *CurrentFnSym << "_param_" << paramIndex;
01414 }
01415 
01416 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
01417   const DataLayout *TD = TM.getDataLayout();
01418   const AttributeSet &PAL = F->getAttributes();
01419   const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
01420   Function::const_arg_iterator I, E;
01421   unsigned paramIndex = 0;
01422   bool first = true;
01423   bool isKernelFunc = llvm::isKernelFunction(*F);
01424   bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
01425   MVT thePointerTy = TLI->getPointerTy();
01426 
01427   O << "(\n";
01428 
01429   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
01430     Type *Ty = I->getType();
01431 
01432     if (!first)
01433       O << ",\n";
01434 
01435     first = false;
01436 
01437     // Handle image/sampler parameters
01438     if (isKernelFunction(*F)) {
01439       if (isSampler(*I) || isImage(*I)) {
01440         if (isImage(*I)) {
01441           std::string sname = I->getName();
01442           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
01443             if (nvptxSubtarget->hasImageHandles())
01444               O << "\t.param .u64 .ptr .surfref ";
01445             else
01446               O << "\t.param .surfref ";
01447             O << *CurrentFnSym << "_param_" << paramIndex;
01448           }
01449           else { // Default image is read_only
01450             if (nvptxSubtarget->hasImageHandles())
01451               O << "\t.param .u64 .ptr .texref ";
01452             else
01453               O << "\t.param .texref ";
01454             O << *CurrentFnSym << "_param_" << paramIndex;
01455           }
01456         } else {
01457           if (nvptxSubtarget->hasImageHandles())
01458             O << "\t.param .u64 .ptr .samplerref ";
01459           else
01460             O << "\t.param .samplerref ";
01461           O << *CurrentFnSym << "_param_" << paramIndex;
01462         }
01463         continue;
01464       }
01465     }
01466 
01467     if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
01468       if (Ty->isAggregateType() || Ty->isVectorTy()) {
01469         // Just print .param .align <a> .b8 .param[size];
01470         // <a> = PAL.getparamalignment
01471         // size = typeallocsize of element type
01472         unsigned align = PAL.getParamAlignment(paramIndex + 1);
01473         if (align == 0)
01474           align = TD->getABITypeAlignment(Ty);
01475 
01476         unsigned sz = TD->getTypeAllocSize(Ty);
01477         O << "\t.param .align " << align << " .b8 ";
01478         printParamName(I, paramIndex, O);
01479         O << "[" << sz << "]";
01480 
01481         continue;
01482       }
01483       // Just a scalar
01484       const PointerType *PTy = dyn_cast<PointerType>(Ty);
01485       if (isKernelFunc) {
01486         if (PTy) {
01487           // Special handling for pointer arguments to kernel
01488           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
01489 
01490           if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
01491               NVPTX::CUDA) {
01492             Type *ETy = PTy->getElementType();
01493             int addrSpace = PTy->getAddressSpace();
01494             switch (addrSpace) {
01495             default:
01496               O << ".ptr ";
01497               break;
01498             case llvm::ADDRESS_SPACE_CONST:
01499               O << ".ptr .const ";
01500               break;
01501             case llvm::ADDRESS_SPACE_SHARED:
01502               O << ".ptr .shared ";
01503               break;
01504             case llvm::ADDRESS_SPACE_GLOBAL:
01505               O << ".ptr .global ";
01506               break;
01507             }
01508             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
01509           }
01510           printParamName(I, paramIndex, O);
01511           continue;
01512         }
01513 
01514         // non-pointer scalar to kernel func
01515         O << "\t.param .";
01516         // Special case: predicate operands become .u8 types
01517         if (Ty->isIntegerTy(1))
01518           O << "u8";
01519         else
01520           O << getPTXFundamentalTypeStr(Ty);
01521         O << " ";
01522         printParamName(I, paramIndex, O);
01523         continue;
01524       }
01525       // Non-kernel function, just print .param .b<size> for ABI
01526       // and .reg .b<size> for non-ABI
01527       unsigned sz = 0;
01528       if (isa<IntegerType>(Ty)) {
01529         sz = cast<IntegerType>(Ty)->getBitWidth();
01530         if (sz < 32)
01531           sz = 32;
01532       } else if (isa<PointerType>(Ty))
01533         sz = thePointerTy.getSizeInBits();
01534       else
01535         sz = Ty->getPrimitiveSizeInBits();
01536       if (isABI)
01537         O << "\t.param .b" << sz << " ";
01538       else
01539         O << "\t.reg .b" << sz << " ";
01540       printParamName(I, paramIndex, O);
01541       continue;
01542     }
01543 
01544     // param has byVal attribute. So should be a pointer
01545     const PointerType *PTy = dyn_cast<PointerType>(Ty);
01546     assert(PTy && "Param with byval attribute should be a pointer type");
01547     Type *ETy = PTy->getElementType();
01548 
01549     if (isABI || isKernelFunc) {
01550       // Just print .param .align <a> .b8 .param[size];
01551       // <a> = PAL.getparamalignment
01552       // size = typeallocsize of element type
01553       unsigned align = PAL.getParamAlignment(paramIndex + 1);
01554       if (align == 0)
01555         align = TD->getABITypeAlignment(ETy);
01556 
01557       unsigned sz = TD->getTypeAllocSize(ETy);
01558       O << "\t.param .align " << align << " .b8 ";
01559       printParamName(I, paramIndex, O);
01560       O << "[" << sz << "]";
01561       continue;
01562     } else {
01563       // Split the ETy into constituent parts and
01564       // print .param .b<size> <name> for each part.
01565       // Further, if a part is vector, print the above for
01566       // each vector element.
01567       SmallVector<EVT, 16> vtparts;
01568       ComputeValueVTs(*TLI, ETy, vtparts);
01569       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
01570         unsigned elems = 1;
01571         EVT elemtype = vtparts[i];
01572         if (vtparts[i].isVector()) {
01573           elems = vtparts[i].getVectorNumElements();
01574           elemtype = vtparts[i].getVectorElementType();
01575         }
01576 
01577         for (unsigned j = 0, je = elems; j != je; ++j) {
01578           unsigned sz = elemtype.getSizeInBits();
01579           if (elemtype.isInteger() && (sz < 32))
01580             sz = 32;
01581           O << "\t.reg .b" << sz << " ";
01582           printParamName(I, paramIndex, O);
01583           if (j < je - 1)
01584             O << ",\n";
01585           ++paramIndex;
01586         }
01587         if (i < e - 1)
01588           O << ",\n";
01589       }
01590       --paramIndex;
01591       continue;
01592     }
01593   }
01594 
01595   O << "\n)\n";
01596 }
01597 
01598 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
01599                                             raw_ostream &O) {
01600   const Function *F = MF.getFunction();
01601   emitFunctionParamList(F, O);
01602 }
01603 
01604 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
01605     const MachineFunction &MF) {
01606   SmallString<128> Str;
01607   raw_svector_ostream O(Str);
01608 
01609   // Map the global virtual register number to a register class specific
01610   // virtual register number starting from 1 with that class.
01611   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
01612   //unsigned numRegClasses = TRI->getNumRegClasses();
01613 
01614   // Emit the Fake Stack Object
01615   const MachineFrameInfo *MFI = MF.getFrameInfo();
01616   int NumBytes = (int) MFI->getStackSize();
01617   if (NumBytes) {
01618     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
01619       << getFunctionNumber() << "[" << NumBytes << "];\n";
01620     if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
01621       O << "\t.reg .b64 \t%SP;\n";
01622       O << "\t.reg .b64 \t%SPL;\n";
01623     } else {
01624       O << "\t.reg .b32 \t%SP;\n";
01625       O << "\t.reg .b32 \t%SPL;\n";
01626     }
01627   }
01628 
01629   // Go through all virtual registers to establish the mapping between the
01630   // global virtual
01631   // register number and the per class virtual register number.
01632   // We use the per class virtual register number in the ptx output.
01633   unsigned int numVRs = MRI->getNumVirtRegs();
01634   for (unsigned i = 0; i < numVRs; i++) {
01635     unsigned int vr = TRI->index2VirtReg(i);
01636     const TargetRegisterClass *RC = MRI->getRegClass(vr);
01637     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01638     int n = regmap.size();
01639     regmap.insert(std::make_pair(vr, n + 1));
01640   }
01641 
01642   // Emit register declarations
01643   // @TODO: Extract out the real register usage
01644   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
01645   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
01646   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
01647   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
01648   // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
01649   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
01650   // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
01651 
01652   // Emit declaration of the virtual registers or 'physical' registers for
01653   // each register class
01654   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
01655     const TargetRegisterClass *RC = TRI->getRegClass(i);
01656     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01657     std::string rcname = getNVPTXRegClassName(RC);
01658     std::string rcStr = getNVPTXRegClassStr(RC);
01659     int n = regmap.size();
01660 
01661     // Only declare those registers that may be used.
01662     if (n) {
01663        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
01664          << ">;\n";
01665     }
01666   }
01667 
01668   OutStreamer->EmitRawText(O.str());
01669 }
01670 
01671 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
01672   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
01673   bool ignored;
01674   unsigned int numHex;
01675   const char *lead;
01676 
01677   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
01678     numHex = 8;
01679     lead = "0f";
01680     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
01681   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
01682     numHex = 16;
01683     lead = "0d";
01684     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
01685   } else
01686     llvm_unreachable("unsupported fp type");
01687 
01688   APInt API = APF.bitcastToAPInt();
01689   std::string hexstr(utohexstr(API.getZExtValue()));
01690   O << lead;
01691   if (hexstr.length() < numHex)
01692     O << std::string(numHex - hexstr.length(), '0');
01693   O << utohexstr(API.getZExtValue());
01694 }
01695 
01696 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
01697   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
01698     O << CI->getValue();
01699     return;
01700   }
01701   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
01702     printFPConstant(CFP, O);
01703     return;
01704   }
01705   if (isa<ConstantPointerNull>(CPV)) {
01706     O << "0";
01707     return;
01708   }
01709   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
01710     PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
01711     bool IsNonGenericPointer = false;
01712     if (PTy && PTy->getAddressSpace() != 0) {
01713       IsNonGenericPointer = true;
01714     }
01715     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
01716       O << "generic(";
01717       O << *getSymbol(GVar);
01718       O << ")";
01719     } else {
01720       O << *getSymbol(GVar);
01721     }
01722     return;
01723   }
01724   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01725     const Value *v = Cexpr->stripPointerCasts();
01726     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
01727     bool IsNonGenericPointer = false;
01728     if (PTy && PTy->getAddressSpace() != 0) {
01729       IsNonGenericPointer = true;
01730     }
01731     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
01732       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
01733         O << "generic(";
01734         O << *getSymbol(GVar);
01735         O << ")";
01736       } else {
01737         O << *getSymbol(GVar);
01738       }
01739       return;
01740     } else {
01741       O << *lowerConstant(CPV);
01742       return;
01743     }
01744   }
01745   llvm_unreachable("Not scalar type found in printScalarConstant()");
01746 }
01747 
01748 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
01749                                    AggBuffer *aggBuffer) {
01750 
01751   const DataLayout *TD = TM.getDataLayout();
01752 
01753   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
01754     int s = TD->getTypeAllocSize(CPV->getType());
01755     if (s < Bytes)
01756       s = Bytes;
01757     aggBuffer->addZeros(s);
01758     return;
01759   }
01760 
01761   unsigned char *ptr;
01762   switch (CPV->getType()->getTypeID()) {
01763 
01764   case Type::IntegerTyID: {
01765     const Type *ETy = CPV->getType();
01766     if (ETy == Type::getInt8Ty(CPV->getContext())) {
01767       unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
01768       ptr = &c;
01769       aggBuffer->addBytes(ptr, 1, Bytes);
01770     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
01771       short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
01772       ptr = (unsigned char *)&int16;
01773       aggBuffer->addBytes(ptr, 2, Bytes);
01774     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
01775       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
01776         int int32 = (int)(constInt->getZExtValue());
01777         ptr = (unsigned char *)&int32;
01778         aggBuffer->addBytes(ptr, 4, Bytes);
01779         break;
01780       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01781         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
01782                 ConstantFoldConstantExpression(Cexpr, *TD))) {
01783           int int32 = (int)(constInt->getZExtValue());
01784           ptr = (unsigned char *)&int32;
01785           aggBuffer->addBytes(ptr, 4, Bytes);
01786           break;
01787         }
01788         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
01789           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
01790           aggBuffer->addSymbol(v, Cexpr->getOperand(0));
01791           aggBuffer->addZeros(4);
01792           break;
01793         }
01794       }
01795       llvm_unreachable("unsupported integer const type");
01796     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
01797       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
01798         long long int64 = (long long)(constInt->getZExtValue());
01799         ptr = (unsigned char *)&int64;
01800         aggBuffer->addBytes(ptr, 8, Bytes);
01801         break;
01802       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01803         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
01804                 ConstantFoldConstantExpression(Cexpr, *TD))) {
01805           long long int64 = (long long)(constInt->getZExtValue());
01806           ptr = (unsigned char *)&int64;
01807           aggBuffer->addBytes(ptr, 8, Bytes);
01808           break;
01809         }
01810         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
01811           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
01812           aggBuffer->addSymbol(v, Cexpr->getOperand(0));
01813           aggBuffer->addZeros(8);
01814           break;
01815         }
01816       }
01817       llvm_unreachable("unsupported integer const type");
01818     } else
01819       llvm_unreachable("unsupported integer const type");
01820     break;
01821   }
01822   case Type::FloatTyID:
01823   case Type::DoubleTyID: {
01824     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
01825     const Type *Ty = CFP->getType();
01826     if (Ty == Type::getFloatTy(CPV->getContext())) {
01827       float float32 = (float) CFP->getValueAPF().convertToFloat();
01828       ptr = (unsigned char *)&float32;
01829       aggBuffer->addBytes(ptr, 4, Bytes);
01830     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
01831       double float64 = CFP->getValueAPF().convertToDouble();
01832       ptr = (unsigned char *)&float64;
01833       aggBuffer->addBytes(ptr, 8, Bytes);
01834     } else {
01835       llvm_unreachable("unsupported fp const type");
01836     }
01837     break;
01838   }
01839   case Type::PointerTyID: {
01840     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
01841       aggBuffer->addSymbol(GVar, GVar);
01842     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01843       const Value *v = Cexpr->stripPointerCasts();
01844       aggBuffer->addSymbol(v, Cexpr);
01845     }
01846     unsigned int s = TD->getTypeAllocSize(CPV->getType());
01847     aggBuffer->addZeros(s);
01848     break;
01849   }
01850 
01851   case Type::ArrayTyID:
01852   case Type::VectorTyID:
01853   case Type::StructTyID: {
01854     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
01855         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
01856       int ElementSize = TD->getTypeAllocSize(CPV->getType());
01857       bufferAggregateConstant(CPV, aggBuffer);
01858       if (Bytes > ElementSize)
01859         aggBuffer->addZeros(Bytes - ElementSize);
01860     } else if (isa<ConstantAggregateZero>(CPV))
01861       aggBuffer->addZeros(Bytes);
01862     else
01863       llvm_unreachable("Unexpected Constant type");
01864     break;
01865   }
01866 
01867   default:
01868     llvm_unreachable("unsupported type");
01869   }
01870 }
01871 
01872 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
01873                                               AggBuffer *aggBuffer) {
01874   const DataLayout *TD = TM.getDataLayout();
01875   int Bytes;
01876 
01877   // Old constants
01878   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
01879     if (CPV->getNumOperands())
01880       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
01881         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
01882     return;
01883   }
01884 
01885   if (const ConstantDataSequential *CDS =
01886           dyn_cast<ConstantDataSequential>(CPV)) {
01887     if (CDS->getNumElements())
01888       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
01889         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
01890                      aggBuffer);
01891     return;
01892   }
01893 
01894   if (isa<ConstantStruct>(CPV)) {
01895     if (CPV->getNumOperands()) {
01896       StructType *ST = cast<StructType>(CPV->getType());
01897       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
01898         if (i == (e - 1))
01899           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
01900                   TD->getTypeAllocSize(ST) -
01901                   TD->getStructLayout(ST)->getElementOffset(i);
01902         else
01903           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
01904                   TD->getStructLayout(ST)->getElementOffset(i);
01905         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
01906       }
01907     }
01908     return;
01909   }
01910   llvm_unreachable("unsupported constant type in printAggregateConstant()");
01911 }
01912 
01913 // buildTypeNameMap - Run through symbol table looking for type names.
01914 //
01915 
01916 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
01917 
01918   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
01919 
01920   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
01921                                   !PI->second.compare("struct._image2d_t") ||
01922                                   !PI->second.compare("struct._image3d_t")))
01923     return true;
01924 
01925   return false;
01926 }
01927 
01928 
01929 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
01930   switch (MI.getOpcode()) {
01931   default:
01932     return false;
01933   case NVPTX::CallArgBeginInst:
01934   case NVPTX::CallArgEndInst0:
01935   case NVPTX::CallArgEndInst1:
01936   case NVPTX::CallArgF32:
01937   case NVPTX::CallArgF64:
01938   case NVPTX::CallArgI16:
01939   case NVPTX::CallArgI32:
01940   case NVPTX::CallArgI32imm:
01941   case NVPTX::CallArgI64:
01942   case NVPTX::CallArgParam:
01943   case NVPTX::CallVoidInst:
01944   case NVPTX::CallVoidInstReg:
01945   case NVPTX::Callseq_End:
01946   case NVPTX::CallVoidInstReg64:
01947   case NVPTX::DeclareParamInst:
01948   case NVPTX::DeclareRetMemInst:
01949   case NVPTX::DeclareRetRegInst:
01950   case NVPTX::DeclareRetScalarInst:
01951   case NVPTX::DeclareScalarParamInst:
01952   case NVPTX::DeclareScalarRegInst:
01953   case NVPTX::StoreParamF32:
01954   case NVPTX::StoreParamF64:
01955   case NVPTX::StoreParamI16:
01956   case NVPTX::StoreParamI32:
01957   case NVPTX::StoreParamI64:
01958   case NVPTX::StoreParamI8:
01959   case NVPTX::StoreRetvalF32:
01960   case NVPTX::StoreRetvalF64:
01961   case NVPTX::StoreRetvalI16:
01962   case NVPTX::StoreRetvalI32:
01963   case NVPTX::StoreRetvalI64:
01964   case NVPTX::StoreRetvalI8:
01965   case NVPTX::LastCallArgF32:
01966   case NVPTX::LastCallArgF64:
01967   case NVPTX::LastCallArgI16:
01968   case NVPTX::LastCallArgI32:
01969   case NVPTX::LastCallArgI32imm:
01970   case NVPTX::LastCallArgI64:
01971   case NVPTX::LastCallArgParam:
01972   case NVPTX::LoadParamMemF32:
01973   case NVPTX::LoadParamMemF64:
01974   case NVPTX::LoadParamMemI16:
01975   case NVPTX::LoadParamMemI32:
01976   case NVPTX::LoadParamMemI64:
01977   case NVPTX::LoadParamMemI8:
01978   case NVPTX::PrototypeInst:
01979   case NVPTX::DBG_VALUE:
01980     return true;
01981   }
01982   return false;
01983 }
01984 
01985 /// lowerConstantForGV - Return an MCExpr for the given Constant.  This is mostly
01986 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
01987 /// expressions that are representable in PTX and create
01988 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
01989 const MCExpr *
01990 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
01991   MCContext &Ctx = OutContext;
01992 
01993   if (CV->isNullValue() || isa<UndefValue>(CV))
01994     return MCConstantExpr::create(0, Ctx);
01995 
01996   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
01997     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
01998 
01999   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
02000     const MCSymbolRefExpr *Expr =
02001       MCSymbolRefExpr::create(getSymbol(GV), Ctx);
02002     if (ProcessingGeneric) {
02003       return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
02004     } else {
02005       return Expr;
02006     }
02007   }
02008 
02009   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
02010   if (!CE) {
02011     llvm_unreachable("Unknown constant value to lower!");
02012   }
02013 
02014   switch (CE->getOpcode()) {
02015   default:
02016     // If the code isn't optimized, there may be outstanding folding
02017     // opportunities. Attempt to fold the expression using DataLayout as a
02018     // last resort before giving up.
02019     if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
02020       if (C != CE)
02021         return lowerConstantForGV(C, ProcessingGeneric);
02022 
02023     // Otherwise report the problem to the user.
02024     {
02025       std::string S;
02026       raw_string_ostream OS(S);
02027       OS << "Unsupported expression in static initializer: ";
02028       CE->printAsOperand(OS, /*PrintType=*/false,
02029                      !MF ? nullptr : MF->getFunction()->getParent());
02030       report_fatal_error(OS.str());
02031     }
02032 
02033   case Instruction::AddrSpaceCast: {
02034     // Strip the addrspacecast and pass along the operand
02035     PointerType *DstTy = cast<PointerType>(CE->getType());
02036     if (DstTy->getAddressSpace() == 0) {
02037       return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
02038     }
02039     std::string S;
02040     raw_string_ostream OS(S);
02041     OS << "Unsupported expression in static initializer: ";
02042     CE->printAsOperand(OS, /*PrintType=*/ false,
02043                        !MF ? 0 : MF->getFunction()->getParent());
02044     report_fatal_error(OS.str());
02045   }
02046 
02047   case Instruction::GetElementPtr: {
02048     const DataLayout &DL = *TM.getDataLayout();
02049 
02050     // Generate a symbolic expression for the byte address
02051     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
02052     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
02053 
02054     const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
02055                                             ProcessingGeneric);
02056     if (!OffsetAI)
02057       return Base;
02058 
02059     int64_t Offset = OffsetAI.getSExtValue();
02060     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
02061                                    Ctx);
02062   }
02063 
02064   case Instruction::Trunc:
02065     // We emit the value and depend on the assembler to truncate the generated
02066     // expression properly.  This is important for differences between
02067     // blockaddress labels.  Since the two labels are in the same function, it
02068     // is reasonable to treat their delta as a 32-bit value.
02069     // FALL THROUGH.
02070   case Instruction::BitCast:
02071     return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
02072 
02073   case Instruction::IntToPtr: {
02074     const DataLayout &DL = *TM.getDataLayout();
02075 
02076     // Handle casts to pointers by changing them into casts to the appropriate
02077     // integer type.  This promotes constant folding and simplifies this code.
02078     Constant *Op = CE->getOperand(0);
02079     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
02080                                       false/*ZExt*/);
02081     return lowerConstantForGV(Op, ProcessingGeneric);
02082   }
02083 
02084   case Instruction::PtrToInt: {
02085     const DataLayout &DL = *TM.getDataLayout();
02086 
02087     // Support only foldable casts to/from pointers that can be eliminated by
02088     // changing the pointer to the appropriately sized integer type.
02089     Constant *Op = CE->getOperand(0);
02090     Type *Ty = CE->getType();
02091 
02092     const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
02093 
02094     // We can emit the pointer value into this slot if the slot is an
02095     // integer slot equal to the size of the pointer.
02096     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
02097       return OpExpr;
02098 
02099     // Otherwise the pointer is smaller than the resultant integer, mask off
02100     // the high bits so we are sure to get a proper truncation if the input is
02101     // a constant expr.
02102     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
02103     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
02104     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
02105   }
02106 
02107   // The MC library also has a right-shift operator, but it isn't consistently
02108   // signed or unsigned between different targets.
02109   case Instruction::Add: {
02110     const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
02111     const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
02112     switch (CE->getOpcode()) {
02113     default: llvm_unreachable("Unknown binary operator constant cast expr");
02114     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
02115     }
02116   }
02117   }
02118 }
02119 
02120 // Copy of MCExpr::print customized for NVPTX
02121 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
02122   switch (Expr.getKind()) {
02123   case MCExpr::Target:
02124     return cast<MCTargetExpr>(&Expr)->printImpl(OS);
02125   case MCExpr::Constant:
02126     OS << cast<MCConstantExpr>(Expr).getValue();
02127     return;
02128 
02129   case MCExpr::SymbolRef: {
02130     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
02131     const MCSymbol &Sym = SRE.getSymbol();
02132     OS << Sym;
02133     return;
02134   }
02135 
02136   case MCExpr::Unary: {
02137     const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
02138     switch (UE.getOpcode()) {
02139     case MCUnaryExpr::LNot:  OS << '!'; break;
02140     case MCUnaryExpr::Minus: OS << '-'; break;
02141     case MCUnaryExpr::Not:   OS << '~'; break;
02142     case MCUnaryExpr::Plus:  OS << '+'; break;
02143     }
02144     printMCExpr(*UE.getSubExpr(), OS);
02145     return;
02146   }
02147 
02148   case MCExpr::Binary: {
02149     const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
02150 
02151     // Only print parens around the LHS if it is non-trivial.
02152     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
02153         isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
02154       printMCExpr(*BE.getLHS(), OS);
02155     } else {
02156       OS << '(';
02157       printMCExpr(*BE.getLHS(), OS);
02158       OS<< ')';
02159     }
02160 
02161     switch (BE.getOpcode()) {
02162     case MCBinaryExpr::Add:
02163       // Print "X-42" instead of "X+-42".
02164       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
02165         if (RHSC->getValue() < 0) {
02166           OS << RHSC->getValue();
02167           return;
02168         }
02169       }
02170 
02171       OS <<  '+';
02172       break;
02173     default: llvm_unreachable("Unhandled binary operator");
02174     }
02175 
02176     // Only print parens around the LHS if it is non-trivial.
02177     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
02178       printMCExpr(*BE.getRHS(), OS);
02179     } else {
02180       OS << '(';
02181       printMCExpr(*BE.getRHS(), OS);
02182       OS << ')';
02183     }
02184     return;
02185   }
02186   }
02187 
02188   llvm_unreachable("Invalid expression kind!");
02189 }
02190 
02191 /// PrintAsmOperand - Print out an operand for an inline asm expression.
02192 ///
02193 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
02194                                       unsigned AsmVariant,
02195                                       const char *ExtraCode, raw_ostream &O) {
02196   if (ExtraCode && ExtraCode[0]) {
02197     if (ExtraCode[1] != 0)
02198       return true; // Unknown modifier.
02199 
02200     switch (ExtraCode[0]) {
02201     default:
02202       // See if this is a generic print operand
02203       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
02204     case 'r':
02205       break;
02206     }
02207   }
02208 
02209   printOperand(MI, OpNo, O);
02210 
02211   return false;
02212 }
02213 
02214 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
02215     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
02216     const char *ExtraCode, raw_ostream &O) {
02217   if (ExtraCode && ExtraCode[0])
02218     return true; // Unknown modifier
02219 
02220   O << '[';
02221   printMemOperand(MI, OpNo, O);
02222   O << ']';
02223 
02224   return false;
02225 }
02226 
02227 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
02228                                    raw_ostream &O, const char *Modifier) {
02229   const MachineOperand &MO = MI->getOperand(opNum);
02230   switch (MO.getType()) {
02231   case MachineOperand::MO_Register:
02232     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
02233       if (MO.getReg() == NVPTX::VRDepot)
02234         O << DEPOTNAME << getFunctionNumber();
02235       else
02236         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
02237     } else {
02238       emitVirtualRegister(MO.getReg(), O);
02239     }
02240     return;
02241 
02242   case MachineOperand::MO_Immediate:
02243     if (!Modifier)
02244       O << MO.getImm();
02245     else if (strstr(Modifier, "vec") == Modifier)
02246       printVecModifiedImmediate(MO, Modifier, O);
02247     else
02248       llvm_unreachable(
02249           "Don't know how to handle modifier on immediate operand");
02250     return;
02251 
02252   case MachineOperand::MO_FPImmediate:
02253     printFPConstant(MO.getFPImm(), O);
02254     break;
02255 
02256   case MachineOperand::MO_GlobalAddress:
02257     O << *getSymbol(MO.getGlobal());
02258     break;
02259 
02260   case MachineOperand::MO_MachineBasicBlock:
02261     O << *MO.getMBB()->getSymbol();
02262     return;
02263 
02264   default:
02265     llvm_unreachable("Operand type not supported.");
02266   }
02267 }
02268 
02269 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
02270                                       raw_ostream &O, const char *Modifier) {
02271   printOperand(MI, opNum, O);
02272 
02273   if (Modifier && !strcmp(Modifier, "add")) {
02274     O << ", ";
02275     printOperand(MI, opNum + 1, O);
02276   } else {
02277     if (MI->getOperand(opNum + 1).isImm() &&
02278         MI->getOperand(opNum + 1).getImm() == 0)
02279       return; // don't print ',0' or '+0'
02280     O << "+";
02281     printOperand(MI, opNum + 1, O);
02282   }
02283 }
02284 
02285 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
02286   std::stringstream temp;
02287   LineReader *reader = this->getReader(filename);
02288   temp << "\n//";
02289   temp << filename.str();
02290   temp << ":";
02291   temp << line;
02292   temp << " ";
02293   temp << reader->readLine(line);
02294   temp << "\n";
02295   this->OutStreamer->EmitRawText(temp.str());
02296 }
02297 
02298 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
02299   if (!reader) {
02300     reader = new LineReader(filename);
02301   }
02302 
02303   if (reader->fileName() != filename) {
02304     delete reader;
02305     reader = new LineReader(filename);
02306   }
02307 
02308   return reader;
02309 }
02310 
02311 std::string LineReader::readLine(unsigned lineNum) {
02312   if (lineNum < theCurLine) {
02313     theCurLine = 0;
02314     fstr.seekg(0, std::ios::beg);
02315   }
02316   while (theCurLine < lineNum) {
02317     fstr.getline(buff, 500);
02318     theCurLine++;
02319   }
02320   return buff;
02321 }
02322 
02323 // Force static initialization.
02324 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
02325   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02326   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02327 }