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 (const MDNode *LoopID =
446 PBB->getTerminator()->getMetadata("llvm.loop")) {
447 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
455 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
456 AsmPrinter::EmitBasicBlockStart(MBB);
457 if (isLoopHeaderOfNoUnroll(MBB))
458 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
461 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
462 SmallString<128> Str;
463 raw_svector_ostream O(Str);
465 if (!GlobalsEmitted) {
466 emitGlobals(*MF->getFunction()->getParent());
467 GlobalsEmitted = true;
471 MRI = &MF->getRegInfo();
472 F = MF->getFunction();
473 emitLinkageDirective(F, O);
474 if (llvm::isKernelFunction(*F))
478 printReturnValStr(*MF, O);
483 emitFunctionParamList(*MF, O);
485 if (llvm::isKernelFunction(*F))
486 emitKernelFunctionDirectives(*F, O);
488 OutStreamer.EmitRawText(O.str());
490 prevDebugLoc = DebugLoc();
493 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
495 OutStreamer.EmitRawText(StringRef("{\n"));
496 setAndEmitFunctionVirtualRegisters(*MF);
498 SmallString<128> Str;
499 raw_svector_ostream O(Str);
500 emitDemotedVars(MF->getFunction(), O);
501 OutStreamer.EmitRawText(O.str());
504 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
505 OutStreamer.EmitRawText(StringRef("}\n"));
509 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
510 unsigned RegNo = MI->getOperand(0).getReg();
511 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
512 if (TRI->isVirtualRegister(RegNo)) {
513 OutStreamer.AddComment(Twine("implicit-def: ") +
514 getVirtualRegisterName(RegNo));
516 OutStreamer.AddComment(
517 Twine("implicit-def: ") +
518 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
520 OutStreamer.AddBlankLine();
523 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
524 raw_ostream &O) const {
525 // If the NVVM IR has some of reqntid* specified, then output
526 // the reqntid directive, and set the unspecified ones to 1.
527 // If none of reqntid* is specified, don't output reqntid directive.
528 unsigned reqntidx, reqntidy, reqntidz;
529 bool specified = false;
530 if (llvm::getReqNTIDx(F, reqntidx) == false)
534 if (llvm::getReqNTIDy(F, reqntidy) == false)
538 if (llvm::getReqNTIDz(F, reqntidz) == false)
544 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
547 // If the NVVM IR has some of maxntid* specified, then output
548 // the maxntid directive, and set the unspecified ones to 1.
549 // If none of maxntid* is specified, don't output maxntid directive.
550 unsigned maxntidx, maxntidy, maxntidz;
552 if (llvm::getMaxNTIDx(F, maxntidx) == false)
556 if (llvm::getMaxNTIDy(F, maxntidy) == false)
560 if (llvm::getMaxNTIDz(F, maxntidz) == false)
566 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
570 if (llvm::getMinCTASm(F, mincta))
571 O << ".minnctapersm " << mincta << "\n";
575 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
576 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
579 raw_string_ostream NameStr(Name);
581 VRegRCMap::const_iterator I = VRegMapping.find(RC);
582 assert(I != VRegMapping.end() && "Bad register class");
583 const DenseMap<unsigned, unsigned> &RegMap = I->second;
585 VRegMap::const_iterator VI = RegMap.find(Reg);
586 assert(VI != RegMap.end() && "Bad virtual register");
587 unsigned MappedVR = VI->second;
589 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
595 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
597 O << getVirtualRegisterName(vr);
600 void NVPTXAsmPrinter::printVecModifiedImmediate(
601 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
602 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
603 int Imm = (int) MO.getImm();
604 if (0 == strcmp(Modifier, "vecelem"))
605 O << "_" << vecelem[Imm];
606 else if (0 == strcmp(Modifier, "vecv4comm1")) {
607 if ((Imm < 0) || (Imm > 3))
609 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
610 if ((Imm < 4) || (Imm > 7))
612 } else if (0 == strcmp(Modifier, "vecv4pos")) {
615 O << "_" << vecelem[Imm % 4];
616 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
617 if ((Imm < 0) || (Imm > 1))
619 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
620 if ((Imm < 2) || (Imm > 3))
622 } else if (0 == strcmp(Modifier, "vecv2pos")) {
625 O << "_" << vecelem[Imm % 2];
627 llvm_unreachable("Unknown Modifier on immediate operand");
632 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
634 emitLinkageDirective(F, O);
635 if (llvm::isKernelFunction(*F))
639 printReturnValStr(F, O);
640 O << *getSymbol(F) << "\n";
641 emitFunctionParamList(F, O);
645 static bool usedInGlobalVarDef(const Constant *C) {
649 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
650 if (GV->getName().str() == "llvm.used")
655 for (const User *U : C->users())
656 if (const Constant *C = dyn_cast<Constant>(U))
657 if (usedInGlobalVarDef(C))
663 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
664 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
665 if (othergv->getName().str() == "llvm.used")
669 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
670 if (instr->getParent() && instr->getParent()->getParent()) {
671 const Function *curFunc = instr->getParent()->getParent();
672 if (oneFunc && (curFunc != oneFunc))
680 for (const User *UU : U->users())
681 if (usedInOneFunc(UU, oneFunc) == false)
687 /* Find out if a global variable can be demoted to local scope.
688 * Currently, this is valid for CUDA shared variables, which have local
689 * scope and global lifetime. So the conditions to check are :
690 * 1. Is the global variable in shared address space?
691 * 2. Does it have internal linkage?
692 * 3. Is the global variable referenced only in one function?
694 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
695 if (gv->hasInternalLinkage() == false)
697 const PointerType *Pty = gv->getType();
698 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
701 const Function *oneFunc = nullptr;
703 bool flag = usedInOneFunc(gv, oneFunc);
712 static bool useFuncSeen(const Constant *C,
713 llvm::DenseMap<const Function *, bool> &seenMap) {
714 for (const User *U : C->users()) {
715 if (const Constant *cu = dyn_cast<Constant>(U)) {
716 if (useFuncSeen(cu, seenMap))
718 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
719 const BasicBlock *bb = I->getParent();
722 const Function *caller = bb->getParent();
725 if (seenMap.find(caller) != seenMap.end())
732 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
733 llvm::DenseMap<const Function *, bool> seenMap;
734 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
735 const Function *F = FI;
737 if (F->isDeclaration()) {
740 if (F->getIntrinsicID())
742 emitDeclaration(F, O);
745 for (const User *U : F->users()) {
746 if (const Constant *C = dyn_cast<Constant>(U)) {
747 if (usedInGlobalVarDef(C)) {
748 // The use is in the initialization of a global variable
749 // that is a function pointer, so print a declaration
750 // for the original function
751 emitDeclaration(F, O);
754 // Emit a declaration of this function if the function that
755 // uses this constant expr has already been seen.
756 if (useFuncSeen(C, seenMap)) {
757 emitDeclaration(F, O);
762 if (!isa<Instruction>(U))
764 const Instruction *instr = cast<Instruction>(U);
765 const BasicBlock *bb = instr->getParent();
768 const Function *caller = bb->getParent();
772 // If a caller has already been seen, then the caller is
773 // appearing in the module before the callee. so print out
774 // a declaration for the callee.
775 if (seenMap.find(caller) != seenMap.end()) {
776 emitDeclaration(F, O);
784 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
785 DebugInfoFinder DbgFinder;
786 DbgFinder.processModule(M);
789 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
790 StringRef Filename(DIUnit.getFilename());
791 StringRef Dirname(DIUnit.getDirectory());
792 SmallString<128> FullPathName = Dirname;
793 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
794 sys::path::append(FullPathName, Filename);
795 Filename = FullPathName.str();
797 if (filenameMap.find(Filename.str()) != filenameMap.end())
799 filenameMap[Filename.str()] = i;
800 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
804 for (DISubprogram SP : DbgFinder.subprograms()) {
805 StringRef Filename(SP.getFilename());
806 StringRef Dirname(SP.getDirectory());
807 SmallString<128> FullPathName = Dirname;
808 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
809 sys::path::append(FullPathName, Filename);
810 Filename = FullPathName.str();
812 if (filenameMap.find(Filename.str()) != filenameMap.end())
814 filenameMap[Filename.str()] = i;
819 bool NVPTXAsmPrinter::doInitialization(Module &M) {
821 SmallString<128> Str1;
822 raw_svector_ostream OS1(Str1);
824 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
825 MMI->AnalyzeModule(M);
827 // We need to call the parent's one explicitly.
828 //bool Result = AsmPrinter::doInitialization(M);
830 // Initialize TargetLoweringObjectFile.
831 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
832 .Initialize(OutContext, TM);
834 Mang = new Mangler(TM.getDataLayout());
836 // Emit header before any dwarf directives are emitted below.
838 OutStreamer.EmitRawText(OS1.str());
840 // Already commented out
841 //bool Result = AsmPrinter::doInitialization(M);
843 // Emit module-level inline asm if it exists.
844 if (!M.getModuleInlineAsm().empty()) {
845 OutStreamer.AddComment("Start of file scope inline assembly");
846 OutStreamer.AddBlankLine();
847 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
848 OutStreamer.AddBlankLine();
849 OutStreamer.AddComment("End of file scope inline assembly");
850 OutStreamer.AddBlankLine();
853 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
854 recordAndEmitFilenames(M);
856 GlobalsEmitted = false;
858 return false; // success
861 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
862 SmallString<128> Str2;
863 raw_svector_ostream OS2(Str2);
865 emitDeclarations(M, OS2);
867 // As ptxas does not support forward references of globals, we need to first
868 // sort the list of module-level globals in def-use order. We visit each
869 // global variable in order, and ensure that we emit it *after* its dependent
870 // globals. We use a little extra memory maintaining both a set and a list to
871 // have fast searches while maintaining a strict ordering.
872 SmallVector<const GlobalVariable *, 8> Globals;
873 DenseSet<const GlobalVariable *> GVVisited;
874 DenseSet<const GlobalVariable *> GVVisiting;
876 // Visit each global variable, in order
877 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
879 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
881 assert(GVVisited.size() == M.getGlobalList().size() &&
882 "Missed a global variable");
883 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
885 // Print out module-level global variables in proper order
886 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
887 printModuleLevelGV(Globals[i], OS2);
891 OutStreamer.EmitRawText(OS2.str());
894 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
896 O << "// Generated by LLVM NVPTX Back-End\n";
900 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
901 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
904 O << nvptxSubtarget.getTargetName();
906 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
907 O << ", texmode_independent";
908 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
909 if (!nvptxSubtarget.hasDouble())
910 O << ", map_f64_to_f32";
913 if (MAI->doesSupportDebugInformation())
918 O << ".address_size ";
919 if (nvptxSubtarget.is64Bit())
928 bool NVPTXAsmPrinter::doFinalization(Module &M) {
930 // If we did not emit any functions, then the global declarations have not
932 if (!GlobalsEmitted) {
934 GlobalsEmitted = true;
937 // XXX Temproarily remove global variables so that doFinalization() will not
938 // emit them again (global variables are emitted at beginning).
940 Module::GlobalListType &global_list = M.getGlobalList();
941 int i, n = global_list.size();
942 GlobalVariable **gv_array = new GlobalVariable *[n];
944 // first, back-up GlobalVariable in gv_array
946 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
950 // second, empty global_list
951 while (!global_list.empty())
952 global_list.remove(global_list.begin());
954 // call doFinalization
955 bool ret = AsmPrinter::doFinalization(M);
957 // now we restore global variables
958 for (i = 0; i < n; i++)
959 global_list.insert(global_list.end(), gv_array[i]);
961 clearAnnotationCache(&M);
966 //bool Result = AsmPrinter::doFinalization(M);
967 // Instead of calling the parents doFinalization, we may
968 // clone parents doFinalization and customize here.
969 // Currently, we if NVISA out the EmitGlobals() in
970 // parent's doFinalization, which is too intrusive.
972 // Same for the doInitialization.
976 // This function emits appropriate linkage directives for
977 // functions and global variables.
979 // extern function declaration -> .extern
980 // extern function definition -> .visible
981 // external global variable with init -> .visible
982 // external without init -> .extern
983 // appending -> not allowed, assert.
984 // for any linkage other than
985 // internal, private, linker_private,
986 // linker_private_weak, linker_private_weak_def_auto,
989 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
991 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
992 if (V->hasExternalLinkage()) {
993 if (isa<GlobalVariable>(V)) {
994 const GlobalVariable *GVar = cast<GlobalVariable>(V);
996 if (GVar->hasInitializer())
1001 } else if (V->isDeclaration())
1005 } else if (V->hasAppendingLinkage()) {
1007 msg.append("Error: ");
1008 msg.append("Symbol ");
1010 msg.append(V->getName().str());
1011 msg.append("has unsupported appending linkage type");
1012 llvm_unreachable(msg.c_str());
1013 } else if (!V->hasInternalLinkage() &&
1014 !V->hasPrivateLinkage()) {
1020 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1022 bool processDemoted) {
1025 if (GVar->hasSection()) {
1026 if (GVar->getSection() == StringRef("llvm.metadata"))
1030 // Skip LLVM intrinsic global variables
1031 if (GVar->getName().startswith("llvm.") ||
1032 GVar->getName().startswith("nvvm."))
1035 const DataLayout *TD = TM.getDataLayout();
1037 // GlobalVariables are always constant pointers themselves.
1038 const PointerType *PTy = GVar->getType();
1039 Type *ETy = PTy->getElementType();
1041 if (GVar->hasExternalLinkage()) {
1042 if (GVar->hasInitializer())
1046 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1047 GVar->hasAvailableExternallyLinkage() ||
1048 GVar->hasCommonLinkage()) {
1052 if (llvm::isTexture(*GVar)) {
1053 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1057 if (llvm::isSurface(*GVar)) {
1058 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1062 if (GVar->isDeclaration()) {
1063 // (extern) declarations, no definition or initializer
1064 // Currently the only known declaration is for an automatic __local
1065 // (.shared) promoted to global.
1066 emitPTXGlobalVariable(GVar, O);
1071 if (llvm::isSampler(*GVar)) {
1072 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1074 const Constant *Initializer = nullptr;
1075 if (GVar->hasInitializer())
1076 Initializer = GVar->getInitializer();
1077 const ConstantInt *CI = nullptr;
1079 CI = dyn_cast<ConstantInt>(Initializer);
1081 unsigned sample = CI->getZExtValue();
1086 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1088 O << "addr_mode_" << i << " = ";
1094 O << "clamp_to_border";
1097 O << "clamp_to_edge";
1108 O << "filter_mode = ";
1109 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1117 llvm_unreachable("Anisotropic filtering is not supported");
1122 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1123 O << ", force_unnormalized_coords = 1";
1132 if (GVar->hasPrivateLinkage()) {
1134 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1137 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1138 if (!strncmp(GVar->getName().data(), "filename", 8))
1140 if (GVar->use_empty())
1144 const Function *demotedFunc = nullptr;
1145 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1146 O << "// " << GVar->getName().str() << " has been demoted\n";
1147 if (localDecls.find(demotedFunc) != localDecls.end())
1148 localDecls[demotedFunc].push_back(GVar);
1150 std::vector<const GlobalVariable *> temp;
1151 temp.push_back(GVar);
1152 localDecls[demotedFunc] = temp;
1158 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1160 if (isManaged(*GVar)) {
1161 O << " .attribute(.managed)";
1164 if (GVar->getAlignment() == 0)
1165 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1167 O << " .align " << GVar->getAlignment();
1169 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1171 // Special case: ABI requires that we use .u8 for predicates
1172 if (ETy->isIntegerTy(1))
1175 O << getPTXFundamentalTypeStr(ETy, false);
1177 O << *getSymbol(GVar);
1179 // Ptx allows variable initilization only for constant and global state
1181 if (GVar->hasInitializer()) {
1182 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1183 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1184 const Constant *Initializer = GVar->getInitializer();
1185 // 'undef' is treated as there is no value spefied.
1186 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1188 printScalarConstant(Initializer, O);
1191 // The frontend adds zero-initializer to variables that don't have an
1192 // initial value, so skip warning for this case.
1193 if (!GVar->getInitializer()->isNullValue()) {
1194 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1195 "' is not allowed in addrspace(" +
1196 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1197 report_fatal_error(warnMsg.c_str());
1202 unsigned int ElementSize = 0;
1204 // Although PTX has direct support for struct type and array type and
1205 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1206 // targets that support these high level field accesses. Structs, arrays
1207 // and vectors are lowered into arrays of bytes.
1208 switch (ETy->getTypeID()) {
1209 case Type::StructTyID:
1210 case Type::ArrayTyID:
1211 case Type::VectorTyID:
1212 ElementSize = TD->getTypeStoreSize(ETy);
1213 // Ptx allows variable initilization only for constant and
1214 // global state spaces.
1215 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1216 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1217 GVar->hasInitializer()) {
1218 const Constant *Initializer = GVar->getInitializer();
1219 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1220 AggBuffer aggBuffer(ElementSize, O, *this);
1221 bufferAggregateConstant(Initializer, &aggBuffer);
1222 if (aggBuffer.numSymbols) {
1223 if (nvptxSubtarget.is64Bit()) {
1224 O << " .u64 " << *getSymbol(GVar) << "[";
1225 O << ElementSize / 8;
1227 O << " .u32 " << *getSymbol(GVar) << "[";
1228 O << ElementSize / 4;
1232 O << " .b8 " << *getSymbol(GVar) << "[";
1240 O << " .b8 " << *getSymbol(GVar);
1248 O << " .b8 " << *getSymbol(GVar);
1257 llvm_unreachable("type not supported yet");
1264 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1265 if (localDecls.find(f) == localDecls.end())
1268 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1270 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1271 O << "\t// demoted variable\n\t";
1272 printModuleLevelGV(gvars[i], O, true);
1276 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1277 raw_ostream &O) const {
1278 switch (AddressSpace) {
1279 case llvm::ADDRESS_SPACE_LOCAL:
1282 case llvm::ADDRESS_SPACE_GLOBAL:
1285 case llvm::ADDRESS_SPACE_CONST:
1288 case llvm::ADDRESS_SPACE_SHARED:
1292 report_fatal_error("Bad address space found while emitting PTX");
1298 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1299 switch (Ty->getTypeID()) {
1301 llvm_unreachable("unexpected type");
1303 case Type::IntegerTyID: {
1304 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1307 else if (NumBits <= 64) {
1308 std::string name = "u";
1309 return name + utostr(NumBits);
1311 llvm_unreachable("Integer too large");
1316 case Type::FloatTyID:
1318 case Type::DoubleTyID:
1320 case Type::PointerTyID:
1321 if (nvptxSubtarget.is64Bit())
1331 llvm_unreachable("unexpected type");
1335 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1338 const DataLayout *TD = TM.getDataLayout();
1340 // GlobalVariables are always constant pointers themselves.
1341 const PointerType *PTy = GVar->getType();
1342 Type *ETy = PTy->getElementType();
1345 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1346 if (GVar->getAlignment() == 0)
1347 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1349 O << " .align " << GVar->getAlignment();
1351 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1353 O << getPTXFundamentalTypeStr(ETy);
1355 O << *getSymbol(GVar);
1359 int64_t ElementSize = 0;
1361 // Although PTX has direct support for struct type and array type and LLVM IR
1362 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1363 // support these high level field accesses. Structs and arrays are lowered
1364 // into arrays of bytes.
1365 switch (ETy->getTypeID()) {
1366 case Type::StructTyID:
1367 case Type::ArrayTyID:
1368 case Type::VectorTyID:
1369 ElementSize = TD->getTypeStoreSize(ETy);
1370 O << " .b8 " << *getSymbol(GVar) << "[";
1372 O << itostr(ElementSize);
1377 llvm_unreachable("type not supported yet");
1382 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1383 if (Ty->isSingleValueType())
1384 return TD->getPrefTypeAlignment(Ty);
1386 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1388 return getOpenCLAlignment(TD, ATy->getElementType());
1390 const StructType *STy = dyn_cast<StructType>(Ty);
1392 unsigned int alignStruct = 1;
1393 // Go through each element of the struct and find the
1394 // largest alignment.
1395 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1396 Type *ETy = STy->getElementType(i);
1397 unsigned int align = getOpenCLAlignment(TD, ETy);
1398 if (align > alignStruct)
1399 alignStruct = align;
1404 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1406 return TD->getPointerPrefAlignment();
1407 return TD->getPrefTypeAlignment(Ty);
1410 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1411 int paramIndex, raw_ostream &O) {
1412 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1413 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1414 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1416 std::string argName = I->getName();
1417 const char *p = argName.c_str();
1428 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1429 Function::const_arg_iterator I, E;
1432 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1433 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1434 O << *CurrentFnSym << "_param_" << paramIndex;
1438 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1439 if (i == paramIndex) {
1440 printParamName(I, paramIndex, O);
1444 llvm_unreachable("paramIndex out of bound");
1447 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1448 const DataLayout *TD = TM.getDataLayout();
1449 const AttributeSet &PAL = F->getAttributes();
1450 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1451 Function::const_arg_iterator I, E;
1452 unsigned paramIndex = 0;
1454 bool isKernelFunc = llvm::isKernelFunction(*F);
1455 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1456 MVT thePointerTy = TLI->getPointerTy();
1460 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1461 Type *Ty = I->getType();
1468 // Handle image/sampler parameters
1469 if (isKernelFunction(*F)) {
1470 if (isSampler(*I) || isImage(*I)) {
1472 std::string sname = I->getName();
1473 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1474 if (nvptxSubtarget.hasImageHandles())
1475 O << "\t.param .u64 .ptr .surfref ";
1477 O << "\t.param .surfref ";
1478 O << *CurrentFnSym << "_param_" << paramIndex;
1480 else { // Default image is read_only
1481 if (nvptxSubtarget.hasImageHandles())
1482 O << "\t.param .u64 .ptr .texref ";
1484 O << "\t.param .texref ";
1485 O << *CurrentFnSym << "_param_" << paramIndex;
1488 if (nvptxSubtarget.hasImageHandles())
1489 O << "\t.param .u64 .ptr .samplerref ";
1491 O << "\t.param .samplerref ";
1492 O << *CurrentFnSym << "_param_" << paramIndex;
1498 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1499 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1500 // Just print .param .align <a> .b8 .param[size];
1501 // <a> = PAL.getparamalignment
1502 // size = typeallocsize of element type
1503 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1505 align = TD->getABITypeAlignment(Ty);
1507 unsigned sz = TD->getTypeAllocSize(Ty);
1508 O << "\t.param .align " << align << " .b8 ";
1509 printParamName(I, paramIndex, O);
1510 O << "[" << sz << "]";
1515 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1518 // Special handling for pointer arguments to kernel
1519 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1521 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1522 Type *ETy = PTy->getElementType();
1523 int addrSpace = PTy->getAddressSpace();
1524 switch (addrSpace) {
1528 case llvm::ADDRESS_SPACE_CONST:
1529 O << ".ptr .const ";
1531 case llvm::ADDRESS_SPACE_SHARED:
1532 O << ".ptr .shared ";
1534 case llvm::ADDRESS_SPACE_GLOBAL:
1535 O << ".ptr .global ";
1538 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1540 printParamName(I, paramIndex, O);
1544 // non-pointer scalar to kernel func
1546 // Special case: predicate operands become .u8 types
1547 if (Ty->isIntegerTy(1))
1550 O << getPTXFundamentalTypeStr(Ty);
1552 printParamName(I, paramIndex, O);
1555 // Non-kernel function, just print .param .b<size> for ABI
1556 // and .reg .b<size> for non-ABI
1558 if (isa<IntegerType>(Ty)) {
1559 sz = cast<IntegerType>(Ty)->getBitWidth();
1562 } else if (isa<PointerType>(Ty))
1563 sz = thePointerTy.getSizeInBits();
1565 sz = Ty->getPrimitiveSizeInBits();
1567 O << "\t.param .b" << sz << " ";
1569 O << "\t.reg .b" << sz << " ";
1570 printParamName(I, paramIndex, O);
1574 // param has byVal attribute. So should be a pointer
1575 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1576 assert(PTy && "Param with byval attribute should be a pointer type");
1577 Type *ETy = PTy->getElementType();
1579 if (isABI || isKernelFunc) {
1580 // Just print .param .align <a> .b8 .param[size];
1581 // <a> = PAL.getparamalignment
1582 // size = typeallocsize of element type
1583 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1585 align = TD->getABITypeAlignment(ETy);
1587 unsigned sz = TD->getTypeAllocSize(ETy);
1588 O << "\t.param .align " << align << " .b8 ";
1589 printParamName(I, paramIndex, O);
1590 O << "[" << sz << "]";
1593 // Split the ETy into constituent parts and
1594 // print .param .b<size> <name> for each part.
1595 // Further, if a part is vector, print the above for
1596 // each vector element.
1597 SmallVector<EVT, 16> vtparts;
1598 ComputeValueVTs(*TLI, ETy, vtparts);
1599 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1601 EVT elemtype = vtparts[i];
1602 if (vtparts[i].isVector()) {
1603 elems = vtparts[i].getVectorNumElements();
1604 elemtype = vtparts[i].getVectorElementType();
1607 for (unsigned j = 0, je = elems; j != je; ++j) {
1608 unsigned sz = elemtype.getSizeInBits();
1609 if (elemtype.isInteger() && (sz < 32))
1611 O << "\t.reg .b" << sz << " ";
1612 printParamName(I, paramIndex, O);
1628 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1630 const Function *F = MF.getFunction();
1631 emitFunctionParamList(F, O);
1634 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1635 const MachineFunction &MF) {
1636 SmallString<128> Str;
1637 raw_svector_ostream O(Str);
1639 // Map the global virtual register number to a register class specific
1640 // virtual register number starting from 1 with that class.
1641 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1642 //unsigned numRegClasses = TRI->getNumRegClasses();
1644 // Emit the Fake Stack Object
1645 const MachineFrameInfo *MFI = MF.getFrameInfo();
1646 int NumBytes = (int) MFI->getStackSize();
1648 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1649 << getFunctionNumber() << "[" << NumBytes << "];\n";
1650 if (nvptxSubtarget.is64Bit()) {
1651 O << "\t.reg .b64 \t%SP;\n";
1652 O << "\t.reg .b64 \t%SPL;\n";
1654 O << "\t.reg .b32 \t%SP;\n";
1655 O << "\t.reg .b32 \t%SPL;\n";
1659 // Go through all virtual registers to establish the mapping between the
1661 // register number and the per class virtual register number.
1662 // We use the per class virtual register number in the ptx output.
1663 unsigned int numVRs = MRI->getNumVirtRegs();
1664 for (unsigned i = 0; i < numVRs; i++) {
1665 unsigned int vr = TRI->index2VirtReg(i);
1666 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1667 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1668 int n = regmap.size();
1669 regmap.insert(std::make_pair(vr, n + 1));
1672 // Emit register declarations
1673 // @TODO: Extract out the real register usage
1674 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1675 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1676 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1677 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1678 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1679 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1680 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1682 // Emit declaration of the virtual registers or 'physical' registers for
1683 // each register class
1684 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1685 const TargetRegisterClass *RC = TRI->getRegClass(i);
1686 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1687 std::string rcname = getNVPTXRegClassName(RC);
1688 std::string rcStr = getNVPTXRegClassStr(RC);
1689 int n = regmap.size();
1691 // Only declare those registers that may be used.
1693 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1698 OutStreamer.EmitRawText(O.str());
1701 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1702 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1704 unsigned int numHex;
1707 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1710 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1711 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1714 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1716 llvm_unreachable("unsupported fp type");
1718 APInt API = APF.bitcastToAPInt();
1719 std::string hexstr(utohexstr(API.getZExtValue()));
1721 if (hexstr.length() < numHex)
1722 O << std::string(numHex - hexstr.length(), '0');
1723 O << utohexstr(API.getZExtValue());
1726 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1727 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1728 O << CI->getValue();
1731 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1732 printFPConstant(CFP, O);
1735 if (isa<ConstantPointerNull>(CPV)) {
1739 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1740 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1741 bool IsNonGenericPointer = false;
1742 if (PTy && PTy->getAddressSpace() != 0) {
1743 IsNonGenericPointer = true;
1745 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1747 O << *getSymbol(GVar);
1750 O << *getSymbol(GVar);
1754 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1755 const Value *v = Cexpr->stripPointerCasts();
1756 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1757 bool IsNonGenericPointer = false;
1758 if (PTy && PTy->getAddressSpace() != 0) {
1759 IsNonGenericPointer = true;
1761 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1762 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1764 O << *getSymbol(GVar);
1767 O << *getSymbol(GVar);
1771 O << *lowerConstant(CPV);
1775 llvm_unreachable("Not scalar type found in printScalarConstant()");
1778 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1779 AggBuffer *aggBuffer) {
1781 const DataLayout *TD = TM.getDataLayout();
1783 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1784 int s = TD->getTypeAllocSize(CPV->getType());
1787 aggBuffer->addZeros(s);
1792 switch (CPV->getType()->getTypeID()) {
1794 case Type::IntegerTyID: {
1795 const Type *ETy = CPV->getType();
1796 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1798 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1800 aggBuffer->addBytes(ptr, 1, Bytes);
1801 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1802 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1803 ptr = (unsigned char *)&int16;
1804 aggBuffer->addBytes(ptr, 2, Bytes);
1805 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1806 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1807 int int32 = (int)(constInt->getZExtValue());
1808 ptr = (unsigned char *)&int32;
1809 aggBuffer->addBytes(ptr, 4, Bytes);
1811 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1812 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1813 ConstantFoldConstantExpression(Cexpr, TD))) {
1814 int int32 = (int)(constInt->getZExtValue());
1815 ptr = (unsigned char *)&int32;
1816 aggBuffer->addBytes(ptr, 4, Bytes);
1819 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1820 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1821 aggBuffer->addSymbol(v);
1822 aggBuffer->addZeros(4);
1826 llvm_unreachable("unsupported integer const type");
1827 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1828 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1829 long long int64 = (long long)(constInt->getZExtValue());
1830 ptr = (unsigned char *)&int64;
1831 aggBuffer->addBytes(ptr, 8, Bytes);
1833 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1834 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1835 ConstantFoldConstantExpression(Cexpr, TD))) {
1836 long long int64 = (long long)(constInt->getZExtValue());
1837 ptr = (unsigned char *)&int64;
1838 aggBuffer->addBytes(ptr, 8, Bytes);
1841 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1842 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1843 aggBuffer->addSymbol(v);
1844 aggBuffer->addZeros(8);
1848 llvm_unreachable("unsupported integer const type");
1850 llvm_unreachable("unsupported integer const type");
1853 case Type::FloatTyID:
1854 case Type::DoubleTyID: {
1855 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1856 const Type *Ty = CFP->getType();
1857 if (Ty == Type::getFloatTy(CPV->getContext())) {
1858 float float32 = (float) CFP->getValueAPF().convertToFloat();
1859 ptr = (unsigned char *)&float32;
1860 aggBuffer->addBytes(ptr, 4, Bytes);
1861 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1862 double float64 = CFP->getValueAPF().convertToDouble();
1863 ptr = (unsigned char *)&float64;
1864 aggBuffer->addBytes(ptr, 8, Bytes);
1866 llvm_unreachable("unsupported fp const type");
1870 case Type::PointerTyID: {
1871 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1872 aggBuffer->addSymbol(GVar);
1873 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1874 const Value *v = Cexpr->stripPointerCasts();
1875 aggBuffer->addSymbol(v);
1877 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1878 aggBuffer->addZeros(s);
1882 case Type::ArrayTyID:
1883 case Type::VectorTyID:
1884 case Type::StructTyID: {
1885 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1886 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1887 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1888 bufferAggregateConstant(CPV, aggBuffer);
1889 if (Bytes > ElementSize)
1890 aggBuffer->addZeros(Bytes - ElementSize);
1891 } else if (isa<ConstantAggregateZero>(CPV))
1892 aggBuffer->addZeros(Bytes);
1894 llvm_unreachable("Unexpected Constant type");
1899 llvm_unreachable("unsupported type");
1903 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1904 AggBuffer *aggBuffer) {
1905 const DataLayout *TD = TM.getDataLayout();
1909 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1910 if (CPV->getNumOperands())
1911 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1912 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1916 if (const ConstantDataSequential *CDS =
1917 dyn_cast<ConstantDataSequential>(CPV)) {
1918 if (CDS->getNumElements())
1919 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1920 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1925 if (isa<ConstantStruct>(CPV)) {
1926 if (CPV->getNumOperands()) {
1927 StructType *ST = cast<StructType>(CPV->getType());
1928 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1930 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1931 TD->getTypeAllocSize(ST) -
1932 TD->getStructLayout(ST)->getElementOffset(i);
1934 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1935 TD->getStructLayout(ST)->getElementOffset(i);
1936 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1941 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1944 // buildTypeNameMap - Run through symbol table looking for type names.
1947 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1949 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1951 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1952 !PI->second.compare("struct._image2d_t") ||
1953 !PI->second.compare("struct._image3d_t")))
1960 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1961 switch (MI.getOpcode()) {
1964 case NVPTX::CallArgBeginInst:
1965 case NVPTX::CallArgEndInst0:
1966 case NVPTX::CallArgEndInst1:
1967 case NVPTX::CallArgF32:
1968 case NVPTX::CallArgF64:
1969 case NVPTX::CallArgI16:
1970 case NVPTX::CallArgI32:
1971 case NVPTX::CallArgI32imm:
1972 case NVPTX::CallArgI64:
1973 case NVPTX::CallArgParam:
1974 case NVPTX::CallVoidInst:
1975 case NVPTX::CallVoidInstReg:
1976 case NVPTX::Callseq_End:
1977 case NVPTX::CallVoidInstReg64:
1978 case NVPTX::DeclareParamInst:
1979 case NVPTX::DeclareRetMemInst:
1980 case NVPTX::DeclareRetRegInst:
1981 case NVPTX::DeclareRetScalarInst:
1982 case NVPTX::DeclareScalarParamInst:
1983 case NVPTX::DeclareScalarRegInst:
1984 case NVPTX::StoreParamF32:
1985 case NVPTX::StoreParamF64:
1986 case NVPTX::StoreParamI16:
1987 case NVPTX::StoreParamI32:
1988 case NVPTX::StoreParamI64:
1989 case NVPTX::StoreParamI8:
1990 case NVPTX::StoreRetvalF32:
1991 case NVPTX::StoreRetvalF64:
1992 case NVPTX::StoreRetvalI16:
1993 case NVPTX::StoreRetvalI32:
1994 case NVPTX::StoreRetvalI64:
1995 case NVPTX::StoreRetvalI8:
1996 case NVPTX::LastCallArgF32:
1997 case NVPTX::LastCallArgF64:
1998 case NVPTX::LastCallArgI16:
1999 case NVPTX::LastCallArgI32:
2000 case NVPTX::LastCallArgI32imm:
2001 case NVPTX::LastCallArgI64:
2002 case NVPTX::LastCallArgParam:
2003 case NVPTX::LoadParamMemF32:
2004 case NVPTX::LoadParamMemF64:
2005 case NVPTX::LoadParamMemI16:
2006 case NVPTX::LoadParamMemI32:
2007 case NVPTX::LoadParamMemI64:
2008 case NVPTX::LoadParamMemI8:
2009 case NVPTX::PrototypeInst:
2010 case NVPTX::DBG_VALUE:
2016 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2018 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2019 unsigned AsmVariant,
2020 const char *ExtraCode, raw_ostream &O) {
2021 if (ExtraCode && ExtraCode[0]) {
2022 if (ExtraCode[1] != 0)
2023 return true; // Unknown modifier.
2025 switch (ExtraCode[0]) {
2027 // See if this is a generic print operand
2028 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2034 printOperand(MI, OpNo, O);
2039 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2040 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2041 const char *ExtraCode, raw_ostream &O) {
2042 if (ExtraCode && ExtraCode[0])
2043 return true; // Unknown modifier
2046 printMemOperand(MI, OpNo, O);
2052 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2053 raw_ostream &O, const char *Modifier) {
2054 const MachineOperand &MO = MI->getOperand(opNum);
2055 switch (MO.getType()) {
2056 case MachineOperand::MO_Register:
2057 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2058 if (MO.getReg() == NVPTX::VRDepot)
2059 O << DEPOTNAME << getFunctionNumber();
2061 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2063 emitVirtualRegister(MO.getReg(), O);
2067 case MachineOperand::MO_Immediate:
2070 else if (strstr(Modifier, "vec") == Modifier)
2071 printVecModifiedImmediate(MO, Modifier, O);
2074 "Don't know how to handle modifier on immediate operand");
2077 case MachineOperand::MO_FPImmediate:
2078 printFPConstant(MO.getFPImm(), O);
2081 case MachineOperand::MO_GlobalAddress:
2082 O << *getSymbol(MO.getGlobal());
2085 case MachineOperand::MO_MachineBasicBlock:
2086 O << *MO.getMBB()->getSymbol();
2090 llvm_unreachable("Operand type not supported.");
2094 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2095 raw_ostream &O, const char *Modifier) {
2096 printOperand(MI, opNum, O);
2098 if (Modifier && !strcmp(Modifier, "add")) {
2100 printOperand(MI, opNum + 1, O);
2102 if (MI->getOperand(opNum + 1).isImm() &&
2103 MI->getOperand(opNum + 1).getImm() == 0)
2104 return; // don't print ',0' or '+0'
2106 printOperand(MI, opNum + 1, O);
2111 // Force static initialization.
2112 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2113 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2114 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2117 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2118 std::stringstream temp;
2119 LineReader *reader = this->getReader(filename.str());
2121 temp << filename.str();
2125 temp << reader->readLine(line);
2127 this->OutStreamer.EmitRawText(Twine(temp.str()));
2130 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2132 reader = new LineReader(filename);
2135 if (reader->fileName() != filename) {
2137 reader = new LineReader(filename);
2143 std::string LineReader::readLine(unsigned lineNum) {
2144 if (lineNum < theCurLine) {
2146 fstr.seekg(0, std::ios::beg);
2148 while (theCurLine < lineNum) {
2149 fstr.getline(buff, 500);
2155 // Force static initialization.
2156 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2157 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2158 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);