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/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TimeValue.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Transforms/Utils/UnrollLoop.h"
53 #define DEPOTNAME "__local_depot"
56 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
61 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
62 cl::desc("NVPTX Specific: Emit source line in ptx file"),
66 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
68 void DiscoverDependentGlobals(const Value *V,
69 DenseSet<const GlobalVariable *> &Globals) {
70 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
73 if (const User *U = dyn_cast<User>(V)) {
74 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
75 DiscoverDependentGlobals(U->getOperand(i), Globals);
81 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
82 /// instances to be emitted, but only after any dependents have been added
84 void VisitGlobalVariableForEmission(
85 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
86 DenseSet<const GlobalVariable *> &Visited,
87 DenseSet<const GlobalVariable *> &Visiting) {
88 // Have we already visited this one?
89 if (Visited.count(GV))
92 // Do we have a circular dependency?
93 if (!Visiting.insert(GV).second)
94 report_fatal_error("Circular dependency found in global variable set");
96 // Make sure we visit all dependents first
97 DenseSet<const GlobalVariable *> Others;
98 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99 DiscoverDependentGlobals(GV->getOperand(i), Others);
101 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
104 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
106 // Now we can visit ourself
113 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
114 if (!EmitLineNumbers)
119 DebugLoc curLoc = MI.getDebugLoc();
121 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
124 if (prevDebugLoc == curLoc)
127 prevDebugLoc = curLoc;
129 if (curLoc.isUnknown())
132 const MachineFunction *MF = MI.getParent()->getParent();
133 //const TargetMachine &TM = MF->getTarget();
135 const LLVMContext &ctx = MF->getFunction()->getContext();
136 DIScope Scope(curLoc.getScope(ctx));
138 assert((!Scope || Scope.isScope()) &&
139 "Scope of a DebugLoc should be null or a DIScope.");
143 StringRef fileName(Scope.getFilename());
144 StringRef dirName(Scope.getDirectory());
145 SmallString<128> FullPathName = dirName;
146 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
147 sys::path::append(FullPathName, fileName);
148 fileName = FullPathName.str();
151 if (filenameMap.find(fileName.str()) == filenameMap.end())
154 // Emit the line from the source file.
156 this->emitSrcInText(fileName.str(), curLoc.getLine());
158 std::stringstream temp;
159 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
160 << " " << curLoc.getCol();
161 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
164 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
165 SmallString<128> Str;
166 raw_svector_ostream OS(Str);
167 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
168 emitLineNumberAsDotLoc(*MI);
171 lowerToMCInst(MI, Inst);
172 EmitToStreamer(OutStreamer, Inst);
175 // Handle symbol backtracking for targets that do not support image handles
176 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
177 unsigned OpNo, MCOperand &MCOp) {
178 const MachineOperand &MO = MI->getOperand(OpNo);
179 const MCInstrDesc &MCID = MI->getDesc();
181 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
182 // This is a texture fetch, so operand 4 is a texref and operand 5 is
184 if (OpNo == 4 && MO.isImm()) {
185 lowerImageHandleSymbol(MO.getImm(), MCOp);
188 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
189 lowerImageHandleSymbol(MO.getImm(), MCOp);
194 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
196 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
198 // For a surface load of vector size N, the Nth operand will be the surfref
199 if (OpNo == VecSize && MO.isImm()) {
200 lowerImageHandleSymbol(MO.getImm(), MCOp);
205 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
206 // This is a surface store, so operand 0 is a surfref
207 if (OpNo == 0 && MO.isImm()) {
208 lowerImageHandleSymbol(MO.getImm(), MCOp);
213 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
214 // This is a query, so operand 1 is a surfref/texref
215 if (OpNo == 1 && MO.isImm()) {
216 lowerImageHandleSymbol(MO.getImm(), MCOp);
226 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
228 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
229 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
230 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
231 const char *Sym = MFI->getImageHandleSymbol(Index);
232 std::string *SymNamePtr =
233 nvTM.getManagedStrPool()->getManagedString(Sym);
234 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
235 StringRef(SymNamePtr->c_str())));
238 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
239 OutMI.setOpcode(MI->getOpcode());
240 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
242 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
243 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
244 const MachineOperand &MO = MI->getOperand(0);
245 OutMI.addOperand(GetSymbolRef(
246 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
250 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
251 const MachineOperand &MO = MI->getOperand(i);
254 if (!ST.hasImageHandles()) {
255 if (lowerImageHandleOperand(MI, i, MCOp)) {
256 OutMI.addOperand(MCOp);
261 if (lowerOperand(MO, MCOp))
262 OutMI.addOperand(MCOp);
266 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
268 switch (MO.getType()) {
269 default: llvm_unreachable("unknown operand type");
270 case MachineOperand::MO_Register:
271 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
273 case MachineOperand::MO_Immediate:
274 MCOp = MCOperand::CreateImm(MO.getImm());
276 case MachineOperand::MO_MachineBasicBlock:
277 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
278 MO.getMBB()->getSymbol(), OutContext));
280 case MachineOperand::MO_ExternalSymbol:
281 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
283 case MachineOperand::MO_GlobalAddress:
284 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
286 case MachineOperand::MO_FPImmediate: {
287 const ConstantFP *Cnt = MO.getFPImm();
288 APFloat Val = Cnt->getValueAPF();
290 switch (Cnt->getType()->getTypeID()) {
291 default: report_fatal_error("Unsupported FP type"); break;
292 case Type::FloatTyID:
293 MCOp = MCOperand::CreateExpr(
294 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
296 case Type::DoubleTyID:
297 MCOp = MCOperand::CreateExpr(
298 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
307 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
308 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
309 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
311 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
312 unsigned RegNum = RegMap[Reg];
314 // Encode the register class in the upper 4 bits
315 // Must be kept in sync with NVPTXInstPrinter::printRegName
317 if (RC == &NVPTX::Int1RegsRegClass) {
319 } else if (RC == &NVPTX::Int16RegsRegClass) {
321 } else if (RC == &NVPTX::Int32RegsRegClass) {
323 } else if (RC == &NVPTX::Int64RegsRegClass) {
325 } else if (RC == &NVPTX::Float32RegsRegClass) {
327 } else if (RC == &NVPTX::Float64RegsRegClass) {
330 report_fatal_error("Bad register class");
333 // Insert the vreg number
334 Ret |= (RegNum & 0x0FFFFFFF);
337 // Some special-use registers are actually physical registers.
338 // Encode this as the register class ID of 0 and the real register ID.
339 return Reg & 0x0FFFFFFF;
343 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
345 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
347 return MCOperand::CreateExpr(Expr);
350 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
351 const DataLayout *TD = TM.getDataLayout();
352 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
354 Type *Ty = F->getReturnType();
356 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
358 if (Ty->getTypeID() == Type::VoidTyID)
364 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
366 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
367 size = ITy->getBitWidth();
371 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
372 size = Ty->getPrimitiveSizeInBits();
375 O << ".param .b" << size << " func_retval0";
376 } else if (isa<PointerType>(Ty)) {
377 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
379 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
380 unsigned totalsz = TD->getTypeAllocSize(Ty);
381 unsigned retAlignment = 0;
382 if (!llvm::getAlign(*F, 0, retAlignment))
383 retAlignment = TD->getABITypeAlignment(Ty);
384 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
387 llvm_unreachable("Unknown return type");
389 SmallVector<EVT, 16> vtparts;
390 ComputeValueVTs(*TLI, Ty, vtparts);
392 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
394 EVT elemtype = vtparts[i];
395 if (vtparts[i].isVector()) {
396 elems = vtparts[i].getVectorNumElements();
397 elemtype = vtparts[i].getVectorElementType();
400 for (unsigned j = 0, je = elems; j != je; ++j) {
401 unsigned sz = elemtype.getSizeInBits();
402 if (elemtype.isInteger() && (sz < 32))
404 O << ".reg .b" << sz << " func_retval" << idx;
417 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
419 const Function *F = MF.getFunction();
420 printReturnValStr(F, O);
423 // Return true if MBB is the header of a loop marked with
424 // llvm.loop.unroll.disable.
425 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
426 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
427 const MachineBasicBlock &MBB) const {
428 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
429 // TODO: isLoopHeader() should take "const MachineBasicBlock *".
430 // We insert .pragma "nounroll" only to the loop header.
431 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
434 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
435 // we iterate through each back edge of the loop with header MBB, and check
436 // whether its metadata contains llvm.loop.unroll.disable.
437 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
438 const MachineBasicBlock *PMBB = *I;
439 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
440 // Edges from other loops to MBB are not back edges.
443 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
444 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
445 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
453 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
454 AsmPrinter::EmitBasicBlockStart(MBB);
455 if (isLoopHeaderOfNoUnroll(MBB))
456 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
459 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
460 SmallString<128> Str;
461 raw_svector_ostream O(Str);
463 if (!GlobalsEmitted) {
464 emitGlobals(*MF->getFunction()->getParent());
465 GlobalsEmitted = true;
469 MRI = &MF->getRegInfo();
470 F = MF->getFunction();
471 emitLinkageDirective(F, O);
472 if (llvm::isKernelFunction(*F))
476 printReturnValStr(*MF, O);
481 emitFunctionParamList(*MF, O);
483 if (llvm::isKernelFunction(*F))
484 emitKernelFunctionDirectives(*F, O);
486 OutStreamer.EmitRawText(O.str());
488 prevDebugLoc = DebugLoc();
491 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
493 OutStreamer.EmitRawText(StringRef("{\n"));
494 setAndEmitFunctionVirtualRegisters(*MF);
496 SmallString<128> Str;
497 raw_svector_ostream O(Str);
498 emitDemotedVars(MF->getFunction(), O);
499 OutStreamer.EmitRawText(O.str());
502 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
503 OutStreamer.EmitRawText(StringRef("}\n"));
507 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
508 unsigned RegNo = MI->getOperand(0).getReg();
509 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
510 if (TRI->isVirtualRegister(RegNo)) {
511 OutStreamer.AddComment(Twine("implicit-def: ") +
512 getVirtualRegisterName(RegNo));
514 OutStreamer.AddComment(
515 Twine("implicit-def: ") +
516 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
518 OutStreamer.AddBlankLine();
521 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
522 raw_ostream &O) const {
523 // If the NVVM IR has some of reqntid* specified, then output
524 // the reqntid directive, and set the unspecified ones to 1.
525 // If none of reqntid* is specified, don't output reqntid directive.
526 unsigned reqntidx, reqntidy, reqntidz;
527 bool specified = false;
528 if (llvm::getReqNTIDx(F, reqntidx) == false)
532 if (llvm::getReqNTIDy(F, reqntidy) == false)
536 if (llvm::getReqNTIDz(F, reqntidz) == false)
542 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
545 // If the NVVM IR has some of maxntid* specified, then output
546 // the maxntid directive, and set the unspecified ones to 1.
547 // If none of maxntid* is specified, don't output maxntid directive.
548 unsigned maxntidx, maxntidy, maxntidz;
550 if (llvm::getMaxNTIDx(F, maxntidx) == false)
554 if (llvm::getMaxNTIDy(F, maxntidy) == false)
558 if (llvm::getMaxNTIDz(F, maxntidz) == false)
564 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
568 if (llvm::getMinCTASm(F, mincta))
569 O << ".minnctapersm " << mincta << "\n";
573 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
574 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
577 raw_string_ostream NameStr(Name);
579 VRegRCMap::const_iterator I = VRegMapping.find(RC);
580 assert(I != VRegMapping.end() && "Bad register class");
581 const DenseMap<unsigned, unsigned> &RegMap = I->second;
583 VRegMap::const_iterator VI = RegMap.find(Reg);
584 assert(VI != RegMap.end() && "Bad virtual register");
585 unsigned MappedVR = VI->second;
587 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
593 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
595 O << getVirtualRegisterName(vr);
598 void NVPTXAsmPrinter::printVecModifiedImmediate(
599 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
600 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
601 int Imm = (int) MO.getImm();
602 if (0 == strcmp(Modifier, "vecelem"))
603 O << "_" << vecelem[Imm];
604 else if (0 == strcmp(Modifier, "vecv4comm1")) {
605 if ((Imm < 0) || (Imm > 3))
607 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
608 if ((Imm < 4) || (Imm > 7))
610 } else if (0 == strcmp(Modifier, "vecv4pos")) {
613 O << "_" << vecelem[Imm % 4];
614 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
615 if ((Imm < 0) || (Imm > 1))
617 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
618 if ((Imm < 2) || (Imm > 3))
620 } else if (0 == strcmp(Modifier, "vecv2pos")) {
623 O << "_" << vecelem[Imm % 2];
625 llvm_unreachable("Unknown Modifier on immediate operand");
630 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
632 emitLinkageDirective(F, O);
633 if (llvm::isKernelFunction(*F))
637 printReturnValStr(F, O);
638 O << *getSymbol(F) << "\n";
639 emitFunctionParamList(F, O);
643 static bool usedInGlobalVarDef(const Constant *C) {
647 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
648 if (GV->getName().str() == "llvm.used")
653 for (const User *U : C->users())
654 if (const Constant *C = dyn_cast<Constant>(U))
655 if (usedInGlobalVarDef(C))
661 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
662 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
663 if (othergv->getName().str() == "llvm.used")
667 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
668 if (instr->getParent() && instr->getParent()->getParent()) {
669 const Function *curFunc = instr->getParent()->getParent();
670 if (oneFunc && (curFunc != oneFunc))
678 for (const User *UU : U->users())
679 if (usedInOneFunc(UU, oneFunc) == false)
685 /* Find out if a global variable can be demoted to local scope.
686 * Currently, this is valid for CUDA shared variables, which have local
687 * scope and global lifetime. So the conditions to check are :
688 * 1. Is the global variable in shared address space?
689 * 2. Does it have internal linkage?
690 * 3. Is the global variable referenced only in one function?
692 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
693 if (gv->hasInternalLinkage() == false)
695 const PointerType *Pty = gv->getType();
696 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
699 const Function *oneFunc = nullptr;
701 bool flag = usedInOneFunc(gv, oneFunc);
710 static bool useFuncSeen(const Constant *C,
711 llvm::DenseMap<const Function *, bool> &seenMap) {
712 for (const User *U : C->users()) {
713 if (const Constant *cu = dyn_cast<Constant>(U)) {
714 if (useFuncSeen(cu, seenMap))
716 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
717 const BasicBlock *bb = I->getParent();
720 const Function *caller = bb->getParent();
723 if (seenMap.find(caller) != seenMap.end())
730 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
731 llvm::DenseMap<const Function *, bool> seenMap;
732 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
733 const Function *F = FI;
735 if (F->isDeclaration()) {
738 if (F->getIntrinsicID())
740 emitDeclaration(F, O);
743 for (const User *U : F->users()) {
744 if (const Constant *C = dyn_cast<Constant>(U)) {
745 if (usedInGlobalVarDef(C)) {
746 // The use is in the initialization of a global variable
747 // that is a function pointer, so print a declaration
748 // for the original function
749 emitDeclaration(F, O);
752 // Emit a declaration of this function if the function that
753 // uses this constant expr has already been seen.
754 if (useFuncSeen(C, seenMap)) {
755 emitDeclaration(F, O);
760 if (!isa<Instruction>(U))
762 const Instruction *instr = cast<Instruction>(U);
763 const BasicBlock *bb = instr->getParent();
766 const Function *caller = bb->getParent();
770 // If a caller has already been seen, then the caller is
771 // appearing in the module before the callee. so print out
772 // a declaration for the callee.
773 if (seenMap.find(caller) != seenMap.end()) {
774 emitDeclaration(F, O);
782 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
783 DebugInfoFinder DbgFinder;
784 DbgFinder.processModule(M);
787 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
788 StringRef Filename(DIUnit.getFilename());
789 StringRef Dirname(DIUnit.getDirectory());
790 SmallString<128> FullPathName = Dirname;
791 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
792 sys::path::append(FullPathName, Filename);
793 Filename = FullPathName.str();
795 if (filenameMap.find(Filename.str()) != filenameMap.end())
797 filenameMap[Filename.str()] = i;
798 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
802 for (DISubprogram SP : DbgFinder.subprograms()) {
803 StringRef Filename(SP.getFilename());
804 StringRef Dirname(SP.getDirectory());
805 SmallString<128> FullPathName = Dirname;
806 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
807 sys::path::append(FullPathName, Filename);
808 Filename = FullPathName.str();
810 if (filenameMap.find(Filename.str()) != filenameMap.end())
812 filenameMap[Filename.str()] = i;
817 bool NVPTXAsmPrinter::doInitialization(Module &M) {
819 SmallString<128> Str1;
820 raw_svector_ostream OS1(Str1);
822 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
823 MMI->AnalyzeModule(M);
825 // We need to call the parent's one explicitly.
826 //bool Result = AsmPrinter::doInitialization(M);
828 // Initialize TargetLoweringObjectFile.
829 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
830 .Initialize(OutContext, TM);
832 Mang = new Mangler(TM.getDataLayout());
834 // Emit header before any dwarf directives are emitted below.
836 OutStreamer.EmitRawText(OS1.str());
838 // Already commented out
839 //bool Result = AsmPrinter::doInitialization(M);
841 // Emit module-level inline asm if it exists.
842 if (!M.getModuleInlineAsm().empty()) {
843 OutStreamer.AddComment("Start of file scope inline assembly");
844 OutStreamer.AddBlankLine();
845 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
846 OutStreamer.AddBlankLine();
847 OutStreamer.AddComment("End of file scope inline assembly");
848 OutStreamer.AddBlankLine();
851 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
852 recordAndEmitFilenames(M);
854 GlobalsEmitted = false;
856 return false; // success
859 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
860 SmallString<128> Str2;
861 raw_svector_ostream OS2(Str2);
863 emitDeclarations(M, OS2);
865 // As ptxas does not support forward references of globals, we need to first
866 // sort the list of module-level globals in def-use order. We visit each
867 // global variable in order, and ensure that we emit it *after* its dependent
868 // globals. We use a little extra memory maintaining both a set and a list to
869 // have fast searches while maintaining a strict ordering.
870 SmallVector<const GlobalVariable *, 8> Globals;
871 DenseSet<const GlobalVariable *> GVVisited;
872 DenseSet<const GlobalVariable *> GVVisiting;
874 // Visit each global variable, in order
875 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
877 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
879 assert(GVVisited.size() == M.getGlobalList().size() &&
880 "Missed a global variable");
881 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
883 // Print out module-level global variables in proper order
884 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
885 printModuleLevelGV(Globals[i], OS2);
889 OutStreamer.EmitRawText(OS2.str());
892 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
894 O << "// Generated by LLVM NVPTX Back-End\n";
898 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
899 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
902 O << nvptxSubtarget.getTargetName();
904 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
905 O << ", texmode_independent";
906 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
907 if (!nvptxSubtarget.hasDouble())
908 O << ", map_f64_to_f32";
911 if (MAI->doesSupportDebugInformation())
916 O << ".address_size ";
917 if (nvptxSubtarget.is64Bit())
926 bool NVPTXAsmPrinter::doFinalization(Module &M) {
928 // If we did not emit any functions, then the global declarations have not
930 if (!GlobalsEmitted) {
932 GlobalsEmitted = true;
935 // XXX Temproarily remove global variables so that doFinalization() will not
936 // emit them again (global variables are emitted at beginning).
938 Module::GlobalListType &global_list = M.getGlobalList();
939 int i, n = global_list.size();
940 GlobalVariable **gv_array = new GlobalVariable *[n];
942 // first, back-up GlobalVariable in gv_array
944 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
948 // second, empty global_list
949 while (!global_list.empty())
950 global_list.remove(global_list.begin());
952 // call doFinalization
953 bool ret = AsmPrinter::doFinalization(M);
955 // now we restore global variables
956 for (i = 0; i < n; i++)
957 global_list.insert(global_list.end(), gv_array[i]);
959 clearAnnotationCache(&M);
964 //bool Result = AsmPrinter::doFinalization(M);
965 // Instead of calling the parents doFinalization, we may
966 // clone parents doFinalization and customize here.
967 // Currently, we if NVISA out the EmitGlobals() in
968 // parent's doFinalization, which is too intrusive.
970 // Same for the doInitialization.
974 // This function emits appropriate linkage directives for
975 // functions and global variables.
977 // extern function declaration -> .extern
978 // extern function definition -> .visible
979 // external global variable with init -> .visible
980 // external without init -> .extern
981 // appending -> not allowed, assert.
982 // for any linkage other than
983 // internal, private, linker_private,
984 // linker_private_weak, linker_private_weak_def_auto,
987 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
989 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
990 if (V->hasExternalLinkage()) {
991 if (isa<GlobalVariable>(V)) {
992 const GlobalVariable *GVar = cast<GlobalVariable>(V);
994 if (GVar->hasInitializer())
999 } else if (V->isDeclaration())
1003 } else if (V->hasAppendingLinkage()) {
1005 msg.append("Error: ");
1006 msg.append("Symbol ");
1008 msg.append(V->getName().str());
1009 msg.append("has unsupported appending linkage type");
1010 llvm_unreachable(msg.c_str());
1011 } else if (!V->hasInternalLinkage() &&
1012 !V->hasPrivateLinkage()) {
1018 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1020 bool processDemoted) {
1023 if (GVar->hasSection()) {
1024 if (GVar->getSection() == StringRef("llvm.metadata"))
1028 // Skip LLVM intrinsic global variables
1029 if (GVar->getName().startswith("llvm.") ||
1030 GVar->getName().startswith("nvvm."))
1033 const DataLayout *TD = TM.getDataLayout();
1035 // GlobalVariables are always constant pointers themselves.
1036 const PointerType *PTy = GVar->getType();
1037 Type *ETy = PTy->getElementType();
1039 if (GVar->hasExternalLinkage()) {
1040 if (GVar->hasInitializer())
1044 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1045 GVar->hasAvailableExternallyLinkage() ||
1046 GVar->hasCommonLinkage()) {
1050 if (llvm::isTexture(*GVar)) {
1051 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1055 if (llvm::isSurface(*GVar)) {
1056 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1060 if (GVar->isDeclaration()) {
1061 // (extern) declarations, no definition or initializer
1062 // Currently the only known declaration is for an automatic __local
1063 // (.shared) promoted to global.
1064 emitPTXGlobalVariable(GVar, O);
1069 if (llvm::isSampler(*GVar)) {
1070 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1072 const Constant *Initializer = nullptr;
1073 if (GVar->hasInitializer())
1074 Initializer = GVar->getInitializer();
1075 const ConstantInt *CI = nullptr;
1077 CI = dyn_cast<ConstantInt>(Initializer);
1079 unsigned sample = CI->getZExtValue();
1084 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1086 O << "addr_mode_" << i << " = ";
1092 O << "clamp_to_border";
1095 O << "clamp_to_edge";
1106 O << "filter_mode = ";
1107 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1115 llvm_unreachable("Anisotropic filtering is not supported");
1120 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1121 O << ", force_unnormalized_coords = 1";
1130 if (GVar->hasPrivateLinkage()) {
1132 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1135 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1136 if (!strncmp(GVar->getName().data(), "filename", 8))
1138 if (GVar->use_empty())
1142 const Function *demotedFunc = nullptr;
1143 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1144 O << "// " << GVar->getName().str() << " has been demoted\n";
1145 if (localDecls.find(demotedFunc) != localDecls.end())
1146 localDecls[demotedFunc].push_back(GVar);
1148 std::vector<const GlobalVariable *> temp;
1149 temp.push_back(GVar);
1150 localDecls[demotedFunc] = temp;
1156 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1158 if (isManaged(*GVar)) {
1159 O << " .attribute(.managed)";
1162 if (GVar->getAlignment() == 0)
1163 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1165 O << " .align " << GVar->getAlignment();
1167 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1169 // Special case: ABI requires that we use .u8 for predicates
1170 if (ETy->isIntegerTy(1))
1173 O << getPTXFundamentalTypeStr(ETy, false);
1175 O << *getSymbol(GVar);
1177 // Ptx allows variable initilization only for constant and global state
1179 if (GVar->hasInitializer()) {
1180 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1181 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1182 const Constant *Initializer = GVar->getInitializer();
1183 // 'undef' is treated as there is no value spefied.
1184 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1186 printScalarConstant(Initializer, O);
1189 // The frontend adds zero-initializer to variables that don't have an
1190 // initial value, so skip warning for this case.
1191 if (!GVar->getInitializer()->isNullValue()) {
1192 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1193 "' is not allowed in addrspace(" +
1194 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1195 report_fatal_error(warnMsg.c_str());
1200 unsigned int ElementSize = 0;
1202 // Although PTX has direct support for struct type and array type and
1203 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1204 // targets that support these high level field accesses. Structs, arrays
1205 // and vectors are lowered into arrays of bytes.
1206 switch (ETy->getTypeID()) {
1207 case Type::StructTyID:
1208 case Type::ArrayTyID:
1209 case Type::VectorTyID:
1210 ElementSize = TD->getTypeStoreSize(ETy);
1211 // Ptx allows variable initilization only for constant and
1212 // global state spaces.
1213 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1214 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1215 GVar->hasInitializer()) {
1216 const Constant *Initializer = GVar->getInitializer();
1217 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1218 AggBuffer aggBuffer(ElementSize, O, *this);
1219 bufferAggregateConstant(Initializer, &aggBuffer);
1220 if (aggBuffer.numSymbols) {
1221 if (nvptxSubtarget.is64Bit()) {
1222 O << " .u64 " << *getSymbol(GVar) << "[";
1223 O << ElementSize / 8;
1225 O << " .u32 " << *getSymbol(GVar) << "[";
1226 O << ElementSize / 4;
1230 O << " .b8 " << *getSymbol(GVar) << "[";
1238 O << " .b8 " << *getSymbol(GVar);
1246 O << " .b8 " << *getSymbol(GVar);
1255 llvm_unreachable("type not supported yet");
1262 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1263 if (localDecls.find(f) == localDecls.end())
1266 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1268 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1269 O << "\t// demoted variable\n\t";
1270 printModuleLevelGV(gvars[i], O, true);
1274 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1275 raw_ostream &O) const {
1276 switch (AddressSpace) {
1277 case llvm::ADDRESS_SPACE_LOCAL:
1280 case llvm::ADDRESS_SPACE_GLOBAL:
1283 case llvm::ADDRESS_SPACE_CONST:
1286 case llvm::ADDRESS_SPACE_SHARED:
1290 report_fatal_error("Bad address space found while emitting PTX");
1296 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1297 switch (Ty->getTypeID()) {
1299 llvm_unreachable("unexpected type");
1301 case Type::IntegerTyID: {
1302 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1305 else if (NumBits <= 64) {
1306 std::string name = "u";
1307 return name + utostr(NumBits);
1309 llvm_unreachable("Integer too large");
1314 case Type::FloatTyID:
1316 case Type::DoubleTyID:
1318 case Type::PointerTyID:
1319 if (nvptxSubtarget.is64Bit())
1329 llvm_unreachable("unexpected type");
1333 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1336 const DataLayout *TD = TM.getDataLayout();
1338 // GlobalVariables are always constant pointers themselves.
1339 const PointerType *PTy = GVar->getType();
1340 Type *ETy = PTy->getElementType();
1343 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1344 if (GVar->getAlignment() == 0)
1345 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1347 O << " .align " << GVar->getAlignment();
1349 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1351 O << getPTXFundamentalTypeStr(ETy);
1353 O << *getSymbol(GVar);
1357 int64_t ElementSize = 0;
1359 // Although PTX has direct support for struct type and array type and LLVM IR
1360 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1361 // support these high level field accesses. Structs and arrays are lowered
1362 // into arrays of bytes.
1363 switch (ETy->getTypeID()) {
1364 case Type::StructTyID:
1365 case Type::ArrayTyID:
1366 case Type::VectorTyID:
1367 ElementSize = TD->getTypeStoreSize(ETy);
1368 O << " .b8 " << *getSymbol(GVar) << "[";
1370 O << itostr(ElementSize);
1375 llvm_unreachable("type not supported yet");
1380 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1381 if (Ty->isSingleValueType())
1382 return TD->getPrefTypeAlignment(Ty);
1384 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1386 return getOpenCLAlignment(TD, ATy->getElementType());
1388 const StructType *STy = dyn_cast<StructType>(Ty);
1390 unsigned int alignStruct = 1;
1391 // Go through each element of the struct and find the
1392 // largest alignment.
1393 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1394 Type *ETy = STy->getElementType(i);
1395 unsigned int align = getOpenCLAlignment(TD, ETy);
1396 if (align > alignStruct)
1397 alignStruct = align;
1402 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1404 return TD->getPointerPrefAlignment();
1405 return TD->getPrefTypeAlignment(Ty);
1408 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1409 int paramIndex, raw_ostream &O) {
1410 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1411 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1412 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1414 std::string argName = I->getName();
1415 const char *p = argName.c_str();
1426 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1427 Function::const_arg_iterator I, E;
1430 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1431 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1432 O << *CurrentFnSym << "_param_" << paramIndex;
1436 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1437 if (i == paramIndex) {
1438 printParamName(I, paramIndex, O);
1442 llvm_unreachable("paramIndex out of bound");
1445 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1446 const DataLayout *TD = TM.getDataLayout();
1447 const AttributeSet &PAL = F->getAttributes();
1448 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1449 Function::const_arg_iterator I, E;
1450 unsigned paramIndex = 0;
1452 bool isKernelFunc = llvm::isKernelFunction(*F);
1453 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1454 MVT thePointerTy = TLI->getPointerTy();
1458 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1459 Type *Ty = I->getType();
1466 // Handle image/sampler parameters
1467 if (isKernelFunction(*F)) {
1468 if (isSampler(*I) || isImage(*I)) {
1470 std::string sname = I->getName();
1471 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1472 if (nvptxSubtarget.hasImageHandles())
1473 O << "\t.param .u64 .ptr .surfref ";
1475 O << "\t.param .surfref ";
1476 O << *CurrentFnSym << "_param_" << paramIndex;
1478 else { // Default image is read_only
1479 if (nvptxSubtarget.hasImageHandles())
1480 O << "\t.param .u64 .ptr .texref ";
1482 O << "\t.param .texref ";
1483 O << *CurrentFnSym << "_param_" << paramIndex;
1486 if (nvptxSubtarget.hasImageHandles())
1487 O << "\t.param .u64 .ptr .samplerref ";
1489 O << "\t.param .samplerref ";
1490 O << *CurrentFnSym << "_param_" << paramIndex;
1496 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1497 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1498 // Just print .param .align <a> .b8 .param[size];
1499 // <a> = PAL.getparamalignment
1500 // size = typeallocsize of element type
1501 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1503 align = TD->getABITypeAlignment(Ty);
1505 unsigned sz = TD->getTypeAllocSize(Ty);
1506 O << "\t.param .align " << align << " .b8 ";
1507 printParamName(I, paramIndex, O);
1508 O << "[" << sz << "]";
1513 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1516 // Special handling for pointer arguments to kernel
1517 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1519 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1520 Type *ETy = PTy->getElementType();
1521 int addrSpace = PTy->getAddressSpace();
1522 switch (addrSpace) {
1526 case llvm::ADDRESS_SPACE_CONST:
1527 O << ".ptr .const ";
1529 case llvm::ADDRESS_SPACE_SHARED:
1530 O << ".ptr .shared ";
1532 case llvm::ADDRESS_SPACE_GLOBAL:
1533 O << ".ptr .global ";
1536 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1538 printParamName(I, paramIndex, O);
1542 // non-pointer scalar to kernel func
1544 // Special case: predicate operands become .u8 types
1545 if (Ty->isIntegerTy(1))
1548 O << getPTXFundamentalTypeStr(Ty);
1550 printParamName(I, paramIndex, O);
1553 // Non-kernel function, just print .param .b<size> for ABI
1554 // and .reg .b<size> for non-ABI
1556 if (isa<IntegerType>(Ty)) {
1557 sz = cast<IntegerType>(Ty)->getBitWidth();
1560 } else if (isa<PointerType>(Ty))
1561 sz = thePointerTy.getSizeInBits();
1563 sz = Ty->getPrimitiveSizeInBits();
1565 O << "\t.param .b" << sz << " ";
1567 O << "\t.reg .b" << sz << " ";
1568 printParamName(I, paramIndex, O);
1572 // param has byVal attribute. So should be a pointer
1573 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1574 assert(PTy && "Param with byval attribute should be a pointer type");
1575 Type *ETy = PTy->getElementType();
1577 if (isABI || isKernelFunc) {
1578 // Just print .param .align <a> .b8 .param[size];
1579 // <a> = PAL.getparamalignment
1580 // size = typeallocsize of element type
1581 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1583 align = TD->getABITypeAlignment(ETy);
1585 unsigned sz = TD->getTypeAllocSize(ETy);
1586 O << "\t.param .align " << align << " .b8 ";
1587 printParamName(I, paramIndex, O);
1588 O << "[" << sz << "]";
1591 // Split the ETy into constituent parts and
1592 // print .param .b<size> <name> for each part.
1593 // Further, if a part is vector, print the above for
1594 // each vector element.
1595 SmallVector<EVT, 16> vtparts;
1596 ComputeValueVTs(*TLI, ETy, vtparts);
1597 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1599 EVT elemtype = vtparts[i];
1600 if (vtparts[i].isVector()) {
1601 elems = vtparts[i].getVectorNumElements();
1602 elemtype = vtparts[i].getVectorElementType();
1605 for (unsigned j = 0, je = elems; j != je; ++j) {
1606 unsigned sz = elemtype.getSizeInBits();
1607 if (elemtype.isInteger() && (sz < 32))
1609 O << "\t.reg .b" << sz << " ";
1610 printParamName(I, paramIndex, O);
1626 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1628 const Function *F = MF.getFunction();
1629 emitFunctionParamList(F, O);
1632 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1633 const MachineFunction &MF) {
1634 SmallString<128> Str;
1635 raw_svector_ostream O(Str);
1637 // Map the global virtual register number to a register class specific
1638 // virtual register number starting from 1 with that class.
1639 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1640 //unsigned numRegClasses = TRI->getNumRegClasses();
1642 // Emit the Fake Stack Object
1643 const MachineFrameInfo *MFI = MF.getFrameInfo();
1644 int NumBytes = (int) MFI->getStackSize();
1646 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1647 << getFunctionNumber() << "[" << NumBytes << "];\n";
1648 if (nvptxSubtarget.is64Bit()) {
1649 O << "\t.reg .b64 \t%SP;\n";
1650 O << "\t.reg .b64 \t%SPL;\n";
1652 O << "\t.reg .b32 \t%SP;\n";
1653 O << "\t.reg .b32 \t%SPL;\n";
1657 // Go through all virtual registers to establish the mapping between the
1659 // register number and the per class virtual register number.
1660 // We use the per class virtual register number in the ptx output.
1661 unsigned int numVRs = MRI->getNumVirtRegs();
1662 for (unsigned i = 0; i < numVRs; i++) {
1663 unsigned int vr = TRI->index2VirtReg(i);
1664 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1665 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1666 int n = regmap.size();
1667 regmap.insert(std::make_pair(vr, n + 1));
1670 // Emit register declarations
1671 // @TODO: Extract out the real register usage
1672 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1673 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1674 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1675 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1676 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1677 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1678 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1680 // Emit declaration of the virtual registers or 'physical' registers for
1681 // each register class
1682 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1683 const TargetRegisterClass *RC = TRI->getRegClass(i);
1684 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1685 std::string rcname = getNVPTXRegClassName(RC);
1686 std::string rcStr = getNVPTXRegClassStr(RC);
1687 int n = regmap.size();
1689 // Only declare those registers that may be used.
1691 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1696 OutStreamer.EmitRawText(O.str());
1699 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1700 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1702 unsigned int numHex;
1705 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1708 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1709 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1712 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1714 llvm_unreachable("unsupported fp type");
1716 APInt API = APF.bitcastToAPInt();
1717 std::string hexstr(utohexstr(API.getZExtValue()));
1719 if (hexstr.length() < numHex)
1720 O << std::string(numHex - hexstr.length(), '0');
1721 O << utohexstr(API.getZExtValue());
1724 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1725 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1726 O << CI->getValue();
1729 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1730 printFPConstant(CFP, O);
1733 if (isa<ConstantPointerNull>(CPV)) {
1737 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1738 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1739 bool IsNonGenericPointer = false;
1740 if (PTy && PTy->getAddressSpace() != 0) {
1741 IsNonGenericPointer = true;
1743 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1745 O << *getSymbol(GVar);
1748 O << *getSymbol(GVar);
1752 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1753 const Value *v = Cexpr->stripPointerCasts();
1754 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1755 bool IsNonGenericPointer = false;
1756 if (PTy && PTy->getAddressSpace() != 0) {
1757 IsNonGenericPointer = true;
1759 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1760 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1762 O << *getSymbol(GVar);
1765 O << *getSymbol(GVar);
1769 O << *lowerConstant(CPV);
1773 llvm_unreachable("Not scalar type found in printScalarConstant()");
1776 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1777 AggBuffer *aggBuffer) {
1779 const DataLayout *TD = TM.getDataLayout();
1781 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1782 int s = TD->getTypeAllocSize(CPV->getType());
1785 aggBuffer->addZeros(s);
1790 switch (CPV->getType()->getTypeID()) {
1792 case Type::IntegerTyID: {
1793 const Type *ETy = CPV->getType();
1794 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1796 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1798 aggBuffer->addBytes(ptr, 1, Bytes);
1799 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1800 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1801 ptr = (unsigned char *)&int16;
1802 aggBuffer->addBytes(ptr, 2, Bytes);
1803 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1804 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1805 int int32 = (int)(constInt->getZExtValue());
1806 ptr = (unsigned char *)&int32;
1807 aggBuffer->addBytes(ptr, 4, Bytes);
1809 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1810 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1811 ConstantFoldConstantExpression(Cexpr, TD))) {
1812 int int32 = (int)(constInt->getZExtValue());
1813 ptr = (unsigned char *)&int32;
1814 aggBuffer->addBytes(ptr, 4, Bytes);
1817 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1818 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1819 aggBuffer->addSymbol(v);
1820 aggBuffer->addZeros(4);
1824 llvm_unreachable("unsupported integer const type");
1825 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1826 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1827 long long int64 = (long long)(constInt->getZExtValue());
1828 ptr = (unsigned char *)&int64;
1829 aggBuffer->addBytes(ptr, 8, Bytes);
1831 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1832 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1833 ConstantFoldConstantExpression(Cexpr, TD))) {
1834 long long int64 = (long long)(constInt->getZExtValue());
1835 ptr = (unsigned char *)&int64;
1836 aggBuffer->addBytes(ptr, 8, Bytes);
1839 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1840 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1841 aggBuffer->addSymbol(v);
1842 aggBuffer->addZeros(8);
1846 llvm_unreachable("unsupported integer const type");
1848 llvm_unreachable("unsupported integer const type");
1851 case Type::FloatTyID:
1852 case Type::DoubleTyID: {
1853 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1854 const Type *Ty = CFP->getType();
1855 if (Ty == Type::getFloatTy(CPV->getContext())) {
1856 float float32 = (float) CFP->getValueAPF().convertToFloat();
1857 ptr = (unsigned char *)&float32;
1858 aggBuffer->addBytes(ptr, 4, Bytes);
1859 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1860 double float64 = CFP->getValueAPF().convertToDouble();
1861 ptr = (unsigned char *)&float64;
1862 aggBuffer->addBytes(ptr, 8, Bytes);
1864 llvm_unreachable("unsupported fp const type");
1868 case Type::PointerTyID: {
1869 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1870 aggBuffer->addSymbol(GVar);
1871 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1872 const Value *v = Cexpr->stripPointerCasts();
1873 aggBuffer->addSymbol(v);
1875 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1876 aggBuffer->addZeros(s);
1880 case Type::ArrayTyID:
1881 case Type::VectorTyID:
1882 case Type::StructTyID: {
1883 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1884 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1885 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1886 bufferAggregateConstant(CPV, aggBuffer);
1887 if (Bytes > ElementSize)
1888 aggBuffer->addZeros(Bytes - ElementSize);
1889 } else if (isa<ConstantAggregateZero>(CPV))
1890 aggBuffer->addZeros(Bytes);
1892 llvm_unreachable("Unexpected Constant type");
1897 llvm_unreachable("unsupported type");
1901 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1902 AggBuffer *aggBuffer) {
1903 const DataLayout *TD = TM.getDataLayout();
1907 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1908 if (CPV->getNumOperands())
1909 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1910 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1914 if (const ConstantDataSequential *CDS =
1915 dyn_cast<ConstantDataSequential>(CPV)) {
1916 if (CDS->getNumElements())
1917 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1918 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1923 if (isa<ConstantStruct>(CPV)) {
1924 if (CPV->getNumOperands()) {
1925 StructType *ST = cast<StructType>(CPV->getType());
1926 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1928 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1929 TD->getTypeAllocSize(ST) -
1930 TD->getStructLayout(ST)->getElementOffset(i);
1932 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1933 TD->getStructLayout(ST)->getElementOffset(i);
1934 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1939 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1942 // buildTypeNameMap - Run through symbol table looking for type names.
1945 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1947 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1949 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1950 !PI->second.compare("struct._image2d_t") ||
1951 !PI->second.compare("struct._image3d_t")))
1958 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1959 switch (MI.getOpcode()) {
1962 case NVPTX::CallArgBeginInst:
1963 case NVPTX::CallArgEndInst0:
1964 case NVPTX::CallArgEndInst1:
1965 case NVPTX::CallArgF32:
1966 case NVPTX::CallArgF64:
1967 case NVPTX::CallArgI16:
1968 case NVPTX::CallArgI32:
1969 case NVPTX::CallArgI32imm:
1970 case NVPTX::CallArgI64:
1971 case NVPTX::CallArgParam:
1972 case NVPTX::CallVoidInst:
1973 case NVPTX::CallVoidInstReg:
1974 case NVPTX::Callseq_End:
1975 case NVPTX::CallVoidInstReg64:
1976 case NVPTX::DeclareParamInst:
1977 case NVPTX::DeclareRetMemInst:
1978 case NVPTX::DeclareRetRegInst:
1979 case NVPTX::DeclareRetScalarInst:
1980 case NVPTX::DeclareScalarParamInst:
1981 case NVPTX::DeclareScalarRegInst:
1982 case NVPTX::StoreParamF32:
1983 case NVPTX::StoreParamF64:
1984 case NVPTX::StoreParamI16:
1985 case NVPTX::StoreParamI32:
1986 case NVPTX::StoreParamI64:
1987 case NVPTX::StoreParamI8:
1988 case NVPTX::StoreRetvalF32:
1989 case NVPTX::StoreRetvalF64:
1990 case NVPTX::StoreRetvalI16:
1991 case NVPTX::StoreRetvalI32:
1992 case NVPTX::StoreRetvalI64:
1993 case NVPTX::StoreRetvalI8:
1994 case NVPTX::LastCallArgF32:
1995 case NVPTX::LastCallArgF64:
1996 case NVPTX::LastCallArgI16:
1997 case NVPTX::LastCallArgI32:
1998 case NVPTX::LastCallArgI32imm:
1999 case NVPTX::LastCallArgI64:
2000 case NVPTX::LastCallArgParam:
2001 case NVPTX::LoadParamMemF32:
2002 case NVPTX::LoadParamMemF64:
2003 case NVPTX::LoadParamMemI16:
2004 case NVPTX::LoadParamMemI32:
2005 case NVPTX::LoadParamMemI64:
2006 case NVPTX::LoadParamMemI8:
2007 case NVPTX::PrototypeInst:
2008 case NVPTX::DBG_VALUE:
2014 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2016 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2017 unsigned AsmVariant,
2018 const char *ExtraCode, raw_ostream &O) {
2019 if (ExtraCode && ExtraCode[0]) {
2020 if (ExtraCode[1] != 0)
2021 return true; // Unknown modifier.
2023 switch (ExtraCode[0]) {
2025 // See if this is a generic print operand
2026 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2032 printOperand(MI, OpNo, O);
2037 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2038 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2039 const char *ExtraCode, raw_ostream &O) {
2040 if (ExtraCode && ExtraCode[0])
2041 return true; // Unknown modifier
2044 printMemOperand(MI, OpNo, O);
2050 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2051 raw_ostream &O, const char *Modifier) {
2052 const MachineOperand &MO = MI->getOperand(opNum);
2053 switch (MO.getType()) {
2054 case MachineOperand::MO_Register:
2055 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2056 if (MO.getReg() == NVPTX::VRDepot)
2057 O << DEPOTNAME << getFunctionNumber();
2059 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2061 emitVirtualRegister(MO.getReg(), O);
2065 case MachineOperand::MO_Immediate:
2068 else if (strstr(Modifier, "vec") == Modifier)
2069 printVecModifiedImmediate(MO, Modifier, O);
2072 "Don't know how to handle modifier on immediate operand");
2075 case MachineOperand::MO_FPImmediate:
2076 printFPConstant(MO.getFPImm(), O);
2079 case MachineOperand::MO_GlobalAddress:
2080 O << *getSymbol(MO.getGlobal());
2083 case MachineOperand::MO_MachineBasicBlock:
2084 O << *MO.getMBB()->getSymbol();
2088 llvm_unreachable("Operand type not supported.");
2092 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2093 raw_ostream &O, const char *Modifier) {
2094 printOperand(MI, opNum, O);
2096 if (Modifier && !strcmp(Modifier, "add")) {
2098 printOperand(MI, opNum + 1, O);
2100 if (MI->getOperand(opNum + 1).isImm() &&
2101 MI->getOperand(opNum + 1).getImm() == 0)
2102 return; // don't print ',0' or '+0'
2104 printOperand(MI, opNum + 1, O);
2109 // Force static initialization.
2110 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2111 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2112 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2115 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2116 std::stringstream temp;
2117 LineReader *reader = this->getReader(filename.str());
2119 temp << filename.str();
2123 temp << reader->readLine(line);
2125 this->OutStreamer.EmitRawText(Twine(temp.str()));
2128 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2130 reader = new LineReader(filename);
2133 if (reader->fileName() != filename) {
2135 reader = new LineReader(filename);
2141 std::string LineReader::readLine(unsigned lineNum) {
2142 if (lineNum < theCurLine) {
2144 fstr.seekg(0, std::ios::beg);
2146 while (theCurLine < lineNum) {
2147 fstr.getline(buff, 500);
2153 // Force static initialization.
2154 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2155 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2156 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);