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(jingyue): consider "#pragma unroll 1" which is equivalent to "#pragma
427 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
428 const MachineBasicBlock &MBB) const {
429 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
430 // TODO(jingyue): isLoopHeader() should take "const MachineBasicBlock *".
431 // We insert .pragma "nounroll" only to the loop header.
432 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
435 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
436 // we iterate through each back edge of the loop with header MBB, and check
437 // whether its metadata contains llvm.loop.unroll.disable.
438 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
439 const MachineBasicBlock *PMBB = *I;
440 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
441 // Edges from other loops to MBB are not back edges.
444 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
445 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
446 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
454 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
455 AsmPrinter::EmitBasicBlockStart(MBB);
456 if (isLoopHeaderOfNoUnroll(MBB))
457 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
460 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
461 SmallString<128> Str;
462 raw_svector_ostream O(Str);
464 if (!GlobalsEmitted) {
465 emitGlobals(*MF->getFunction()->getParent());
466 GlobalsEmitted = true;
470 MRI = &MF->getRegInfo();
471 F = MF->getFunction();
472 emitLinkageDirective(F, O);
473 if (llvm::isKernelFunction(*F))
477 printReturnValStr(*MF, O);
482 emitFunctionParamList(*MF, O);
484 if (llvm::isKernelFunction(*F))
485 emitKernelFunctionDirectives(*F, O);
487 OutStreamer.EmitRawText(O.str());
489 prevDebugLoc = DebugLoc();
492 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
494 OutStreamer.EmitRawText(StringRef("{\n"));
495 setAndEmitFunctionVirtualRegisters(*MF);
497 SmallString<128> Str;
498 raw_svector_ostream O(Str);
499 emitDemotedVars(MF->getFunction(), O);
500 OutStreamer.EmitRawText(O.str());
503 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
504 OutStreamer.EmitRawText(StringRef("}\n"));
508 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
509 unsigned RegNo = MI->getOperand(0).getReg();
510 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
511 if (TRI->isVirtualRegister(RegNo)) {
512 OutStreamer.AddComment(Twine("implicit-def: ") +
513 getVirtualRegisterName(RegNo));
515 OutStreamer.AddComment(
516 Twine("implicit-def: ") +
517 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
519 OutStreamer.AddBlankLine();
522 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
523 raw_ostream &O) const {
524 // If the NVVM IR has some of reqntid* specified, then output
525 // the reqntid directive, and set the unspecified ones to 1.
526 // If none of reqntid* is specified, don't output reqntid directive.
527 unsigned reqntidx, reqntidy, reqntidz;
528 bool specified = false;
529 if (llvm::getReqNTIDx(F, reqntidx) == false)
533 if (llvm::getReqNTIDy(F, reqntidy) == false)
537 if (llvm::getReqNTIDz(F, reqntidz) == false)
543 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
546 // If the NVVM IR has some of maxntid* specified, then output
547 // the maxntid directive, and set the unspecified ones to 1.
548 // If none of maxntid* is specified, don't output maxntid directive.
549 unsigned maxntidx, maxntidy, maxntidz;
551 if (llvm::getMaxNTIDx(F, maxntidx) == false)
555 if (llvm::getMaxNTIDy(F, maxntidy) == false)
559 if (llvm::getMaxNTIDz(F, maxntidz) == false)
565 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
569 if (llvm::getMinCTASm(F, mincta))
570 O << ".minnctapersm " << mincta << "\n";
574 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
575 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
578 raw_string_ostream NameStr(Name);
580 VRegRCMap::const_iterator I = VRegMapping.find(RC);
581 assert(I != VRegMapping.end() && "Bad register class");
582 const DenseMap<unsigned, unsigned> &RegMap = I->second;
584 VRegMap::const_iterator VI = RegMap.find(Reg);
585 assert(VI != RegMap.end() && "Bad virtual register");
586 unsigned MappedVR = VI->second;
588 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
594 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
596 O << getVirtualRegisterName(vr);
599 void NVPTXAsmPrinter::printVecModifiedImmediate(
600 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
601 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
602 int Imm = (int) MO.getImm();
603 if (0 == strcmp(Modifier, "vecelem"))
604 O << "_" << vecelem[Imm];
605 else if (0 == strcmp(Modifier, "vecv4comm1")) {
606 if ((Imm < 0) || (Imm > 3))
608 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
609 if ((Imm < 4) || (Imm > 7))
611 } else if (0 == strcmp(Modifier, "vecv4pos")) {
614 O << "_" << vecelem[Imm % 4];
615 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
616 if ((Imm < 0) || (Imm > 1))
618 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
619 if ((Imm < 2) || (Imm > 3))
621 } else if (0 == strcmp(Modifier, "vecv2pos")) {
624 O << "_" << vecelem[Imm % 2];
626 llvm_unreachable("Unknown Modifier on immediate operand");
631 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
633 emitLinkageDirective(F, O);
634 if (llvm::isKernelFunction(*F))
638 printReturnValStr(F, O);
639 O << *getSymbol(F) << "\n";
640 emitFunctionParamList(F, O);
644 static bool usedInGlobalVarDef(const Constant *C) {
648 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
649 if (GV->getName().str() == "llvm.used")
654 for (const User *U : C->users())
655 if (const Constant *C = dyn_cast<Constant>(U))
656 if (usedInGlobalVarDef(C))
662 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
663 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
664 if (othergv->getName().str() == "llvm.used")
668 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
669 if (instr->getParent() && instr->getParent()->getParent()) {
670 const Function *curFunc = instr->getParent()->getParent();
671 if (oneFunc && (curFunc != oneFunc))
679 for (const User *UU : U->users())
680 if (usedInOneFunc(UU, oneFunc) == false)
686 /* Find out if a global variable can be demoted to local scope.
687 * Currently, this is valid for CUDA shared variables, which have local
688 * scope and global lifetime. So the conditions to check are :
689 * 1. Is the global variable in shared address space?
690 * 2. Does it have internal linkage?
691 * 3. Is the global variable referenced only in one function?
693 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
694 if (gv->hasInternalLinkage() == false)
696 const PointerType *Pty = gv->getType();
697 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
700 const Function *oneFunc = nullptr;
702 bool flag = usedInOneFunc(gv, oneFunc);
711 static bool useFuncSeen(const Constant *C,
712 llvm::DenseMap<const Function *, bool> &seenMap) {
713 for (const User *U : C->users()) {
714 if (const Constant *cu = dyn_cast<Constant>(U)) {
715 if (useFuncSeen(cu, seenMap))
717 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
718 const BasicBlock *bb = I->getParent();
721 const Function *caller = bb->getParent();
724 if (seenMap.find(caller) != seenMap.end())
731 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
732 llvm::DenseMap<const Function *, bool> seenMap;
733 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
734 const Function *F = FI;
736 if (F->isDeclaration()) {
739 if (F->getIntrinsicID())
741 emitDeclaration(F, O);
744 for (const User *U : F->users()) {
745 if (const Constant *C = dyn_cast<Constant>(U)) {
746 if (usedInGlobalVarDef(C)) {
747 // The use is in the initialization of a global variable
748 // that is a function pointer, so print a declaration
749 // for the original function
750 emitDeclaration(F, O);
753 // Emit a declaration of this function if the function that
754 // uses this constant expr has already been seen.
755 if (useFuncSeen(C, seenMap)) {
756 emitDeclaration(F, O);
761 if (!isa<Instruction>(U))
763 const Instruction *instr = cast<Instruction>(U);
764 const BasicBlock *bb = instr->getParent();
767 const Function *caller = bb->getParent();
771 // If a caller has already been seen, then the caller is
772 // appearing in the module before the callee. so print out
773 // a declaration for the callee.
774 if (seenMap.find(caller) != seenMap.end()) {
775 emitDeclaration(F, O);
783 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
784 DebugInfoFinder DbgFinder;
785 DbgFinder.processModule(M);
788 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
789 StringRef Filename(DIUnit.getFilename());
790 StringRef Dirname(DIUnit.getDirectory());
791 SmallString<128> FullPathName = Dirname;
792 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
793 sys::path::append(FullPathName, Filename);
794 Filename = FullPathName.str();
796 if (filenameMap.find(Filename.str()) != filenameMap.end())
798 filenameMap[Filename.str()] = i;
799 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
803 for (DISubprogram SP : DbgFinder.subprograms()) {
804 StringRef Filename(SP.getFilename());
805 StringRef Dirname(SP.getDirectory());
806 SmallString<128> FullPathName = Dirname;
807 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
808 sys::path::append(FullPathName, Filename);
809 Filename = FullPathName.str();
811 if (filenameMap.find(Filename.str()) != filenameMap.end())
813 filenameMap[Filename.str()] = i;
818 bool NVPTXAsmPrinter::doInitialization(Module &M) {
820 SmallString<128> Str1;
821 raw_svector_ostream OS1(Str1);
823 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
824 MMI->AnalyzeModule(M);
826 // We need to call the parent's one explicitly.
827 //bool Result = AsmPrinter::doInitialization(M);
829 // Initialize TargetLoweringObjectFile.
830 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
831 .Initialize(OutContext, TM);
833 Mang = new Mangler(TM.getDataLayout());
835 // Emit header before any dwarf directives are emitted below.
837 OutStreamer.EmitRawText(OS1.str());
839 // Already commented out
840 //bool Result = AsmPrinter::doInitialization(M);
842 // Emit module-level inline asm if it exists.
843 if (!M.getModuleInlineAsm().empty()) {
844 OutStreamer.AddComment("Start of file scope inline assembly");
845 OutStreamer.AddBlankLine();
846 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
847 OutStreamer.AddBlankLine();
848 OutStreamer.AddComment("End of file scope inline assembly");
849 OutStreamer.AddBlankLine();
852 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
853 recordAndEmitFilenames(M);
855 GlobalsEmitted = false;
857 return false; // success
860 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
861 SmallString<128> Str2;
862 raw_svector_ostream OS2(Str2);
864 emitDeclarations(M, OS2);
866 // As ptxas does not support forward references of globals, we need to first
867 // sort the list of module-level globals in def-use order. We visit each
868 // global variable in order, and ensure that we emit it *after* its dependent
869 // globals. We use a little extra memory maintaining both a set and a list to
870 // have fast searches while maintaining a strict ordering.
871 SmallVector<const GlobalVariable *, 8> Globals;
872 DenseSet<const GlobalVariable *> GVVisited;
873 DenseSet<const GlobalVariable *> GVVisiting;
875 // Visit each global variable, in order
876 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
878 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
880 assert(GVVisited.size() == M.getGlobalList().size() &&
881 "Missed a global variable");
882 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
884 // Print out module-level global variables in proper order
885 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
886 printModuleLevelGV(Globals[i], OS2);
890 OutStreamer.EmitRawText(OS2.str());
893 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
895 O << "// Generated by LLVM NVPTX Back-End\n";
899 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
900 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
903 O << nvptxSubtarget.getTargetName();
905 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
906 O << ", texmode_independent";
907 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
908 if (!nvptxSubtarget.hasDouble())
909 O << ", map_f64_to_f32";
912 if (MAI->doesSupportDebugInformation())
917 O << ".address_size ";
918 if (nvptxSubtarget.is64Bit())
927 bool NVPTXAsmPrinter::doFinalization(Module &M) {
929 // If we did not emit any functions, then the global declarations have not
931 if (!GlobalsEmitted) {
933 GlobalsEmitted = true;
936 // XXX Temproarily remove global variables so that doFinalization() will not
937 // emit them again (global variables are emitted at beginning).
939 Module::GlobalListType &global_list = M.getGlobalList();
940 int i, n = global_list.size();
941 GlobalVariable **gv_array = new GlobalVariable *[n];
943 // first, back-up GlobalVariable in gv_array
945 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
949 // second, empty global_list
950 while (!global_list.empty())
951 global_list.remove(global_list.begin());
953 // call doFinalization
954 bool ret = AsmPrinter::doFinalization(M);
956 // now we restore global variables
957 for (i = 0; i < n; i++)
958 global_list.insert(global_list.end(), gv_array[i]);
960 clearAnnotationCache(&M);
965 //bool Result = AsmPrinter::doFinalization(M);
966 // Instead of calling the parents doFinalization, we may
967 // clone parents doFinalization and customize here.
968 // Currently, we if NVISA out the EmitGlobals() in
969 // parent's doFinalization, which is too intrusive.
971 // Same for the doInitialization.
975 // This function emits appropriate linkage directives for
976 // functions and global variables.
978 // extern function declaration -> .extern
979 // extern function definition -> .visible
980 // external global variable with init -> .visible
981 // external without init -> .extern
982 // appending -> not allowed, assert.
983 // for any linkage other than
984 // internal, private, linker_private,
985 // linker_private_weak, linker_private_weak_def_auto,
988 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
990 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
991 if (V->hasExternalLinkage()) {
992 if (isa<GlobalVariable>(V)) {
993 const GlobalVariable *GVar = cast<GlobalVariable>(V);
995 if (GVar->hasInitializer())
1000 } else if (V->isDeclaration())
1004 } else if (V->hasAppendingLinkage()) {
1006 msg.append("Error: ");
1007 msg.append("Symbol ");
1009 msg.append(V->getName().str());
1010 msg.append("has unsupported appending linkage type");
1011 llvm_unreachable(msg.c_str());
1012 } else if (!V->hasInternalLinkage() &&
1013 !V->hasPrivateLinkage()) {
1019 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1021 bool processDemoted) {
1024 if (GVar->hasSection()) {
1025 if (GVar->getSection() == StringRef("llvm.metadata"))
1029 // Skip LLVM intrinsic global variables
1030 if (GVar->getName().startswith("llvm.") ||
1031 GVar->getName().startswith("nvvm."))
1034 const DataLayout *TD = TM.getDataLayout();
1036 // GlobalVariables are always constant pointers themselves.
1037 const PointerType *PTy = GVar->getType();
1038 Type *ETy = PTy->getElementType();
1040 if (GVar->hasExternalLinkage()) {
1041 if (GVar->hasInitializer())
1045 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1046 GVar->hasAvailableExternallyLinkage() ||
1047 GVar->hasCommonLinkage()) {
1051 if (llvm::isTexture(*GVar)) {
1052 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1056 if (llvm::isSurface(*GVar)) {
1057 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1061 if (GVar->isDeclaration()) {
1062 // (extern) declarations, no definition or initializer
1063 // Currently the only known declaration is for an automatic __local
1064 // (.shared) promoted to global.
1065 emitPTXGlobalVariable(GVar, O);
1070 if (llvm::isSampler(*GVar)) {
1071 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1073 const Constant *Initializer = nullptr;
1074 if (GVar->hasInitializer())
1075 Initializer = GVar->getInitializer();
1076 const ConstantInt *CI = nullptr;
1078 CI = dyn_cast<ConstantInt>(Initializer);
1080 unsigned sample = CI->getZExtValue();
1085 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1087 O << "addr_mode_" << i << " = ";
1093 O << "clamp_to_border";
1096 O << "clamp_to_edge";
1107 O << "filter_mode = ";
1108 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1116 llvm_unreachable("Anisotropic filtering is not supported");
1121 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1122 O << ", force_unnormalized_coords = 1";
1131 if (GVar->hasPrivateLinkage()) {
1133 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1136 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1137 if (!strncmp(GVar->getName().data(), "filename", 8))
1139 if (GVar->use_empty())
1143 const Function *demotedFunc = nullptr;
1144 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1145 O << "// " << GVar->getName().str() << " has been demoted\n";
1146 if (localDecls.find(demotedFunc) != localDecls.end())
1147 localDecls[demotedFunc].push_back(GVar);
1149 std::vector<const GlobalVariable *> temp;
1150 temp.push_back(GVar);
1151 localDecls[demotedFunc] = temp;
1157 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1159 if (isManaged(*GVar)) {
1160 O << " .attribute(.managed)";
1163 if (GVar->getAlignment() == 0)
1164 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1166 O << " .align " << GVar->getAlignment();
1168 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1170 // Special case: ABI requires that we use .u8 for predicates
1171 if (ETy->isIntegerTy(1))
1174 O << getPTXFundamentalTypeStr(ETy, false);
1176 O << *getSymbol(GVar);
1178 // Ptx allows variable initilization only for constant and global state
1180 if (GVar->hasInitializer()) {
1181 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1182 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1183 const Constant *Initializer = GVar->getInitializer();
1184 // 'undef' is treated as there is no value spefied.
1185 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1187 printScalarConstant(Initializer, O);
1190 // The frontend adds zero-initializer to variables that don't have an
1191 // initial value, so skip warning for this case.
1192 if (!GVar->getInitializer()->isNullValue()) {
1193 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1194 "' is not allowed in addrspace(" +
1195 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1196 report_fatal_error(warnMsg.c_str());
1201 unsigned int ElementSize = 0;
1203 // Although PTX has direct support for struct type and array type and
1204 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1205 // targets that support these high level field accesses. Structs, arrays
1206 // and vectors are lowered into arrays of bytes.
1207 switch (ETy->getTypeID()) {
1208 case Type::StructTyID:
1209 case Type::ArrayTyID:
1210 case Type::VectorTyID:
1211 ElementSize = TD->getTypeStoreSize(ETy);
1212 // Ptx allows variable initilization only for constant and
1213 // global state spaces.
1214 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1215 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1216 GVar->hasInitializer()) {
1217 const Constant *Initializer = GVar->getInitializer();
1218 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1219 AggBuffer aggBuffer(ElementSize, O, *this);
1220 bufferAggregateConstant(Initializer, &aggBuffer);
1221 if (aggBuffer.numSymbols) {
1222 if (nvptxSubtarget.is64Bit()) {
1223 O << " .u64 " << *getSymbol(GVar) << "[";
1224 O << ElementSize / 8;
1226 O << " .u32 " << *getSymbol(GVar) << "[";
1227 O << ElementSize / 4;
1231 O << " .b8 " << *getSymbol(GVar) << "[";
1239 O << " .b8 " << *getSymbol(GVar);
1247 O << " .b8 " << *getSymbol(GVar);
1256 llvm_unreachable("type not supported yet");
1263 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1264 if (localDecls.find(f) == localDecls.end())
1267 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1269 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1270 O << "\t// demoted variable\n\t";
1271 printModuleLevelGV(gvars[i], O, true);
1275 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1276 raw_ostream &O) const {
1277 switch (AddressSpace) {
1278 case llvm::ADDRESS_SPACE_LOCAL:
1281 case llvm::ADDRESS_SPACE_GLOBAL:
1284 case llvm::ADDRESS_SPACE_CONST:
1287 case llvm::ADDRESS_SPACE_SHARED:
1291 report_fatal_error("Bad address space found while emitting PTX");
1297 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1298 switch (Ty->getTypeID()) {
1300 llvm_unreachable("unexpected type");
1302 case Type::IntegerTyID: {
1303 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1306 else if (NumBits <= 64) {
1307 std::string name = "u";
1308 return name + utostr(NumBits);
1310 llvm_unreachable("Integer too large");
1315 case Type::FloatTyID:
1317 case Type::DoubleTyID:
1319 case Type::PointerTyID:
1320 if (nvptxSubtarget.is64Bit())
1330 llvm_unreachable("unexpected type");
1334 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1337 const DataLayout *TD = TM.getDataLayout();
1339 // GlobalVariables are always constant pointers themselves.
1340 const PointerType *PTy = GVar->getType();
1341 Type *ETy = PTy->getElementType();
1344 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1345 if (GVar->getAlignment() == 0)
1346 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1348 O << " .align " << GVar->getAlignment();
1350 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1352 O << getPTXFundamentalTypeStr(ETy);
1354 O << *getSymbol(GVar);
1358 int64_t ElementSize = 0;
1360 // Although PTX has direct support for struct type and array type and LLVM IR
1361 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1362 // support these high level field accesses. Structs and arrays are lowered
1363 // into arrays of bytes.
1364 switch (ETy->getTypeID()) {
1365 case Type::StructTyID:
1366 case Type::ArrayTyID:
1367 case Type::VectorTyID:
1368 ElementSize = TD->getTypeStoreSize(ETy);
1369 O << " .b8 " << *getSymbol(GVar) << "[";
1371 O << itostr(ElementSize);
1376 llvm_unreachable("type not supported yet");
1381 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1382 if (Ty->isSingleValueType())
1383 return TD->getPrefTypeAlignment(Ty);
1385 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1387 return getOpenCLAlignment(TD, ATy->getElementType());
1389 const StructType *STy = dyn_cast<StructType>(Ty);
1391 unsigned int alignStruct = 1;
1392 // Go through each element of the struct and find the
1393 // largest alignment.
1394 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1395 Type *ETy = STy->getElementType(i);
1396 unsigned int align = getOpenCLAlignment(TD, ETy);
1397 if (align > alignStruct)
1398 alignStruct = align;
1403 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1405 return TD->getPointerPrefAlignment();
1406 return TD->getPrefTypeAlignment(Ty);
1409 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1410 int paramIndex, raw_ostream &O) {
1411 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1412 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1413 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1415 std::string argName = I->getName();
1416 const char *p = argName.c_str();
1427 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1428 Function::const_arg_iterator I, E;
1431 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1432 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1433 O << *CurrentFnSym << "_param_" << paramIndex;
1437 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1438 if (i == paramIndex) {
1439 printParamName(I, paramIndex, O);
1443 llvm_unreachable("paramIndex out of bound");
1446 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1447 const DataLayout *TD = TM.getDataLayout();
1448 const AttributeSet &PAL = F->getAttributes();
1449 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1450 Function::const_arg_iterator I, E;
1451 unsigned paramIndex = 0;
1453 bool isKernelFunc = llvm::isKernelFunction(*F);
1454 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1455 MVT thePointerTy = TLI->getPointerTy();
1459 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1460 Type *Ty = I->getType();
1467 // Handle image/sampler parameters
1468 if (isKernelFunction(*F)) {
1469 if (isSampler(*I) || isImage(*I)) {
1471 std::string sname = I->getName();
1472 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1473 if (nvptxSubtarget.hasImageHandles())
1474 O << "\t.param .u64 .ptr .surfref ";
1476 O << "\t.param .surfref ";
1477 O << *CurrentFnSym << "_param_" << paramIndex;
1479 else { // Default image is read_only
1480 if (nvptxSubtarget.hasImageHandles())
1481 O << "\t.param .u64 .ptr .texref ";
1483 O << "\t.param .texref ";
1484 O << *CurrentFnSym << "_param_" << paramIndex;
1487 if (nvptxSubtarget.hasImageHandles())
1488 O << "\t.param .u64 .ptr .samplerref ";
1490 O << "\t.param .samplerref ";
1491 O << *CurrentFnSym << "_param_" << paramIndex;
1497 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1498 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1499 // Just print .param .align <a> .b8 .param[size];
1500 // <a> = PAL.getparamalignment
1501 // size = typeallocsize of element type
1502 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1504 align = TD->getABITypeAlignment(Ty);
1506 unsigned sz = TD->getTypeAllocSize(Ty);
1507 O << "\t.param .align " << align << " .b8 ";
1508 printParamName(I, paramIndex, O);
1509 O << "[" << sz << "]";
1514 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1517 // Special handling for pointer arguments to kernel
1518 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1520 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1521 Type *ETy = PTy->getElementType();
1522 int addrSpace = PTy->getAddressSpace();
1523 switch (addrSpace) {
1527 case llvm::ADDRESS_SPACE_CONST:
1528 O << ".ptr .const ";
1530 case llvm::ADDRESS_SPACE_SHARED:
1531 O << ".ptr .shared ";
1533 case llvm::ADDRESS_SPACE_GLOBAL:
1534 O << ".ptr .global ";
1537 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1539 printParamName(I, paramIndex, O);
1543 // non-pointer scalar to kernel func
1545 // Special case: predicate operands become .u8 types
1546 if (Ty->isIntegerTy(1))
1549 O << getPTXFundamentalTypeStr(Ty);
1551 printParamName(I, paramIndex, O);
1554 // Non-kernel function, just print .param .b<size> for ABI
1555 // and .reg .b<size> for non-ABI
1557 if (isa<IntegerType>(Ty)) {
1558 sz = cast<IntegerType>(Ty)->getBitWidth();
1561 } else if (isa<PointerType>(Ty))
1562 sz = thePointerTy.getSizeInBits();
1564 sz = Ty->getPrimitiveSizeInBits();
1566 O << "\t.param .b" << sz << " ";
1568 O << "\t.reg .b" << sz << " ";
1569 printParamName(I, paramIndex, O);
1573 // param has byVal attribute. So should be a pointer
1574 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1575 assert(PTy && "Param with byval attribute should be a pointer type");
1576 Type *ETy = PTy->getElementType();
1578 if (isABI || isKernelFunc) {
1579 // Just print .param .align <a> .b8 .param[size];
1580 // <a> = PAL.getparamalignment
1581 // size = typeallocsize of element type
1582 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1584 align = TD->getABITypeAlignment(ETy);
1586 unsigned sz = TD->getTypeAllocSize(ETy);
1587 O << "\t.param .align " << align << " .b8 ";
1588 printParamName(I, paramIndex, O);
1589 O << "[" << sz << "]";
1592 // Split the ETy into constituent parts and
1593 // print .param .b<size> <name> for each part.
1594 // Further, if a part is vector, print the above for
1595 // each vector element.
1596 SmallVector<EVT, 16> vtparts;
1597 ComputeValueVTs(*TLI, ETy, vtparts);
1598 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1600 EVT elemtype = vtparts[i];
1601 if (vtparts[i].isVector()) {
1602 elems = vtparts[i].getVectorNumElements();
1603 elemtype = vtparts[i].getVectorElementType();
1606 for (unsigned j = 0, je = elems; j != je; ++j) {
1607 unsigned sz = elemtype.getSizeInBits();
1608 if (elemtype.isInteger() && (sz < 32))
1610 O << "\t.reg .b" << sz << " ";
1611 printParamName(I, paramIndex, O);
1627 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1629 const Function *F = MF.getFunction();
1630 emitFunctionParamList(F, O);
1633 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1634 const MachineFunction &MF) {
1635 SmallString<128> Str;
1636 raw_svector_ostream O(Str);
1638 // Map the global virtual register number to a register class specific
1639 // virtual register number starting from 1 with that class.
1640 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1641 //unsigned numRegClasses = TRI->getNumRegClasses();
1643 // Emit the Fake Stack Object
1644 const MachineFrameInfo *MFI = MF.getFrameInfo();
1645 int NumBytes = (int) MFI->getStackSize();
1647 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1648 << getFunctionNumber() << "[" << NumBytes << "];\n";
1649 if (nvptxSubtarget.is64Bit()) {
1650 O << "\t.reg .b64 \t%SP;\n";
1651 O << "\t.reg .b64 \t%SPL;\n";
1653 O << "\t.reg .b32 \t%SP;\n";
1654 O << "\t.reg .b32 \t%SPL;\n";
1658 // Go through all virtual registers to establish the mapping between the
1660 // register number and the per class virtual register number.
1661 // We use the per class virtual register number in the ptx output.
1662 unsigned int numVRs = MRI->getNumVirtRegs();
1663 for (unsigned i = 0; i < numVRs; i++) {
1664 unsigned int vr = TRI->index2VirtReg(i);
1665 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1666 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1667 int n = regmap.size();
1668 regmap.insert(std::make_pair(vr, n + 1));
1671 // Emit register declarations
1672 // @TODO: Extract out the real register usage
1673 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1674 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1675 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1676 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1677 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1678 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1679 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1681 // Emit declaration of the virtual registers or 'physical' registers for
1682 // each register class
1683 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1684 const TargetRegisterClass *RC = TRI->getRegClass(i);
1685 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1686 std::string rcname = getNVPTXRegClassName(RC);
1687 std::string rcStr = getNVPTXRegClassStr(RC);
1688 int n = regmap.size();
1690 // Only declare those registers that may be used.
1692 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1697 OutStreamer.EmitRawText(O.str());
1700 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1701 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1703 unsigned int numHex;
1706 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1709 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1710 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1713 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1715 llvm_unreachable("unsupported fp type");
1717 APInt API = APF.bitcastToAPInt();
1718 std::string hexstr(utohexstr(API.getZExtValue()));
1720 if (hexstr.length() < numHex)
1721 O << std::string(numHex - hexstr.length(), '0');
1722 O << utohexstr(API.getZExtValue());
1725 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1726 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1727 O << CI->getValue();
1730 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1731 printFPConstant(CFP, O);
1734 if (isa<ConstantPointerNull>(CPV)) {
1738 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1739 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1740 bool IsNonGenericPointer = false;
1741 if (PTy && PTy->getAddressSpace() != 0) {
1742 IsNonGenericPointer = true;
1744 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1746 O << *getSymbol(GVar);
1749 O << *getSymbol(GVar);
1753 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1754 const Value *v = Cexpr->stripPointerCasts();
1755 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1756 bool IsNonGenericPointer = false;
1757 if (PTy && PTy->getAddressSpace() != 0) {
1758 IsNonGenericPointer = true;
1760 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1761 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1763 O << *getSymbol(GVar);
1766 O << *getSymbol(GVar);
1770 O << *lowerConstant(CPV);
1774 llvm_unreachable("Not scalar type found in printScalarConstant()");
1777 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1778 AggBuffer *aggBuffer) {
1780 const DataLayout *TD = TM.getDataLayout();
1782 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1783 int s = TD->getTypeAllocSize(CPV->getType());
1786 aggBuffer->addZeros(s);
1791 switch (CPV->getType()->getTypeID()) {
1793 case Type::IntegerTyID: {
1794 const Type *ETy = CPV->getType();
1795 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1797 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1799 aggBuffer->addBytes(ptr, 1, Bytes);
1800 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1801 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1802 ptr = (unsigned char *)&int16;
1803 aggBuffer->addBytes(ptr, 2, Bytes);
1804 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1805 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1806 int int32 = (int)(constInt->getZExtValue());
1807 ptr = (unsigned char *)&int32;
1808 aggBuffer->addBytes(ptr, 4, Bytes);
1810 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1811 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1812 ConstantFoldConstantExpression(Cexpr, TD))) {
1813 int int32 = (int)(constInt->getZExtValue());
1814 ptr = (unsigned char *)&int32;
1815 aggBuffer->addBytes(ptr, 4, Bytes);
1818 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1819 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1820 aggBuffer->addSymbol(v);
1821 aggBuffer->addZeros(4);
1825 llvm_unreachable("unsupported integer const type");
1826 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1827 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1828 long long int64 = (long long)(constInt->getZExtValue());
1829 ptr = (unsigned char *)&int64;
1830 aggBuffer->addBytes(ptr, 8, Bytes);
1832 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1833 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1834 ConstantFoldConstantExpression(Cexpr, TD))) {
1835 long long int64 = (long long)(constInt->getZExtValue());
1836 ptr = (unsigned char *)&int64;
1837 aggBuffer->addBytes(ptr, 8, Bytes);
1840 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1841 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1842 aggBuffer->addSymbol(v);
1843 aggBuffer->addZeros(8);
1847 llvm_unreachable("unsupported integer const type");
1849 llvm_unreachable("unsupported integer const type");
1852 case Type::FloatTyID:
1853 case Type::DoubleTyID: {
1854 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1855 const Type *Ty = CFP->getType();
1856 if (Ty == Type::getFloatTy(CPV->getContext())) {
1857 float float32 = (float) CFP->getValueAPF().convertToFloat();
1858 ptr = (unsigned char *)&float32;
1859 aggBuffer->addBytes(ptr, 4, Bytes);
1860 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1861 double float64 = CFP->getValueAPF().convertToDouble();
1862 ptr = (unsigned char *)&float64;
1863 aggBuffer->addBytes(ptr, 8, Bytes);
1865 llvm_unreachable("unsupported fp const type");
1869 case Type::PointerTyID: {
1870 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1871 aggBuffer->addSymbol(GVar);
1872 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1873 const Value *v = Cexpr->stripPointerCasts();
1874 aggBuffer->addSymbol(v);
1876 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1877 aggBuffer->addZeros(s);
1881 case Type::ArrayTyID:
1882 case Type::VectorTyID:
1883 case Type::StructTyID: {
1884 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1885 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1886 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1887 bufferAggregateConstant(CPV, aggBuffer);
1888 if (Bytes > ElementSize)
1889 aggBuffer->addZeros(Bytes - ElementSize);
1890 } else if (isa<ConstantAggregateZero>(CPV))
1891 aggBuffer->addZeros(Bytes);
1893 llvm_unreachable("Unexpected Constant type");
1898 llvm_unreachable("unsupported type");
1902 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1903 AggBuffer *aggBuffer) {
1904 const DataLayout *TD = TM.getDataLayout();
1908 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1909 if (CPV->getNumOperands())
1910 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1911 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1915 if (const ConstantDataSequential *CDS =
1916 dyn_cast<ConstantDataSequential>(CPV)) {
1917 if (CDS->getNumElements())
1918 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1919 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1924 if (isa<ConstantStruct>(CPV)) {
1925 if (CPV->getNumOperands()) {
1926 StructType *ST = cast<StructType>(CPV->getType());
1927 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1929 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1930 TD->getTypeAllocSize(ST) -
1931 TD->getStructLayout(ST)->getElementOffset(i);
1933 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1934 TD->getStructLayout(ST)->getElementOffset(i);
1935 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1940 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1943 // buildTypeNameMap - Run through symbol table looking for type names.
1946 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1948 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1950 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1951 !PI->second.compare("struct._image2d_t") ||
1952 !PI->second.compare("struct._image3d_t")))
1959 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1960 switch (MI.getOpcode()) {
1963 case NVPTX::CallArgBeginInst:
1964 case NVPTX::CallArgEndInst0:
1965 case NVPTX::CallArgEndInst1:
1966 case NVPTX::CallArgF32:
1967 case NVPTX::CallArgF64:
1968 case NVPTX::CallArgI16:
1969 case NVPTX::CallArgI32:
1970 case NVPTX::CallArgI32imm:
1971 case NVPTX::CallArgI64:
1972 case NVPTX::CallArgParam:
1973 case NVPTX::CallVoidInst:
1974 case NVPTX::CallVoidInstReg:
1975 case NVPTX::Callseq_End:
1976 case NVPTX::CallVoidInstReg64:
1977 case NVPTX::DeclareParamInst:
1978 case NVPTX::DeclareRetMemInst:
1979 case NVPTX::DeclareRetRegInst:
1980 case NVPTX::DeclareRetScalarInst:
1981 case NVPTX::DeclareScalarParamInst:
1982 case NVPTX::DeclareScalarRegInst:
1983 case NVPTX::StoreParamF32:
1984 case NVPTX::StoreParamF64:
1985 case NVPTX::StoreParamI16:
1986 case NVPTX::StoreParamI32:
1987 case NVPTX::StoreParamI64:
1988 case NVPTX::StoreParamI8:
1989 case NVPTX::StoreRetvalF32:
1990 case NVPTX::StoreRetvalF64:
1991 case NVPTX::StoreRetvalI16:
1992 case NVPTX::StoreRetvalI32:
1993 case NVPTX::StoreRetvalI64:
1994 case NVPTX::StoreRetvalI8:
1995 case NVPTX::LastCallArgF32:
1996 case NVPTX::LastCallArgF64:
1997 case NVPTX::LastCallArgI16:
1998 case NVPTX::LastCallArgI32:
1999 case NVPTX::LastCallArgI32imm:
2000 case NVPTX::LastCallArgI64:
2001 case NVPTX::LastCallArgParam:
2002 case NVPTX::LoadParamMemF32:
2003 case NVPTX::LoadParamMemF64:
2004 case NVPTX::LoadParamMemI16:
2005 case NVPTX::LoadParamMemI32:
2006 case NVPTX::LoadParamMemI64:
2007 case NVPTX::LoadParamMemI8:
2008 case NVPTX::PrototypeInst:
2009 case NVPTX::DBG_VALUE:
2015 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2017 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2018 unsigned AsmVariant,
2019 const char *ExtraCode, raw_ostream &O) {
2020 if (ExtraCode && ExtraCode[0]) {
2021 if (ExtraCode[1] != 0)
2022 return true; // Unknown modifier.
2024 switch (ExtraCode[0]) {
2026 // See if this is a generic print operand
2027 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2033 printOperand(MI, OpNo, O);
2038 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2039 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2040 const char *ExtraCode, raw_ostream &O) {
2041 if (ExtraCode && ExtraCode[0])
2042 return true; // Unknown modifier
2045 printMemOperand(MI, OpNo, O);
2051 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2052 raw_ostream &O, const char *Modifier) {
2053 const MachineOperand &MO = MI->getOperand(opNum);
2054 switch (MO.getType()) {
2055 case MachineOperand::MO_Register:
2056 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2057 if (MO.getReg() == NVPTX::VRDepot)
2058 O << DEPOTNAME << getFunctionNumber();
2060 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2062 emitVirtualRegister(MO.getReg(), O);
2066 case MachineOperand::MO_Immediate:
2069 else if (strstr(Modifier, "vec") == Modifier)
2070 printVecModifiedImmediate(MO, Modifier, O);
2073 "Don't know how to handle modifier on immediate operand");
2076 case MachineOperand::MO_FPImmediate:
2077 printFPConstant(MO.getFPImm(), O);
2080 case MachineOperand::MO_GlobalAddress:
2081 O << *getSymbol(MO.getGlobal());
2084 case MachineOperand::MO_MachineBasicBlock:
2085 O << *MO.getMBB()->getSymbol();
2089 llvm_unreachable("Operand type not supported.");
2093 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2094 raw_ostream &O, const char *Modifier) {
2095 printOperand(MI, opNum, O);
2097 if (Modifier && !strcmp(Modifier, "add")) {
2099 printOperand(MI, opNum + 1, O);
2101 if (MI->getOperand(opNum + 1).isImm() &&
2102 MI->getOperand(opNum + 1).getImm() == 0)
2103 return; // don't print ',0' or '+0'
2105 printOperand(MI, opNum + 1, O);
2110 // Force static initialization.
2111 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2112 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2113 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2116 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2117 std::stringstream temp;
2118 LineReader *reader = this->getReader(filename.str());
2120 temp << filename.str();
2124 temp << reader->readLine(line);
2126 this->OutStreamer.EmitRawText(Twine(temp.str()));
2129 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2131 reader = new LineReader(filename);
2134 if (reader->fileName() != filename) {
2136 reader = new LineReader(filename);
2142 std::string LineReader::readLine(unsigned lineNum) {
2143 if (lineNum < theCurLine) {
2145 fstr.seekg(0, std::ios::beg);
2147 while (theCurLine < lineNum) {
2148 fstr.getline(buff, 500);
2154 // Force static initialization.
2155 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2156 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2157 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);