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 "NVPTXNumRegisters.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "cl_common_defines.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Assembly/Writer.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/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TimeValue.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "NVPTXGenAsmWriter.inc"
52 bool RegAllocNilUsed = true;
54 #define DEPOTNAME "__local_depot"
57 EmitLineNumbers("nvptx-emit-line-numbers",
58 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
61 namespace llvm { bool InterleaveSrcInPtx = false; }
63 static cl::opt<bool, true>
64 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
65 cl::desc("NVPTX Specific: Emit source line in ptx file"),
66 cl::location(llvm::InterleaveSrcInPtx));
69 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
71 void DiscoverDependentGlobals(Value *V, DenseSet<GlobalVariable *> &Globals) {
72 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
75 if (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 GlobalVariable *GV, SmallVectorImpl<GlobalVariable *> &Order,
88 DenseSet<GlobalVariable *> &Visited, DenseSet<GlobalVariable *> &Visiting) {
89 // Have we already visited this one?
90 if (Visited.count(GV))
93 // Do we have a circular dependency?
94 if (Visiting.count(GV))
95 report_fatal_error("Circular dependency found in global variable set");
97 // Start visiting this global
100 // Make sure we visit all dependents first
101 DenseSet<GlobalVariable *> Others;
102 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
103 DiscoverDependentGlobals(GV->getOperand(i), Others);
105 for (DenseSet<GlobalVariable *>::iterator I = Others.begin(),
108 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
110 // Now we can visit ourself
117 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
118 // cannot just link to the existing version.
119 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
121 using namespace nvptx;
122 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
123 MCContext &Ctx = AP.OutContext;
125 if (CV->isNullValue() || isa<UndefValue>(CV))
126 return MCConstantExpr::Create(0, Ctx);
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
129 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
131 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
132 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
134 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
135 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
137 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
139 llvm_unreachable("Unknown constant value to lower!");
141 switch (CE->getOpcode()) {
143 // If the code isn't optimized, there may be outstanding folding
144 // opportunities. Attempt to fold the expression using DataLayout as a
145 // last resort before giving up.
146 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
148 return LowerConstant(C, AP);
150 // Otherwise report the problem to the user.
153 raw_string_ostream OS(S);
154 OS << "Unsupported expression in static initializer: ";
155 WriteAsOperand(OS, CE, /*PrintType=*/ false,
156 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
157 report_fatal_error(OS.str());
159 case Instruction::GetElementPtr: {
160 const DataLayout &TD = *AP.TM.getDataLayout();
161 // Generate a symbolic expression for the byte address
162 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
163 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
165 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
169 int64_t Offset = OffsetAI.getSExtValue();
170 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
174 case Instruction::Trunc:
175 // We emit the value and depend on the assembler to truncate the generated
176 // expression properly. This is important for differences between
177 // blockaddress labels. Since the two labels are in the same function, it
178 // is reasonable to treat their delta as a 32-bit value.
180 case Instruction::BitCast:
181 return LowerConstant(CE->getOperand(0), AP);
183 case Instruction::IntToPtr: {
184 const DataLayout &TD = *AP.TM.getDataLayout();
185 // Handle casts to pointers by changing them into casts to the appropriate
186 // integer type. This promotes constant folding and simplifies this code.
187 Constant *Op = CE->getOperand(0);
188 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
190 return LowerConstant(Op, AP);
193 case Instruction::PtrToInt: {
194 const DataLayout &TD = *AP.TM.getDataLayout();
195 // Support only foldable casts to/from pointers that can be eliminated by
196 // changing the pointer to the appropriately sized integer type.
197 Constant *Op = CE->getOperand(0);
198 Type *Ty = CE->getType();
200 const MCExpr *OpExpr = LowerConstant(Op, AP);
202 // We can emit the pointer value into this slot if the slot is an
203 // integer slot equal to the size of the pointer.
204 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
207 // Otherwise the pointer is smaller than the resultant integer, mask off
208 // the high bits so we are sure to get a proper truncation if the input is
210 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
211 const MCExpr *MaskExpr =
212 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
213 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
216 // The MC library also has a right-shift operator, but it isn't consistently
217 // signed or unsigned between different targets.
218 case Instruction::Add:
219 case Instruction::Sub:
220 case Instruction::Mul:
221 case Instruction::SDiv:
222 case Instruction::SRem:
223 case Instruction::Shl:
224 case Instruction::And:
225 case Instruction::Or:
226 case Instruction::Xor: {
227 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
228 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
229 switch (CE->getOpcode()) {
231 llvm_unreachable("Unknown binary operator constant cast expr");
232 case Instruction::Add:
233 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
234 case Instruction::Sub:
235 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
236 case Instruction::Mul:
237 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
238 case Instruction::SDiv:
239 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
240 case Instruction::SRem:
241 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
242 case Instruction::Shl:
243 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
244 case Instruction::And:
245 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
246 case Instruction::Or:
247 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
248 case Instruction::Xor:
249 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
255 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
256 if (!EmitLineNumbers)
261 DebugLoc curLoc = MI.getDebugLoc();
263 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
266 if (prevDebugLoc == curLoc)
269 prevDebugLoc = curLoc;
271 if (curLoc.isUnknown())
274 const MachineFunction *MF = MI.getParent()->getParent();
275 //const TargetMachine &TM = MF->getTarget();
277 const LLVMContext &ctx = MF->getFunction()->getContext();
278 DIScope Scope(curLoc.getScope(ctx));
283 StringRef fileName(Scope.getFilename());
284 StringRef dirName(Scope.getDirectory());
285 SmallString<128> FullPathName = dirName;
286 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
287 sys::path::append(FullPathName, fileName);
288 fileName = FullPathName.str();
291 if (filenameMap.find(fileName.str()) == filenameMap.end())
294 // Emit the line from the source file.
295 if (llvm::InterleaveSrcInPtx)
296 this->emitSrcInText(fileName.str(), curLoc.getLine());
298 std::stringstream temp;
299 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
300 << " " << curLoc.getCol();
301 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
304 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
305 SmallString<128> Str;
306 raw_svector_ostream OS(Str);
307 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
308 emitLineNumberAsDotLoc(*MI);
309 printInstruction(MI, OS);
310 OutStreamer.EmitRawText(OS.str());
313 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
314 const DataLayout *TD = TM.getDataLayout();
315 const TargetLowering *TLI = TM.getTargetLowering();
317 Type *Ty = F->getReturnType();
319 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
321 if (Ty->getTypeID() == Type::VoidTyID)
327 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
329 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
330 size = ITy->getBitWidth();
334 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
335 size = Ty->getPrimitiveSizeInBits();
338 O << ".param .b" << size << " func_retval0";
339 } else if (isa<PointerType>(Ty)) {
340 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
343 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
344 SmallVector<EVT, 16> vtparts;
345 ComputeValueVTs(*TLI, Ty, vtparts);
346 unsigned totalsz = 0;
347 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
349 EVT elemtype = vtparts[i];
350 if (vtparts[i].isVector()) {
351 elems = vtparts[i].getVectorNumElements();
352 elemtype = vtparts[i].getVectorElementType();
354 for (unsigned j = 0, je = elems; j != je; ++j) {
355 unsigned sz = elemtype.getSizeInBits();
356 if (elemtype.isInteger() && (sz < 8))
361 unsigned retAlignment = 0;
362 if (!llvm::getAlign(*F, 0, retAlignment))
363 retAlignment = TD->getABITypeAlignment(Ty);
364 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
367 assert(false && "Unknown return type");
370 SmallVector<EVT, 16> vtparts;
371 ComputeValueVTs(*TLI, Ty, vtparts);
373 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
375 EVT elemtype = vtparts[i];
376 if (vtparts[i].isVector()) {
377 elems = vtparts[i].getVectorNumElements();
378 elemtype = vtparts[i].getVectorElementType();
381 for (unsigned j = 0, je = elems; j != je; ++j) {
382 unsigned sz = elemtype.getSizeInBits();
383 if (elemtype.isInteger() && (sz < 32))
385 O << ".reg .b" << sz << " func_retval" << idx;
398 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
400 const Function *F = MF.getFunction();
401 printReturnValStr(F, O);
404 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
405 SmallString<128> Str;
406 raw_svector_ostream O(Str);
409 MRI = &MF->getRegInfo();
410 F = MF->getFunction();
411 emitLinkageDirective(F, O);
412 if (llvm::isKernelFunction(*F))
416 printReturnValStr(*MF, O);
421 emitFunctionParamList(*MF, O);
423 if (llvm::isKernelFunction(*F))
424 emitKernelFunctionDirectives(*F, O);
426 OutStreamer.EmitRawText(O.str());
428 prevDebugLoc = DebugLoc();
431 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
432 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
433 unsigned numRegClasses = TRI.getNumRegClasses();
434 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses + 1];
435 OutStreamer.EmitRawText(StringRef("{\n"));
436 setAndEmitFunctionVirtualRegisters(*MF);
438 SmallString<128> Str;
439 raw_svector_ostream O(Str);
440 emitDemotedVars(MF->getFunction(), O);
441 OutStreamer.EmitRawText(O.str());
444 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
445 OutStreamer.EmitRawText(StringRef("}\n"));
446 delete[] VRidGlobal2LocalMap;
449 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
450 raw_ostream &O) const {
451 // If the NVVM IR has some of reqntid* specified, then output
452 // the reqntid directive, and set the unspecified ones to 1.
453 // If none of reqntid* is specified, don't output reqntid directive.
454 unsigned reqntidx, reqntidy, reqntidz;
455 bool specified = false;
456 if (llvm::getReqNTIDx(F, reqntidx) == false)
460 if (llvm::getReqNTIDy(F, reqntidy) == false)
464 if (llvm::getReqNTIDz(F, reqntidz) == false)
470 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
473 // If the NVVM IR has some of maxntid* specified, then output
474 // the maxntid directive, and set the unspecified ones to 1.
475 // If none of maxntid* is specified, don't output maxntid directive.
476 unsigned maxntidx, maxntidy, maxntidz;
478 if (llvm::getMaxNTIDx(F, maxntidx) == false)
482 if (llvm::getMaxNTIDy(F, maxntidy) == false)
486 if (llvm::getMaxNTIDz(F, maxntidz) == false)
492 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
496 if (llvm::getMinCTASm(F, mincta))
497 O << ".minnctapersm " << mincta << "\n";
500 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
502 const TargetRegisterClass *RC = MRI->getRegClass(vr);
503 unsigned id = RC->getID();
505 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[id];
506 unsigned mapped_vr = regmap[vr];
509 O << getNVPTXRegClassStr(RC) << mapped_vr;
512 report_fatal_error("Bad register!");
515 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
517 getVirtualRegisterName(vr, isVec, O);
520 void NVPTXAsmPrinter::printVecModifiedImmediate(
521 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
522 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
523 int Imm = (int) MO.getImm();
524 if (0 == strcmp(Modifier, "vecelem"))
525 O << "_" << vecelem[Imm];
526 else if (0 == strcmp(Modifier, "vecv4comm1")) {
527 if ((Imm < 0) || (Imm > 3))
529 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
530 if ((Imm < 4) || (Imm > 7))
532 } else if (0 == strcmp(Modifier, "vecv4pos")) {
535 O << "_" << vecelem[Imm % 4];
536 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
537 if ((Imm < 0) || (Imm > 1))
539 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
540 if ((Imm < 2) || (Imm > 3))
542 } else if (0 == strcmp(Modifier, "vecv2pos")) {
545 O << "_" << vecelem[Imm % 2];
547 llvm_unreachable("Unknown Modifier on immediate operand");
550 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
551 raw_ostream &O, const char *Modifier) {
552 const MachineOperand &MO = MI->getOperand(opNum);
553 switch (MO.getType()) {
554 case MachineOperand::MO_Register:
555 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
556 if (MO.getReg() == NVPTX::VRDepot)
557 O << DEPOTNAME << getFunctionNumber();
559 O << getRegisterName(MO.getReg());
562 emitVirtualRegister(MO.getReg(), false, O);
564 if (strcmp(Modifier, "vecfull") == 0)
565 emitVirtualRegister(MO.getReg(), true, O);
568 "Don't know how to handle the modifier on virtual register.");
573 case MachineOperand::MO_Immediate:
576 else if (strstr(Modifier, "vec") == Modifier)
577 printVecModifiedImmediate(MO, Modifier, O);
580 "Don't know how to handle modifier on immediate operand");
583 case MachineOperand::MO_FPImmediate:
584 printFPConstant(MO.getFPImm(), O);
587 case MachineOperand::MO_GlobalAddress:
588 O << *Mang->getSymbol(MO.getGlobal());
591 case MachineOperand::MO_ExternalSymbol: {
592 const char *symbname = MO.getSymbolName();
593 if (strstr(symbname, ".PARAM") == symbname) {
595 sscanf(symbname + 6, "%u[];", &index);
596 printParamName(index, O);
597 } else if (strstr(symbname, ".HLPPARAM") == symbname) {
599 sscanf(symbname + 9, "%u[];", &index);
600 O << *CurrentFnSym << "_param_" << index << "_offset";
606 case MachineOperand::MO_MachineBasicBlock:
607 O << *MO.getMBB()->getSymbol();
611 llvm_unreachable("Operand type not supported.");
615 void NVPTXAsmPrinter::printImplicitDef(const MachineInstr *MI,
616 raw_ostream &O) const {
618 O << "\t// Implicit def :";
619 //printOperand(MI, 0);
624 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
625 raw_ostream &O, const char *Modifier) {
626 printOperand(MI, opNum, O);
628 if (Modifier && !strcmp(Modifier, "add")) {
630 printOperand(MI, opNum + 1, O);
632 if (MI->getOperand(opNum + 1).isImm() &&
633 MI->getOperand(opNum + 1).getImm() == 0)
634 return; // don't print ',0' or '+0'
636 printOperand(MI, opNum + 1, O);
640 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
641 raw_ostream &O, const char *Modifier) {
643 const MachineOperand &MO = MI->getOperand(opNum);
644 int Imm = (int) MO.getImm();
645 if (!strcmp(Modifier, "volatile")) {
648 } else if (!strcmp(Modifier, "addsp")) {
650 case NVPTX::PTXLdStInstCode::GLOBAL:
653 case NVPTX::PTXLdStInstCode::SHARED:
656 case NVPTX::PTXLdStInstCode::LOCAL:
659 case NVPTX::PTXLdStInstCode::PARAM:
662 case NVPTX::PTXLdStInstCode::CONSTANT:
665 case NVPTX::PTXLdStInstCode::GENERIC:
666 if (!nvptxSubtarget.hasGenericLdSt())
670 llvm_unreachable("Wrong Address Space");
672 } else if (!strcmp(Modifier, "sign")) {
673 if (Imm == NVPTX::PTXLdStInstCode::Signed)
675 else if (Imm == NVPTX::PTXLdStInstCode::Unsigned)
679 } else if (!strcmp(Modifier, "vec")) {
680 if (Imm == NVPTX::PTXLdStInstCode::V2)
682 else if (Imm == NVPTX::PTXLdStInstCode::V4)
685 llvm_unreachable("Unknown Modifier");
687 llvm_unreachable("Empty Modifier");
690 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
692 emitLinkageDirective(F, O);
693 if (llvm::isKernelFunction(*F))
697 printReturnValStr(F, O);
698 O << *CurrentFnSym << "\n";
699 emitFunctionParamList(F, O);
703 static bool usedInGlobalVarDef(const Constant *C) {
707 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
708 if (GV->getName().str() == "llvm.used")
713 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
715 const Constant *C = dyn_cast<Constant>(*ui);
716 if (usedInGlobalVarDef(C))
722 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
723 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
724 if (othergv->getName().str() == "llvm.used")
728 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
729 if (instr->getParent() && instr->getParent()->getParent()) {
730 const Function *curFunc = instr->getParent()->getParent();
731 if (oneFunc && (curFunc != oneFunc))
739 if (const MDNode *md = dyn_cast<MDNode>(U))
740 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
741 (md->getName().str() == "llvm.dbg.sp")))
744 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
746 if (usedInOneFunc(*ui, oneFunc) == false)
752 /* Find out if a global variable can be demoted to local scope.
753 * Currently, this is valid for CUDA shared variables, which have local
754 * scope and global lifetime. So the conditions to check are :
755 * 1. Is the global variable in shared address space?
756 * 2. Does it have internal linkage?
757 * 3. Is the global variable referenced only in one function?
759 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
760 if (gv->hasInternalLinkage() == false)
762 const PointerType *Pty = gv->getType();
763 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
766 const Function *oneFunc = 0;
768 bool flag = usedInOneFunc(gv, oneFunc);
777 static bool useFuncSeen(const Constant *C,
778 llvm::DenseMap<const Function *, bool> &seenMap) {
779 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
781 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
782 if (useFuncSeen(cu, seenMap))
784 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
785 const BasicBlock *bb = I->getParent();
788 const Function *caller = bb->getParent();
791 if (seenMap.find(caller) != seenMap.end())
798 void NVPTXAsmPrinter::emitDeclarations(Module &M, raw_ostream &O) {
799 llvm::DenseMap<const Function *, bool> seenMap;
800 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
801 const Function *F = FI;
803 if (F->isDeclaration()) {
806 if (F->getIntrinsicID())
808 CurrentFnSym = Mang->getSymbol(F);
809 emitDeclaration(F, O);
812 for (Value::const_use_iterator iter = F->use_begin(),
813 iterEnd = F->use_end();
814 iter != iterEnd; ++iter) {
815 if (const Constant *C = dyn_cast<Constant>(*iter)) {
816 if (usedInGlobalVarDef(C)) {
817 // The use is in the initialization of a global variable
818 // that is a function pointer, so print a declaration
819 // for the original function
820 CurrentFnSym = Mang->getSymbol(F);
821 emitDeclaration(F, O);
824 // Emit a declaration of this function if the function that
825 // uses this constant expr has already been seen.
826 if (useFuncSeen(C, seenMap)) {
827 CurrentFnSym = Mang->getSymbol(F);
828 emitDeclaration(F, O);
833 if (!isa<Instruction>(*iter))
835 const Instruction *instr = cast<Instruction>(*iter);
836 const BasicBlock *bb = instr->getParent();
839 const Function *caller = bb->getParent();
843 // If a caller has already been seen, then the caller is
844 // appearing in the module before the callee. so print out
845 // a declaration for the callee.
846 if (seenMap.find(caller) != seenMap.end()) {
847 CurrentFnSym = Mang->getSymbol(F);
848 emitDeclaration(F, O);
856 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
857 DebugInfoFinder DbgFinder;
858 DbgFinder.processModule(M);
861 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
862 E = DbgFinder.compile_unit_end();
864 DICompileUnit DIUnit(*I);
865 StringRef Filename(DIUnit.getFilename());
866 StringRef Dirname(DIUnit.getDirectory());
867 SmallString<128> FullPathName = Dirname;
868 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
869 sys::path::append(FullPathName, Filename);
870 Filename = FullPathName.str();
872 if (filenameMap.find(Filename.str()) != filenameMap.end())
874 filenameMap[Filename.str()] = i;
875 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
879 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
880 E = DbgFinder.subprogram_end();
883 StringRef Filename(SP.getFilename());
884 StringRef Dirname(SP.getDirectory());
885 SmallString<128> FullPathName = Dirname;
886 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
887 sys::path::append(FullPathName, Filename);
888 Filename = FullPathName.str();
890 if (filenameMap.find(Filename.str()) != filenameMap.end())
892 filenameMap[Filename.str()] = i;
897 bool NVPTXAsmPrinter::doInitialization(Module &M) {
899 SmallString<128> Str1;
900 raw_svector_ostream OS1(Str1);
902 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
903 MMI->AnalyzeModule(M);
905 // We need to call the parent's one explicitly.
906 //bool Result = AsmPrinter::doInitialization(M);
908 // Initialize TargetLoweringObjectFile.
909 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
910 .Initialize(OutContext, TM);
912 Mang = new Mangler(OutContext, *TM.getDataLayout());
914 // Emit header before any dwarf directives are emitted below.
916 OutStreamer.EmitRawText(OS1.str());
918 // Already commented out
919 //bool Result = AsmPrinter::doInitialization(M);
921 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
922 recordAndEmitFilenames(M);
924 SmallString<128> Str2;
925 raw_svector_ostream OS2(Str2);
927 emitDeclarations(M, OS2);
929 // As ptxas does not support forward references of globals, we need to first
930 // sort the list of module-level globals in def-use order. We visit each
931 // global variable in order, and ensure that we emit it *after* its dependent
932 // globals. We use a little extra memory maintaining both a set and a list to
933 // have fast searches while maintaining a strict ordering.
934 SmallVector<GlobalVariable *, 8> Globals;
935 DenseSet<GlobalVariable *> GVVisited;
936 DenseSet<GlobalVariable *> GVVisiting;
938 // Visit each global variable, in order
939 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
941 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
943 assert(GVVisited.size() == M.getGlobalList().size() &&
944 "Missed a global variable");
945 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
947 // Print out module-level global variables in proper order
948 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
949 printModuleLevelGV(Globals[i], OS2);
953 OutStreamer.EmitRawText(OS2.str());
954 return false; // success
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) {
992 // XXX Temproarily remove global variables so that doFinalization() will not
993 // emit them again (global variables are emitted at beginning).
995 Module::GlobalListType &global_list = M.getGlobalList();
996 int i, n = global_list.size();
997 GlobalVariable **gv_array = new GlobalVariable *[n];
999 // first, back-up GlobalVariable in gv_array
1001 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1003 gv_array[i++] = &*I;
1005 // second, empty global_list
1006 while (!global_list.empty())
1007 global_list.remove(global_list.begin());
1009 // call doFinalization
1010 bool ret = AsmPrinter::doFinalization(M);
1012 // now we restore global variables
1013 for (i = 0; i < n; i++)
1014 global_list.insert(global_list.end(), gv_array[i]);
1019 //bool Result = AsmPrinter::doFinalization(M);
1020 // Instead of calling the parents doFinalization, we may
1021 // clone parents doFinalization and customize here.
1022 // Currently, we if NVISA out the EmitGlobals() in
1023 // parent's doFinalization, which is too intrusive.
1025 // Same for the doInitialization.
1029 // This function emits appropriate linkage directives for
1030 // functions and global variables.
1032 // extern function declaration -> .extern
1033 // extern function definition -> .visible
1034 // external global variable with init -> .visible
1035 // external without init -> .extern
1036 // appending -> not allowed, assert.
1038 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1040 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1041 if (V->hasExternalLinkage()) {
1042 if (isa<GlobalVariable>(V)) {
1043 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1045 if (GVar->hasInitializer())
1050 } else if (V->isDeclaration())
1054 } else if (V->hasAppendingLinkage()) {
1056 msg.append("Error: ");
1057 msg.append("Symbol ");
1059 msg.append(V->getName().str());
1060 msg.append("has unsupported appending linkage type");
1061 llvm_unreachable(msg.c_str());
1066 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable *GVar, raw_ostream &O,
1067 bool processDemoted) {
1070 if (GVar->hasSection()) {
1071 if (GVar->getSection() == "llvm.metadata")
1075 const DataLayout *TD = TM.getDataLayout();
1077 // GlobalVariables are always constant pointers themselves.
1078 const PointerType *PTy = GVar->getType();
1079 Type *ETy = PTy->getElementType();
1081 if (GVar->hasExternalLinkage()) {
1082 if (GVar->hasInitializer())
1088 if (llvm::isTexture(*GVar)) {
1089 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1093 if (llvm::isSurface(*GVar)) {
1094 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1098 if (GVar->isDeclaration()) {
1099 // (extern) declarations, no definition or initializer
1100 // Currently the only known declaration is for an automatic __local
1101 // (.shared) promoted to global.
1102 emitPTXGlobalVariable(GVar, O);
1107 if (llvm::isSampler(*GVar)) {
1108 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1110 Constant *Initializer = NULL;
1111 if (GVar->hasInitializer())
1112 Initializer = GVar->getInitializer();
1113 ConstantInt *CI = NULL;
1115 CI = dyn_cast<ConstantInt>(Initializer);
1117 unsigned sample = CI->getZExtValue();
1122 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1124 O << "addr_mode_" << i << " = ";
1130 O << "clamp_to_border";
1133 O << "clamp_to_edge";
1144 O << "filter_mode = ";
1145 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1153 assert(0 && "Anisotropic filtering is not supported");
1158 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1159 O << ", force_unnormalized_coords = 1";
1168 if (GVar->hasPrivateLinkage()) {
1170 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1173 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1174 if (!strncmp(GVar->getName().data(), "filename", 8))
1176 if (GVar->use_empty())
1180 const Function *demotedFunc = 0;
1181 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1182 O << "// " << GVar->getName().str() << " has been demoted\n";
1183 if (localDecls.find(demotedFunc) != localDecls.end())
1184 localDecls[demotedFunc].push_back(GVar);
1186 std::vector<GlobalVariable *> temp;
1187 temp.push_back(GVar);
1188 localDecls[demotedFunc] = temp;
1194 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1195 if (GVar->getAlignment() == 0)
1196 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1198 O << " .align " << GVar->getAlignment();
1200 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1202 // Special case: ABI requires that we use .u8 for predicates
1203 if (ETy->isIntegerTy(1))
1206 O << getPTXFundamentalTypeStr(ETy, false);
1208 O << *Mang->getSymbol(GVar);
1210 // Ptx allows variable initilization only for constant and global state
1212 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1213 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1214 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1215 GVar->hasInitializer()) {
1216 Constant *Initializer = GVar->getInitializer();
1217 if (!Initializer->isNullValue()) {
1219 printScalarConstant(Initializer, O);
1223 unsigned int ElementSize = 0;
1225 // Although PTX has direct support for struct type and array type and
1226 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1227 // targets that support these high level field accesses. Structs, arrays
1228 // and vectors are lowered into arrays of bytes.
1229 switch (ETy->getTypeID()) {
1230 case Type::StructTyID:
1231 case Type::ArrayTyID:
1232 case Type::VectorTyID:
1233 ElementSize = TD->getTypeStoreSize(ETy);
1234 // Ptx allows variable initilization only for constant and
1235 // global state spaces.
1236 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1237 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1238 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1239 GVar->hasInitializer()) {
1240 Constant *Initializer = GVar->getInitializer();
1241 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1242 AggBuffer aggBuffer(ElementSize, O, *this);
1243 bufferAggregateConstant(Initializer, &aggBuffer);
1244 if (aggBuffer.numSymbols) {
1245 if (nvptxSubtarget.is64Bit()) {
1246 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1247 O << ElementSize / 8;
1249 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1250 O << ElementSize / 4;
1254 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1262 O << " .b8 " << *Mang->getSymbol(GVar);
1270 O << " .b8 " << *Mang->getSymbol(GVar);
1279 assert(0 && "type not supported yet");
1286 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1287 if (localDecls.find(f) == localDecls.end())
1290 std::vector<GlobalVariable *> &gvars = localDecls[f];
1292 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1293 O << "\t// demoted variable\n\t";
1294 printModuleLevelGV(gvars[i], O, true);
1298 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1299 raw_ostream &O) const {
1300 switch (AddressSpace) {
1301 case llvm::ADDRESS_SPACE_LOCAL:
1304 case llvm::ADDRESS_SPACE_GLOBAL:
1307 case llvm::ADDRESS_SPACE_CONST:
1308 // This logic should be consistent with that in
1309 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1310 if (nvptxSubtarget.hasGenericLdSt())
1315 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1318 case llvm::ADDRESS_SPACE_SHARED:
1322 report_fatal_error("Bad address space found while emitting PTX");
1328 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1329 switch (Ty->getTypeID()) {
1331 llvm_unreachable("unexpected type");
1333 case Type::IntegerTyID: {
1334 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1337 else if (NumBits <= 64) {
1338 std::string name = "u";
1339 return name + utostr(NumBits);
1341 llvm_unreachable("Integer too large");
1346 case Type::FloatTyID:
1348 case Type::DoubleTyID:
1350 case Type::PointerTyID:
1351 if (nvptxSubtarget.is64Bit())
1361 llvm_unreachable("unexpected type");
1365 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1368 const DataLayout *TD = TM.getDataLayout();
1370 // GlobalVariables are always constant pointers themselves.
1371 const PointerType *PTy = GVar->getType();
1372 Type *ETy = PTy->getElementType();
1375 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1376 if (GVar->getAlignment() == 0)
1377 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1379 O << " .align " << GVar->getAlignment();
1381 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1383 O << getPTXFundamentalTypeStr(ETy);
1385 O << *Mang->getSymbol(GVar);
1389 int64_t ElementSize = 0;
1391 // Although PTX has direct support for struct type and array type and LLVM IR
1392 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1393 // support these high level field accesses. Structs and arrays are lowered
1394 // into arrays of bytes.
1395 switch (ETy->getTypeID()) {
1396 case Type::StructTyID:
1397 case Type::ArrayTyID:
1398 case Type::VectorTyID:
1399 ElementSize = TD->getTypeStoreSize(ETy);
1400 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1402 O << itostr(ElementSize);
1407 assert(0 && "type not supported yet");
1412 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1413 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1414 return TD->getPrefTypeAlignment(Ty);
1416 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1418 return getOpenCLAlignment(TD, ATy->getElementType());
1420 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1422 Type *ETy = VTy->getElementType();
1423 unsigned int numE = VTy->getNumElements();
1424 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1428 return numE * alignE;
1431 const StructType *STy = dyn_cast<StructType>(Ty);
1433 unsigned int alignStruct = 1;
1434 // Go through each element of the struct and find the
1435 // largest alignment.
1436 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1437 Type *ETy = STy->getElementType(i);
1438 unsigned int align = getOpenCLAlignment(TD, ETy);
1439 if (align > alignStruct)
1440 alignStruct = align;
1445 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1447 return TD->getPointerPrefAlignment();
1448 return TD->getPrefTypeAlignment(Ty);
1451 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1452 int paramIndex, raw_ostream &O) {
1453 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1454 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1455 O << *CurrentFnSym << "_param_" << paramIndex;
1457 std::string argName = I->getName();
1458 const char *p = argName.c_str();
1469 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1470 Function::const_arg_iterator I, E;
1473 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1474 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1475 O << *CurrentFnSym << "_param_" << paramIndex;
1479 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1480 if (i == paramIndex) {
1481 printParamName(I, paramIndex, O);
1485 llvm_unreachable("paramIndex out of bound");
1488 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1489 const DataLayout *TD = TM.getDataLayout();
1490 const AttributeSet &PAL = F->getAttributes();
1491 const TargetLowering *TLI = TM.getTargetLowering();
1492 Function::const_arg_iterator I, E;
1493 unsigned paramIndex = 0;
1495 bool isKernelFunc = llvm::isKernelFunction(*F);
1496 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1497 MVT thePointerTy = TLI->getPointerTy();
1501 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1502 Type *Ty = I->getType();
1509 // Handle image/sampler parameters
1510 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1511 if (llvm::isImage(*I)) {
1512 std::string sname = I->getName();
1513 if (llvm::isImageWriteOnly(*I))
1514 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1515 else // Default image is read_only
1516 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1517 } else // Should be llvm::isSampler(*I)
1518 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1523 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1524 if (Ty->isVectorTy()) {
1525 // Just print .param .b8 .align <a> .param[size];
1526 // <a> = PAL.getparamalignment
1527 // size = typeallocsize of element type
1528 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1530 align = TD->getABITypeAlignment(Ty);
1532 unsigned sz = TD->getTypeAllocSize(Ty);
1533 O << "\t.param .align " << align << " .b8 ";
1534 printParamName(I, paramIndex, O);
1535 O << "[" << sz << "]";
1540 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1543 // Special handling for pointer arguments to kernel
1544 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1546 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1547 Type *ETy = PTy->getElementType();
1548 int addrSpace = PTy->getAddressSpace();
1549 switch (addrSpace) {
1553 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1554 O << ".ptr .const ";
1556 case llvm::ADDRESS_SPACE_SHARED:
1557 O << ".ptr .shared ";
1559 case llvm::ADDRESS_SPACE_GLOBAL:
1560 case llvm::ADDRESS_SPACE_CONST:
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 ABY
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 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[RC->getID()];
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< numRegClasses; i++) {
1711 // std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[i];
1712 // const TargetRegisterClass *RC = TRI->getRegClass(i);
1713 // std::string rcname = getNVPTXRegClassName(RC);
1714 // std::string rcStr = getNVPTXRegClassStr(RC);
1715 // //int n = regmap.size();
1716 // if (!isNVPTXVectorRegClass(RC)) {
1717 // O << "\t.reg " << rcname << " \t" << rcStr << "<"
1718 // << NVPTXNumRegisters << ">;\n";
1721 // Only declare those registers that may be used. And do not emit vector
1723 // they are all elementized to scalar registers.
1724 //if (n && !isNVPTXVectorRegClass(RC)) {
1725 // if (RegAllocNilUsed) {
1726 // O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1730 // O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1731 // << "<" << 32 << ">;\n";
1736 OutStreamer.EmitRawText(O.str());
1739 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1740 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1742 unsigned int numHex;
1745 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1748 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1749 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1752 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1754 llvm_unreachable("unsupported fp type");
1756 APInt API = APF.bitcastToAPInt();
1757 std::string hexstr(utohexstr(API.getZExtValue()));
1759 if (hexstr.length() < numHex)
1760 O << std::string(numHex - hexstr.length(), '0');
1761 O << utohexstr(API.getZExtValue());
1764 void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1765 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1766 O << CI->getValue();
1769 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1770 printFPConstant(CFP, O);
1773 if (isa<ConstantPointerNull>(CPV)) {
1777 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1778 O << *Mang->getSymbol(GVar);
1781 if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1782 Value *v = Cexpr->stripPointerCasts();
1783 if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1784 O << *Mang->getSymbol(GVar);
1787 O << *LowerConstant(CPV, *this);
1791 llvm_unreachable("Not scalar type found in printScalarConstant()");
1794 void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1795 AggBuffer *aggBuffer) {
1797 const DataLayout *TD = TM.getDataLayout();
1799 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1800 int s = TD->getTypeAllocSize(CPV->getType());
1803 aggBuffer->addZeros(s);
1808 switch (CPV->getType()->getTypeID()) {
1810 case Type::IntegerTyID: {
1811 const Type *ETy = CPV->getType();
1812 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1814 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1816 aggBuffer->addBytes(ptr, 1, Bytes);
1817 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1818 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1819 ptr = (unsigned char *)&int16;
1820 aggBuffer->addBytes(ptr, 2, Bytes);
1821 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1822 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1823 int int32 = (int)(constInt->getZExtValue());
1824 ptr = (unsigned char *)&int32;
1825 aggBuffer->addBytes(ptr, 4, Bytes);
1827 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1828 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1829 ConstantFoldConstantExpression(Cexpr, TD))) {
1830 int int32 = (int)(constInt->getZExtValue());
1831 ptr = (unsigned char *)&int32;
1832 aggBuffer->addBytes(ptr, 4, Bytes);
1835 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1836 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1837 aggBuffer->addSymbol(v);
1838 aggBuffer->addZeros(4);
1842 llvm_unreachable("unsupported integer const type");
1843 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1844 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1845 long long int64 = (long long)(constInt->getZExtValue());
1846 ptr = (unsigned char *)&int64;
1847 aggBuffer->addBytes(ptr, 8, Bytes);
1849 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1850 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1851 ConstantFoldConstantExpression(Cexpr, TD))) {
1852 long long int64 = (long long)(constInt->getZExtValue());
1853 ptr = (unsigned char *)&int64;
1854 aggBuffer->addBytes(ptr, 8, Bytes);
1857 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1858 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1859 aggBuffer->addSymbol(v);
1860 aggBuffer->addZeros(8);
1864 llvm_unreachable("unsupported integer const type");
1866 llvm_unreachable("unsupported integer const type");
1869 case Type::FloatTyID:
1870 case Type::DoubleTyID: {
1871 ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1872 const Type *Ty = CFP->getType();
1873 if (Ty == Type::getFloatTy(CPV->getContext())) {
1874 float float32 = (float) CFP->getValueAPF().convertToFloat();
1875 ptr = (unsigned char *)&float32;
1876 aggBuffer->addBytes(ptr, 4, Bytes);
1877 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1878 double float64 = CFP->getValueAPF().convertToDouble();
1879 ptr = (unsigned char *)&float64;
1880 aggBuffer->addBytes(ptr, 8, Bytes);
1882 llvm_unreachable("unsupported fp const type");
1886 case Type::PointerTyID: {
1887 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1888 aggBuffer->addSymbol(GVar);
1889 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1890 Value *v = Cexpr->stripPointerCasts();
1891 aggBuffer->addSymbol(v);
1893 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1894 aggBuffer->addZeros(s);
1898 case Type::ArrayTyID:
1899 case Type::VectorTyID:
1900 case Type::StructTyID: {
1901 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1902 isa<ConstantStruct>(CPV)) {
1903 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1904 bufferAggregateConstant(CPV, aggBuffer);
1905 if (Bytes > ElementSize)
1906 aggBuffer->addZeros(Bytes - ElementSize);
1907 } else if (isa<ConstantAggregateZero>(CPV))
1908 aggBuffer->addZeros(Bytes);
1910 llvm_unreachable("Unexpected Constant type");
1915 llvm_unreachable("unsupported type");
1919 void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1920 AggBuffer *aggBuffer) {
1921 const DataLayout *TD = TM.getDataLayout();
1925 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1926 if (CPV->getNumOperands())
1927 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1928 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1932 if (const ConstantDataSequential *CDS =
1933 dyn_cast<ConstantDataSequential>(CPV)) {
1934 if (CDS->getNumElements())
1935 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1936 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1941 if (isa<ConstantStruct>(CPV)) {
1942 if (CPV->getNumOperands()) {
1943 StructType *ST = cast<StructType>(CPV->getType());
1944 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1946 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1947 TD->getTypeAllocSize(ST) -
1948 TD->getStructLayout(ST)->getElementOffset(i);
1950 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1951 TD->getStructLayout(ST)->getElementOffset(i);
1952 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1957 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1960 // buildTypeNameMap - Run through symbol table looking for type names.
1963 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1965 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1967 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1968 !PI->second.compare("struct._image2d_t") ||
1969 !PI->second.compare("struct._image3d_t")))
1975 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1977 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1978 unsigned AsmVariant,
1979 const char *ExtraCode, raw_ostream &O) {
1980 if (ExtraCode && ExtraCode[0]) {
1981 if (ExtraCode[1] != 0)
1982 return true; // Unknown modifier.
1984 switch (ExtraCode[0]) {
1986 // See if this is a generic print operand
1987 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1993 printOperand(MI, OpNo, O);
1998 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
1999 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2000 const char *ExtraCode, raw_ostream &O) {
2001 if (ExtraCode && ExtraCode[0])
2002 return true; // Unknown modifier
2005 printMemOperand(MI, OpNo, O);
2011 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2012 switch (MI.getOpcode()) {
2015 case NVPTX::CallArgBeginInst:
2016 case NVPTX::CallArgEndInst0:
2017 case NVPTX::CallArgEndInst1:
2018 case NVPTX::CallArgF32:
2019 case NVPTX::CallArgF64:
2020 case NVPTX::CallArgI16:
2021 case NVPTX::CallArgI32:
2022 case NVPTX::CallArgI32imm:
2023 case NVPTX::CallArgI64:
2024 case NVPTX::CallArgI8:
2025 case NVPTX::CallArgParam:
2026 case NVPTX::CallVoidInst:
2027 case NVPTX::CallVoidInstReg:
2028 case NVPTX::Callseq_End:
2029 case NVPTX::CallVoidInstReg64:
2030 case NVPTX::DeclareParamInst:
2031 case NVPTX::DeclareRetMemInst:
2032 case NVPTX::DeclareRetRegInst:
2033 case NVPTX::DeclareRetScalarInst:
2034 case NVPTX::DeclareScalarParamInst:
2035 case NVPTX::DeclareScalarRegInst:
2036 case NVPTX::StoreParamF32:
2037 case NVPTX::StoreParamF64:
2038 case NVPTX::StoreParamI16:
2039 case NVPTX::StoreParamI32:
2040 case NVPTX::StoreParamI64:
2041 case NVPTX::StoreParamI8:
2042 case NVPTX::StoreParamS32I8:
2043 case NVPTX::StoreParamU32I8:
2044 case NVPTX::StoreParamS32I16:
2045 case NVPTX::StoreParamU32I16:
2046 case NVPTX::StoreRetvalF32:
2047 case NVPTX::StoreRetvalF64:
2048 case NVPTX::StoreRetvalI16:
2049 case NVPTX::StoreRetvalI32:
2050 case NVPTX::StoreRetvalI64:
2051 case NVPTX::StoreRetvalI8:
2052 case NVPTX::LastCallArgF32:
2053 case NVPTX::LastCallArgF64:
2054 case NVPTX::LastCallArgI16:
2055 case NVPTX::LastCallArgI32:
2056 case NVPTX::LastCallArgI32imm:
2057 case NVPTX::LastCallArgI64:
2058 case NVPTX::LastCallArgI8:
2059 case NVPTX::LastCallArgParam:
2060 case NVPTX::LoadParamMemF32:
2061 case NVPTX::LoadParamMemF64:
2062 case NVPTX::LoadParamMemI16:
2063 case NVPTX::LoadParamMemI32:
2064 case NVPTX::LoadParamMemI64:
2065 case NVPTX::LoadParamMemI8:
2066 case NVPTX::LoadParamRegF32:
2067 case NVPTX::LoadParamRegF64:
2068 case NVPTX::LoadParamRegI16:
2069 case NVPTX::LoadParamRegI32:
2070 case NVPTX::LoadParamRegI64:
2071 case NVPTX::LoadParamRegI8:
2072 case NVPTX::PrototypeInst:
2073 case NVPTX::DBG_VALUE:
2079 // Force static initialization.
2080 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2081 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2082 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2085 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2086 std::stringstream temp;
2087 LineReader *reader = this->getReader(filename.str());
2089 temp << filename.str();
2093 temp << reader->readLine(line);
2095 this->OutStreamer.EmitRawText(Twine(temp.str()));
2098 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2099 if (reader == NULL) {
2100 reader = new LineReader(filename);
2103 if (reader->fileName() != filename) {
2105 reader = new LineReader(filename);
2111 std::string LineReader::readLine(unsigned lineNum) {
2112 if (lineNum < theCurLine) {
2114 fstr.seekg(0, std::ios::beg);
2116 while (theCurLine < lineNum) {
2117 fstr.getline(buff, 500);
2123 // Force static initialization.
2124 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2125 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2126 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);