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 "MCTargetDesc/NVPTXMCAsmInfo.h"
18 #include "NVPTXInstrInfo.h"
19 #include "NVPTXMCExpr.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "InstPrinter/NVPTXInstPrinter.h"
24 #include "cl_common_defines.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.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/Mangler.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 bool RegAllocNilUsed = true;
53 #define DEPOTNAME "__local_depot"
56 EmitLineNumbers("nvptx-emit-line-numbers",
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
60 namespace llvm { bool InterleaveSrcInPtx = false; }
62 static cl::opt<bool, true>
63 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
64 cl::desc("NVPTX Specific: Emit source line in ptx file"),
65 cl::location(llvm::InterleaveSrcInPtx));
68 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
70 void DiscoverDependentGlobals(const Value *V,
71 DenseSet<const GlobalVariable *> &Globals) {
72 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
75 if (const User *U = dyn_cast<User>(V)) {
76 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
77 DiscoverDependentGlobals(U->getOperand(i), Globals);
83 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
84 /// instances to be emitted, but only after any dependents have been added
86 void VisitGlobalVariableForEmission(
87 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
88 DenseSet<const GlobalVariable *> &Visited,
89 DenseSet<const GlobalVariable *> &Visiting) {
90 // Have we already visited this one?
91 if (Visited.count(GV))
94 // Do we have a circular dependency?
95 if (Visiting.count(GV))
96 report_fatal_error("Circular dependency found in global variable set");
98 // Start visiting this global
101 // Make sure we visit all dependents first
102 DenseSet<const GlobalVariable *> Others;
103 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
104 DiscoverDependentGlobals(GV->getOperand(i), Others);
106 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
109 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
111 // Now we can visit ourself
118 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
119 // cannot just link to the existing version.
120 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
122 using namespace nvptx;
123 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
124 MCContext &Ctx = AP.OutContext;
126 if (CV->isNullValue() || isa<UndefValue>(CV))
127 return MCConstantExpr::Create(0, Ctx);
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
130 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
133 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
135 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
136 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
140 llvm_unreachable("Unknown constant value to lower!");
142 switch (CE->getOpcode()) {
144 // If the code isn't optimized, there may be outstanding folding
145 // opportunities. Attempt to fold the expression using DataLayout as a
146 // last resort before giving up.
147 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
149 return LowerConstant(C, AP);
151 // Otherwise report the problem to the user.
154 raw_string_ostream OS(S);
155 OS << "Unsupported expression in static initializer: ";
156 WriteAsOperand(OS, CE, /*PrintType=*/ false,
157 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
158 report_fatal_error(OS.str());
160 case Instruction::GetElementPtr: {
161 const DataLayout &TD = *AP.TM.getDataLayout();
162 // Generate a symbolic expression for the byte address
163 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
164 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
166 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
170 int64_t Offset = OffsetAI.getSExtValue();
171 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
175 case Instruction::Trunc:
176 // We emit the value and depend on the assembler to truncate the generated
177 // expression properly. This is important for differences between
178 // blockaddress labels. Since the two labels are in the same function, it
179 // is reasonable to treat their delta as a 32-bit value.
181 case Instruction::BitCast:
182 return LowerConstant(CE->getOperand(0), AP);
184 case Instruction::IntToPtr: {
185 const DataLayout &TD = *AP.TM.getDataLayout();
186 // Handle casts to pointers by changing them into casts to the appropriate
187 // integer type. This promotes constant folding and simplifies this code.
188 Constant *Op = CE->getOperand(0);
189 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
191 return LowerConstant(Op, AP);
194 case Instruction::PtrToInt: {
195 const DataLayout &TD = *AP.TM.getDataLayout();
196 // Support only foldable casts to/from pointers that can be eliminated by
197 // changing the pointer to the appropriately sized integer type.
198 Constant *Op = CE->getOperand(0);
199 Type *Ty = CE->getType();
201 const MCExpr *OpExpr = LowerConstant(Op, AP);
203 // We can emit the pointer value into this slot if the slot is an
204 // integer slot equal to the size of the pointer.
205 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
208 // Otherwise the pointer is smaller than the resultant integer, mask off
209 // the high bits so we are sure to get a proper truncation if the input is
211 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
212 const MCExpr *MaskExpr =
213 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
214 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
217 // The MC library also has a right-shift operator, but it isn't consistently
218 // signed or unsigned between different targets.
219 case Instruction::Add:
220 case Instruction::Sub:
221 case Instruction::Mul:
222 case Instruction::SDiv:
223 case Instruction::SRem:
224 case Instruction::Shl:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor: {
228 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
229 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
230 switch (CE->getOpcode()) {
232 llvm_unreachable("Unknown binary operator constant cast expr");
233 case Instruction::Add:
234 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
235 case Instruction::Sub:
236 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
237 case Instruction::Mul:
238 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
239 case Instruction::SDiv:
240 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
241 case Instruction::SRem:
242 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
243 case Instruction::Shl:
244 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
245 case Instruction::And:
246 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
247 case Instruction::Or:
248 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
249 case Instruction::Xor:
250 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
256 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
257 if (!EmitLineNumbers)
262 DebugLoc curLoc = MI.getDebugLoc();
264 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
267 if (prevDebugLoc == curLoc)
270 prevDebugLoc = curLoc;
272 if (curLoc.isUnknown())
275 const MachineFunction *MF = MI.getParent()->getParent();
276 //const TargetMachine &TM = MF->getTarget();
278 const LLVMContext &ctx = MF->getFunction()->getContext();
279 DIScope Scope(curLoc.getScope(ctx));
281 assert((!Scope || Scope.isScope()) &&
282 "Scope of a DebugLoc should be null or a DIScope.");
286 StringRef fileName(Scope.getFilename());
287 StringRef dirName(Scope.getDirectory());
288 SmallString<128> FullPathName = dirName;
289 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
290 sys::path::append(FullPathName, fileName);
291 fileName = FullPathName.str();
294 if (filenameMap.find(fileName.str()) == filenameMap.end())
297 // Emit the line from the source file.
298 if (llvm::InterleaveSrcInPtx)
299 this->emitSrcInText(fileName.str(), curLoc.getLine());
301 std::stringstream temp;
302 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
303 << " " << curLoc.getCol();
304 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
307 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
308 SmallString<128> Str;
309 raw_svector_ostream OS(Str);
310 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
311 emitLineNumberAsDotLoc(*MI);
314 lowerToMCInst(MI, Inst);
315 OutStreamer.EmitInstruction(Inst);
318 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
319 OutMI.setOpcode(MI->getOpcode());
321 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
322 const MachineOperand &MO = MI->getOperand(i);
325 if (lowerOperand(MO, MCOp))
326 OutMI.addOperand(MCOp);
330 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
332 switch (MO.getType()) {
333 default: llvm_unreachable("unknown operand type");
334 case MachineOperand::MO_Register:
335 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
337 case MachineOperand::MO_Immediate:
338 MCOp = MCOperand::CreateImm(MO.getImm());
340 case MachineOperand::MO_MachineBasicBlock:
341 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
342 MO.getMBB()->getSymbol(), OutContext));
344 case MachineOperand::MO_ExternalSymbol:
345 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
347 case MachineOperand::MO_GlobalAddress:
348 MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
350 case MachineOperand::MO_FPImmediate: {
351 const ConstantFP *Cnt = MO.getFPImm();
352 APFloat Val = Cnt->getValueAPF();
354 switch (Cnt->getType()->getTypeID()) {
355 default: report_fatal_error("Unsupported FP type"); break;
356 case Type::FloatTyID:
357 MCOp = MCOperand::CreateExpr(
358 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
360 case Type::DoubleTyID:
361 MCOp = MCOperand::CreateExpr(
362 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
371 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
372 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
373 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
375 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
376 unsigned RegNum = RegMap[Reg];
378 // Encode the register class in the upper 4 bits
379 // Must be kept in sync with NVPTXInstPrinter::printRegName
381 if (RC == &NVPTX::Int1RegsRegClass) {
383 } else if (RC == &NVPTX::Int16RegsRegClass) {
385 } else if (RC == &NVPTX::Int32RegsRegClass) {
387 } else if (RC == &NVPTX::Int64RegsRegClass) {
389 } else if (RC == &NVPTX::Float32RegsRegClass) {
391 } else if (RC == &NVPTX::Float64RegsRegClass) {
394 report_fatal_error("Bad register class");
397 // Insert the vreg number
398 Ret |= (RegNum & 0x0FFFFFFF);
401 // Some special-use registers are actually physical registers.
402 // Encode this as the register class ID of 0 and the real register ID.
403 return Reg & 0x0FFFFFFF;
407 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
408 const MCSymbol *Symbol) {
410 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
412 return MCOperand::CreateExpr(Expr);
415 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
416 const DataLayout *TD = TM.getDataLayout();
417 const TargetLowering *TLI = TM.getTargetLowering();
419 Type *Ty = F->getReturnType();
421 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
423 if (Ty->getTypeID() == Type::VoidTyID)
429 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
431 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
432 size = ITy->getBitWidth();
436 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
437 size = Ty->getPrimitiveSizeInBits();
440 O << ".param .b" << size << " func_retval0";
441 } else if (isa<PointerType>(Ty)) {
442 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
445 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
446 SmallVector<EVT, 16> vtparts;
447 ComputeValueVTs(*TLI, Ty, vtparts);
448 unsigned totalsz = 0;
449 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
451 EVT elemtype = vtparts[i];
452 if (vtparts[i].isVector()) {
453 elems = vtparts[i].getVectorNumElements();
454 elemtype = vtparts[i].getVectorElementType();
456 for (unsigned j = 0, je = elems; j != je; ++j) {
457 unsigned sz = elemtype.getSizeInBits();
458 if (elemtype.isInteger() && (sz < 8))
463 unsigned retAlignment = 0;
464 if (!llvm::getAlign(*F, 0, retAlignment))
465 retAlignment = TD->getABITypeAlignment(Ty);
466 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
469 assert(false && "Unknown return type");
472 SmallVector<EVT, 16> vtparts;
473 ComputeValueVTs(*TLI, Ty, vtparts);
475 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
477 EVT elemtype = vtparts[i];
478 if (vtparts[i].isVector()) {
479 elems = vtparts[i].getVectorNumElements();
480 elemtype = vtparts[i].getVectorElementType();
483 for (unsigned j = 0, je = elems; j != je; ++j) {
484 unsigned sz = elemtype.getSizeInBits();
485 if (elemtype.isInteger() && (sz < 32))
487 O << ".reg .b" << sz << " func_retval" << idx;
500 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
502 const Function *F = MF.getFunction();
503 printReturnValStr(F, O);
506 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
507 SmallString<128> Str;
508 raw_svector_ostream O(Str);
510 if (!GlobalsEmitted) {
511 emitGlobals(*MF->getFunction()->getParent());
512 GlobalsEmitted = true;
516 MRI = &MF->getRegInfo();
517 F = MF->getFunction();
518 emitLinkageDirective(F, O);
519 if (llvm::isKernelFunction(*F))
523 printReturnValStr(*MF, O);
528 emitFunctionParamList(*MF, O);
530 if (llvm::isKernelFunction(*F))
531 emitKernelFunctionDirectives(*F, O);
533 OutStreamer.EmitRawText(O.str());
535 prevDebugLoc = DebugLoc();
538 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
540 OutStreamer.EmitRawText(StringRef("{\n"));
541 setAndEmitFunctionVirtualRegisters(*MF);
543 SmallString<128> Str;
544 raw_svector_ostream O(Str);
545 emitDemotedVars(MF->getFunction(), O);
546 OutStreamer.EmitRawText(O.str());
549 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
550 OutStreamer.EmitRawText(StringRef("}\n"));
554 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
555 raw_ostream &O) const {
556 // If the NVVM IR has some of reqntid* specified, then output
557 // the reqntid directive, and set the unspecified ones to 1.
558 // If none of reqntid* is specified, don't output reqntid directive.
559 unsigned reqntidx, reqntidy, reqntidz;
560 bool specified = false;
561 if (llvm::getReqNTIDx(F, reqntidx) == false)
565 if (llvm::getReqNTIDy(F, reqntidy) == false)
569 if (llvm::getReqNTIDz(F, reqntidz) == false)
575 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
578 // If the NVVM IR has some of maxntid* specified, then output
579 // the maxntid directive, and set the unspecified ones to 1.
580 // If none of maxntid* is specified, don't output maxntid directive.
581 unsigned maxntidx, maxntidy, maxntidz;
583 if (llvm::getMaxNTIDx(F, maxntidx) == false)
587 if (llvm::getMaxNTIDy(F, maxntidy) == false)
591 if (llvm::getMaxNTIDz(F, maxntidz) == false)
597 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
601 if (llvm::getMinCTASm(F, mincta))
602 O << ".minnctapersm " << mincta << "\n";
605 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
607 const TargetRegisterClass *RC = MRI->getRegClass(vr);
609 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
610 unsigned mapped_vr = regmap[vr];
613 O << getNVPTXRegClassStr(RC) << mapped_vr;
616 report_fatal_error("Bad register!");
619 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
621 getVirtualRegisterName(vr, isVec, O);
624 void NVPTXAsmPrinter::printVecModifiedImmediate(
625 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
626 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
627 int Imm = (int) MO.getImm();
628 if (0 == strcmp(Modifier, "vecelem"))
629 O << "_" << vecelem[Imm];
630 else if (0 == strcmp(Modifier, "vecv4comm1")) {
631 if ((Imm < 0) || (Imm > 3))
633 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
634 if ((Imm < 4) || (Imm > 7))
636 } else if (0 == strcmp(Modifier, "vecv4pos")) {
639 O << "_" << vecelem[Imm % 4];
640 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
641 if ((Imm < 0) || (Imm > 1))
643 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
644 if ((Imm < 2) || (Imm > 3))
646 } else if (0 == strcmp(Modifier, "vecv2pos")) {
649 O << "_" << vecelem[Imm % 2];
651 llvm_unreachable("Unknown Modifier on immediate operand");
656 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
658 emitLinkageDirective(F, O);
659 if (llvm::isKernelFunction(*F))
663 printReturnValStr(F, O);
664 O << *Mang->getSymbol(F) << "\n";
665 emitFunctionParamList(F, O);
669 static bool usedInGlobalVarDef(const Constant *C) {
673 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
674 if (GV->getName().str() == "llvm.used")
679 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
681 const Constant *C = dyn_cast<Constant>(*ui);
682 if (usedInGlobalVarDef(C))
688 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
689 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
690 if (othergv->getName().str() == "llvm.used")
694 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
695 if (instr->getParent() && instr->getParent()->getParent()) {
696 const Function *curFunc = instr->getParent()->getParent();
697 if (oneFunc && (curFunc != oneFunc))
705 if (const MDNode *md = dyn_cast<MDNode>(U))
706 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
707 (md->getName().str() == "llvm.dbg.sp")))
710 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
712 if (usedInOneFunc(*ui, oneFunc) == false)
718 /* Find out if a global variable can be demoted to local scope.
719 * Currently, this is valid for CUDA shared variables, which have local
720 * scope and global lifetime. So the conditions to check are :
721 * 1. Is the global variable in shared address space?
722 * 2. Does it have internal linkage?
723 * 3. Is the global variable referenced only in one function?
725 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
726 if (gv->hasInternalLinkage() == false)
728 const PointerType *Pty = gv->getType();
729 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
732 const Function *oneFunc = 0;
734 bool flag = usedInOneFunc(gv, oneFunc);
743 static bool useFuncSeen(const Constant *C,
744 llvm::DenseMap<const Function *, bool> &seenMap) {
745 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
747 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
748 if (useFuncSeen(cu, seenMap))
750 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
751 const BasicBlock *bb = I->getParent();
754 const Function *caller = bb->getParent();
757 if (seenMap.find(caller) != seenMap.end())
764 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
765 llvm::DenseMap<const Function *, bool> seenMap;
766 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
767 const Function *F = FI;
769 if (F->isDeclaration()) {
772 if (F->getIntrinsicID())
774 emitDeclaration(F, O);
777 for (Value::const_use_iterator iter = F->use_begin(),
778 iterEnd = F->use_end();
779 iter != iterEnd; ++iter) {
780 if (const Constant *C = dyn_cast<Constant>(*iter)) {
781 if (usedInGlobalVarDef(C)) {
782 // The use is in the initialization of a global variable
783 // that is a function pointer, so print a declaration
784 // for the original function
785 emitDeclaration(F, O);
788 // Emit a declaration of this function if the function that
789 // uses this constant expr has already been seen.
790 if (useFuncSeen(C, seenMap)) {
791 emitDeclaration(F, O);
796 if (!isa<Instruction>(*iter))
798 const Instruction *instr = cast<Instruction>(*iter);
799 const BasicBlock *bb = instr->getParent();
802 const Function *caller = bb->getParent();
806 // If a caller has already been seen, then the caller is
807 // appearing in the module before the callee. so print out
808 // a declaration for the callee.
809 if (seenMap.find(caller) != seenMap.end()) {
810 emitDeclaration(F, O);
818 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
819 DebugInfoFinder DbgFinder;
820 DbgFinder.processModule(M);
823 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
824 E = DbgFinder.compile_unit_end();
826 DICompileUnit DIUnit(*I);
827 StringRef Filename(DIUnit.getFilename());
828 StringRef Dirname(DIUnit.getDirectory());
829 SmallString<128> FullPathName = Dirname;
830 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
831 sys::path::append(FullPathName, Filename);
832 Filename = FullPathName.str();
834 if (filenameMap.find(Filename.str()) != filenameMap.end())
836 filenameMap[Filename.str()] = i;
837 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
841 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
842 E = DbgFinder.subprogram_end();
845 StringRef Filename(SP.getFilename());
846 StringRef Dirname(SP.getDirectory());
847 SmallString<128> FullPathName = Dirname;
848 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
849 sys::path::append(FullPathName, Filename);
850 Filename = FullPathName.str();
852 if (filenameMap.find(Filename.str()) != filenameMap.end())
854 filenameMap[Filename.str()] = i;
859 bool NVPTXAsmPrinter::doInitialization(Module &M) {
861 SmallString<128> Str1;
862 raw_svector_ostream OS1(Str1);
864 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
865 MMI->AnalyzeModule(M);
867 // We need to call the parent's one explicitly.
868 //bool Result = AsmPrinter::doInitialization(M);
870 // Initialize TargetLoweringObjectFile.
871 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
872 .Initialize(OutContext, TM);
874 Mang = new Mangler(OutContext, &TM);
876 // Emit header before any dwarf directives are emitted below.
878 OutStreamer.EmitRawText(OS1.str());
880 // Already commented out
881 //bool Result = AsmPrinter::doInitialization(M);
883 // Emit module-level inline asm if it exists.
884 if (!M.getModuleInlineAsm().empty()) {
885 OutStreamer.AddComment("Start of file scope inline assembly");
886 OutStreamer.AddBlankLine();
887 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
888 OutStreamer.AddBlankLine();
889 OutStreamer.AddComment("End of file scope inline assembly");
890 OutStreamer.AddBlankLine();
893 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
894 recordAndEmitFilenames(M);
896 GlobalsEmitted = false;
898 return false; // success
901 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
902 SmallString<128> Str2;
903 raw_svector_ostream OS2(Str2);
905 emitDeclarations(M, OS2);
907 // As ptxas does not support forward references of globals, we need to first
908 // sort the list of module-level globals in def-use order. We visit each
909 // global variable in order, and ensure that we emit it *after* its dependent
910 // globals. We use a little extra memory maintaining both a set and a list to
911 // have fast searches while maintaining a strict ordering.
912 SmallVector<const GlobalVariable *, 8> Globals;
913 DenseSet<const GlobalVariable *> GVVisited;
914 DenseSet<const GlobalVariable *> GVVisiting;
916 // Visit each global variable, in order
917 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
919 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
921 assert(GVVisited.size() == M.getGlobalList().size() &&
922 "Missed a global variable");
923 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
925 // Print out module-level global variables in proper order
926 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
927 printModuleLevelGV(Globals[i], OS2);
931 OutStreamer.EmitRawText(OS2.str());
934 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
936 O << "// Generated by LLVM NVPTX Back-End\n";
940 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
941 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
944 O << nvptxSubtarget.getTargetName();
946 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
947 O << ", texmode_independent";
948 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
949 if (!nvptxSubtarget.hasDouble())
950 O << ", map_f64_to_f32";
953 if (MAI->doesSupportDebugInformation())
958 O << ".address_size ";
959 if (nvptxSubtarget.is64Bit())
968 bool NVPTXAsmPrinter::doFinalization(Module &M) {
970 // If we did not emit any functions, then the global declarations have not
972 if (!GlobalsEmitted) {
974 GlobalsEmitted = true;
977 // XXX Temproarily remove global variables so that doFinalization() will not
978 // emit them again (global variables are emitted at beginning).
980 Module::GlobalListType &global_list = M.getGlobalList();
981 int i, n = global_list.size();
982 GlobalVariable **gv_array = new GlobalVariable *[n];
984 // first, back-up GlobalVariable in gv_array
986 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
990 // second, empty global_list
991 while (!global_list.empty())
992 global_list.remove(global_list.begin());
994 // call doFinalization
995 bool ret = AsmPrinter::doFinalization(M);
997 // now we restore global variables
998 for (i = 0; i < n; i++)
999 global_list.insert(global_list.end(), gv_array[i]);
1004 //bool Result = AsmPrinter::doFinalization(M);
1005 // Instead of calling the parents doFinalization, we may
1006 // clone parents doFinalization and customize here.
1007 // Currently, we if NVISA out the EmitGlobals() in
1008 // parent's doFinalization, which is too intrusive.
1010 // Same for the doInitialization.
1014 // This function emits appropriate linkage directives for
1015 // functions and global variables.
1017 // extern function declaration -> .extern
1018 // extern function definition -> .visible
1019 // external global variable with init -> .visible
1020 // external without init -> .extern
1021 // appending -> not allowed, assert.
1023 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1025 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1026 if (V->hasExternalLinkage()) {
1027 if (isa<GlobalVariable>(V)) {
1028 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1030 if (GVar->hasInitializer())
1035 } else if (V->isDeclaration())
1039 } else if (V->hasAppendingLinkage()) {
1041 msg.append("Error: ");
1042 msg.append("Symbol ");
1044 msg.append(V->getName().str());
1045 msg.append("has unsupported appending linkage type");
1046 llvm_unreachable(msg.c_str());
1051 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1053 bool processDemoted) {
1056 if (GVar->hasSection()) {
1057 if (GVar->getSection() == "llvm.metadata")
1061 const DataLayout *TD = TM.getDataLayout();
1063 // GlobalVariables are always constant pointers themselves.
1064 const PointerType *PTy = GVar->getType();
1065 Type *ETy = PTy->getElementType();
1067 if (GVar->hasExternalLinkage()) {
1068 if (GVar->hasInitializer())
1074 if (llvm::isTexture(*GVar)) {
1075 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1079 if (llvm::isSurface(*GVar)) {
1080 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1084 if (GVar->isDeclaration()) {
1085 // (extern) declarations, no definition or initializer
1086 // Currently the only known declaration is for an automatic __local
1087 // (.shared) promoted to global.
1088 emitPTXGlobalVariable(GVar, O);
1093 if (llvm::isSampler(*GVar)) {
1094 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1096 const Constant *Initializer = NULL;
1097 if (GVar->hasInitializer())
1098 Initializer = GVar->getInitializer();
1099 const ConstantInt *CI = NULL;
1101 CI = dyn_cast<ConstantInt>(Initializer);
1103 unsigned sample = CI->getZExtValue();
1108 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1110 O << "addr_mode_" << i << " = ";
1116 O << "clamp_to_border";
1119 O << "clamp_to_edge";
1130 O << "filter_mode = ";
1131 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1139 assert(0 && "Anisotropic filtering is not supported");
1144 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1145 O << ", force_unnormalized_coords = 1";
1154 if (GVar->hasPrivateLinkage()) {
1156 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1159 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1160 if (!strncmp(GVar->getName().data(), "filename", 8))
1162 if (GVar->use_empty())
1166 const Function *demotedFunc = 0;
1167 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1168 O << "// " << GVar->getName().str() << " has been demoted\n";
1169 if (localDecls.find(demotedFunc) != localDecls.end())
1170 localDecls[demotedFunc].push_back(GVar);
1172 std::vector<const GlobalVariable *> temp;
1173 temp.push_back(GVar);
1174 localDecls[demotedFunc] = temp;
1180 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1181 if (GVar->getAlignment() == 0)
1182 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1184 O << " .align " << GVar->getAlignment();
1186 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1188 // Special case: ABI requires that we use .u8 for predicates
1189 if (ETy->isIntegerTy(1))
1192 O << getPTXFundamentalTypeStr(ETy, false);
1194 O << *Mang->getSymbol(GVar);
1196 // Ptx allows variable initilization only for constant and global state
1198 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1199 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1200 GVar->hasInitializer()) {
1201 const Constant *Initializer = GVar->getInitializer();
1202 if (!Initializer->isNullValue()) {
1204 printScalarConstant(Initializer, O);
1208 unsigned int ElementSize = 0;
1210 // Although PTX has direct support for struct type and array type and
1211 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1212 // targets that support these high level field accesses. Structs, arrays
1213 // and vectors are lowered into arrays of bytes.
1214 switch (ETy->getTypeID()) {
1215 case Type::StructTyID:
1216 case Type::ArrayTyID:
1217 case Type::VectorTyID:
1218 ElementSize = TD->getTypeStoreSize(ETy);
1219 // Ptx allows variable initilization only for constant and
1220 // global state spaces.
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 (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1226 AggBuffer aggBuffer(ElementSize, O, *this);
1227 bufferAggregateConstant(Initializer, &aggBuffer);
1228 if (aggBuffer.numSymbols) {
1229 if (nvptxSubtarget.is64Bit()) {
1230 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1231 O << ElementSize / 8;
1233 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1234 O << ElementSize / 4;
1238 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1246 O << " .b8 " << *Mang->getSymbol(GVar);
1254 O << " .b8 " << *Mang->getSymbol(GVar);
1263 assert(0 && "type not supported yet");
1270 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1271 if (localDecls.find(f) == localDecls.end())
1274 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1276 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1277 O << "\t// demoted variable\n\t";
1278 printModuleLevelGV(gvars[i], O, true);
1282 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1283 raw_ostream &O) const {
1284 switch (AddressSpace) {
1285 case llvm::ADDRESS_SPACE_LOCAL:
1288 case llvm::ADDRESS_SPACE_GLOBAL:
1291 case llvm::ADDRESS_SPACE_CONST:
1294 case llvm::ADDRESS_SPACE_SHARED:
1298 report_fatal_error("Bad address space found while emitting PTX");
1304 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1305 switch (Ty->getTypeID()) {
1307 llvm_unreachable("unexpected type");
1309 case Type::IntegerTyID: {
1310 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1313 else if (NumBits <= 64) {
1314 std::string name = "u";
1315 return name + utostr(NumBits);
1317 llvm_unreachable("Integer too large");
1322 case Type::FloatTyID:
1324 case Type::DoubleTyID:
1326 case Type::PointerTyID:
1327 if (nvptxSubtarget.is64Bit())
1337 llvm_unreachable("unexpected type");
1341 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1344 const DataLayout *TD = TM.getDataLayout();
1346 // GlobalVariables are always constant pointers themselves.
1347 const PointerType *PTy = GVar->getType();
1348 Type *ETy = PTy->getElementType();
1351 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1352 if (GVar->getAlignment() == 0)
1353 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1355 O << " .align " << GVar->getAlignment();
1357 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1359 O << getPTXFundamentalTypeStr(ETy);
1361 O << *Mang->getSymbol(GVar);
1365 int64_t ElementSize = 0;
1367 // Although PTX has direct support for struct type and array type and LLVM IR
1368 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1369 // support these high level field accesses. Structs and arrays are lowered
1370 // into arrays of bytes.
1371 switch (ETy->getTypeID()) {
1372 case Type::StructTyID:
1373 case Type::ArrayTyID:
1374 case Type::VectorTyID:
1375 ElementSize = TD->getTypeStoreSize(ETy);
1376 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1378 O << itostr(ElementSize);
1383 assert(0 && "type not supported yet");
1388 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1389 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1390 return TD->getPrefTypeAlignment(Ty);
1392 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1394 return getOpenCLAlignment(TD, ATy->getElementType());
1396 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1398 Type *ETy = VTy->getElementType();
1399 unsigned int numE = VTy->getNumElements();
1400 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1404 return numE * alignE;
1407 const StructType *STy = dyn_cast<StructType>(Ty);
1409 unsigned int alignStruct = 1;
1410 // Go through each element of the struct and find the
1411 // largest alignment.
1412 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1413 Type *ETy = STy->getElementType(i);
1414 unsigned int align = getOpenCLAlignment(TD, ETy);
1415 if (align > alignStruct)
1416 alignStruct = align;
1421 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1423 return TD->getPointerPrefAlignment();
1424 return TD->getPrefTypeAlignment(Ty);
1427 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1428 int paramIndex, raw_ostream &O) {
1429 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1430 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1431 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1433 std::string argName = I->getName();
1434 const char *p = argName.c_str();
1445 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1446 Function::const_arg_iterator I, E;
1449 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1450 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1451 O << *CurrentFnSym << "_param_" << paramIndex;
1455 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1456 if (i == paramIndex) {
1457 printParamName(I, paramIndex, O);
1461 llvm_unreachable("paramIndex out of bound");
1464 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1465 const DataLayout *TD = TM.getDataLayout();
1466 const AttributeSet &PAL = F->getAttributes();
1467 const TargetLowering *TLI = TM.getTargetLowering();
1468 Function::const_arg_iterator I, E;
1469 unsigned paramIndex = 0;
1471 bool isKernelFunc = llvm::isKernelFunction(*F);
1472 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1473 MVT thePointerTy = TLI->getPointerTy();
1477 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1478 Type *Ty = I->getType();
1485 // Handle image/sampler parameters
1486 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1487 if (llvm::isImage(*I)) {
1488 std::string sname = I->getName();
1489 if (llvm::isImageWriteOnly(*I))
1490 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1492 else // Default image is read_only
1493 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1495 } else // Should be llvm::isSampler(*I)
1496 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1501 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1502 if (Ty->isVectorTy()) {
1503 // Just print .param .b8 .align <a> .param[size];
1504 // <a> = PAL.getparamalignment
1505 // size = typeallocsize of element type
1506 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1508 align = TD->getABITypeAlignment(Ty);
1510 unsigned sz = TD->getTypeAllocSize(Ty);
1511 O << "\t.param .align " << align << " .b8 ";
1512 printParamName(I, paramIndex, O);
1513 O << "[" << sz << "]";
1518 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1521 // Special handling for pointer arguments to kernel
1522 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1524 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1525 Type *ETy = PTy->getElementType();
1526 int addrSpace = PTy->getAddressSpace();
1527 switch (addrSpace) {
1531 case llvm::ADDRESS_SPACE_CONST:
1532 O << ".ptr .const ";
1534 case llvm::ADDRESS_SPACE_SHARED:
1535 O << ".ptr .shared ";
1537 case llvm::ADDRESS_SPACE_GLOBAL:
1538 O << ".ptr .global ";
1541 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1543 printParamName(I, paramIndex, O);
1547 // non-pointer scalar to kernel func
1549 // Special case: predicate operands become .u8 types
1550 if (Ty->isIntegerTy(1))
1553 O << getPTXFundamentalTypeStr(Ty);
1555 printParamName(I, paramIndex, O);
1558 // Non-kernel function, just print .param .b<size> for ABI
1559 // and .reg .b<size> for non ABY
1561 if (isa<IntegerType>(Ty)) {
1562 sz = cast<IntegerType>(Ty)->getBitWidth();
1565 } else if (isa<PointerType>(Ty))
1566 sz = thePointerTy.getSizeInBits();
1568 sz = Ty->getPrimitiveSizeInBits();
1570 O << "\t.param .b" << sz << " ";
1572 O << "\t.reg .b" << sz << " ";
1573 printParamName(I, paramIndex, O);
1577 // param has byVal attribute. So should be a pointer
1578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1579 assert(PTy && "Param with byval attribute should be a pointer type");
1580 Type *ETy = PTy->getElementType();
1582 if (isABI || isKernelFunc) {
1583 // Just print .param .b8 .align <a> .param[size];
1584 // <a> = PAL.getparamalignment
1585 // size = typeallocsize of element type
1586 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1588 align = TD->getABITypeAlignment(ETy);
1590 unsigned sz = TD->getTypeAllocSize(ETy);
1591 O << "\t.param .align " << align << " .b8 ";
1592 printParamName(I, paramIndex, O);
1593 O << "[" << sz << "]";
1596 // Split the ETy into constituent parts and
1597 // print .param .b<size> <name> for each part.
1598 // Further, if a part is vector, print the above for
1599 // each vector element.
1600 SmallVector<EVT, 16> vtparts;
1601 ComputeValueVTs(*TLI, ETy, vtparts);
1602 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1604 EVT elemtype = vtparts[i];
1605 if (vtparts[i].isVector()) {
1606 elems = vtparts[i].getVectorNumElements();
1607 elemtype = vtparts[i].getVectorElementType();
1610 for (unsigned j = 0, je = elems; j != je; ++j) {
1611 unsigned sz = elemtype.getSizeInBits();
1612 if (elemtype.isInteger() && (sz < 32))
1614 O << "\t.reg .b" << sz << " ";
1615 printParamName(I, paramIndex, O);
1631 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1633 const Function *F = MF.getFunction();
1634 emitFunctionParamList(F, O);
1637 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1638 const MachineFunction &MF) {
1639 SmallString<128> Str;
1640 raw_svector_ostream O(Str);
1642 // Map the global virtual register number to a register class specific
1643 // virtual register number starting from 1 with that class.
1644 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1645 //unsigned numRegClasses = TRI->getNumRegClasses();
1647 // Emit the Fake Stack Object
1648 const MachineFrameInfo *MFI = MF.getFrameInfo();
1649 int NumBytes = (int) MFI->getStackSize();
1651 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1652 << getFunctionNumber() << "[" << NumBytes << "];\n";
1653 if (nvptxSubtarget.is64Bit()) {
1654 O << "\t.reg .b64 \t%SP;\n";
1655 O << "\t.reg .b64 \t%SPL;\n";
1657 O << "\t.reg .b32 \t%SP;\n";
1658 O << "\t.reg .b32 \t%SPL;\n";
1662 // Go through all virtual registers to establish the mapping between the
1664 // register number and the per class virtual register number.
1665 // We use the per class virtual register number in the ptx output.
1666 unsigned int numVRs = MRI->getNumVirtRegs();
1667 for (unsigned i = 0; i < numVRs; i++) {
1668 unsigned int vr = TRI->index2VirtReg(i);
1669 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1670 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1671 int n = regmap.size();
1672 regmap.insert(std::make_pair(vr, n + 1));
1675 // Emit register declarations
1676 // @TODO: Extract out the real register usage
1677 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1678 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1679 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1680 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1681 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1682 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1683 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1685 // Emit declaration of the virtual registers or 'physical' registers for
1686 // each register class
1687 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1688 const TargetRegisterClass *RC = TRI->getRegClass(i);
1689 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1690 std::string rcname = getNVPTXRegClassName(RC);
1691 std::string rcStr = getNVPTXRegClassStr(RC);
1692 int n = regmap.size();
1694 // Only declare those registers that may be used.
1696 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1701 OutStreamer.EmitRawText(O.str());
1704 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1705 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1707 unsigned int numHex;
1710 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1713 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1714 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1717 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1719 llvm_unreachable("unsupported fp type");
1721 APInt API = APF.bitcastToAPInt();
1722 std::string hexstr(utohexstr(API.getZExtValue()));
1724 if (hexstr.length() < numHex)
1725 O << std::string(numHex - hexstr.length(), '0');
1726 O << utohexstr(API.getZExtValue());
1729 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1730 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1731 O << CI->getValue();
1734 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1735 printFPConstant(CFP, O);
1738 if (isa<ConstantPointerNull>(CPV)) {
1742 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1743 O << *Mang->getSymbol(GVar);
1746 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1747 const Value *v = Cexpr->stripPointerCasts();
1748 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1749 O << *Mang->getSymbol(GVar);
1752 O << *LowerConstant(CPV, *this);
1756 llvm_unreachable("Not scalar type found in printScalarConstant()");
1759 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1760 AggBuffer *aggBuffer) {
1762 const DataLayout *TD = TM.getDataLayout();
1764 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1765 int s = TD->getTypeAllocSize(CPV->getType());
1768 aggBuffer->addZeros(s);
1773 switch (CPV->getType()->getTypeID()) {
1775 case Type::IntegerTyID: {
1776 const Type *ETy = CPV->getType();
1777 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1779 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1781 aggBuffer->addBytes(ptr, 1, Bytes);
1782 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1783 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1784 ptr = (unsigned char *)&int16;
1785 aggBuffer->addBytes(ptr, 2, Bytes);
1786 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1787 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1788 int int32 = (int)(constInt->getZExtValue());
1789 ptr = (unsigned char *)&int32;
1790 aggBuffer->addBytes(ptr, 4, Bytes);
1792 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1793 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1794 ConstantFoldConstantExpression(Cexpr, TD))) {
1795 int int32 = (int)(constInt->getZExtValue());
1796 ptr = (unsigned char *)&int32;
1797 aggBuffer->addBytes(ptr, 4, Bytes);
1800 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1801 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1802 aggBuffer->addSymbol(v);
1803 aggBuffer->addZeros(4);
1807 llvm_unreachable("unsupported integer const type");
1808 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1809 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1810 long long int64 = (long long)(constInt->getZExtValue());
1811 ptr = (unsigned char *)&int64;
1812 aggBuffer->addBytes(ptr, 8, Bytes);
1814 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1815 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1816 ConstantFoldConstantExpression(Cexpr, TD))) {
1817 long long int64 = (long long)(constInt->getZExtValue());
1818 ptr = (unsigned char *)&int64;
1819 aggBuffer->addBytes(ptr, 8, Bytes);
1822 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1823 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1824 aggBuffer->addSymbol(v);
1825 aggBuffer->addZeros(8);
1829 llvm_unreachable("unsupported integer const type");
1831 llvm_unreachable("unsupported integer const type");
1834 case Type::FloatTyID:
1835 case Type::DoubleTyID: {
1836 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1837 const Type *Ty = CFP->getType();
1838 if (Ty == Type::getFloatTy(CPV->getContext())) {
1839 float float32 = (float) CFP->getValueAPF().convertToFloat();
1840 ptr = (unsigned char *)&float32;
1841 aggBuffer->addBytes(ptr, 4, Bytes);
1842 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1843 double float64 = CFP->getValueAPF().convertToDouble();
1844 ptr = (unsigned char *)&float64;
1845 aggBuffer->addBytes(ptr, 8, Bytes);
1847 llvm_unreachable("unsupported fp const type");
1851 case Type::PointerTyID: {
1852 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1853 aggBuffer->addSymbol(GVar);
1854 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1855 const Value *v = Cexpr->stripPointerCasts();
1856 aggBuffer->addSymbol(v);
1858 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1859 aggBuffer->addZeros(s);
1863 case Type::ArrayTyID:
1864 case Type::VectorTyID:
1865 case Type::StructTyID: {
1866 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1867 isa<ConstantStruct>(CPV)) {
1868 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1869 bufferAggregateConstant(CPV, aggBuffer);
1870 if (Bytes > ElementSize)
1871 aggBuffer->addZeros(Bytes - ElementSize);
1872 } else if (isa<ConstantAggregateZero>(CPV))
1873 aggBuffer->addZeros(Bytes);
1875 llvm_unreachable("Unexpected Constant type");
1880 llvm_unreachable("unsupported type");
1884 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1885 AggBuffer *aggBuffer) {
1886 const DataLayout *TD = TM.getDataLayout();
1890 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1891 if (CPV->getNumOperands())
1892 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1893 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1897 if (const ConstantDataSequential *CDS =
1898 dyn_cast<ConstantDataSequential>(CPV)) {
1899 if (CDS->getNumElements())
1900 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1901 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1906 if (isa<ConstantStruct>(CPV)) {
1907 if (CPV->getNumOperands()) {
1908 StructType *ST = cast<StructType>(CPV->getType());
1909 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1911 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1912 TD->getTypeAllocSize(ST) -
1913 TD->getStructLayout(ST)->getElementOffset(i);
1915 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1916 TD->getStructLayout(ST)->getElementOffset(i);
1917 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1922 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1925 // buildTypeNameMap - Run through symbol table looking for type names.
1928 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1930 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1932 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1933 !PI->second.compare("struct._image2d_t") ||
1934 !PI->second.compare("struct._image3d_t")))
1941 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1942 switch (MI.getOpcode()) {
1945 case NVPTX::CallArgBeginInst:
1946 case NVPTX::CallArgEndInst0:
1947 case NVPTX::CallArgEndInst1:
1948 case NVPTX::CallArgF32:
1949 case NVPTX::CallArgF64:
1950 case NVPTX::CallArgI16:
1951 case NVPTX::CallArgI32:
1952 case NVPTX::CallArgI32imm:
1953 case NVPTX::CallArgI64:
1954 case NVPTX::CallArgParam:
1955 case NVPTX::CallVoidInst:
1956 case NVPTX::CallVoidInstReg:
1957 case NVPTX::Callseq_End:
1958 case NVPTX::CallVoidInstReg64:
1959 case NVPTX::DeclareParamInst:
1960 case NVPTX::DeclareRetMemInst:
1961 case NVPTX::DeclareRetRegInst:
1962 case NVPTX::DeclareRetScalarInst:
1963 case NVPTX::DeclareScalarParamInst:
1964 case NVPTX::DeclareScalarRegInst:
1965 case NVPTX::StoreParamF32:
1966 case NVPTX::StoreParamF64:
1967 case NVPTX::StoreParamI16:
1968 case NVPTX::StoreParamI32:
1969 case NVPTX::StoreParamI64:
1970 case NVPTX::StoreParamI8:
1971 case NVPTX::StoreRetvalF32:
1972 case NVPTX::StoreRetvalF64:
1973 case NVPTX::StoreRetvalI16:
1974 case NVPTX::StoreRetvalI32:
1975 case NVPTX::StoreRetvalI64:
1976 case NVPTX::StoreRetvalI8:
1977 case NVPTX::LastCallArgF32:
1978 case NVPTX::LastCallArgF64:
1979 case NVPTX::LastCallArgI16:
1980 case NVPTX::LastCallArgI32:
1981 case NVPTX::LastCallArgI32imm:
1982 case NVPTX::LastCallArgI64:
1983 case NVPTX::LastCallArgParam:
1984 case NVPTX::LoadParamMemF32:
1985 case NVPTX::LoadParamMemF64:
1986 case NVPTX::LoadParamMemI16:
1987 case NVPTX::LoadParamMemI32:
1988 case NVPTX::LoadParamMemI64:
1989 case NVPTX::LoadParamMemI8:
1990 case NVPTX::PrototypeInst:
1991 case NVPTX::DBG_VALUE:
1997 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1999 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2000 unsigned AsmVariant,
2001 const char *ExtraCode, raw_ostream &O) {
2002 if (ExtraCode && ExtraCode[0]) {
2003 if (ExtraCode[1] != 0)
2004 return true; // Unknown modifier.
2006 switch (ExtraCode[0]) {
2008 // See if this is a generic print operand
2009 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2015 printOperand(MI, OpNo, O);
2020 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2021 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2022 const char *ExtraCode, raw_ostream &O) {
2023 if (ExtraCode && ExtraCode[0])
2024 return true; // Unknown modifier
2027 printMemOperand(MI, OpNo, O);
2033 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2034 raw_ostream &O, const char *Modifier) {
2035 const MachineOperand &MO = MI->getOperand(opNum);
2036 switch (MO.getType()) {
2037 case MachineOperand::MO_Register:
2038 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2039 if (MO.getReg() == NVPTX::VRDepot)
2040 O << DEPOTNAME << getFunctionNumber();
2042 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2044 emitVirtualRegister(MO.getReg(), false, O);
2048 case MachineOperand::MO_Immediate:
2051 else if (strstr(Modifier, "vec") == Modifier)
2052 printVecModifiedImmediate(MO, Modifier, O);
2055 "Don't know how to handle modifier on immediate operand");
2058 case MachineOperand::MO_FPImmediate:
2059 printFPConstant(MO.getFPImm(), O);
2062 case MachineOperand::MO_GlobalAddress:
2063 O << *Mang->getSymbol(MO.getGlobal());
2066 case MachineOperand::MO_ExternalSymbol: {
2067 const char *symbname = MO.getSymbolName();
2068 if (strstr(symbname, ".PARAM") == symbname) {
2070 sscanf(symbname + 6, "%u[];", &index);
2071 printParamName(index, O);
2072 } else if (strstr(symbname, ".HLPPARAM") == symbname) {
2074 sscanf(symbname + 9, "%u[];", &index);
2075 O << *CurrentFnSym << "_param_" << index << "_offset";
2081 case MachineOperand::MO_MachineBasicBlock:
2082 O << *MO.getMBB()->getSymbol();
2086 llvm_unreachable("Operand type not supported.");
2090 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2091 raw_ostream &O, const char *Modifier) {
2092 printOperand(MI, opNum, O);
2094 if (Modifier && !strcmp(Modifier, "add")) {
2096 printOperand(MI, opNum + 1, O);
2098 if (MI->getOperand(opNum + 1).isImm() &&
2099 MI->getOperand(opNum + 1).getImm() == 0)
2100 return; // don't print ',0' or '+0'
2102 printOperand(MI, opNum + 1, O);
2107 // Force static initialization.
2108 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2109 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2110 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2113 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2114 std::stringstream temp;
2115 LineReader *reader = this->getReader(filename.str());
2117 temp << filename.str();
2121 temp << reader->readLine(line);
2123 this->OutStreamer.EmitRawText(Twine(temp.str()));
2126 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2127 if (reader == NULL) {
2128 reader = new LineReader(filename);
2131 if (reader->fileName() != filename) {
2133 reader = new LineReader(filename);
2139 std::string LineReader::readLine(unsigned lineNum) {
2140 if (lineNum < theCurLine) {
2142 fstr.seekg(0, std::ios::beg);
2144 while (theCurLine < lineNum) {
2145 fstr.getline(buff, 500);
2151 // Force static initialization.
2152 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2153 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2154 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);