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 "NVPTXRegisterInfo.h"
22 #include "NVPTXTargetMachine.h"
23 #include "NVPTXUtilities.h"
24 #include "cl_common_defines.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Mangler.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TimeValue.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #define DEPOTNAME "__local_depot"
53 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
54 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
58 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
59 cl::desc("NVPTX Specific: Emit source line in ptx file"),
63 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
65 void DiscoverDependentGlobals(const Value *V,
66 DenseSet<const GlobalVariable *> &Globals) {
67 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
70 if (const User *U = dyn_cast<User>(V)) {
71 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
72 DiscoverDependentGlobals(U->getOperand(i), Globals);
78 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
79 /// instances to be emitted, but only after any dependents have been added
81 void VisitGlobalVariableForEmission(
82 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
83 DenseSet<const GlobalVariable *> &Visited,
84 DenseSet<const GlobalVariable *> &Visiting) {
85 // Have we already visited this one?
86 if (Visited.count(GV))
89 // Do we have a circular dependency?
90 if (Visiting.count(GV))
91 report_fatal_error("Circular dependency found in global variable set");
93 // Start visiting this global
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 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
114 // cannot just link to the existing version.
115 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
117 using namespace nvptx;
118 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
119 MCContext &Ctx = AP.OutContext;
121 if (CV->isNullValue() || isa<UndefValue>(CV))
122 return MCConstantExpr::Create(0, Ctx);
124 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
125 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
127 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
128 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
130 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
131 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
133 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
135 llvm_unreachable("Unknown constant value to lower!");
137 switch (CE->getOpcode()) {
139 // If the code isn't optimized, there may be outstanding folding
140 // opportunities. Attempt to fold the expression using DataLayout as a
141 // last resort before giving up.
142 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
144 return LowerConstant(C, AP);
146 // Otherwise report the problem to the user.
149 raw_string_ostream OS(S);
150 OS << "Unsupported expression in static initializer: ";
151 CE->printAsOperand(OS, /*PrintType=*/ false,
152 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
153 report_fatal_error(OS.str());
155 case Instruction::GetElementPtr: {
156 const DataLayout &TD = *AP.TM.getDataLayout();
157 // Generate a symbolic expression for the byte address
158 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
159 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
161 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
165 int64_t Offset = OffsetAI.getSExtValue();
166 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
170 case Instruction::Trunc:
171 // We emit the value and depend on the assembler to truncate the generated
172 // expression properly. This is important for differences between
173 // blockaddress labels. Since the two labels are in the same function, it
174 // is reasonable to treat their delta as a 32-bit value.
176 case Instruction::BitCast:
177 return LowerConstant(CE->getOperand(0), AP);
179 case Instruction::IntToPtr: {
180 const DataLayout &TD = *AP.TM.getDataLayout();
181 // Handle casts to pointers by changing them into casts to the appropriate
182 // integer type. This promotes constant folding and simplifies this code.
183 Constant *Op = CE->getOperand(0);
184 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
186 return LowerConstant(Op, AP);
189 case Instruction::PtrToInt: {
190 const DataLayout &TD = *AP.TM.getDataLayout();
191 // Support only foldable casts to/from pointers that can be eliminated by
192 // changing the pointer to the appropriately sized integer type.
193 Constant *Op = CE->getOperand(0);
194 Type *Ty = CE->getType();
196 const MCExpr *OpExpr = LowerConstant(Op, AP);
198 // We can emit the pointer value into this slot if the slot is an
199 // integer slot equal to the size of the pointer.
200 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
203 // Otherwise the pointer is smaller than the resultant integer, mask off
204 // the high bits so we are sure to get a proper truncation if the input is
206 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
207 const MCExpr *MaskExpr =
208 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
209 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
212 // The MC library also has a right-shift operator, but it isn't consistently
213 // signed or unsigned between different targets.
214 case Instruction::Add:
215 case Instruction::Sub:
216 case Instruction::Mul:
217 case Instruction::SDiv:
218 case Instruction::SRem:
219 case Instruction::Shl:
220 case Instruction::And:
221 case Instruction::Or:
222 case Instruction::Xor: {
223 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
224 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
225 switch (CE->getOpcode()) {
227 llvm_unreachable("Unknown binary operator constant cast expr");
228 case Instruction::Add:
229 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
230 case Instruction::Sub:
231 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
232 case Instruction::Mul:
233 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
234 case Instruction::SDiv:
235 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
236 case Instruction::SRem:
237 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
238 case Instruction::Shl:
239 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
240 case Instruction::And:
241 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
242 case Instruction::Or:
243 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
244 case Instruction::Xor:
245 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
251 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
252 if (!EmitLineNumbers)
257 DebugLoc curLoc = MI.getDebugLoc();
259 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
262 if (prevDebugLoc == curLoc)
265 prevDebugLoc = curLoc;
267 if (curLoc.isUnknown())
270 const MachineFunction *MF = MI.getParent()->getParent();
271 //const TargetMachine &TM = MF->getTarget();
273 const LLVMContext &ctx = MF->getFunction()->getContext();
274 DIScope Scope(curLoc.getScope(ctx));
276 assert((!Scope || Scope.isScope()) &&
277 "Scope of a DebugLoc should be null or a DIScope.");
281 StringRef fileName(Scope.getFilename());
282 StringRef dirName(Scope.getDirectory());
283 SmallString<128> FullPathName = dirName;
284 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
285 sys::path::append(FullPathName, fileName);
286 fileName = FullPathName.str();
289 if (filenameMap.find(fileName.str()) == filenameMap.end())
292 // Emit the line from the source file.
294 this->emitSrcInText(fileName.str(), curLoc.getLine());
296 std::stringstream temp;
297 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
298 << " " << curLoc.getCol();
299 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
302 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
303 SmallString<128> Str;
304 raw_svector_ostream OS(Str);
305 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
306 emitLineNumberAsDotLoc(*MI);
309 lowerToMCInst(MI, Inst);
310 EmitToStreamer(OutStreamer, Inst);
313 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
314 OutMI.setOpcode(MI->getOpcode());
316 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
317 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
318 const MachineOperand &MO = MI->getOperand(0);
319 OutMI.addOperand(GetSymbolRef(MO,
320 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
324 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
325 const MachineOperand &MO = MI->getOperand(i);
328 if (lowerOperand(MO, MCOp))
329 OutMI.addOperand(MCOp);
333 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
335 switch (MO.getType()) {
336 default: llvm_unreachable("unknown operand type");
337 case MachineOperand::MO_Register:
338 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
340 case MachineOperand::MO_Immediate:
341 MCOp = MCOperand::CreateImm(MO.getImm());
343 case MachineOperand::MO_MachineBasicBlock:
344 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
345 MO.getMBB()->getSymbol(), OutContext));
347 case MachineOperand::MO_ExternalSymbol:
348 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
350 case MachineOperand::MO_GlobalAddress:
351 MCOp = GetSymbolRef(MO, getSymbol(MO.getGlobal()));
353 case MachineOperand::MO_FPImmediate: {
354 const ConstantFP *Cnt = MO.getFPImm();
355 APFloat Val = Cnt->getValueAPF();
357 switch (Cnt->getType()->getTypeID()) {
358 default: report_fatal_error("Unsupported FP type"); break;
359 case Type::FloatTyID:
360 MCOp = MCOperand::CreateExpr(
361 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
363 case Type::DoubleTyID:
364 MCOp = MCOperand::CreateExpr(
365 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
374 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
375 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
376 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
378 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
379 unsigned RegNum = RegMap[Reg];
381 // Encode the register class in the upper 4 bits
382 // Must be kept in sync with NVPTXInstPrinter::printRegName
384 if (RC == &NVPTX::Int1RegsRegClass) {
386 } else if (RC == &NVPTX::Int16RegsRegClass) {
388 } else if (RC == &NVPTX::Int32RegsRegClass) {
390 } else if (RC == &NVPTX::Int64RegsRegClass) {
392 } else if (RC == &NVPTX::Float32RegsRegClass) {
394 } else if (RC == &NVPTX::Float64RegsRegClass) {
397 report_fatal_error("Bad register class");
400 // Insert the vreg number
401 Ret |= (RegNum & 0x0FFFFFFF);
404 // Some special-use registers are actually physical registers.
405 // Encode this as the register class ID of 0 and the real register ID.
406 return Reg & 0x0FFFFFFF;
410 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
411 const MCSymbol *Symbol) {
413 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
415 return MCOperand::CreateExpr(Expr);
418 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
419 const DataLayout *TD = TM.getDataLayout();
420 const TargetLowering *TLI = TM.getTargetLowering();
422 Type *Ty = F->getReturnType();
424 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
426 if (Ty->getTypeID() == Type::VoidTyID)
432 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
434 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
435 size = ITy->getBitWidth();
439 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
440 size = Ty->getPrimitiveSizeInBits();
443 O << ".param .b" << size << " func_retval0";
444 } else if (isa<PointerType>(Ty)) {
445 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
448 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
449 SmallVector<EVT, 16> vtparts;
450 ComputeValueVTs(*TLI, Ty, vtparts);
451 unsigned totalsz = 0;
452 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
454 EVT elemtype = vtparts[i];
455 if (vtparts[i].isVector()) {
456 elems = vtparts[i].getVectorNumElements();
457 elemtype = vtparts[i].getVectorElementType();
459 for (unsigned j = 0, je = elems; j != je; ++j) {
460 unsigned sz = elemtype.getSizeInBits();
461 if (elemtype.isInteger() && (sz < 8))
466 unsigned retAlignment = 0;
467 if (!llvm::getAlign(*F, 0, retAlignment))
468 retAlignment = TD->getABITypeAlignment(Ty);
469 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
472 assert(false && "Unknown return type");
475 SmallVector<EVT, 16> vtparts;
476 ComputeValueVTs(*TLI, Ty, vtparts);
478 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
480 EVT elemtype = vtparts[i];
481 if (vtparts[i].isVector()) {
482 elems = vtparts[i].getVectorNumElements();
483 elemtype = vtparts[i].getVectorElementType();
486 for (unsigned j = 0, je = elems; j != je; ++j) {
487 unsigned sz = elemtype.getSizeInBits();
488 if (elemtype.isInteger() && (sz < 32))
490 O << ".reg .b" << sz << " func_retval" << idx;
503 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
505 const Function *F = MF.getFunction();
506 printReturnValStr(F, O);
509 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
510 SmallString<128> Str;
511 raw_svector_ostream O(Str);
513 if (!GlobalsEmitted) {
514 emitGlobals(*MF->getFunction()->getParent());
515 GlobalsEmitted = true;
519 MRI = &MF->getRegInfo();
520 F = MF->getFunction();
521 emitLinkageDirective(F, O);
522 if (llvm::isKernelFunction(*F))
526 printReturnValStr(*MF, O);
531 emitFunctionParamList(*MF, O);
533 if (llvm::isKernelFunction(*F))
534 emitKernelFunctionDirectives(*F, O);
536 OutStreamer.EmitRawText(O.str());
538 prevDebugLoc = DebugLoc();
541 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
543 OutStreamer.EmitRawText(StringRef("{\n"));
544 setAndEmitFunctionVirtualRegisters(*MF);
546 SmallString<128> Str;
547 raw_svector_ostream O(Str);
548 emitDemotedVars(MF->getFunction(), O);
549 OutStreamer.EmitRawText(O.str());
552 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
553 OutStreamer.EmitRawText(StringRef("}\n"));
557 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
558 unsigned RegNo = MI->getOperand(0).getReg();
559 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
560 if (TRI->isVirtualRegister(RegNo)) {
561 OutStreamer.AddComment(Twine("implicit-def: ") +
562 getVirtualRegisterName(RegNo));
564 OutStreamer.AddComment(Twine("implicit-def: ") +
565 TM.getRegisterInfo()->getName(RegNo));
567 OutStreamer.AddBlankLine();
570 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
571 raw_ostream &O) const {
572 // If the NVVM IR has some of reqntid* specified, then output
573 // the reqntid directive, and set the unspecified ones to 1.
574 // If none of reqntid* is specified, don't output reqntid directive.
575 unsigned reqntidx, reqntidy, reqntidz;
576 bool specified = false;
577 if (llvm::getReqNTIDx(F, reqntidx) == false)
581 if (llvm::getReqNTIDy(F, reqntidy) == false)
585 if (llvm::getReqNTIDz(F, reqntidz) == false)
591 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
594 // If the NVVM IR has some of maxntid* specified, then output
595 // the maxntid directive, and set the unspecified ones to 1.
596 // If none of maxntid* is specified, don't output maxntid directive.
597 unsigned maxntidx, maxntidy, maxntidz;
599 if (llvm::getMaxNTIDx(F, maxntidx) == false)
603 if (llvm::getMaxNTIDy(F, maxntidy) == false)
607 if (llvm::getMaxNTIDz(F, maxntidz) == false)
613 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
617 if (llvm::getMinCTASm(F, mincta))
618 O << ".minnctapersm " << mincta << "\n";
622 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
623 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
626 raw_string_ostream NameStr(Name);
628 VRegRCMap::const_iterator I = VRegMapping.find(RC);
629 assert(I != VRegMapping.end() && "Bad register class");
630 const DenseMap<unsigned, unsigned> &RegMap = I->second;
632 VRegMap::const_iterator VI = RegMap.find(Reg);
633 assert(VI != RegMap.end() && "Bad virtual register");
634 unsigned MappedVR = VI->second;
636 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
642 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
644 O << getVirtualRegisterName(vr);
647 void NVPTXAsmPrinter::printVecModifiedImmediate(
648 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
649 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
650 int Imm = (int) MO.getImm();
651 if (0 == strcmp(Modifier, "vecelem"))
652 O << "_" << vecelem[Imm];
653 else if (0 == strcmp(Modifier, "vecv4comm1")) {
654 if ((Imm < 0) || (Imm > 3))
656 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
657 if ((Imm < 4) || (Imm > 7))
659 } else if (0 == strcmp(Modifier, "vecv4pos")) {
662 O << "_" << vecelem[Imm % 4];
663 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
664 if ((Imm < 0) || (Imm > 1))
666 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
667 if ((Imm < 2) || (Imm > 3))
669 } else if (0 == strcmp(Modifier, "vecv2pos")) {
672 O << "_" << vecelem[Imm % 2];
674 llvm_unreachable("Unknown Modifier on immediate operand");
679 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
681 emitLinkageDirective(F, O);
682 if (llvm::isKernelFunction(*F))
686 printReturnValStr(F, O);
687 O << getSymbolName(F) << "\n";
688 emitFunctionParamList(F, O);
692 static bool usedInGlobalVarDef(const Constant *C) {
696 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
697 if (GV->getName().str() == "llvm.used")
702 for (const User *U : C->users())
703 if (const Constant *C = dyn_cast<Constant>(U))
704 if (usedInGlobalVarDef(C))
710 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
711 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
712 if (othergv->getName().str() == "llvm.used")
716 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
717 if (instr->getParent() && instr->getParent()->getParent()) {
718 const Function *curFunc = instr->getParent()->getParent();
719 if (oneFunc && (curFunc != oneFunc))
727 if (const MDNode *md = dyn_cast<MDNode>(U))
728 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
729 (md->getName().str() == "llvm.dbg.sp")))
732 for (const User *UU : U->users())
733 if (usedInOneFunc(UU, oneFunc) == false)
739 /* Find out if a global variable can be demoted to local scope.
740 * Currently, this is valid for CUDA shared variables, which have local
741 * scope and global lifetime. So the conditions to check are :
742 * 1. Is the global variable in shared address space?
743 * 2. Does it have internal linkage?
744 * 3. Is the global variable referenced only in one function?
746 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
747 if (gv->hasInternalLinkage() == false)
749 const PointerType *Pty = gv->getType();
750 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
753 const Function *oneFunc = 0;
755 bool flag = usedInOneFunc(gv, oneFunc);
764 static bool useFuncSeen(const Constant *C,
765 llvm::DenseMap<const Function *, bool> &seenMap) {
766 for (const User *U : C->users()) {
767 if (const Constant *cu = dyn_cast<Constant>(U)) {
768 if (useFuncSeen(cu, seenMap))
770 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
771 const BasicBlock *bb = I->getParent();
774 const Function *caller = bb->getParent();
777 if (seenMap.find(caller) != seenMap.end())
784 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
785 llvm::DenseMap<const Function *, bool> seenMap;
786 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
787 const Function *F = FI;
789 if (F->isDeclaration()) {
792 if (F->getIntrinsicID())
794 emitDeclaration(F, O);
797 for (const User *U : F->users()) {
798 if (const Constant *C = dyn_cast<Constant>(U)) {
799 if (usedInGlobalVarDef(C)) {
800 // The use is in the initialization of a global variable
801 // that is a function pointer, so print a declaration
802 // for the original function
803 emitDeclaration(F, O);
806 // Emit a declaration of this function if the function that
807 // uses this constant expr has already been seen.
808 if (useFuncSeen(C, seenMap)) {
809 emitDeclaration(F, O);
814 if (!isa<Instruction>(U))
816 const Instruction *instr = cast<Instruction>(U);
817 const BasicBlock *bb = instr->getParent();
820 const Function *caller = bb->getParent();
824 // If a caller has already been seen, then the caller is
825 // appearing in the module before the callee. so print out
826 // a declaration for the callee.
827 if (seenMap.find(caller) != seenMap.end()) {
828 emitDeclaration(F, O);
836 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
837 DebugInfoFinder DbgFinder;
838 DbgFinder.processModule(M);
841 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
842 StringRef Filename(DIUnit.getFilename());
843 StringRef Dirname(DIUnit.getDirectory());
844 SmallString<128> FullPathName = Dirname;
845 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
846 sys::path::append(FullPathName, Filename);
847 Filename = FullPathName.str();
849 if (filenameMap.find(Filename.str()) != filenameMap.end())
851 filenameMap[Filename.str()] = i;
852 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
856 for (DISubprogram SP : DbgFinder.subprograms()) {
857 StringRef Filename(SP.getFilename());
858 StringRef Dirname(SP.getDirectory());
859 SmallString<128> FullPathName = Dirname;
860 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
861 sys::path::append(FullPathName, Filename);
862 Filename = FullPathName.str();
864 if (filenameMap.find(Filename.str()) != filenameMap.end())
866 filenameMap[Filename.str()] = i;
871 bool NVPTXAsmPrinter::doInitialization(Module &M) {
873 SmallString<128> Str1;
874 raw_svector_ostream OS1(Str1);
876 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
877 MMI->AnalyzeModule(M);
879 // We need to call the parent's one explicitly.
880 //bool Result = AsmPrinter::doInitialization(M);
882 // Initialize TargetLoweringObjectFile.
883 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
884 .Initialize(OutContext, TM);
886 Mang = new Mangler(TM.getDataLayout());
888 // Emit header before any dwarf directives are emitted below.
890 OutStreamer.EmitRawText(OS1.str());
892 // Already commented out
893 //bool Result = AsmPrinter::doInitialization(M);
895 // Emit module-level inline asm if it exists.
896 if (!M.getModuleInlineAsm().empty()) {
897 OutStreamer.AddComment("Start of file scope inline assembly");
898 OutStreamer.AddBlankLine();
899 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
900 OutStreamer.AddBlankLine();
901 OutStreamer.AddComment("End of file scope inline assembly");
902 OutStreamer.AddBlankLine();
905 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
906 recordAndEmitFilenames(M);
908 GlobalsEmitted = false;
910 return false; // success
913 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
914 SmallString<128> Str2;
915 raw_svector_ostream OS2(Str2);
917 emitDeclarations(M, OS2);
919 // As ptxas does not support forward references of globals, we need to first
920 // sort the list of module-level globals in def-use order. We visit each
921 // global variable in order, and ensure that we emit it *after* its dependent
922 // globals. We use a little extra memory maintaining both a set and a list to
923 // have fast searches while maintaining a strict ordering.
924 SmallVector<const GlobalVariable *, 8> Globals;
925 DenseSet<const GlobalVariable *> GVVisited;
926 DenseSet<const GlobalVariable *> GVVisiting;
928 // Visit each global variable, in order
929 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
931 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
933 assert(GVVisited.size() == M.getGlobalList().size() &&
934 "Missed a global variable");
935 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
937 // Print out module-level global variables in proper order
938 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
939 printModuleLevelGV(Globals[i], OS2);
943 OutStreamer.EmitRawText(OS2.str());
946 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
948 O << "// Generated by LLVM NVPTX Back-End\n";
952 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
953 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
956 O << nvptxSubtarget.getTargetName();
958 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
959 O << ", texmode_independent";
960 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
961 if (!nvptxSubtarget.hasDouble())
962 O << ", map_f64_to_f32";
965 if (MAI->doesSupportDebugInformation())
970 O << ".address_size ";
971 if (nvptxSubtarget.is64Bit())
980 bool NVPTXAsmPrinter::doFinalization(Module &M) {
982 // If we did not emit any functions, then the global declarations have not
984 if (!GlobalsEmitted) {
986 GlobalsEmitted = true;
989 // XXX Temproarily remove global variables so that doFinalization() will not
990 // emit them again (global variables are emitted at beginning).
992 Module::GlobalListType &global_list = M.getGlobalList();
993 int i, n = global_list.size();
994 GlobalVariable **gv_array = new GlobalVariable *[n];
996 // first, back-up GlobalVariable in gv_array
998 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1000 gv_array[i++] = &*I;
1002 // second, empty global_list
1003 while (!global_list.empty())
1004 global_list.remove(global_list.begin());
1006 // call doFinalization
1007 bool ret = AsmPrinter::doFinalization(M);
1009 // now we restore global variables
1010 for (i = 0; i < n; i++)
1011 global_list.insert(global_list.end(), gv_array[i]);
1016 //bool Result = AsmPrinter::doFinalization(M);
1017 // Instead of calling the parents doFinalization, we may
1018 // clone parents doFinalization and customize here.
1019 // Currently, we if NVISA out the EmitGlobals() in
1020 // parent's doFinalization, which is too intrusive.
1022 // Same for the doInitialization.
1026 // This function emits appropriate linkage directives for
1027 // functions and global variables.
1029 // extern function declaration -> .extern
1030 // extern function definition -> .visible
1031 // external global variable with init -> .visible
1032 // external without init -> .extern
1033 // appending -> not allowed, assert.
1035 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1037 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1038 if (V->hasExternalLinkage()) {
1039 if (isa<GlobalVariable>(V)) {
1040 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1042 if (GVar->hasInitializer())
1047 } else if (V->isDeclaration())
1051 } else if (V->hasAppendingLinkage()) {
1053 msg.append("Error: ");
1054 msg.append("Symbol ");
1056 msg.append(V->getName().str());
1057 msg.append("has unsupported appending linkage type");
1058 llvm_unreachable(msg.c_str());
1063 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1065 bool processDemoted) {
1068 if (GVar->hasSection()) {
1069 if (GVar->getSection() == "llvm.metadata")
1073 const DataLayout *TD = TM.getDataLayout();
1075 // GlobalVariables are always constant pointers themselves.
1076 const PointerType *PTy = GVar->getType();
1077 Type *ETy = PTy->getElementType();
1079 if (GVar->hasExternalLinkage()) {
1080 if (GVar->hasInitializer())
1086 if (llvm::isTexture(*GVar)) {
1087 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1091 if (llvm::isSurface(*GVar)) {
1092 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1096 if (GVar->isDeclaration()) {
1097 // (extern) declarations, no definition or initializer
1098 // Currently the only known declaration is for an automatic __local
1099 // (.shared) promoted to global.
1100 emitPTXGlobalVariable(GVar, O);
1105 if (llvm::isSampler(*GVar)) {
1106 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1108 const Constant *Initializer = NULL;
1109 if (GVar->hasInitializer())
1110 Initializer = GVar->getInitializer();
1111 const ConstantInt *CI = NULL;
1113 CI = dyn_cast<ConstantInt>(Initializer);
1115 unsigned sample = CI->getZExtValue();
1120 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1122 O << "addr_mode_" << i << " = ";
1128 O << "clamp_to_border";
1131 O << "clamp_to_edge";
1142 O << "filter_mode = ";
1143 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1151 assert(0 && "Anisotropic filtering is not supported");
1156 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1157 O << ", force_unnormalized_coords = 1";
1166 if (GVar->hasPrivateLinkage()) {
1168 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1171 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1172 if (!strncmp(GVar->getName().data(), "filename", 8))
1174 if (GVar->use_empty())
1178 const Function *demotedFunc = 0;
1179 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1180 O << "// " << GVar->getName().str() << " has been demoted\n";
1181 if (localDecls.find(demotedFunc) != localDecls.end())
1182 localDecls[demotedFunc].push_back(GVar);
1184 std::vector<const GlobalVariable *> temp;
1185 temp.push_back(GVar);
1186 localDecls[demotedFunc] = temp;
1192 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1193 if (GVar->getAlignment() == 0)
1194 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1196 O << " .align " << GVar->getAlignment();
1198 if (ETy->isSingleValueType()) {
1200 // Special case: ABI requires that we use .u8 for predicates
1201 if (ETy->isIntegerTy(1))
1204 O << getPTXFundamentalTypeStr(ETy, false);
1206 O << getSymbolName(GVar);
1208 // Ptx allows variable initilization only for constant and global state
1210 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1211 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1212 GVar->hasInitializer()) {
1213 const Constant *Initializer = GVar->getInitializer();
1214 if (!Initializer->isNullValue()) {
1216 printScalarConstant(Initializer, O);
1220 unsigned int ElementSize = 0;
1222 // Although PTX has direct support for struct type and array type and
1223 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1224 // targets that support these high level field accesses. Structs, arrays
1225 // and vectors are lowered into arrays of bytes.
1226 switch (ETy->getTypeID()) {
1227 case Type::StructTyID:
1228 case Type::ArrayTyID:
1229 case Type::VectorTyID:
1230 ElementSize = TD->getTypeStoreSize(ETy);
1231 // Ptx allows variable initilization only for constant and
1232 // global state spaces.
1233 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1234 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1235 GVar->hasInitializer()) {
1236 const Constant *Initializer = GVar->getInitializer();
1237 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1238 AggBuffer aggBuffer(ElementSize, O, *this);
1239 bufferAggregateConstant(Initializer, &aggBuffer);
1240 if (aggBuffer.numSymbols) {
1241 if (nvptxSubtarget.is64Bit()) {
1242 O << " .u64 " << getSymbolName(GVar) << "[";
1243 O << ElementSize / 8;
1245 O << " .u32 " << getSymbolName(GVar) << "[";
1246 O << ElementSize / 4;
1250 O << " .b8 " << getSymbolName(GVar) << "[";
1258 O << " .b8 " << getSymbolName(GVar);
1266 O << " .b8 " << getSymbolName(GVar);
1275 assert(0 && "type not supported yet");
1282 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1283 if (localDecls.find(f) == localDecls.end())
1286 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1288 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1289 O << "\t// demoted variable\n\t";
1290 printModuleLevelGV(gvars[i], O, true);
1294 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1295 raw_ostream &O) const {
1296 switch (AddressSpace) {
1297 case llvm::ADDRESS_SPACE_LOCAL:
1300 case llvm::ADDRESS_SPACE_GLOBAL:
1303 case llvm::ADDRESS_SPACE_CONST:
1306 case llvm::ADDRESS_SPACE_SHARED:
1310 report_fatal_error("Bad address space found while emitting PTX");
1316 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1317 switch (Ty->getTypeID()) {
1319 llvm_unreachable("unexpected type");
1321 case Type::IntegerTyID: {
1322 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1325 else if (NumBits <= 64) {
1326 std::string name = "u";
1327 return name + utostr(NumBits);
1329 llvm_unreachable("Integer too large");
1334 case Type::FloatTyID:
1336 case Type::DoubleTyID:
1338 case Type::PointerTyID:
1339 if (nvptxSubtarget.is64Bit())
1349 llvm_unreachable("unexpected type");
1353 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1356 const DataLayout *TD = TM.getDataLayout();
1358 // GlobalVariables are always constant pointers themselves.
1359 const PointerType *PTy = GVar->getType();
1360 Type *ETy = PTy->getElementType();
1363 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1364 if (GVar->getAlignment() == 0)
1365 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1367 O << " .align " << GVar->getAlignment();
1369 if (ETy->isSingleValueType()) {
1371 O << getPTXFundamentalTypeStr(ETy);
1373 O << getSymbolName(GVar);
1377 int64_t ElementSize = 0;
1379 // Although PTX has direct support for struct type and array type and LLVM IR
1380 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1381 // support these high level field accesses. Structs and arrays are lowered
1382 // into arrays of bytes.
1383 switch (ETy->getTypeID()) {
1384 case Type::StructTyID:
1385 case Type::ArrayTyID:
1386 case Type::VectorTyID:
1387 ElementSize = TD->getTypeStoreSize(ETy);
1388 O << " .b8 " << getSymbolName(GVar) << "[";
1390 O << itostr(ElementSize);
1395 assert(0 && "type not supported yet");
1400 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1401 if (Ty->isSingleValueType())
1402 return TD->getPrefTypeAlignment(Ty);
1404 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1406 return getOpenCLAlignment(TD, ATy->getElementType());
1408 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1410 Type *ETy = VTy->getElementType();
1411 unsigned int numE = VTy->getNumElements();
1412 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1416 return numE * alignE;
1419 const StructType *STy = dyn_cast<StructType>(Ty);
1421 unsigned int alignStruct = 1;
1422 // Go through each element of the struct and find the
1423 // largest alignment.
1424 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1425 Type *ETy = STy->getElementType(i);
1426 unsigned int align = getOpenCLAlignment(TD, ETy);
1427 if (align > alignStruct)
1428 alignStruct = align;
1433 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1435 return TD->getPointerPrefAlignment();
1436 return TD->getPrefTypeAlignment(Ty);
1439 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1440 int paramIndex, raw_ostream &O) {
1441 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1442 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1443 O << getSymbolName(I->getParent()) << "_param_" << paramIndex;
1445 std::string argName = I->getName();
1446 const char *p = argName.c_str();
1457 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1458 Function::const_arg_iterator I, E;
1461 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1462 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1463 O << *CurrentFnSym << "_param_" << paramIndex;
1467 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1468 if (i == paramIndex) {
1469 printParamName(I, paramIndex, O);
1473 llvm_unreachable("paramIndex out of bound");
1476 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1477 const DataLayout *TD = TM.getDataLayout();
1478 const AttributeSet &PAL = F->getAttributes();
1479 const TargetLowering *TLI = TM.getTargetLowering();
1480 Function::const_arg_iterator I, E;
1481 unsigned paramIndex = 0;
1483 bool isKernelFunc = llvm::isKernelFunction(*F);
1484 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1485 MVT thePointerTy = TLI->getPointerTy();
1489 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1490 Type *Ty = I->getType();
1497 // Handle image/sampler parameters
1498 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1499 if (llvm::isImage(*I)) {
1500 std::string sname = I->getName();
1501 if (llvm::isImageWriteOnly(*I))
1502 O << "\t.param .surfref " << getSymbolName(F) << "_param_"
1504 else // Default image is read_only
1505 O << "\t.param .texref " << getSymbolName(F) << "_param_"
1507 } else // Should be llvm::isSampler(*I)
1508 O << "\t.param .samplerref " << getSymbolName(F) << "_param_"
1513 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1514 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1515 // Just print .param .align <a> .b8 .param[size];
1516 // <a> = PAL.getparamalignment
1517 // size = typeallocsize of element type
1518 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1520 align = TD->getABITypeAlignment(Ty);
1522 unsigned sz = TD->getTypeAllocSize(Ty);
1523 O << "\t.param .align " << align << " .b8 ";
1524 printParamName(I, paramIndex, O);
1525 O << "[" << sz << "]";
1530 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1533 // Special handling for pointer arguments to kernel
1534 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1536 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1537 Type *ETy = PTy->getElementType();
1538 int addrSpace = PTy->getAddressSpace();
1539 switch (addrSpace) {
1543 case llvm::ADDRESS_SPACE_CONST:
1544 O << ".ptr .const ";
1546 case llvm::ADDRESS_SPACE_SHARED:
1547 O << ".ptr .shared ";
1549 case llvm::ADDRESS_SPACE_GLOBAL:
1550 O << ".ptr .global ";
1553 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1555 printParamName(I, paramIndex, O);
1559 // non-pointer scalar to kernel func
1561 // Special case: predicate operands become .u8 types
1562 if (Ty->isIntegerTy(1))
1565 O << getPTXFundamentalTypeStr(Ty);
1567 printParamName(I, paramIndex, O);
1570 // Non-kernel function, just print .param .b<size> for ABI
1571 // and .reg .b<size> for non-ABI
1573 if (isa<IntegerType>(Ty)) {
1574 sz = cast<IntegerType>(Ty)->getBitWidth();
1577 } else if (isa<PointerType>(Ty))
1578 sz = thePointerTy.getSizeInBits();
1580 sz = Ty->getPrimitiveSizeInBits();
1582 O << "\t.param .b" << sz << " ";
1584 O << "\t.reg .b" << sz << " ";
1585 printParamName(I, paramIndex, O);
1589 // param has byVal attribute. So should be a pointer
1590 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1591 assert(PTy && "Param with byval attribute should be a pointer type");
1592 Type *ETy = PTy->getElementType();
1594 if (isABI || isKernelFunc) {
1595 // Just print .param .align <a> .b8 .param[size];
1596 // <a> = PAL.getparamalignment
1597 // size = typeallocsize of element type
1598 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1600 align = TD->getABITypeAlignment(ETy);
1602 unsigned sz = TD->getTypeAllocSize(ETy);
1603 O << "\t.param .align " << align << " .b8 ";
1604 printParamName(I, paramIndex, O);
1605 O << "[" << sz << "]";
1608 // Split the ETy into constituent parts and
1609 // print .param .b<size> <name> for each part.
1610 // Further, if a part is vector, print the above for
1611 // each vector element.
1612 SmallVector<EVT, 16> vtparts;
1613 ComputeValueVTs(*TLI, ETy, vtparts);
1614 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1616 EVT elemtype = vtparts[i];
1617 if (vtparts[i].isVector()) {
1618 elems = vtparts[i].getVectorNumElements();
1619 elemtype = vtparts[i].getVectorElementType();
1622 for (unsigned j = 0, je = elems; j != je; ++j) {
1623 unsigned sz = elemtype.getSizeInBits();
1624 if (elemtype.isInteger() && (sz < 32))
1626 O << "\t.reg .b" << sz << " ";
1627 printParamName(I, paramIndex, O);
1643 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1645 const Function *F = MF.getFunction();
1646 emitFunctionParamList(F, O);
1649 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1650 const MachineFunction &MF) {
1651 SmallString<128> Str;
1652 raw_svector_ostream O(Str);
1654 // Map the global virtual register number to a register class specific
1655 // virtual register number starting from 1 with that class.
1656 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1657 //unsigned numRegClasses = TRI->getNumRegClasses();
1659 // Emit the Fake Stack Object
1660 const MachineFrameInfo *MFI = MF.getFrameInfo();
1661 int NumBytes = (int) MFI->getStackSize();
1663 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1664 << getFunctionNumber() << "[" << NumBytes << "];\n";
1665 if (nvptxSubtarget.is64Bit()) {
1666 O << "\t.reg .b64 \t%SP;\n";
1667 O << "\t.reg .b64 \t%SPL;\n";
1669 O << "\t.reg .b32 \t%SP;\n";
1670 O << "\t.reg .b32 \t%SPL;\n";
1674 // Go through all virtual registers to establish the mapping between the
1676 // register number and the per class virtual register number.
1677 // We use the per class virtual register number in the ptx output.
1678 unsigned int numVRs = MRI->getNumVirtRegs();
1679 for (unsigned i = 0; i < numVRs; i++) {
1680 unsigned int vr = TRI->index2VirtReg(i);
1681 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1682 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1683 int n = regmap.size();
1684 regmap.insert(std::make_pair(vr, n + 1));
1687 // Emit register declarations
1688 // @TODO: Extract out the real register usage
1689 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1690 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1691 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1692 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1693 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1694 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1695 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1697 // Emit declaration of the virtual registers or 'physical' registers for
1698 // each register class
1699 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1700 const TargetRegisterClass *RC = TRI->getRegClass(i);
1701 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1702 std::string rcname = getNVPTXRegClassName(RC);
1703 std::string rcStr = getNVPTXRegClassStr(RC);
1704 int n = regmap.size();
1706 // Only declare those registers that may be used.
1708 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1713 OutStreamer.EmitRawText(O.str());
1716 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1717 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1719 unsigned int numHex;
1722 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1725 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1726 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1729 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1731 llvm_unreachable("unsupported fp type");
1733 APInt API = APF.bitcastToAPInt();
1734 std::string hexstr(utohexstr(API.getZExtValue()));
1736 if (hexstr.length() < numHex)
1737 O << std::string(numHex - hexstr.length(), '0');
1738 O << utohexstr(API.getZExtValue());
1741 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1742 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1743 O << CI->getValue();
1746 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1747 printFPConstant(CFP, O);
1750 if (isa<ConstantPointerNull>(CPV)) {
1754 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1755 O << getSymbolName(GVar);
1758 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1759 const Value *v = Cexpr->stripPointerCasts();
1760 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1761 O << getSymbolName(GVar);
1764 O << *LowerConstant(CPV, *this);
1768 llvm_unreachable("Not scalar type found in printScalarConstant()");
1771 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1772 AggBuffer *aggBuffer) {
1774 const DataLayout *TD = TM.getDataLayout();
1776 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1777 int s = TD->getTypeAllocSize(CPV->getType());
1780 aggBuffer->addZeros(s);
1785 switch (CPV->getType()->getTypeID()) {
1787 case Type::IntegerTyID: {
1788 const Type *ETy = CPV->getType();
1789 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1791 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1793 aggBuffer->addBytes(ptr, 1, Bytes);
1794 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1795 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1796 ptr = (unsigned char *)&int16;
1797 aggBuffer->addBytes(ptr, 2, Bytes);
1798 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1799 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1800 int int32 = (int)(constInt->getZExtValue());
1801 ptr = (unsigned char *)&int32;
1802 aggBuffer->addBytes(ptr, 4, Bytes);
1804 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1805 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1806 ConstantFoldConstantExpression(Cexpr, TD))) {
1807 int int32 = (int)(constInt->getZExtValue());
1808 ptr = (unsigned char *)&int32;
1809 aggBuffer->addBytes(ptr, 4, Bytes);
1812 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1813 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1814 aggBuffer->addSymbol(v);
1815 aggBuffer->addZeros(4);
1819 llvm_unreachable("unsupported integer const type");
1820 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1821 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1822 long long int64 = (long long)(constInt->getZExtValue());
1823 ptr = (unsigned char *)&int64;
1824 aggBuffer->addBytes(ptr, 8, Bytes);
1826 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1827 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1828 ConstantFoldConstantExpression(Cexpr, TD))) {
1829 long long int64 = (long long)(constInt->getZExtValue());
1830 ptr = (unsigned char *)&int64;
1831 aggBuffer->addBytes(ptr, 8, Bytes);
1834 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1835 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1836 aggBuffer->addSymbol(v);
1837 aggBuffer->addZeros(8);
1841 llvm_unreachable("unsupported integer const type");
1843 llvm_unreachable("unsupported integer const type");
1846 case Type::FloatTyID:
1847 case Type::DoubleTyID: {
1848 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1849 const Type *Ty = CFP->getType();
1850 if (Ty == Type::getFloatTy(CPV->getContext())) {
1851 float float32 = (float) CFP->getValueAPF().convertToFloat();
1852 ptr = (unsigned char *)&float32;
1853 aggBuffer->addBytes(ptr, 4, Bytes);
1854 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1855 double float64 = CFP->getValueAPF().convertToDouble();
1856 ptr = (unsigned char *)&float64;
1857 aggBuffer->addBytes(ptr, 8, Bytes);
1859 llvm_unreachable("unsupported fp const type");
1863 case Type::PointerTyID: {
1864 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1865 aggBuffer->addSymbol(GVar);
1866 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1867 const Value *v = Cexpr->stripPointerCasts();
1868 aggBuffer->addSymbol(v);
1870 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1871 aggBuffer->addZeros(s);
1875 case Type::ArrayTyID:
1876 case Type::VectorTyID:
1877 case Type::StructTyID: {
1878 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1879 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1880 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1881 bufferAggregateConstant(CPV, aggBuffer);
1882 if (Bytes > ElementSize)
1883 aggBuffer->addZeros(Bytes - ElementSize);
1884 } else if (isa<ConstantAggregateZero>(CPV))
1885 aggBuffer->addZeros(Bytes);
1887 llvm_unreachable("Unexpected Constant type");
1892 llvm_unreachable("unsupported type");
1896 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1897 AggBuffer *aggBuffer) {
1898 const DataLayout *TD = TM.getDataLayout();
1902 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1903 if (CPV->getNumOperands())
1904 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1905 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1909 if (const ConstantDataSequential *CDS =
1910 dyn_cast<ConstantDataSequential>(CPV)) {
1911 if (CDS->getNumElements())
1912 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1913 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1918 if (isa<ConstantStruct>(CPV)) {
1919 if (CPV->getNumOperands()) {
1920 StructType *ST = cast<StructType>(CPV->getType());
1921 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1923 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1924 TD->getTypeAllocSize(ST) -
1925 TD->getStructLayout(ST)->getElementOffset(i);
1927 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1928 TD->getStructLayout(ST)->getElementOffset(i);
1929 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1934 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1937 // buildTypeNameMap - Run through symbol table looking for type names.
1940 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1942 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1944 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1945 !PI->second.compare("struct._image2d_t") ||
1946 !PI->second.compare("struct._image3d_t")))
1953 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1954 switch (MI.getOpcode()) {
1957 case NVPTX::CallArgBeginInst:
1958 case NVPTX::CallArgEndInst0:
1959 case NVPTX::CallArgEndInst1:
1960 case NVPTX::CallArgF32:
1961 case NVPTX::CallArgF64:
1962 case NVPTX::CallArgI16:
1963 case NVPTX::CallArgI32:
1964 case NVPTX::CallArgI32imm:
1965 case NVPTX::CallArgI64:
1966 case NVPTX::CallArgParam:
1967 case NVPTX::CallVoidInst:
1968 case NVPTX::CallVoidInstReg:
1969 case NVPTX::Callseq_End:
1970 case NVPTX::CallVoidInstReg64:
1971 case NVPTX::DeclareParamInst:
1972 case NVPTX::DeclareRetMemInst:
1973 case NVPTX::DeclareRetRegInst:
1974 case NVPTX::DeclareRetScalarInst:
1975 case NVPTX::DeclareScalarParamInst:
1976 case NVPTX::DeclareScalarRegInst:
1977 case NVPTX::StoreParamF32:
1978 case NVPTX::StoreParamF64:
1979 case NVPTX::StoreParamI16:
1980 case NVPTX::StoreParamI32:
1981 case NVPTX::StoreParamI64:
1982 case NVPTX::StoreParamI8:
1983 case NVPTX::StoreRetvalF32:
1984 case NVPTX::StoreRetvalF64:
1985 case NVPTX::StoreRetvalI16:
1986 case NVPTX::StoreRetvalI32:
1987 case NVPTX::StoreRetvalI64:
1988 case NVPTX::StoreRetvalI8:
1989 case NVPTX::LastCallArgF32:
1990 case NVPTX::LastCallArgF64:
1991 case NVPTX::LastCallArgI16:
1992 case NVPTX::LastCallArgI32:
1993 case NVPTX::LastCallArgI32imm:
1994 case NVPTX::LastCallArgI64:
1995 case NVPTX::LastCallArgParam:
1996 case NVPTX::LoadParamMemF32:
1997 case NVPTX::LoadParamMemF64:
1998 case NVPTX::LoadParamMemI16:
1999 case NVPTX::LoadParamMemI32:
2000 case NVPTX::LoadParamMemI64:
2001 case NVPTX::LoadParamMemI8:
2002 case NVPTX::PrototypeInst:
2003 case NVPTX::DBG_VALUE:
2009 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2011 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2012 unsigned AsmVariant,
2013 const char *ExtraCode, raw_ostream &O) {
2014 if (ExtraCode && ExtraCode[0]) {
2015 if (ExtraCode[1] != 0)
2016 return true; // Unknown modifier.
2018 switch (ExtraCode[0]) {
2020 // See if this is a generic print operand
2021 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2027 printOperand(MI, OpNo, O);
2032 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2033 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2034 const char *ExtraCode, raw_ostream &O) {
2035 if (ExtraCode && ExtraCode[0])
2036 return true; // Unknown modifier
2039 printMemOperand(MI, OpNo, O);
2045 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2046 raw_ostream &O, const char *Modifier) {
2047 const MachineOperand &MO = MI->getOperand(opNum);
2048 switch (MO.getType()) {
2049 case MachineOperand::MO_Register:
2050 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2051 if (MO.getReg() == NVPTX::VRDepot)
2052 O << DEPOTNAME << getFunctionNumber();
2054 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2056 emitVirtualRegister(MO.getReg(), O);
2060 case MachineOperand::MO_Immediate:
2063 else if (strstr(Modifier, "vec") == Modifier)
2064 printVecModifiedImmediate(MO, Modifier, O);
2067 "Don't know how to handle modifier on immediate operand");
2070 case MachineOperand::MO_FPImmediate:
2071 printFPConstant(MO.getFPImm(), O);
2074 case MachineOperand::MO_GlobalAddress:
2075 O << getSymbolName(MO.getGlobal());
2078 case MachineOperand::MO_MachineBasicBlock:
2079 O << *MO.getMBB()->getSymbol();
2083 llvm_unreachable("Operand type not supported.");
2087 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2088 raw_ostream &O, const char *Modifier) {
2089 printOperand(MI, opNum, O);
2091 if (Modifier && !strcmp(Modifier, "add")) {
2093 printOperand(MI, opNum + 1, O);
2095 if (MI->getOperand(opNum + 1).isImm() &&
2096 MI->getOperand(opNum + 1).getImm() == 0)
2097 return; // don't print ',0' or '+0'
2099 printOperand(MI, opNum + 1, O);
2104 // Force static initialization.
2105 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2106 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2107 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2110 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2111 std::stringstream temp;
2112 LineReader *reader = this->getReader(filename.str());
2114 temp << filename.str();
2118 temp << reader->readLine(line);
2120 this->OutStreamer.EmitRawText(Twine(temp.str()));
2123 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2124 if (reader == NULL) {
2125 reader = new LineReader(filename);
2128 if (reader->fileName() != filename) {
2130 reader = new LineReader(filename);
2136 std::string NVPTXAsmPrinter::getSymbolName(const GlobalValue *GV) const {
2137 // Obtain the original symbol name.
2138 MCSymbol *Sym = getSymbol(GV);
2139 std::string OriginalName;
2140 raw_string_ostream OriginalNameStream(OriginalName);
2141 Sym->print(OriginalNameStream);
2142 OriginalNameStream.flush();
2144 // MCSymbol already does symbol-name sanitizing, so names it produces are
2145 // valid for object files. The only two characters valida in that context
2146 // and indigestible by the PTX assembler are '.' and '@'.
2147 std::string CleanName;
2148 raw_string_ostream CleanNameStream(CleanName);
2149 for (unsigned I = 0, E = OriginalName.size(); I != E; ++I) {
2150 char C = OriginalName[I];
2152 CleanNameStream << "_$_";
2153 } else if (C == '@') {
2154 CleanNameStream << "_%_";
2156 CleanNameStream << C;
2160 return CleanNameStream.str();
2163 std::string LineReader::readLine(unsigned lineNum) {
2164 if (lineNum < theCurLine) {
2166 fstr.seekg(0, std::ios::beg);
2168 while (theCurLine < lineNum) {
2169 fstr.getline(buff, 500);
2175 // Force static initialization.
2176 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2177 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2178 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);