1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMCExpr.h"
21 #include "NVPTXMachineFunctionInfo.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Mangler.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TimeValue.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Transforms/Utils/UnrollLoop.h"
54 #define DEPOTNAME "__local_depot"
57 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
58 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
62 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
63 cl::desc("NVPTX Specific: Emit source line in ptx file"),
67 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
69 void DiscoverDependentGlobals(const Value *V,
70 DenseSet<const GlobalVariable *> &Globals) {
71 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
74 if (const User *U = dyn_cast<User>(V)) {
75 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76 DiscoverDependentGlobals(U->getOperand(i), Globals);
82 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83 /// instances to be emitted, but only after any dependents have been added
85 void VisitGlobalVariableForEmission(
86 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87 DenseSet<const GlobalVariable *> &Visited,
88 DenseSet<const GlobalVariable *> &Visiting) {
89 // Have we already visited this one?
90 if (Visited.count(GV))
93 // Do we have a circular dependency?
94 if (!Visiting.insert(GV).second)
95 report_fatal_error("Circular dependency found in global variable set");
97 // Make sure we visit all dependents first
98 DenseSet<const GlobalVariable *> Others;
99 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
100 DiscoverDependentGlobals(GV->getOperand(i), Others);
102 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
105 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
107 // Now we can visit ourself
114 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
115 if (!EmitLineNumbers)
120 DebugLoc curLoc = MI.getDebugLoc();
122 if (!prevDebugLoc && !curLoc)
125 if (prevDebugLoc == curLoc)
128 prevDebugLoc = curLoc;
133 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
137 StringRef fileName(Scope->getFilename());
138 StringRef dirName(Scope->getDirectory());
139 SmallString<128> FullPathName = dirName;
140 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
141 sys::path::append(FullPathName, fileName);
142 fileName = FullPathName;
145 if (filenameMap.find(fileName) == filenameMap.end())
148 // Emit the line from the source file.
150 this->emitSrcInText(fileName, curLoc.getLine());
152 std::stringstream temp;
153 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
154 << " " << curLoc.getCol();
155 OutStreamer->EmitRawText(temp.str());
158 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
159 SmallString<128> Str;
160 raw_svector_ostream OS(Str);
161 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
162 emitLineNumberAsDotLoc(*MI);
165 lowerToMCInst(MI, Inst);
166 EmitToStreamer(*OutStreamer, Inst);
169 // Handle symbol backtracking for targets that do not support image handles
170 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
171 unsigned OpNo, MCOperand &MCOp) {
172 const MachineOperand &MO = MI->getOperand(OpNo);
173 const MCInstrDesc &MCID = MI->getDesc();
175 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
176 // This is a texture fetch, so operand 4 is a texref and operand 5 is
178 if (OpNo == 4 && MO.isImm()) {
179 lowerImageHandleSymbol(MO.getImm(), MCOp);
182 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
183 lowerImageHandleSymbol(MO.getImm(), MCOp);
188 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
190 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
192 // For a surface load of vector size N, the Nth operand will be the surfref
193 if (OpNo == VecSize && MO.isImm()) {
194 lowerImageHandleSymbol(MO.getImm(), MCOp);
199 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
200 // This is a surface store, so operand 0 is a surfref
201 if (OpNo == 0 && MO.isImm()) {
202 lowerImageHandleSymbol(MO.getImm(), MCOp);
207 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
208 // This is a query, so operand 1 is a surfref/texref
209 if (OpNo == 1 && MO.isImm()) {
210 lowerImageHandleSymbol(MO.getImm(), MCOp);
220 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
222 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
223 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
224 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
225 const char *Sym = MFI->getImageHandleSymbol(Index);
226 std::string *SymNamePtr =
227 nvTM.getManagedStrPool()->getManagedString(Sym);
228 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(
229 StringRef(SymNamePtr->c_str())));
232 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
233 OutMI.setOpcode(MI->getOpcode());
234 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
235 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
236 const MachineOperand &MO = MI->getOperand(0);
237 OutMI.addOperand(GetSymbolRef(
238 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
242 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
243 const MachineOperand &MO = MI->getOperand(i);
246 if (!nvptxSubtarget->hasImageHandles()) {
247 if (lowerImageHandleOperand(MI, i, MCOp)) {
248 OutMI.addOperand(MCOp);
253 if (lowerOperand(MO, MCOp))
254 OutMI.addOperand(MCOp);
258 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
260 switch (MO.getType()) {
261 default: llvm_unreachable("unknown operand type");
262 case MachineOperand::MO_Register:
263 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
265 case MachineOperand::MO_Immediate:
266 MCOp = MCOperand::createImm(MO.getImm());
268 case MachineOperand::MO_MachineBasicBlock:
269 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
270 MO.getMBB()->getSymbol(), OutContext));
272 case MachineOperand::MO_ExternalSymbol:
273 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
275 case MachineOperand::MO_GlobalAddress:
276 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
278 case MachineOperand::MO_FPImmediate: {
279 const ConstantFP *Cnt = MO.getFPImm();
280 APFloat Val = Cnt->getValueAPF();
282 switch (Cnt->getType()->getTypeID()) {
283 default: report_fatal_error("Unsupported FP type"); break;
284 case Type::FloatTyID:
285 MCOp = MCOperand::createExpr(
286 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
288 case Type::DoubleTyID:
289 MCOp = MCOperand::createExpr(
290 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
299 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
300 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
301 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
303 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
304 unsigned RegNum = RegMap[Reg];
306 // Encode the register class in the upper 4 bits
307 // Must be kept in sync with NVPTXInstPrinter::printRegName
309 if (RC == &NVPTX::Int1RegsRegClass) {
311 } else if (RC == &NVPTX::Int16RegsRegClass) {
313 } else if (RC == &NVPTX::Int32RegsRegClass) {
315 } else if (RC == &NVPTX::Int64RegsRegClass) {
317 } else if (RC == &NVPTX::Float32RegsRegClass) {
319 } else if (RC == &NVPTX::Float64RegsRegClass) {
322 report_fatal_error("Bad register class");
325 // Insert the vreg number
326 Ret |= (RegNum & 0x0FFFFFFF);
329 // Some special-use registers are actually physical registers.
330 // Encode this as the register class ID of 0 and the real register ID.
331 return Reg & 0x0FFFFFFF;
335 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
337 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
339 return MCOperand::createExpr(Expr);
342 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
343 const DataLayout &DL = getDataLayout();
344 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
346 Type *Ty = F->getReturnType();
348 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
350 if (Ty->getTypeID() == Type::VoidTyID)
356 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
358 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
359 size = ITy->getBitWidth();
363 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
364 size = Ty->getPrimitiveSizeInBits();
367 O << ".param .b" << size << " func_retval0";
368 } else if (isa<PointerType>(Ty)) {
369 O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
371 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
372 unsigned totalsz = DL.getTypeAllocSize(Ty);
373 unsigned retAlignment = 0;
374 if (!llvm::getAlign(*F, 0, retAlignment))
375 retAlignment = DL.getABITypeAlignment(Ty);
376 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
379 llvm_unreachable("Unknown return type");
381 SmallVector<EVT, 16> vtparts;
382 ComputeValueVTs(*TLI, DL, Ty, vtparts);
384 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
386 EVT elemtype = vtparts[i];
387 if (vtparts[i].isVector()) {
388 elems = vtparts[i].getVectorNumElements();
389 elemtype = vtparts[i].getVectorElementType();
392 for (unsigned j = 0, je = elems; j != je; ++j) {
393 unsigned sz = elemtype.getSizeInBits();
394 if (elemtype.isInteger() && (sz < 32))
396 O << ".reg .b" << sz << " func_retval" << idx;
409 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
411 const Function *F = MF.getFunction();
412 printReturnValStr(F, O);
415 // Return true if MBB is the header of a loop marked with
416 // llvm.loop.unroll.disable.
417 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
418 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
419 const MachineBasicBlock &MBB) const {
420 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
421 // We insert .pragma "nounroll" only to the loop header.
422 if (!LI.isLoopHeader(&MBB))
425 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
426 // we iterate through each back edge of the loop with header MBB, and check
427 // whether its metadata contains llvm.loop.unroll.disable.
428 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
429 const MachineBasicBlock *PMBB = *I;
430 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
431 // Edges from other loops to MBB are not back edges.
434 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
435 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
436 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
444 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
445 AsmPrinter::EmitBasicBlockStart(MBB);
446 if (isLoopHeaderOfNoUnroll(MBB))
447 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
450 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
451 SmallString<128> Str;
452 raw_svector_ostream O(Str);
454 if (!GlobalsEmitted) {
455 emitGlobals(*MF->getFunction()->getParent());
456 GlobalsEmitted = true;
460 MRI = &MF->getRegInfo();
461 F = MF->getFunction();
462 emitLinkageDirective(F, O);
463 if (llvm::isKernelFunction(*F))
467 printReturnValStr(*MF, O);
470 CurrentFnSym->print(O, MAI);
472 emitFunctionParamList(*MF, O);
474 if (llvm::isKernelFunction(*F))
475 emitKernelFunctionDirectives(*F, O);
477 OutStreamer->EmitRawText(O.str());
479 prevDebugLoc = DebugLoc();
482 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
484 OutStreamer->EmitRawText(StringRef("{\n"));
485 setAndEmitFunctionVirtualRegisters(*MF);
487 SmallString<128> Str;
488 raw_svector_ostream O(Str);
489 emitDemotedVars(MF->getFunction(), O);
490 OutStreamer->EmitRawText(O.str());
493 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
494 OutStreamer->EmitRawText(StringRef("}\n"));
498 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
499 unsigned RegNo = MI->getOperand(0).getReg();
500 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
501 OutStreamer->AddComment(Twine("implicit-def: ") +
502 getVirtualRegisterName(RegNo));
504 OutStreamer->AddComment(Twine("implicit-def: ") +
505 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
507 OutStreamer->AddBlankLine();
510 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
511 raw_ostream &O) const {
512 // If the NVVM IR has some of reqntid* specified, then output
513 // the reqntid directive, and set the unspecified ones to 1.
514 // If none of reqntid* is specified, don't output reqntid directive.
515 unsigned reqntidx, reqntidy, reqntidz;
516 bool specified = false;
517 if (!llvm::getReqNTIDx(F, reqntidx))
521 if (!llvm::getReqNTIDy(F, reqntidy))
525 if (!llvm::getReqNTIDz(F, reqntidz))
531 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
534 // If the NVVM IR has some of maxntid* specified, then output
535 // the maxntid directive, and set the unspecified ones to 1.
536 // If none of maxntid* is specified, don't output maxntid directive.
537 unsigned maxntidx, maxntidy, maxntidz;
539 if (!llvm::getMaxNTIDx(F, maxntidx))
543 if (!llvm::getMaxNTIDy(F, maxntidy))
547 if (!llvm::getMaxNTIDz(F, maxntidz))
553 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
557 if (llvm::getMinCTASm(F, mincta))
558 O << ".minnctapersm " << mincta << "\n";
562 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
563 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
566 raw_string_ostream NameStr(Name);
568 VRegRCMap::const_iterator I = VRegMapping.find(RC);
569 assert(I != VRegMapping.end() && "Bad register class");
570 const DenseMap<unsigned, unsigned> &RegMap = I->second;
572 VRegMap::const_iterator VI = RegMap.find(Reg);
573 assert(VI != RegMap.end() && "Bad virtual register");
574 unsigned MappedVR = VI->second;
576 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
582 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
584 O << getVirtualRegisterName(vr);
587 void NVPTXAsmPrinter::printVecModifiedImmediate(
588 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
589 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
590 int Imm = (int) MO.getImm();
591 if (0 == strcmp(Modifier, "vecelem"))
592 O << "_" << vecelem[Imm];
593 else if (0 == strcmp(Modifier, "vecv4comm1")) {
594 if ((Imm < 0) || (Imm > 3))
596 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
597 if ((Imm < 4) || (Imm > 7))
599 } else if (0 == strcmp(Modifier, "vecv4pos")) {
602 O << "_" << vecelem[Imm % 4];
603 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
604 if ((Imm < 0) || (Imm > 1))
606 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
607 if ((Imm < 2) || (Imm > 3))
609 } else if (0 == strcmp(Modifier, "vecv2pos")) {
612 O << "_" << vecelem[Imm % 2];
614 llvm_unreachable("Unknown Modifier on immediate operand");
619 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
621 emitLinkageDirective(F, O);
622 if (llvm::isKernelFunction(*F))
626 printReturnValStr(F, O);
627 getSymbol(F)->print(O, MAI);
629 emitFunctionParamList(F, O);
633 static bool usedInGlobalVarDef(const Constant *C) {
637 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
638 return GV->getName() != "llvm.used";
641 for (const User *U : C->users())
642 if (const Constant *C = dyn_cast<Constant>(U))
643 if (usedInGlobalVarDef(C))
649 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
650 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
651 if (othergv->getName() == "llvm.used")
655 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
656 if (instr->getParent() && instr->getParent()->getParent()) {
657 const Function *curFunc = instr->getParent()->getParent();
658 if (oneFunc && (curFunc != oneFunc))
666 for (const User *UU : U->users())
667 if (!usedInOneFunc(UU, oneFunc))
673 /* Find out if a global variable can be demoted to local scope.
674 * Currently, this is valid for CUDA shared variables, which have local
675 * scope and global lifetime. So the conditions to check are :
676 * 1. Is the global variable in shared address space?
677 * 2. Does it have internal linkage?
678 * 3. Is the global variable referenced only in one function?
680 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
681 if (!gv->hasInternalLinkage())
683 PointerType *Pty = gv->getType();
684 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
687 const Function *oneFunc = nullptr;
689 bool flag = usedInOneFunc(gv, oneFunc);
698 static bool useFuncSeen(const Constant *C,
699 llvm::DenseMap<const Function *, bool> &seenMap) {
700 for (const User *U : C->users()) {
701 if (const Constant *cu = dyn_cast<Constant>(U)) {
702 if (useFuncSeen(cu, seenMap))
704 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
705 const BasicBlock *bb = I->getParent();
708 const Function *caller = bb->getParent();
711 if (seenMap.find(caller) != seenMap.end())
718 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
719 llvm::DenseMap<const Function *, bool> seenMap;
720 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
721 const Function *F = FI;
723 if (F->isDeclaration()) {
726 if (F->getIntrinsicID())
728 emitDeclaration(F, O);
731 for (const User *U : F->users()) {
732 if (const Constant *C = dyn_cast<Constant>(U)) {
733 if (usedInGlobalVarDef(C)) {
734 // The use is in the initialization of a global variable
735 // that is a function pointer, so print a declaration
736 // for the original function
737 emitDeclaration(F, O);
740 // Emit a declaration of this function if the function that
741 // uses this constant expr has already been seen.
742 if (useFuncSeen(C, seenMap)) {
743 emitDeclaration(F, O);
748 if (!isa<Instruction>(U))
750 const Instruction *instr = cast<Instruction>(U);
751 const BasicBlock *bb = instr->getParent();
754 const Function *caller = bb->getParent();
758 // If a caller has already been seen, then the caller is
759 // appearing in the module before the callee. so print out
760 // a declaration for the callee.
761 if (seenMap.find(caller) != seenMap.end()) {
762 emitDeclaration(F, O);
770 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
771 DebugInfoFinder DbgFinder;
772 DbgFinder.processModule(M);
775 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
776 StringRef Filename = DIUnit->getFilename();
777 StringRef Dirname = DIUnit->getDirectory();
778 SmallString<128> FullPathName = Dirname;
779 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
780 sys::path::append(FullPathName, Filename);
781 Filename = FullPathName;
783 if (filenameMap.find(Filename) != filenameMap.end())
785 filenameMap[Filename] = i;
786 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
790 for (DISubprogram *SP : DbgFinder.subprograms()) {
791 StringRef Filename = SP->getFilename();
792 StringRef Dirname = SP->getDirectory();
793 SmallString<128> FullPathName = Dirname;
794 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
795 sys::path::append(FullPathName, Filename);
796 Filename = FullPathName;
798 if (filenameMap.find(Filename) != filenameMap.end())
800 filenameMap[Filename] = i;
805 bool NVPTXAsmPrinter::doInitialization(Module &M) {
806 // Construct a default subtarget off of the TargetMachine defaults. The
807 // rest of NVPTX isn't friendly to change subtargets per function and
808 // so the default TargetMachine will have all of the options.
809 const Triple &TT = TM.getTargetTriple();
810 StringRef CPU = TM.getTargetCPU();
811 StringRef FS = TM.getTargetFeatureString();
812 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
813 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
815 SmallString<128> Str1;
816 raw_svector_ostream OS1(Str1);
818 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
820 // We need to call the parent's one explicitly.
821 //bool Result = AsmPrinter::doInitialization(M);
823 // Initialize TargetLoweringObjectFile.
824 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
825 .Initialize(OutContext, TM);
827 Mang = new Mangler();
829 // Emit header before any dwarf directives are emitted below.
830 emitHeader(M, OS1, STI);
831 OutStreamer->EmitRawText(OS1.str());
833 // Already commented out
834 //bool Result = AsmPrinter::doInitialization(M);
836 // Emit module-level inline asm if it exists.
837 if (!M.getModuleInlineAsm().empty()) {
838 OutStreamer->AddComment("Start of file scope inline assembly");
839 OutStreamer->AddBlankLine();
840 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
841 OutStreamer->AddBlankLine();
842 OutStreamer->AddComment("End of file scope inline assembly");
843 OutStreamer->AddBlankLine();
846 // If we're not NVCL we're CUDA, go ahead and emit filenames.
847 if (TM.getTargetTriple().getOS() != Triple::NVCL)
848 recordAndEmitFilenames(M);
850 GlobalsEmitted = false;
852 return false; // success
855 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
856 SmallString<128> Str2;
857 raw_svector_ostream OS2(Str2);
859 emitDeclarations(M, OS2);
861 // As ptxas does not support forward references of globals, we need to first
862 // sort the list of module-level globals in def-use order. We visit each
863 // global variable in order, and ensure that we emit it *after* its dependent
864 // globals. We use a little extra memory maintaining both a set and a list to
865 // have fast searches while maintaining a strict ordering.
866 SmallVector<const GlobalVariable *, 8> Globals;
867 DenseSet<const GlobalVariable *> GVVisited;
868 DenseSet<const GlobalVariable *> GVVisiting;
870 // Visit each global variable, in order
871 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
873 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
875 assert(GVVisited.size() == M.getGlobalList().size() &&
876 "Missed a global variable");
877 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
879 // Print out module-level global variables in proper order
880 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
881 printModuleLevelGV(Globals[i], OS2);
885 OutStreamer->EmitRawText(OS2.str());
888 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
889 const NVPTXSubtarget &STI) {
891 O << "// Generated by LLVM NVPTX Back-End\n";
895 unsigned PTXVersion = STI.getPTXVersion();
896 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
899 O << STI.getTargetName();
901 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
902 if (NTM.getDrvInterface() == NVPTX::NVCL)
903 O << ", texmode_independent";
905 if (!STI.hasDouble())
906 O << ", map_f64_to_f32";
909 if (MAI->doesSupportDebugInformation())
914 O << ".address_size ";
924 bool NVPTXAsmPrinter::doFinalization(Module &M) {
925 // If we did not emit any functions, then the global declarations have not
927 if (!GlobalsEmitted) {
929 GlobalsEmitted = true;
932 // XXX Temproarily remove global variables so that doFinalization() will not
933 // emit them again (global variables are emitted at beginning).
935 Module::GlobalListType &global_list = M.getGlobalList();
936 int i, n = global_list.size();
937 GlobalVariable **gv_array = new GlobalVariable *[n];
939 // first, back-up GlobalVariable in gv_array
941 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
945 // second, empty global_list
946 while (!global_list.empty())
947 global_list.remove(global_list.begin());
949 // call doFinalization
950 bool ret = AsmPrinter::doFinalization(M);
952 // now we restore global variables
953 for (i = 0; i < n; i++)
954 global_list.insert(global_list.end(), gv_array[i]);
956 clearAnnotationCache(&M);
961 //bool Result = AsmPrinter::doFinalization(M);
962 // Instead of calling the parents doFinalization, we may
963 // clone parents doFinalization and customize here.
964 // Currently, we if NVISA out the EmitGlobals() in
965 // parent's doFinalization, which is too intrusive.
967 // Same for the doInitialization.
971 // This function emits appropriate linkage directives for
972 // functions and global variables.
974 // extern function declaration -> .extern
975 // extern function definition -> .visible
976 // external global variable with init -> .visible
977 // external without init -> .extern
978 // appending -> not allowed, assert.
979 // for any linkage other than
980 // internal, private, linker_private,
981 // linker_private_weak, linker_private_weak_def_auto,
984 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
986 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
987 if (V->hasExternalLinkage()) {
988 if (isa<GlobalVariable>(V)) {
989 const GlobalVariable *GVar = cast<GlobalVariable>(V);
991 if (GVar->hasInitializer())
996 } else if (V->isDeclaration())
1000 } else if (V->hasAppendingLinkage()) {
1002 msg.append("Error: ");
1003 msg.append("Symbol ");
1005 msg.append(V->getName());
1006 msg.append("has unsupported appending linkage type");
1007 llvm_unreachable(msg.c_str());
1008 } else if (!V->hasInternalLinkage() &&
1009 !V->hasPrivateLinkage()) {
1015 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1017 bool processDemoted) {
1020 if (GVar->hasSection()) {
1021 if (GVar->getSection() == StringRef("llvm.metadata"))
1025 // Skip LLVM intrinsic global variables
1026 if (GVar->getName().startswith("llvm.") ||
1027 GVar->getName().startswith("nvvm."))
1030 const DataLayout &DL = getDataLayout();
1032 // GlobalVariables are always constant pointers themselves.
1033 PointerType *PTy = GVar->getType();
1034 Type *ETy = PTy->getElementType();
1036 if (GVar->hasExternalLinkage()) {
1037 if (GVar->hasInitializer())
1041 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1042 GVar->hasAvailableExternallyLinkage() ||
1043 GVar->hasCommonLinkage()) {
1047 if (llvm::isTexture(*GVar)) {
1048 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1052 if (llvm::isSurface(*GVar)) {
1053 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1057 if (GVar->isDeclaration()) {
1058 // (extern) declarations, no definition or initializer
1059 // Currently the only known declaration is for an automatic __local
1060 // (.shared) promoted to global.
1061 emitPTXGlobalVariable(GVar, O);
1066 if (llvm::isSampler(*GVar)) {
1067 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1069 const Constant *Initializer = nullptr;
1070 if (GVar->hasInitializer())
1071 Initializer = GVar->getInitializer();
1072 const ConstantInt *CI = nullptr;
1074 CI = dyn_cast<ConstantInt>(Initializer);
1076 unsigned sample = CI->getZExtValue();
1081 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1083 O << "addr_mode_" << i << " = ";
1089 O << "clamp_to_border";
1092 O << "clamp_to_edge";
1103 O << "filter_mode = ";
1104 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1112 llvm_unreachable("Anisotropic filtering is not supported");
1117 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1118 O << ", force_unnormalized_coords = 1";
1127 if (GVar->hasPrivateLinkage()) {
1129 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1132 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1133 if (!strncmp(GVar->getName().data(), "filename", 8))
1135 if (GVar->use_empty())
1139 const Function *demotedFunc = nullptr;
1140 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1141 O << "// " << GVar->getName() << " has been demoted\n";
1142 if (localDecls.find(demotedFunc) != localDecls.end())
1143 localDecls[demotedFunc].push_back(GVar);
1145 std::vector<const GlobalVariable *> temp;
1146 temp.push_back(GVar);
1147 localDecls[demotedFunc] = temp;
1153 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1155 if (isManaged(*GVar)) {
1156 O << " .attribute(.managed)";
1159 if (GVar->getAlignment() == 0)
1160 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1162 O << " .align " << GVar->getAlignment();
1164 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1166 // Special case: ABI requires that we use .u8 for predicates
1167 if (ETy->isIntegerTy(1))
1170 O << getPTXFundamentalTypeStr(ETy, false);
1172 getSymbol(GVar)->print(O, MAI);
1174 // Ptx allows variable initilization only for constant and global state
1176 if (GVar->hasInitializer()) {
1177 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1178 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1179 const Constant *Initializer = GVar->getInitializer();
1180 // 'undef' is treated as there is no value specified.
1181 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1183 printScalarConstant(Initializer, O);
1186 // The frontend adds zero-initializer to variables that don't have an
1187 // initial value, so skip warning for this case.
1188 if (!GVar->getInitializer()->isNullValue()) {
1189 report_fatal_error("initial value of '" + GVar->getName() +
1190 "' is not allowed in addrspace(" +
1191 Twine(PTy->getAddressSpace()) + ")");
1196 unsigned int ElementSize = 0;
1198 // Although PTX has direct support for struct type and array type and
1199 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1200 // targets that support these high level field accesses. Structs, arrays
1201 // and vectors are lowered into arrays of bytes.
1202 switch (ETy->getTypeID()) {
1203 case Type::StructTyID:
1204 case Type::ArrayTyID:
1205 case Type::VectorTyID:
1206 ElementSize = DL.getTypeStoreSize(ETy);
1207 // Ptx allows variable initilization only for constant and
1208 // global state spaces.
1209 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1210 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1211 GVar->hasInitializer()) {
1212 const Constant *Initializer = GVar->getInitializer();
1213 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1214 AggBuffer aggBuffer(ElementSize, O, *this);
1215 bufferAggregateConstant(Initializer, &aggBuffer);
1216 if (aggBuffer.numSymbols) {
1217 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1219 getSymbol(GVar)->print(O, MAI);
1221 O << ElementSize / 8;
1224 getSymbol(GVar)->print(O, MAI);
1226 O << ElementSize / 4;
1231 getSymbol(GVar)->print(O, MAI);
1241 getSymbol(GVar)->print(O, MAI);
1250 getSymbol(GVar)->print(O, MAI);
1259 llvm_unreachable("type not supported yet");
1266 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1267 if (localDecls.find(f) == localDecls.end())
1270 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1272 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1273 O << "\t// demoted variable\n\t";
1274 printModuleLevelGV(gvars[i], O, true);
1278 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1279 raw_ostream &O) const {
1280 switch (AddressSpace) {
1281 case llvm::ADDRESS_SPACE_LOCAL:
1284 case llvm::ADDRESS_SPACE_GLOBAL:
1287 case llvm::ADDRESS_SPACE_CONST:
1290 case llvm::ADDRESS_SPACE_SHARED:
1294 report_fatal_error("Bad address space found while emitting PTX");
1300 NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
1301 switch (Ty->getTypeID()) {
1303 llvm_unreachable("unexpected type");
1305 case Type::IntegerTyID: {
1306 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1309 else if (NumBits <= 64) {
1310 std::string name = "u";
1311 return name + utostr(NumBits);
1313 llvm_unreachable("Integer too large");
1318 case Type::FloatTyID:
1320 case Type::DoubleTyID:
1322 case Type::PointerTyID:
1323 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1333 llvm_unreachable("unexpected type");
1337 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1340 const DataLayout &DL = getDataLayout();
1342 // GlobalVariables are always constant pointers themselves.
1343 PointerType *PTy = GVar->getType();
1344 Type *ETy = PTy->getElementType();
1347 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1348 if (GVar->getAlignment() == 0)
1349 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1351 O << " .align " << GVar->getAlignment();
1353 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1355 O << getPTXFundamentalTypeStr(ETy);
1357 getSymbol(GVar)->print(O, MAI);
1361 int64_t ElementSize = 0;
1363 // Although PTX has direct support for struct type and array type and LLVM IR
1364 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1365 // support these high level field accesses. Structs and arrays are lowered
1366 // into arrays of bytes.
1367 switch (ETy->getTypeID()) {
1368 case Type::StructTyID:
1369 case Type::ArrayTyID:
1370 case Type::VectorTyID:
1371 ElementSize = DL.getTypeStoreSize(ETy);
1373 getSymbol(GVar)->print(O, MAI);
1381 llvm_unreachable("type not supported yet");
1386 static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
1387 if (Ty->isSingleValueType())
1388 return DL.getPrefTypeAlignment(Ty);
1390 auto *ATy = dyn_cast<ArrayType>(Ty);
1392 return getOpenCLAlignment(DL, ATy->getElementType());
1394 auto *STy = dyn_cast<StructType>(Ty);
1396 unsigned int alignStruct = 1;
1397 // Go through each element of the struct and find the
1398 // largest alignment.
1399 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1400 Type *ETy = STy->getElementType(i);
1401 unsigned int align = getOpenCLAlignment(DL, ETy);
1402 if (align > alignStruct)
1403 alignStruct = align;
1408 auto *FTy = dyn_cast<FunctionType>(Ty);
1410 return DL.getPointerPrefAlignment();
1411 return DL.getPrefTypeAlignment(Ty);
1414 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1415 int paramIndex, raw_ostream &O) {
1416 getSymbol(I->getParent())->print(O, MAI);
1417 O << "_param_" << paramIndex;
1420 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1421 CurrentFnSym->print(O, MAI);
1422 O << "_param_" << paramIndex;
1425 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1426 const DataLayout &DL = getDataLayout();
1427 const AttributeSet &PAL = F->getAttributes();
1428 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1429 Function::const_arg_iterator I, E;
1430 unsigned paramIndex = 0;
1432 bool isKernelFunc = llvm::isKernelFunction(*F);
1433 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1434 MVT thePointerTy = TLI->getPointerTy(DL);
1438 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1439 Type *Ty = I->getType();
1446 // Handle image/sampler parameters
1447 if (isKernelFunction(*F)) {
1448 if (isSampler(*I) || isImage(*I)) {
1450 std::string sname = I->getName();
1451 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1452 if (nvptxSubtarget->hasImageHandles())
1453 O << "\t.param .u64 .ptr .surfref ";
1455 O << "\t.param .surfref ";
1456 CurrentFnSym->print(O, MAI);
1457 O << "_param_" << paramIndex;
1459 else { // Default image is read_only
1460 if (nvptxSubtarget->hasImageHandles())
1461 O << "\t.param .u64 .ptr .texref ";
1463 O << "\t.param .texref ";
1464 CurrentFnSym->print(O, MAI);
1465 O << "_param_" << paramIndex;
1468 if (nvptxSubtarget->hasImageHandles())
1469 O << "\t.param .u64 .ptr .samplerref ";
1471 O << "\t.param .samplerref ";
1472 CurrentFnSym->print(O, MAI);
1473 O << "_param_" << paramIndex;
1479 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
1480 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1481 // Just print .param .align <a> .b8 .param[size];
1482 // <a> = PAL.getparamalignment
1483 // size = typeallocsize of element type
1484 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1486 align = DL.getABITypeAlignment(Ty);
1488 unsigned sz = DL.getTypeAllocSize(Ty);
1489 O << "\t.param .align " << align << " .b8 ";
1490 printParamName(I, paramIndex, O);
1491 O << "[" << sz << "]";
1496 auto *PTy = dyn_cast<PointerType>(Ty);
1499 // Special handling for pointer arguments to kernel
1500 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1502 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1504 Type *ETy = PTy->getElementType();
1505 int addrSpace = PTy->getAddressSpace();
1506 switch (addrSpace) {
1510 case llvm::ADDRESS_SPACE_CONST:
1511 O << ".ptr .const ";
1513 case llvm::ADDRESS_SPACE_SHARED:
1514 O << ".ptr .shared ";
1516 case llvm::ADDRESS_SPACE_GLOBAL:
1517 O << ".ptr .global ";
1520 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
1522 printParamName(I, paramIndex, O);
1526 // non-pointer scalar to kernel func
1528 // Special case: predicate operands become .u8 types
1529 if (Ty->isIntegerTy(1))
1532 O << getPTXFundamentalTypeStr(Ty);
1534 printParamName(I, paramIndex, O);
1537 // Non-kernel function, just print .param .b<size> for ABI
1538 // and .reg .b<size> for non-ABI
1540 if (isa<IntegerType>(Ty)) {
1541 sz = cast<IntegerType>(Ty)->getBitWidth();
1544 } else if (isa<PointerType>(Ty))
1545 sz = thePointerTy.getSizeInBits();
1547 sz = Ty->getPrimitiveSizeInBits();
1549 O << "\t.param .b" << sz << " ";
1551 O << "\t.reg .b" << sz << " ";
1552 printParamName(I, paramIndex, O);
1556 // param has byVal attribute. So should be a pointer
1557 auto *PTy = dyn_cast<PointerType>(Ty);
1558 assert(PTy && "Param with byval attribute should be a pointer type");
1559 Type *ETy = PTy->getElementType();
1561 if (isABI || isKernelFunc) {
1562 // Just print .param .align <a> .b8 .param[size];
1563 // <a> = PAL.getparamalignment
1564 // size = typeallocsize of element type
1565 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1567 align = DL.getABITypeAlignment(ETy);
1569 unsigned sz = DL.getTypeAllocSize(ETy);
1570 O << "\t.param .align " << align << " .b8 ";
1571 printParamName(I, paramIndex, O);
1572 O << "[" << sz << "]";
1575 // Split the ETy into constituent parts and
1576 // print .param .b<size> <name> for each part.
1577 // Further, if a part is vector, print the above for
1578 // each vector element.
1579 SmallVector<EVT, 16> vtparts;
1580 ComputeValueVTs(*TLI, DL, ETy, vtparts);
1581 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1583 EVT elemtype = vtparts[i];
1584 if (vtparts[i].isVector()) {
1585 elems = vtparts[i].getVectorNumElements();
1586 elemtype = vtparts[i].getVectorElementType();
1589 for (unsigned j = 0, je = elems; j != je; ++j) {
1590 unsigned sz = elemtype.getSizeInBits();
1591 if (elemtype.isInteger() && (sz < 32))
1593 O << "\t.reg .b" << sz << " ";
1594 printParamName(I, paramIndex, O);
1610 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1612 const Function *F = MF.getFunction();
1613 emitFunctionParamList(F, O);
1616 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1617 const MachineFunction &MF) {
1618 SmallString<128> Str;
1619 raw_svector_ostream O(Str);
1621 // Map the global virtual register number to a register class specific
1622 // virtual register number starting from 1 with that class.
1623 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1624 //unsigned numRegClasses = TRI->getNumRegClasses();
1626 // Emit the Fake Stack Object
1627 const MachineFrameInfo *MFI = MF.getFrameInfo();
1628 int NumBytes = (int) MFI->getStackSize();
1630 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1631 << getFunctionNumber() << "[" << NumBytes << "];\n";
1632 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1633 O << "\t.reg .b64 \t%SP;\n";
1634 O << "\t.reg .b64 \t%SPL;\n";
1636 O << "\t.reg .b32 \t%SP;\n";
1637 O << "\t.reg .b32 \t%SPL;\n";
1641 // Go through all virtual registers to establish the mapping between the
1643 // register number and the per class virtual register number.
1644 // We use the per class virtual register number in the ptx output.
1645 unsigned int numVRs = MRI->getNumVirtRegs();
1646 for (unsigned i = 0; i < numVRs; i++) {
1647 unsigned int vr = TRI->index2VirtReg(i);
1648 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1649 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1650 int n = regmap.size();
1651 regmap.insert(std::make_pair(vr, n + 1));
1654 // Emit register declarations
1655 // @TODO: Extract out the real register usage
1656 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1657 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1658 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1659 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1660 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1661 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1662 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1664 // Emit declaration of the virtual registers or 'physical' registers for
1665 // each register class
1666 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1667 const TargetRegisterClass *RC = TRI->getRegClass(i);
1668 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1669 std::string rcname = getNVPTXRegClassName(RC);
1670 std::string rcStr = getNVPTXRegClassStr(RC);
1671 int n = regmap.size();
1673 // Only declare those registers that may be used.
1675 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1680 OutStreamer->EmitRawText(O.str());
1683 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1684 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1686 unsigned int numHex;
1689 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1692 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1693 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1696 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1698 llvm_unreachable("unsupported fp type");
1700 APInt API = APF.bitcastToAPInt();
1701 std::string hexstr(utohexstr(API.getZExtValue()));
1703 if (hexstr.length() < numHex)
1704 O << std::string(numHex - hexstr.length(), '0');
1705 O << utohexstr(API.getZExtValue());
1708 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1709 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1710 O << CI->getValue();
1713 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1714 printFPConstant(CFP, O);
1717 if (isa<ConstantPointerNull>(CPV)) {
1721 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1722 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1723 bool IsNonGenericPointer = false;
1724 if (PTy && PTy->getAddressSpace() != 0) {
1725 IsNonGenericPointer = true;
1727 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1729 getSymbol(GVar)->print(O, MAI);
1732 getSymbol(GVar)->print(O, MAI);
1736 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1737 const Value *v = Cexpr->stripPointerCasts();
1738 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1739 bool IsNonGenericPointer = false;
1740 if (PTy && PTy->getAddressSpace() != 0) {
1741 IsNonGenericPointer = true;
1743 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1744 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1746 getSymbol(GVar)->print(O, MAI);
1749 getSymbol(GVar)->print(O, MAI);
1753 lowerConstant(CPV)->print(O, MAI);
1757 llvm_unreachable("Not scalar type found in printScalarConstant()");
1760 // These utility functions assure we get the right sequence of bytes for a given
1761 // type even for big-endian machines
1762 template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1763 int64_t vp = (int64_t)val;
1764 for (unsigned i = 0; i < sizeof(T); ++i) {
1765 p[i] = (unsigned char)vp;
1769 static void ConvertFloatToBytes(unsigned char *p, float val) {
1770 int32_t *vp = (int32_t *)&val;
1771 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1772 p[i] = (unsigned char)*vp;
1776 static void ConvertDoubleToBytes(unsigned char *p, double val) {
1777 int64_t *vp = (int64_t *)&val;
1778 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1779 p[i] = (unsigned char)*vp;
1784 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1785 AggBuffer *aggBuffer) {
1787 const DataLayout &DL = getDataLayout();
1789 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1790 int s = DL.getTypeAllocSize(CPV->getType());
1793 aggBuffer->addZeros(s);
1797 unsigned char ptr[8];
1798 switch (CPV->getType()->getTypeID()) {
1800 case Type::IntegerTyID: {
1801 Type *ETy = CPV->getType();
1802 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1803 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1804 ConvertIntToBytes<>(ptr, c);
1805 aggBuffer->addBytes(ptr, 1, Bytes);
1806 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1807 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1808 ConvertIntToBytes<>(ptr, int16);
1809 aggBuffer->addBytes(ptr, 2, Bytes);
1810 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1811 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1812 int int32 = (int)(constInt->getZExtValue());
1813 ConvertIntToBytes<>(ptr, int32);
1814 aggBuffer->addBytes(ptr, 4, Bytes);
1816 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1817 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1818 ConstantFoldConstantExpression(Cexpr, DL))) {
1819 int int32 = (int)(constInt->getZExtValue());
1820 ConvertIntToBytes<>(ptr, int32);
1821 aggBuffer->addBytes(ptr, 4, Bytes);
1824 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1825 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1826 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1827 aggBuffer->addZeros(4);
1831 llvm_unreachable("unsupported integer const type");
1832 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1833 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1834 long long int64 = (long long)(constInt->getZExtValue());
1835 ConvertIntToBytes<>(ptr, int64);
1836 aggBuffer->addBytes(ptr, 8, Bytes);
1838 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1839 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1840 ConstantFoldConstantExpression(Cexpr, DL))) {
1841 long long int64 = (long long)(constInt->getZExtValue());
1842 ConvertIntToBytes<>(ptr, int64);
1843 aggBuffer->addBytes(ptr, 8, Bytes);
1846 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1847 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1848 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1849 aggBuffer->addZeros(8);
1853 llvm_unreachable("unsupported integer const type");
1855 llvm_unreachable("unsupported integer const type");
1858 case Type::FloatTyID:
1859 case Type::DoubleTyID: {
1860 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1861 Type *Ty = CFP->getType();
1862 if (Ty == Type::getFloatTy(CPV->getContext())) {
1863 float float32 = (float) CFP->getValueAPF().convertToFloat();
1864 ConvertFloatToBytes(ptr, float32);
1865 aggBuffer->addBytes(ptr, 4, Bytes);
1866 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1867 double float64 = CFP->getValueAPF().convertToDouble();
1868 ConvertDoubleToBytes(ptr, float64);
1869 aggBuffer->addBytes(ptr, 8, Bytes);
1871 llvm_unreachable("unsupported fp const type");
1875 case Type::PointerTyID: {
1876 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1877 aggBuffer->addSymbol(GVar, GVar);
1878 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1879 const Value *v = Cexpr->stripPointerCasts();
1880 aggBuffer->addSymbol(v, Cexpr);
1882 unsigned int s = DL.getTypeAllocSize(CPV->getType());
1883 aggBuffer->addZeros(s);
1887 case Type::ArrayTyID:
1888 case Type::VectorTyID:
1889 case Type::StructTyID: {
1890 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1891 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1892 int ElementSize = DL.getTypeAllocSize(CPV->getType());
1893 bufferAggregateConstant(CPV, aggBuffer);
1894 if (Bytes > ElementSize)
1895 aggBuffer->addZeros(Bytes - ElementSize);
1896 } else if (isa<ConstantAggregateZero>(CPV))
1897 aggBuffer->addZeros(Bytes);
1899 llvm_unreachable("Unexpected Constant type");
1904 llvm_unreachable("unsupported type");
1908 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1909 AggBuffer *aggBuffer) {
1910 const DataLayout &DL = getDataLayout();
1914 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1915 if (CPV->getNumOperands())
1916 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1917 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1921 if (const ConstantDataSequential *CDS =
1922 dyn_cast<ConstantDataSequential>(CPV)) {
1923 if (CDS->getNumElements())
1924 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1925 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1930 if (isa<ConstantStruct>(CPV)) {
1931 if (CPV->getNumOperands()) {
1932 StructType *ST = cast<StructType>(CPV->getType());
1933 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1935 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1936 DL.getTypeAllocSize(ST) -
1937 DL.getStructLayout(ST)->getElementOffset(i);
1939 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1940 DL.getStructLayout(ST)->getElementOffset(i);
1941 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1946 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1949 // buildTypeNameMap - Run through symbol table looking for type names.
1952 bool NVPTXAsmPrinter::isImageType(Type *Ty) {
1954 std::map<Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1956 return PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1957 !PI->second.compare("struct._image2d_t") ||
1958 !PI->second.compare("struct._image3d_t"));
1962 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1963 switch (MI.getOpcode()) {
1966 case NVPTX::CallArgBeginInst:
1967 case NVPTX::CallArgEndInst0:
1968 case NVPTX::CallArgEndInst1:
1969 case NVPTX::CallArgF32:
1970 case NVPTX::CallArgF64:
1971 case NVPTX::CallArgI16:
1972 case NVPTX::CallArgI32:
1973 case NVPTX::CallArgI32imm:
1974 case NVPTX::CallArgI64:
1975 case NVPTX::CallArgParam:
1976 case NVPTX::CallVoidInst:
1977 case NVPTX::CallVoidInstReg:
1978 case NVPTX::Callseq_End:
1979 case NVPTX::CallVoidInstReg64:
1980 case NVPTX::DeclareParamInst:
1981 case NVPTX::DeclareRetMemInst:
1982 case NVPTX::DeclareRetRegInst:
1983 case NVPTX::DeclareRetScalarInst:
1984 case NVPTX::DeclareScalarParamInst:
1985 case NVPTX::DeclareScalarRegInst:
1986 case NVPTX::StoreParamF32:
1987 case NVPTX::StoreParamF64:
1988 case NVPTX::StoreParamI16:
1989 case NVPTX::StoreParamI32:
1990 case NVPTX::StoreParamI64:
1991 case NVPTX::StoreParamI8:
1992 case NVPTX::StoreRetvalF32:
1993 case NVPTX::StoreRetvalF64:
1994 case NVPTX::StoreRetvalI16:
1995 case NVPTX::StoreRetvalI32:
1996 case NVPTX::StoreRetvalI64:
1997 case NVPTX::StoreRetvalI8:
1998 case NVPTX::LastCallArgF32:
1999 case NVPTX::LastCallArgF64:
2000 case NVPTX::LastCallArgI16:
2001 case NVPTX::LastCallArgI32:
2002 case NVPTX::LastCallArgI32imm:
2003 case NVPTX::LastCallArgI64:
2004 case NVPTX::LastCallArgParam:
2005 case NVPTX::LoadParamMemF32:
2006 case NVPTX::LoadParamMemF64:
2007 case NVPTX::LoadParamMemI16:
2008 case NVPTX::LoadParamMemI32:
2009 case NVPTX::LoadParamMemI64:
2010 case NVPTX::LoadParamMemI8:
2011 case NVPTX::PrototypeInst:
2012 case NVPTX::DBG_VALUE:
2018 /// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2019 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
2020 /// expressions that are representable in PTX and create
2021 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2023 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2024 MCContext &Ctx = OutContext;
2026 if (CV->isNullValue() || isa<UndefValue>(CV))
2027 return MCConstantExpr::create(0, Ctx);
2029 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2030 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2032 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2033 const MCSymbolRefExpr *Expr =
2034 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2035 if (ProcessingGeneric) {
2036 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2042 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2044 llvm_unreachable("Unknown constant value to lower!");
2047 switch (CE->getOpcode()) {
2049 // If the code isn't optimized, there may be outstanding folding
2050 // opportunities. Attempt to fold the expression using DataLayout as a
2051 // last resort before giving up.
2052 if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout()))
2054 return lowerConstantForGV(C, ProcessingGeneric);
2056 // Otherwise report the problem to the user.
2059 raw_string_ostream OS(S);
2060 OS << "Unsupported expression in static initializer: ";
2061 CE->printAsOperand(OS, /*PrintType=*/false,
2062 !MF ? nullptr : MF->getFunction()->getParent());
2063 report_fatal_error(OS.str());
2066 case Instruction::AddrSpaceCast: {
2067 // Strip the addrspacecast and pass along the operand
2068 PointerType *DstTy = cast<PointerType>(CE->getType());
2069 if (DstTy->getAddressSpace() == 0) {
2070 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2073 raw_string_ostream OS(S);
2074 OS << "Unsupported expression in static initializer: ";
2075 CE->printAsOperand(OS, /*PrintType=*/ false,
2076 !MF ? 0 : MF->getFunction()->getParent());
2077 report_fatal_error(OS.str());
2080 case Instruction::GetElementPtr: {
2081 const DataLayout &DL = getDataLayout();
2083 // Generate a symbolic expression for the byte address
2084 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2085 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2087 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2092 int64_t Offset = OffsetAI.getSExtValue();
2093 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2097 case Instruction::Trunc:
2098 // We emit the value and depend on the assembler to truncate the generated
2099 // expression properly. This is important for differences between
2100 // blockaddress labels. Since the two labels are in the same function, it
2101 // is reasonable to treat their delta as a 32-bit value.
2103 case Instruction::BitCast:
2104 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2106 case Instruction::IntToPtr: {
2107 const DataLayout &DL = getDataLayout();
2109 // Handle casts to pointers by changing them into casts to the appropriate
2110 // integer type. This promotes constant folding and simplifies this code.
2111 Constant *Op = CE->getOperand(0);
2112 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2114 return lowerConstantForGV(Op, ProcessingGeneric);
2117 case Instruction::PtrToInt: {
2118 const DataLayout &DL = getDataLayout();
2120 // Support only foldable casts to/from pointers that can be eliminated by
2121 // changing the pointer to the appropriately sized integer type.
2122 Constant *Op = CE->getOperand(0);
2123 Type *Ty = CE->getType();
2125 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2127 // We can emit the pointer value into this slot if the slot is an
2128 // integer slot equal to the size of the pointer.
2129 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2132 // Otherwise the pointer is smaller than the resultant integer, mask off
2133 // the high bits so we are sure to get a proper truncation if the input is
2135 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2136 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2137 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2140 // The MC library also has a right-shift operator, but it isn't consistently
2141 // signed or unsigned between different targets.
2142 case Instruction::Add: {
2143 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2144 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2145 switch (CE->getOpcode()) {
2146 default: llvm_unreachable("Unknown binary operator constant cast expr");
2147 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2153 // Copy of MCExpr::print customized for NVPTX
2154 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2155 switch (Expr.getKind()) {
2156 case MCExpr::Target:
2157 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
2158 case MCExpr::Constant:
2159 OS << cast<MCConstantExpr>(Expr).getValue();
2162 case MCExpr::SymbolRef: {
2163 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2164 const MCSymbol &Sym = SRE.getSymbol();
2169 case MCExpr::Unary: {
2170 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2171 switch (UE.getOpcode()) {
2172 case MCUnaryExpr::LNot: OS << '!'; break;
2173 case MCUnaryExpr::Minus: OS << '-'; break;
2174 case MCUnaryExpr::Not: OS << '~'; break;
2175 case MCUnaryExpr::Plus: OS << '+'; break;
2177 printMCExpr(*UE.getSubExpr(), OS);
2181 case MCExpr::Binary: {
2182 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2184 // Only print parens around the LHS if it is non-trivial.
2185 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2186 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2187 printMCExpr(*BE.getLHS(), OS);
2190 printMCExpr(*BE.getLHS(), OS);
2194 switch (BE.getOpcode()) {
2195 case MCBinaryExpr::Add:
2196 // Print "X-42" instead of "X+-42".
2197 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2198 if (RHSC->getValue() < 0) {
2199 OS << RHSC->getValue();
2206 default: llvm_unreachable("Unhandled binary operator");
2209 // Only print parens around the LHS if it is non-trivial.
2210 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2211 printMCExpr(*BE.getRHS(), OS);
2214 printMCExpr(*BE.getRHS(), OS);
2221 llvm_unreachable("Invalid expression kind!");
2224 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2226 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2227 unsigned AsmVariant,
2228 const char *ExtraCode, raw_ostream &O) {
2229 if (ExtraCode && ExtraCode[0]) {
2230 if (ExtraCode[1] != 0)
2231 return true; // Unknown modifier.
2233 switch (ExtraCode[0]) {
2235 // See if this is a generic print operand
2236 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2242 printOperand(MI, OpNo, O);
2247 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2248 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2249 const char *ExtraCode, raw_ostream &O) {
2250 if (ExtraCode && ExtraCode[0])
2251 return true; // Unknown modifier
2254 printMemOperand(MI, OpNo, O);
2260 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2261 raw_ostream &O, const char *Modifier) {
2262 const MachineOperand &MO = MI->getOperand(opNum);
2263 switch (MO.getType()) {
2264 case MachineOperand::MO_Register:
2265 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2266 if (MO.getReg() == NVPTX::VRDepot)
2267 O << DEPOTNAME << getFunctionNumber();
2269 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2271 emitVirtualRegister(MO.getReg(), O);
2275 case MachineOperand::MO_Immediate:
2278 else if (strstr(Modifier, "vec") == Modifier)
2279 printVecModifiedImmediate(MO, Modifier, O);
2282 "Don't know how to handle modifier on immediate operand");
2285 case MachineOperand::MO_FPImmediate:
2286 printFPConstant(MO.getFPImm(), O);
2289 case MachineOperand::MO_GlobalAddress:
2290 getSymbol(MO.getGlobal())->print(O, MAI);
2293 case MachineOperand::MO_MachineBasicBlock:
2294 MO.getMBB()->getSymbol()->print(O, MAI);
2298 llvm_unreachable("Operand type not supported.");
2302 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2303 raw_ostream &O, const char *Modifier) {
2304 printOperand(MI, opNum, O);
2306 if (Modifier && !strcmp(Modifier, "add")) {
2308 printOperand(MI, opNum + 1, O);
2310 if (MI->getOperand(opNum + 1).isImm() &&
2311 MI->getOperand(opNum + 1).getImm() == 0)
2312 return; // don't print ',0' or '+0'
2314 printOperand(MI, opNum + 1, O);
2318 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2319 std::stringstream temp;
2320 LineReader *reader = this->getReader(filename);
2322 temp << filename.str();
2326 temp << reader->readLine(line);
2328 this->OutStreamer->EmitRawText(temp.str());
2331 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2333 reader = new LineReader(filename);
2336 if (reader->fileName() != filename) {
2338 reader = new LineReader(filename);
2344 std::string LineReader::readLine(unsigned lineNum) {
2345 if (lineNum < theCurLine) {
2347 fstr.seekg(0, std::ios::beg);
2349 while (theCurLine < lineNum) {
2350 fstr.getline(buff, 500);
2356 // Force static initialization.
2357 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2358 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2359 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);