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/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 OutStreamer.EmitInstruction(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 << *getSymbol(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 (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
704 const Constant *C = dyn_cast<Constant>(*ui);
705 if (usedInGlobalVarDef(C))
711 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
712 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
713 if (othergv->getName().str() == "llvm.used")
717 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
718 if (instr->getParent() && instr->getParent()->getParent()) {
719 const Function *curFunc = instr->getParent()->getParent();
720 if (oneFunc && (curFunc != oneFunc))
728 if (const MDNode *md = dyn_cast<MDNode>(U))
729 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
730 (md->getName().str() == "llvm.dbg.sp")))
733 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
735 if (usedInOneFunc(*ui, oneFunc) == false)
741 /* Find out if a global variable can be demoted to local scope.
742 * Currently, this is valid for CUDA shared variables, which have local
743 * scope and global lifetime. So the conditions to check are :
744 * 1. Is the global variable in shared address space?
745 * 2. Does it have internal linkage?
746 * 3. Is the global variable referenced only in one function?
748 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
749 if (gv->hasInternalLinkage() == false)
751 const PointerType *Pty = gv->getType();
752 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
755 const Function *oneFunc = 0;
757 bool flag = usedInOneFunc(gv, oneFunc);
766 static bool useFuncSeen(const Constant *C,
767 llvm::DenseMap<const Function *, bool> &seenMap) {
768 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
770 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
771 if (useFuncSeen(cu, seenMap))
773 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
774 const BasicBlock *bb = I->getParent();
777 const Function *caller = bb->getParent();
780 if (seenMap.find(caller) != seenMap.end())
787 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
788 llvm::DenseMap<const Function *, bool> seenMap;
789 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
790 const Function *F = FI;
792 if (F->isDeclaration()) {
795 if (F->getIntrinsicID())
797 emitDeclaration(F, O);
800 for (Value::const_use_iterator iter = F->use_begin(),
801 iterEnd = F->use_end();
802 iter != iterEnd; ++iter) {
803 if (const Constant *C = dyn_cast<Constant>(*iter)) {
804 if (usedInGlobalVarDef(C)) {
805 // The use is in the initialization of a global variable
806 // that is a function pointer, so print a declaration
807 // for the original function
808 emitDeclaration(F, O);
811 // Emit a declaration of this function if the function that
812 // uses this constant expr has already been seen.
813 if (useFuncSeen(C, seenMap)) {
814 emitDeclaration(F, O);
819 if (!isa<Instruction>(*iter))
821 const Instruction *instr = cast<Instruction>(*iter);
822 const BasicBlock *bb = instr->getParent();
825 const Function *caller = bb->getParent();
829 // If a caller has already been seen, then the caller is
830 // appearing in the module before the callee. so print out
831 // a declaration for the callee.
832 if (seenMap.find(caller) != seenMap.end()) {
833 emitDeclaration(F, O);
841 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
842 DebugInfoFinder DbgFinder;
843 DbgFinder.processModule(M);
846 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
847 E = DbgFinder.compile_unit_end();
849 DICompileUnit DIUnit(*I);
850 StringRef Filename(DIUnit.getFilename());
851 StringRef Dirname(DIUnit.getDirectory());
852 SmallString<128> FullPathName = Dirname;
853 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
854 sys::path::append(FullPathName, Filename);
855 Filename = FullPathName.str();
857 if (filenameMap.find(Filename.str()) != filenameMap.end())
859 filenameMap[Filename.str()] = i;
860 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
864 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
865 E = DbgFinder.subprogram_end();
868 StringRef Filename(SP.getFilename());
869 StringRef Dirname(SP.getDirectory());
870 SmallString<128> FullPathName = Dirname;
871 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
872 sys::path::append(FullPathName, Filename);
873 Filename = FullPathName.str();
875 if (filenameMap.find(Filename.str()) != filenameMap.end())
877 filenameMap[Filename.str()] = i;
882 bool NVPTXAsmPrinter::doInitialization(Module &M) {
884 SmallString<128> Str1;
885 raw_svector_ostream OS1(Str1);
887 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
888 MMI->AnalyzeModule(M);
890 // We need to call the parent's one explicitly.
891 //bool Result = AsmPrinter::doInitialization(M);
893 // Initialize TargetLoweringObjectFile.
894 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
895 .Initialize(OutContext, TM);
897 Mang = new Mangler(TM.getDataLayout());
899 // Emit header before any dwarf directives are emitted below.
901 OutStreamer.EmitRawText(OS1.str());
903 // Already commented out
904 //bool Result = AsmPrinter::doInitialization(M);
906 // Emit module-level inline asm if it exists.
907 if (!M.getModuleInlineAsm().empty()) {
908 OutStreamer.AddComment("Start of file scope inline assembly");
909 OutStreamer.AddBlankLine();
910 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
911 OutStreamer.AddBlankLine();
912 OutStreamer.AddComment("End of file scope inline assembly");
913 OutStreamer.AddBlankLine();
916 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
917 recordAndEmitFilenames(M);
919 GlobalsEmitted = false;
921 return false; // success
924 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
925 SmallString<128> Str2;
926 raw_svector_ostream OS2(Str2);
928 emitDeclarations(M, OS2);
930 // As ptxas does not support forward references of globals, we need to first
931 // sort the list of module-level globals in def-use order. We visit each
932 // global variable in order, and ensure that we emit it *after* its dependent
933 // globals. We use a little extra memory maintaining both a set and a list to
934 // have fast searches while maintaining a strict ordering.
935 SmallVector<const GlobalVariable *, 8> Globals;
936 DenseSet<const GlobalVariable *> GVVisited;
937 DenseSet<const GlobalVariable *> GVVisiting;
939 // Visit each global variable, in order
940 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
942 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
944 assert(GVVisited.size() == M.getGlobalList().size() &&
945 "Missed a global variable");
946 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
948 // Print out module-level global variables in proper order
949 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
950 printModuleLevelGV(Globals[i], OS2);
954 OutStreamer.EmitRawText(OS2.str());
957 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
959 O << "// Generated by LLVM NVPTX Back-End\n";
963 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
964 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
967 O << nvptxSubtarget.getTargetName();
969 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
970 O << ", texmode_independent";
971 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
972 if (!nvptxSubtarget.hasDouble())
973 O << ", map_f64_to_f32";
976 if (MAI->doesSupportDebugInformation())
981 O << ".address_size ";
982 if (nvptxSubtarget.is64Bit())
991 bool NVPTXAsmPrinter::doFinalization(Module &M) {
993 // If we did not emit any functions, then the global declarations have not
995 if (!GlobalsEmitted) {
997 GlobalsEmitted = true;
1000 // XXX Temproarily remove global variables so that doFinalization() will not
1001 // emit them again (global variables are emitted at beginning).
1003 Module::GlobalListType &global_list = M.getGlobalList();
1004 int i, n = global_list.size();
1005 GlobalVariable **gv_array = new GlobalVariable *[n];
1007 // first, back-up GlobalVariable in gv_array
1009 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1011 gv_array[i++] = &*I;
1013 // second, empty global_list
1014 while (!global_list.empty())
1015 global_list.remove(global_list.begin());
1017 // call doFinalization
1018 bool ret = AsmPrinter::doFinalization(M);
1020 // now we restore global variables
1021 for (i = 0; i < n; i++)
1022 global_list.insert(global_list.end(), gv_array[i]);
1027 //bool Result = AsmPrinter::doFinalization(M);
1028 // Instead of calling the parents doFinalization, we may
1029 // clone parents doFinalization and customize here.
1030 // Currently, we if NVISA out the EmitGlobals() in
1031 // parent's doFinalization, which is too intrusive.
1033 // Same for the doInitialization.
1037 // This function emits appropriate linkage directives for
1038 // functions and global variables.
1040 // extern function declaration -> .extern
1041 // extern function definition -> .visible
1042 // external global variable with init -> .visible
1043 // external without init -> .extern
1044 // appending -> not allowed, assert.
1046 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1048 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1049 if (V->hasExternalLinkage()) {
1050 if (isa<GlobalVariable>(V)) {
1051 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1053 if (GVar->hasInitializer())
1058 } else if (V->isDeclaration())
1062 } else if (V->hasAppendingLinkage()) {
1064 msg.append("Error: ");
1065 msg.append("Symbol ");
1067 msg.append(V->getName().str());
1068 msg.append("has unsupported appending linkage type");
1069 llvm_unreachable(msg.c_str());
1074 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1076 bool processDemoted) {
1079 if (GVar->hasSection()) {
1080 if (GVar->getSection() == "llvm.metadata")
1084 const DataLayout *TD = TM.getDataLayout();
1086 // GlobalVariables are always constant pointers themselves.
1087 const PointerType *PTy = GVar->getType();
1088 Type *ETy = PTy->getElementType();
1090 if (GVar->hasExternalLinkage()) {
1091 if (GVar->hasInitializer())
1097 if (llvm::isTexture(*GVar)) {
1098 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1102 if (llvm::isSurface(*GVar)) {
1103 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1107 if (GVar->isDeclaration()) {
1108 // (extern) declarations, no definition or initializer
1109 // Currently the only known declaration is for an automatic __local
1110 // (.shared) promoted to global.
1111 emitPTXGlobalVariable(GVar, O);
1116 if (llvm::isSampler(*GVar)) {
1117 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1119 const Constant *Initializer = NULL;
1120 if (GVar->hasInitializer())
1121 Initializer = GVar->getInitializer();
1122 const ConstantInt *CI = NULL;
1124 CI = dyn_cast<ConstantInt>(Initializer);
1126 unsigned sample = CI->getZExtValue();
1131 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1133 O << "addr_mode_" << i << " = ";
1139 O << "clamp_to_border";
1142 O << "clamp_to_edge";
1153 O << "filter_mode = ";
1154 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1162 assert(0 && "Anisotropic filtering is not supported");
1167 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1168 O << ", force_unnormalized_coords = 1";
1177 if (GVar->hasPrivateLinkage()) {
1179 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1182 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1183 if (!strncmp(GVar->getName().data(), "filename", 8))
1185 if (GVar->use_empty())
1189 const Function *demotedFunc = 0;
1190 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1191 O << "// " << GVar->getName().str() << " has been demoted\n";
1192 if (localDecls.find(demotedFunc) != localDecls.end())
1193 localDecls[demotedFunc].push_back(GVar);
1195 std::vector<const GlobalVariable *> temp;
1196 temp.push_back(GVar);
1197 localDecls[demotedFunc] = temp;
1203 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1204 if (GVar->getAlignment() == 0)
1205 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1207 O << " .align " << GVar->getAlignment();
1209 if (ETy->isSingleValueType()) {
1211 // Special case: ABI requires that we use .u8 for predicates
1212 if (ETy->isIntegerTy(1))
1215 O << getPTXFundamentalTypeStr(ETy, false);
1217 O << *getSymbol(GVar);
1219 // Ptx allows variable initilization only for constant and global state
1221 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1222 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1223 GVar->hasInitializer()) {
1224 const Constant *Initializer = GVar->getInitializer();
1225 if (!Initializer->isNullValue()) {
1227 printScalarConstant(Initializer, O);
1231 unsigned int ElementSize = 0;
1233 // Although PTX has direct support for struct type and array type and
1234 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1235 // targets that support these high level field accesses. Structs, arrays
1236 // and vectors are lowered into arrays of bytes.
1237 switch (ETy->getTypeID()) {
1238 case Type::StructTyID:
1239 case Type::ArrayTyID:
1240 case Type::VectorTyID:
1241 ElementSize = TD->getTypeStoreSize(ETy);
1242 // Ptx allows variable initilization only for constant and
1243 // global state spaces.
1244 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1245 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1246 GVar->hasInitializer()) {
1247 const Constant *Initializer = GVar->getInitializer();
1248 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1249 AggBuffer aggBuffer(ElementSize, O, *this);
1250 bufferAggregateConstant(Initializer, &aggBuffer);
1251 if (aggBuffer.numSymbols) {
1252 if (nvptxSubtarget.is64Bit()) {
1253 O << " .u64 " << *getSymbol(GVar) << "[";
1254 O << ElementSize / 8;
1256 O << " .u32 " << *getSymbol(GVar) << "[";
1257 O << ElementSize / 4;
1261 O << " .b8 " << *getSymbol(GVar) << "[";
1269 O << " .b8 " << *getSymbol(GVar);
1277 O << " .b8 " << *getSymbol(GVar);
1286 assert(0 && "type not supported yet");
1293 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1294 if (localDecls.find(f) == localDecls.end())
1297 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1299 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1300 O << "\t// demoted variable\n\t";
1301 printModuleLevelGV(gvars[i], O, true);
1305 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1306 raw_ostream &O) const {
1307 switch (AddressSpace) {
1308 case llvm::ADDRESS_SPACE_LOCAL:
1311 case llvm::ADDRESS_SPACE_GLOBAL:
1314 case llvm::ADDRESS_SPACE_CONST:
1317 case llvm::ADDRESS_SPACE_SHARED:
1321 report_fatal_error("Bad address space found while emitting PTX");
1327 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1328 switch (Ty->getTypeID()) {
1330 llvm_unreachable("unexpected type");
1332 case Type::IntegerTyID: {
1333 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1336 else if (NumBits <= 64) {
1337 std::string name = "u";
1338 return name + utostr(NumBits);
1340 llvm_unreachable("Integer too large");
1345 case Type::FloatTyID:
1347 case Type::DoubleTyID:
1349 case Type::PointerTyID:
1350 if (nvptxSubtarget.is64Bit())
1360 llvm_unreachable("unexpected type");
1364 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1367 const DataLayout *TD = TM.getDataLayout();
1369 // GlobalVariables are always constant pointers themselves.
1370 const PointerType *PTy = GVar->getType();
1371 Type *ETy = PTy->getElementType();
1374 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1375 if (GVar->getAlignment() == 0)
1376 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1378 O << " .align " << GVar->getAlignment();
1380 if (ETy->isSingleValueType()) {
1382 O << getPTXFundamentalTypeStr(ETy);
1384 O << *getSymbol(GVar);
1388 int64_t ElementSize = 0;
1390 // Although PTX has direct support for struct type and array type and LLVM IR
1391 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1392 // support these high level field accesses. Structs and arrays are lowered
1393 // into arrays of bytes.
1394 switch (ETy->getTypeID()) {
1395 case Type::StructTyID:
1396 case Type::ArrayTyID:
1397 case Type::VectorTyID:
1398 ElementSize = TD->getTypeStoreSize(ETy);
1399 O << " .b8 " << *getSymbol(GVar) << "[";
1401 O << itostr(ElementSize);
1406 assert(0 && "type not supported yet");
1411 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1412 if (Ty->isSingleValueType())
1413 return TD->getPrefTypeAlignment(Ty);
1415 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1417 return getOpenCLAlignment(TD, ATy->getElementType());
1419 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1421 Type *ETy = VTy->getElementType();
1422 unsigned int numE = VTy->getNumElements();
1423 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1427 return numE * alignE;
1430 const StructType *STy = dyn_cast<StructType>(Ty);
1432 unsigned int alignStruct = 1;
1433 // Go through each element of the struct and find the
1434 // largest alignment.
1435 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1436 Type *ETy = STy->getElementType(i);
1437 unsigned int align = getOpenCLAlignment(TD, ETy);
1438 if (align > alignStruct)
1439 alignStruct = align;
1444 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1446 return TD->getPointerPrefAlignment();
1447 return TD->getPrefTypeAlignment(Ty);
1450 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1451 int paramIndex, raw_ostream &O) {
1452 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1453 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1454 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1456 std::string argName = I->getName();
1457 const char *p = argName.c_str();
1468 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1469 Function::const_arg_iterator I, E;
1472 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1473 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1474 O << *CurrentFnSym << "_param_" << paramIndex;
1478 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1479 if (i == paramIndex) {
1480 printParamName(I, paramIndex, O);
1484 llvm_unreachable("paramIndex out of bound");
1487 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1488 const DataLayout *TD = TM.getDataLayout();
1489 const AttributeSet &PAL = F->getAttributes();
1490 const TargetLowering *TLI = TM.getTargetLowering();
1491 Function::const_arg_iterator I, E;
1492 unsigned paramIndex = 0;
1494 bool isKernelFunc = llvm::isKernelFunction(*F);
1495 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1496 MVT thePointerTy = TLI->getPointerTy();
1500 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1501 Type *Ty = I->getType();
1508 // Handle image/sampler parameters
1509 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1510 if (llvm::isImage(*I)) {
1511 std::string sname = I->getName();
1512 if (llvm::isImageWriteOnly(*I))
1513 O << "\t.param .surfref " << *getSymbol(F) << "_param_"
1515 else // Default image is read_only
1516 O << "\t.param .texref " << *getSymbol(F) << "_param_"
1518 } else // Should be llvm::isSampler(*I)
1519 O << "\t.param .samplerref " << *getSymbol(F) << "_param_"
1524 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1525 if (Ty->isVectorTy()) {
1526 // Just print .param .b8 .align <a> .param[size];
1527 // <a> = PAL.getparamalignment
1528 // size = typeallocsize of element type
1529 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1531 align = TD->getABITypeAlignment(Ty);
1533 unsigned sz = TD->getTypeAllocSize(Ty);
1534 O << "\t.param .align " << align << " .b8 ";
1535 printParamName(I, paramIndex, O);
1536 O << "[" << sz << "]";
1541 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1544 // Special handling for pointer arguments to kernel
1545 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1547 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1548 Type *ETy = PTy->getElementType();
1549 int addrSpace = PTy->getAddressSpace();
1550 switch (addrSpace) {
1554 case llvm::ADDRESS_SPACE_CONST:
1555 O << ".ptr .const ";
1557 case llvm::ADDRESS_SPACE_SHARED:
1558 O << ".ptr .shared ";
1560 case llvm::ADDRESS_SPACE_GLOBAL:
1561 O << ".ptr .global ";
1564 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1566 printParamName(I, paramIndex, O);
1570 // non-pointer scalar to kernel func
1572 // Special case: predicate operands become .u8 types
1573 if (Ty->isIntegerTy(1))
1576 O << getPTXFundamentalTypeStr(Ty);
1578 printParamName(I, paramIndex, O);
1581 // Non-kernel function, just print .param .b<size> for ABI
1582 // and .reg .b<size> for non-ABI
1584 if (isa<IntegerType>(Ty)) {
1585 sz = cast<IntegerType>(Ty)->getBitWidth();
1588 } else if (isa<PointerType>(Ty))
1589 sz = thePointerTy.getSizeInBits();
1591 sz = Ty->getPrimitiveSizeInBits();
1593 O << "\t.param .b" << sz << " ";
1595 O << "\t.reg .b" << sz << " ";
1596 printParamName(I, paramIndex, O);
1600 // param has byVal attribute. So should be a pointer
1601 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1602 assert(PTy && "Param with byval attribute should be a pointer type");
1603 Type *ETy = PTy->getElementType();
1605 if (isABI || isKernelFunc) {
1606 // Just print .param .b8 .align <a> .param[size];
1607 // <a> = PAL.getparamalignment
1608 // size = typeallocsize of element type
1609 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1611 align = TD->getABITypeAlignment(ETy);
1613 unsigned sz = TD->getTypeAllocSize(ETy);
1614 O << "\t.param .align " << align << " .b8 ";
1615 printParamName(I, paramIndex, O);
1616 O << "[" << sz << "]";
1619 // Split the ETy into constituent parts and
1620 // print .param .b<size> <name> for each part.
1621 // Further, if a part is vector, print the above for
1622 // each vector element.
1623 SmallVector<EVT, 16> vtparts;
1624 ComputeValueVTs(*TLI, ETy, vtparts);
1625 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1627 EVT elemtype = vtparts[i];
1628 if (vtparts[i].isVector()) {
1629 elems = vtparts[i].getVectorNumElements();
1630 elemtype = vtparts[i].getVectorElementType();
1633 for (unsigned j = 0, je = elems; j != je; ++j) {
1634 unsigned sz = elemtype.getSizeInBits();
1635 if (elemtype.isInteger() && (sz < 32))
1637 O << "\t.reg .b" << sz << " ";
1638 printParamName(I, paramIndex, O);
1654 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1656 const Function *F = MF.getFunction();
1657 emitFunctionParamList(F, O);
1660 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1661 const MachineFunction &MF) {
1662 SmallString<128> Str;
1663 raw_svector_ostream O(Str);
1665 // Map the global virtual register number to a register class specific
1666 // virtual register number starting from 1 with that class.
1667 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1668 //unsigned numRegClasses = TRI->getNumRegClasses();
1670 // Emit the Fake Stack Object
1671 const MachineFrameInfo *MFI = MF.getFrameInfo();
1672 int NumBytes = (int) MFI->getStackSize();
1674 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1675 << getFunctionNumber() << "[" << NumBytes << "];\n";
1676 if (nvptxSubtarget.is64Bit()) {
1677 O << "\t.reg .b64 \t%SP;\n";
1678 O << "\t.reg .b64 \t%SPL;\n";
1680 O << "\t.reg .b32 \t%SP;\n";
1681 O << "\t.reg .b32 \t%SPL;\n";
1685 // Go through all virtual registers to establish the mapping between the
1687 // register number and the per class virtual register number.
1688 // We use the per class virtual register number in the ptx output.
1689 unsigned int numVRs = MRI->getNumVirtRegs();
1690 for (unsigned i = 0; i < numVRs; i++) {
1691 unsigned int vr = TRI->index2VirtReg(i);
1692 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1693 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1694 int n = regmap.size();
1695 regmap.insert(std::make_pair(vr, n + 1));
1698 // Emit register declarations
1699 // @TODO: Extract out the real register usage
1700 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1701 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1702 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1703 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1704 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1705 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1706 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1708 // Emit declaration of the virtual registers or 'physical' registers for
1709 // each register class
1710 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1711 const TargetRegisterClass *RC = TRI->getRegClass(i);
1712 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1713 std::string rcname = getNVPTXRegClassName(RC);
1714 std::string rcStr = getNVPTXRegClassStr(RC);
1715 int n = regmap.size();
1717 // Only declare those registers that may be used.
1719 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1724 OutStreamer.EmitRawText(O.str());
1727 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1728 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1730 unsigned int numHex;
1733 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1736 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1737 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1740 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1742 llvm_unreachable("unsupported fp type");
1744 APInt API = APF.bitcastToAPInt();
1745 std::string hexstr(utohexstr(API.getZExtValue()));
1747 if (hexstr.length() < numHex)
1748 O << std::string(numHex - hexstr.length(), '0');
1749 O << utohexstr(API.getZExtValue());
1752 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1754 O << CI->getValue();
1757 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1758 printFPConstant(CFP, O);
1761 if (isa<ConstantPointerNull>(CPV)) {
1765 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1766 O << *getSymbol(GVar);
1769 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1770 const Value *v = Cexpr->stripPointerCasts();
1771 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1772 O << *getSymbol(GVar);
1775 O << *LowerConstant(CPV, *this);
1779 llvm_unreachable("Not scalar type found in printScalarConstant()");
1782 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1783 AggBuffer *aggBuffer) {
1785 const DataLayout *TD = TM.getDataLayout();
1787 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1788 int s = TD->getTypeAllocSize(CPV->getType());
1791 aggBuffer->addZeros(s);
1796 switch (CPV->getType()->getTypeID()) {
1798 case Type::IntegerTyID: {
1799 const Type *ETy = CPV->getType();
1800 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1802 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1804 aggBuffer->addBytes(ptr, 1, Bytes);
1805 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1806 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1807 ptr = (unsigned char *)&int16;
1808 aggBuffer->addBytes(ptr, 2, Bytes);
1809 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1810 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1811 int int32 = (int)(constInt->getZExtValue());
1812 ptr = (unsigned char *)&int32;
1813 aggBuffer->addBytes(ptr, 4, Bytes);
1815 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1816 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1817 ConstantFoldConstantExpression(Cexpr, TD))) {
1818 int int32 = (int)(constInt->getZExtValue());
1819 ptr = (unsigned char *)&int32;
1820 aggBuffer->addBytes(ptr, 4, Bytes);
1823 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1824 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1825 aggBuffer->addSymbol(v);
1826 aggBuffer->addZeros(4);
1830 llvm_unreachable("unsupported integer const type");
1831 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1832 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1833 long long int64 = (long long)(constInt->getZExtValue());
1834 ptr = (unsigned char *)&int64;
1835 aggBuffer->addBytes(ptr, 8, Bytes);
1837 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1838 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1839 ConstantFoldConstantExpression(Cexpr, TD))) {
1840 long long int64 = (long long)(constInt->getZExtValue());
1841 ptr = (unsigned char *)&int64;
1842 aggBuffer->addBytes(ptr, 8, Bytes);
1845 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1846 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1847 aggBuffer->addSymbol(v);
1848 aggBuffer->addZeros(8);
1852 llvm_unreachable("unsupported integer const type");
1854 llvm_unreachable("unsupported integer const type");
1857 case Type::FloatTyID:
1858 case Type::DoubleTyID: {
1859 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1860 const Type *Ty = CFP->getType();
1861 if (Ty == Type::getFloatTy(CPV->getContext())) {
1862 float float32 = (float) CFP->getValueAPF().convertToFloat();
1863 ptr = (unsigned char *)&float32;
1864 aggBuffer->addBytes(ptr, 4, Bytes);
1865 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1866 double float64 = CFP->getValueAPF().convertToDouble();
1867 ptr = (unsigned char *)&float64;
1868 aggBuffer->addBytes(ptr, 8, Bytes);
1870 llvm_unreachable("unsupported fp const type");
1874 case Type::PointerTyID: {
1875 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1876 aggBuffer->addSymbol(GVar);
1877 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1878 const Value *v = Cexpr->stripPointerCasts();
1879 aggBuffer->addSymbol(v);
1881 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1882 aggBuffer->addZeros(s);
1886 case Type::ArrayTyID:
1887 case Type::VectorTyID:
1888 case Type::StructTyID: {
1889 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1890 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1891 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1892 bufferAggregateConstant(CPV, aggBuffer);
1893 if (Bytes > ElementSize)
1894 aggBuffer->addZeros(Bytes - ElementSize);
1895 } else if (isa<ConstantAggregateZero>(CPV))
1896 aggBuffer->addZeros(Bytes);
1898 llvm_unreachable("Unexpected Constant type");
1903 llvm_unreachable("unsupported type");
1907 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1908 AggBuffer *aggBuffer) {
1909 const DataLayout *TD = TM.getDataLayout();
1913 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1914 if (CPV->getNumOperands())
1915 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1916 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1920 if (const ConstantDataSequential *CDS =
1921 dyn_cast<ConstantDataSequential>(CPV)) {
1922 if (CDS->getNumElements())
1923 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1924 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1929 if (isa<ConstantStruct>(CPV)) {
1930 if (CPV->getNumOperands()) {
1931 StructType *ST = cast<StructType>(CPV->getType());
1932 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1934 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1935 TD->getTypeAllocSize(ST) -
1936 TD->getStructLayout(ST)->getElementOffset(i);
1938 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1939 TD->getStructLayout(ST)->getElementOffset(i);
1940 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1945 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1948 // buildTypeNameMap - Run through symbol table looking for type names.
1951 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1953 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1955 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1956 !PI->second.compare("struct._image2d_t") ||
1957 !PI->second.compare("struct._image3d_t")))
1964 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1965 switch (MI.getOpcode()) {
1968 case NVPTX::CallArgBeginInst:
1969 case NVPTX::CallArgEndInst0:
1970 case NVPTX::CallArgEndInst1:
1971 case NVPTX::CallArgF32:
1972 case NVPTX::CallArgF64:
1973 case NVPTX::CallArgI16:
1974 case NVPTX::CallArgI32:
1975 case NVPTX::CallArgI32imm:
1976 case NVPTX::CallArgI64:
1977 case NVPTX::CallArgParam:
1978 case NVPTX::CallVoidInst:
1979 case NVPTX::CallVoidInstReg:
1980 case NVPTX::Callseq_End:
1981 case NVPTX::CallVoidInstReg64:
1982 case NVPTX::DeclareParamInst:
1983 case NVPTX::DeclareRetMemInst:
1984 case NVPTX::DeclareRetRegInst:
1985 case NVPTX::DeclareRetScalarInst:
1986 case NVPTX::DeclareScalarParamInst:
1987 case NVPTX::DeclareScalarRegInst:
1988 case NVPTX::StoreParamF32:
1989 case NVPTX::StoreParamF64:
1990 case NVPTX::StoreParamI16:
1991 case NVPTX::StoreParamI32:
1992 case NVPTX::StoreParamI64:
1993 case NVPTX::StoreParamI8:
1994 case NVPTX::StoreRetvalF32:
1995 case NVPTX::StoreRetvalF64:
1996 case NVPTX::StoreRetvalI16:
1997 case NVPTX::StoreRetvalI32:
1998 case NVPTX::StoreRetvalI64:
1999 case NVPTX::StoreRetvalI8:
2000 case NVPTX::LastCallArgF32:
2001 case NVPTX::LastCallArgF64:
2002 case NVPTX::LastCallArgI16:
2003 case NVPTX::LastCallArgI32:
2004 case NVPTX::LastCallArgI32imm:
2005 case NVPTX::LastCallArgI64:
2006 case NVPTX::LastCallArgParam:
2007 case NVPTX::LoadParamMemF32:
2008 case NVPTX::LoadParamMemF64:
2009 case NVPTX::LoadParamMemI16:
2010 case NVPTX::LoadParamMemI32:
2011 case NVPTX::LoadParamMemI64:
2012 case NVPTX::LoadParamMemI8:
2013 case NVPTX::PrototypeInst:
2014 case NVPTX::DBG_VALUE:
2020 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2022 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2023 unsigned AsmVariant,
2024 const char *ExtraCode, raw_ostream &O) {
2025 if (ExtraCode && ExtraCode[0]) {
2026 if (ExtraCode[1] != 0)
2027 return true; // Unknown modifier.
2029 switch (ExtraCode[0]) {
2031 // See if this is a generic print operand
2032 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2038 printOperand(MI, OpNo, O);
2043 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2044 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2045 const char *ExtraCode, raw_ostream &O) {
2046 if (ExtraCode && ExtraCode[0])
2047 return true; // Unknown modifier
2050 printMemOperand(MI, OpNo, O);
2056 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2057 raw_ostream &O, const char *Modifier) {
2058 const MachineOperand &MO = MI->getOperand(opNum);
2059 switch (MO.getType()) {
2060 case MachineOperand::MO_Register:
2061 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2062 if (MO.getReg() == NVPTX::VRDepot)
2063 O << DEPOTNAME << getFunctionNumber();
2065 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2067 emitVirtualRegister(MO.getReg(), O);
2071 case MachineOperand::MO_Immediate:
2074 else if (strstr(Modifier, "vec") == Modifier)
2075 printVecModifiedImmediate(MO, Modifier, O);
2078 "Don't know how to handle modifier on immediate operand");
2081 case MachineOperand::MO_FPImmediate:
2082 printFPConstant(MO.getFPImm(), O);
2085 case MachineOperand::MO_GlobalAddress:
2086 O << *getSymbol(MO.getGlobal());
2089 case MachineOperand::MO_MachineBasicBlock:
2090 O << *MO.getMBB()->getSymbol();
2094 llvm_unreachable("Operand type not supported.");
2098 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2099 raw_ostream &O, const char *Modifier) {
2100 printOperand(MI, opNum, O);
2102 if (Modifier && !strcmp(Modifier, "add")) {
2104 printOperand(MI, opNum + 1, O);
2106 if (MI->getOperand(opNum + 1).isImm() &&
2107 MI->getOperand(opNum + 1).getImm() == 0)
2108 return; // don't print ',0' or '+0'
2110 printOperand(MI, opNum + 1, O);
2115 // Force static initialization.
2116 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2117 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2118 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2121 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2122 std::stringstream temp;
2123 LineReader *reader = this->getReader(filename.str());
2125 temp << filename.str();
2129 temp << reader->readLine(line);
2131 this->OutStreamer.EmitRawText(Twine(temp.str()));
2134 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2135 if (reader == NULL) {
2136 reader = new LineReader(filename);
2139 if (reader->fileName() != filename) {
2141 reader = new LineReader(filename);
2147 std::string LineReader::readLine(unsigned lineNum) {
2148 if (lineNum < theCurLine) {
2150 fstr.seekg(0, std::ios::beg);
2152 while (theCurLine < lineNum) {
2153 fstr.getline(buff, 500);
2159 // Force static initialization.
2160 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2161 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2162 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);