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"
51 #include "NVPTXGenAsmWriter.inc"
53 bool RegAllocNilUsed = true;
55 #define DEPOTNAME "__local_depot"
58 EmitLineNumbers("nvptx-emit-line-numbers",
59 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
63 bool InterleaveSrcInPtx = false;
66 static cl::opt<bool, true>InterleaveSrc("nvptx-emit-src",
68 cl::desc("NVPTX Specific: Emit source line in ptx file"),
69 cl::location(llvm::InterleaveSrcInPtx));
73 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
75 void DiscoverDependentGlobals(Value *V,
76 DenseSet<GlobalVariable*> &Globals) {
77 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
80 if (User *U = dyn_cast<User>(V)) {
81 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
82 DiscoverDependentGlobals(U->getOperand(i), Globals);
88 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
89 /// instances to be emitted, but only after any dependents have been added
91 void VisitGlobalVariableForEmission(GlobalVariable *GV,
92 SmallVectorImpl<GlobalVariable*> &Order,
93 DenseSet<GlobalVariable*> &Visited,
94 DenseSet<GlobalVariable*> &Visiting) {
95 // Have we already visited this one?
96 if (Visited.count(GV)) return;
98 // Do we have a circular dependency?
99 if (Visiting.count(GV))
100 report_fatal_error("Circular dependency found in global variable set");
102 // Start visiting this global
105 // Make sure we visit all dependents first
106 DenseSet<GlobalVariable*> Others;
107 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
108 DiscoverDependentGlobals(GV->getOperand(i), Others);
110 for (DenseSet<GlobalVariable*>::iterator I = Others.begin(),
111 E = Others.end(); I != E; ++I)
112 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
114 // Now we can visit ourself
121 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
122 // cannot just link to the existing version.
123 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
125 using namespace nvptx;
126 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
127 MCContext &Ctx = AP.OutContext;
129 if (CV->isNullValue() || isa<UndefValue>(CV))
130 return MCConstantExpr::Create(0, Ctx);
132 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
133 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
135 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
136 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
138 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
139 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
141 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
143 llvm_unreachable("Unknown constant value to lower!");
146 switch (CE->getOpcode()) {
148 // If the code isn't optimized, there may be outstanding folding
149 // opportunities. Attempt to fold the expression using DataLayout as a
150 // last resort before giving up.
152 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
154 return LowerConstant(C, AP);
156 // Otherwise report the problem to the user.
159 raw_string_ostream OS(S);
160 OS << "Unsupported expression in static initializer: ";
161 WriteAsOperand(OS, CE, /*PrintType=*/false,
162 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
163 report_fatal_error(OS.str());
165 case Instruction::GetElementPtr: {
166 const DataLayout &TD = *AP.TM.getDataLayout();
167 // Generate a symbolic expression for the byte address
168 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
169 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
171 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
175 int64_t Offset = OffsetAI.getSExtValue();
176 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
180 case Instruction::Trunc:
181 // We emit the value and depend on the assembler to truncate the generated
182 // expression properly. This is important for differences between
183 // blockaddress labels. Since the two labels are in the same function, it
184 // is reasonable to treat their delta as a 32-bit value.
186 case Instruction::BitCast:
187 return LowerConstant(CE->getOperand(0), AP);
189 case Instruction::IntToPtr: {
190 const DataLayout &TD = *AP.TM.getDataLayout();
191 // Handle casts to pointers by changing them into casts to the appropriate
192 // integer type. This promotes constant folding and simplifies this code.
193 Constant *Op = CE->getOperand(0);
194 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
196 return LowerConstant(Op, AP);
199 case Instruction::PtrToInt: {
200 const DataLayout &TD = *AP.TM.getDataLayout();
201 // Support only foldable casts to/from pointers that can be eliminated by
202 // changing the pointer to the appropriately sized integer type.
203 Constant *Op = CE->getOperand(0);
204 Type *Ty = CE->getType();
206 const MCExpr *OpExpr = LowerConstant(Op, AP);
208 // We can emit the pointer value into this slot if the slot is an
209 // integer slot equal to the size of the pointer.
210 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
213 // Otherwise the pointer is smaller than the resultant integer, mask off
214 // the high bits so we are sure to get a proper truncation if the input is
216 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
217 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
218 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
221 // The MC library also has a right-shift operator, but it isn't consistently
222 // signed or unsigned between different targets.
223 case Instruction::Add:
224 case Instruction::Sub:
225 case Instruction::Mul:
226 case Instruction::SDiv:
227 case Instruction::SRem:
228 case Instruction::Shl:
229 case Instruction::And:
230 case Instruction::Or:
231 case Instruction::Xor: {
232 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
233 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
234 switch (CE->getOpcode()) {
235 default: llvm_unreachable("Unknown binary operator constant cast expr");
236 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
237 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
238 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
239 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
240 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
241 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
242 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
243 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
244 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
251 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
253 if (!EmitLineNumbers)
258 DebugLoc curLoc = MI.getDebugLoc();
260 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
263 if (prevDebugLoc == curLoc)
266 prevDebugLoc = curLoc;
268 if (curLoc.isUnknown())
272 const MachineFunction *MF = MI.getParent()->getParent();
273 //const TargetMachine &TM = MF->getTarget();
275 const LLVMContext &ctx = MF->getFunction()->getContext();
276 DIScope Scope(curLoc.getScope(ctx));
281 StringRef fileName(Scope.getFilename());
282 StringRef dirName(Scope.getDirectory());
283 SmallString<128> FullPathName = dirName;
284 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
285 sys::path::append(FullPathName, fileName);
286 fileName = FullPathName.str();
289 if (filenameMap.find(fileName.str()) == filenameMap.end())
293 // Emit the line from the source file.
294 if (llvm::InterleaveSrcInPtx)
295 this->emitSrcInText(fileName.str(), curLoc.getLine());
297 std::stringstream temp;
298 temp << "\t.loc " << filenameMap[fileName.str()]
299 << " " << curLoc.getLine() << " " << curLoc.getCol();
300 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
303 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
304 SmallString<128> Str;
305 raw_svector_ostream OS(Str);
306 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
307 emitLineNumberAsDotLoc(*MI);
308 printInstruction(MI, OS);
309 OutStreamer.EmitRawText(OS.str());
312 void NVPTXAsmPrinter::printReturnValStr(const Function *F,
315 const DataLayout *TD = TM.getDataLayout();
316 const TargetLowering *TLI = TM.getTargetLowering();
318 Type *Ty = F->getReturnType();
320 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
322 if (Ty->getTypeID() == Type::VoidTyID)
328 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
330 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
331 size = ITy->getBitWidth();
332 if (size < 32) size = 32;
334 assert(Ty->isFloatingPointTy() &&
335 "Floating point type expected here");
336 size = Ty->getPrimitiveSizeInBits();
339 O << ".param .b" << size << " func_retval0";
341 else if (isa<PointerType>(Ty)) {
342 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
345 if ((Ty->getTypeID() == Type::StructTyID) ||
346 isa<VectorType>(Ty)) {
347 SmallVector<EVT, 16> vtparts;
348 ComputeValueVTs(*TLI, Ty, vtparts);
349 unsigned totalsz = 0;
350 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
352 EVT elemtype = vtparts[i];
353 if (vtparts[i].isVector()) {
354 elems = vtparts[i].getVectorNumElements();
355 elemtype = vtparts[i].getVectorElementType();
357 for (unsigned j=0, je=elems; j!=je; ++j) {
358 unsigned sz = elemtype.getSizeInBits();
359 if (elemtype.isInteger() && (sz < 8)) sz = 8;
363 unsigned retAlignment = 0;
364 if (!llvm::getAlign(*F, 0, retAlignment))
365 retAlignment = TD->getABITypeAlignment(Ty);
366 O << ".param .align "
368 << " .b8 func_retval0["
372 "Unknown return type");
375 SmallVector<EVT, 16> vtparts;
376 ComputeValueVTs(*TLI, Ty, vtparts);
378 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
380 EVT elemtype = vtparts[i];
381 if (vtparts[i].isVector()) {
382 elems = vtparts[i].getVectorNumElements();
383 elemtype = vtparts[i].getVectorElementType();
386 for (unsigned j=0, je=elems; j!=je; ++j) {
387 unsigned sz = elemtype.getSizeInBits();
388 if (elemtype.isInteger() && (sz < 32)) sz = 32;
389 O << ".reg .b" << sz << " func_retval" << idx;
390 if (j<je-1) O << ", ";
401 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
403 const Function *F = MF.getFunction();
404 printReturnValStr(F, O);
407 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
408 SmallString<128> Str;
409 raw_svector_ostream O(Str);
412 MRI = &MF->getRegInfo();
413 F = MF->getFunction();
414 emitLinkageDirective(F,O);
415 if (llvm::isKernelFunction(*F))
419 printReturnValStr(*MF, O);
424 emitFunctionParamList(*MF, O);
426 if (llvm::isKernelFunction(*F))
427 emitKernelFunctionDirectives(*F, O);
429 OutStreamer.EmitRawText(O.str());
431 prevDebugLoc = DebugLoc();
434 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
435 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
436 unsigned numRegClasses = TRI.getNumRegClasses();
437 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
438 OutStreamer.EmitRawText(StringRef("{\n"));
439 setAndEmitFunctionVirtualRegisters(*MF);
441 SmallString<128> Str;
442 raw_svector_ostream O(Str);
443 emitDemotedVars(MF->getFunction(), O);
444 OutStreamer.EmitRawText(O.str());
447 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
448 OutStreamer.EmitRawText(StringRef("}\n"));
449 delete []VRidGlobal2LocalMap;
454 NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
455 raw_ostream &O) const {
456 // If the NVVM IR has some of reqntid* specified, then output
457 // the reqntid directive, and set the unspecified ones to 1.
458 // If none of reqntid* is specified, don't output reqntid directive.
459 unsigned reqntidx, reqntidy, reqntidz;
460 bool specified = false;
461 if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
462 else specified = true;
463 if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
464 else specified = true;
465 if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
466 else specified = true;
469 O << ".reqntid " << reqntidx << ", "
470 << reqntidy << ", " << reqntidz << "\n";
472 // If the NVVM IR has some of maxntid* specified, then output
473 // the maxntid directive, and set the unspecified ones to 1.
474 // If none of maxntid* is specified, don't output maxntid directive.
475 unsigned maxntidx, maxntidy, maxntidz;
477 if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
478 else specified = true;
479 if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
480 else specified = true;
481 if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
482 else specified = true;
485 O << ".maxntid " << maxntidx << ", "
486 << maxntidy << ", " << maxntidz << "\n";
489 if (llvm::getMinCTASm(F, mincta))
490 O << ".minnctapersm " << mincta << "\n";
494 NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
496 const TargetRegisterClass * RC = MRI->getRegClass(vr);
497 unsigned id = RC->getID();
499 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[id];
500 unsigned mapped_vr = regmap[vr];
503 O << getNVPTXRegClassStr(RC) << mapped_vr;
506 report_fatal_error("Bad register!");
510 NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
512 getVirtualRegisterName(vr, isVec, O);
515 void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
516 const char *Modifier,
518 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
519 int Imm = (int)MO.getImm();
520 if(0 == strcmp(Modifier, "vecelem"))
521 O << "_" << vecelem[Imm];
522 else if(0 == strcmp(Modifier, "vecv4comm1")) {
523 if((Imm < 0) || (Imm > 3))
526 else if(0 == strcmp(Modifier, "vecv4comm2")) {
527 if((Imm < 4) || (Imm > 7))
530 else if(0 == strcmp(Modifier, "vecv4pos")) {
532 O << "_" << vecelem[Imm%4];
534 else if(0 == strcmp(Modifier, "vecv2comm1")) {
535 if((Imm < 0) || (Imm > 1))
538 else if(0 == strcmp(Modifier, "vecv2comm2")) {
539 if((Imm < 2) || (Imm > 3))
542 else if(0 == strcmp(Modifier, "vecv2pos")) {
544 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);
579 llvm_unreachable("Don't know how to handle modifier on immediate operand");
582 case MachineOperand::MO_FPImmediate:
583 printFPConstant(MO.getFPImm(), O);
586 case MachineOperand::MO_GlobalAddress:
587 O << *Mang->getSymbol(MO.getGlobal());
590 case MachineOperand::MO_ExternalSymbol: {
591 const char * symbname = MO.getSymbolName();
592 if (strstr(symbname, ".PARAM") == symbname) {
594 sscanf(symbname+6, "%u[];", &index);
595 printParamName(index, O);
597 else if (strstr(symbname, ".HLPPARAM") == symbname) {
599 sscanf(symbname+9, "%u[];", &index);
600 O << *CurrentFnSym << "_param_" << index << "_offset";
607 case MachineOperand::MO_MachineBasicBlock:
608 O << *MO.getMBB()->getSymbol();
612 llvm_unreachable("Operand type not supported.");
616 void NVPTXAsmPrinter::
617 printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
619 O << "\t// Implicit def :";
620 //printOperand(MI, 0);
625 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
626 raw_ostream &O, const char *Modifier) {
627 printOperand(MI, opNum, O);
629 if (Modifier && !strcmp(Modifier, "add")) {
631 printOperand(MI, opNum+1, O);
633 if (MI->getOperand(opNum+1).isImm() &&
634 MI->getOperand(opNum+1).getImm() == 0)
635 return; // don't print ',0' or '+0'
637 printOperand(MI, opNum+1, O);
641 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
642 raw_ostream &O, const char *Modifier)
645 const MachineOperand &MO = MI->getOperand(opNum);
646 int Imm = (int)MO.getImm();
647 if (!strcmp(Modifier, "volatile")) {
650 } else if (!strcmp(Modifier, "addsp")) {
652 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
653 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
654 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
655 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
656 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
657 case NVPTX::PTXLdStInstCode::GENERIC:
658 if (!nvptxSubtarget.hasGenericLdSt())
662 llvm_unreachable("Wrong Address Space");
665 else if (!strcmp(Modifier, "sign")) {
666 if (Imm==NVPTX::PTXLdStInstCode::Signed)
668 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
673 else if (!strcmp(Modifier, "vec")) {
674 if (Imm==NVPTX::PTXLdStInstCode::V2)
676 else if (Imm==NVPTX::PTXLdStInstCode::V4)
680 llvm_unreachable("Unknown Modifier");
683 llvm_unreachable("Empty Modifier");
686 void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
688 emitLinkageDirective(F,O);
689 if (llvm::isKernelFunction(*F))
693 printReturnValStr(F, O);
694 O << *CurrentFnSym << "\n";
695 emitFunctionParamList(F, O);
699 static bool usedInGlobalVarDef(const Constant *C)
704 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
705 if (GV->getName().str() == "llvm.used")
710 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
712 const Constant *C = dyn_cast<Constant>(*ui);
713 if (usedInGlobalVarDef(C))
719 static bool usedInOneFunc(const User *U, Function const *&oneFunc)
721 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
722 if (othergv->getName().str() == "llvm.used")
726 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
727 if (instr->getParent() && instr->getParent()->getParent()) {
728 const Function *curFunc = instr->getParent()->getParent();
729 if (oneFunc && (curFunc != oneFunc))
738 if (const MDNode *md = dyn_cast<MDNode>(U))
739 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
740 (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();
787 const Function *caller = bb->getParent();
788 if (!caller) continue;
789 if (seenMap.find(caller) != seenMap.end())
796 void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
797 llvm::DenseMap<const Function *, bool> seenMap;
798 for (Module::const_iterator FI=M.begin(), FE=M.end();
800 const Function *F = FI;
802 if (F->isDeclaration()) {
805 if (F->getIntrinsicID())
807 CurrentFnSym = Mang->getSymbol(F);
808 emitDeclaration(F, O);
811 for (Value::const_use_iterator iter=F->use_begin(),
812 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
813 if (const Constant *C = dyn_cast<Constant>(*iter)) {
814 if (usedInGlobalVarDef(C)) {
815 // The use is in the initialization of a global variable
816 // that is a function pointer, so print a declaration
817 // for the original function
818 CurrentFnSym = Mang->getSymbol(F);
819 emitDeclaration(F, O);
822 // Emit a declaration of this function if the function that
823 // uses this constant expr has already been seen.
824 if (useFuncSeen(C, seenMap)) {
825 CurrentFnSym = Mang->getSymbol(F);
826 emitDeclaration(F, O);
831 if (!isa<Instruction>(*iter)) continue;
832 const Instruction *instr = cast<Instruction>(*iter);
833 const BasicBlock *bb = instr->getParent();
835 const Function *caller = bb->getParent();
836 if (!caller) continue;
838 // If a caller has already been seen, then the caller is
839 // appearing in the module before the callee. so print out
840 // a declaration for the callee.
841 if (seenMap.find(caller) != seenMap.end()) {
842 CurrentFnSym = Mang->getSymbol(F);
843 emitDeclaration(F, O);
851 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
852 DebugInfoFinder DbgFinder;
853 DbgFinder.processModule(M);
856 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
857 E = DbgFinder.compile_unit_end(); I != E; ++I) {
858 DICompileUnit DIUnit(*I);
859 StringRef Filename(DIUnit.getFilename());
860 StringRef Dirname(DIUnit.getDirectory());
861 SmallString<128> FullPathName = Dirname;
862 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
863 sys::path::append(FullPathName, Filename);
864 Filename = FullPathName.str();
866 if (filenameMap.find(Filename.str()) != filenameMap.end())
868 filenameMap[Filename.str()] = i;
869 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
873 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
874 E = DbgFinder.subprogram_end(); I != E; ++I) {
876 StringRef Filename(SP.getFilename());
877 StringRef Dirname(SP.getDirectory());
878 SmallString<128> FullPathName = Dirname;
879 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
880 sys::path::append(FullPathName, Filename);
881 Filename = FullPathName.str();
883 if (filenameMap.find(Filename.str()) != filenameMap.end())
885 filenameMap[Filename.str()] = i;
890 bool NVPTXAsmPrinter::doInitialization (Module &M) {
892 SmallString<128> Str1;
893 raw_svector_ostream OS1(Str1);
895 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
896 MMI->AnalyzeModule(M);
898 // We need to call the parent's one explicitly.
899 //bool Result = AsmPrinter::doInitialization(M);
901 // Initialize TargetLoweringObjectFile.
902 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
903 .Initialize(OutContext, TM);
905 Mang = new Mangler(OutContext, *TM.getDataLayout());
907 // Emit header before any dwarf directives are emitted below.
909 OutStreamer.EmitRawText(OS1.str());
912 // Already commented out
913 //bool Result = AsmPrinter::doInitialization(M);
916 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
917 recordAndEmitFilenames(M);
919 SmallString<128> Str2;
920 raw_svector_ostream OS2(Str2);
922 emitDeclarations(M, OS2);
924 // As ptxas does not support forward references of globals, we need to first
925 // sort the list of module-level globals in def-use order. We visit each
926 // global variable in order, and ensure that we emit it *after* its dependent
927 // globals. We use a little extra memory maintaining both a set and a list to
928 // have fast searches while maintaining a strict ordering.
929 SmallVector<GlobalVariable*,8> Globals;
930 DenseSet<GlobalVariable*> GVVisited;
931 DenseSet<GlobalVariable*> GVVisiting;
933 // Visit each global variable, in order
934 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
936 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
938 assert(GVVisited.size() == M.getGlobalList().size() &&
939 "Missed a global variable");
940 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
942 // Print out module-level global variables in proper order
943 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
944 printModuleLevelGV(Globals[i], OS2);
948 OutStreamer.EmitRawText(OS2.str());
949 return false; // success
952 void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
954 O << "// Generated by LLVM NVPTX Back-End\n";
958 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
959 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
962 O << nvptxSubtarget.getTargetName();
964 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
965 O << ", texmode_independent";
966 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
967 if (!nvptxSubtarget.hasDouble())
968 O << ", map_f64_to_f32";
971 if (MAI->doesSupportDebugInformation())
976 O << ".address_size ";
977 if (nvptxSubtarget.is64Bit())
986 bool NVPTXAsmPrinter::doFinalization(Module &M) {
987 // XXX Temproarily remove global variables so that doFinalization() will not
988 // emit them again (global variables are emitted at beginning).
990 Module::GlobalListType &global_list = M.getGlobalList();
991 int i, n = global_list.size();
992 GlobalVariable **gv_array = new GlobalVariable* [n];
994 // first, back-up GlobalVariable in gv_array
996 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1000 // second, empty global_list
1001 while (!global_list.empty())
1002 global_list.remove(global_list.begin());
1004 // call doFinalization
1005 bool ret = AsmPrinter::doFinalization(M);
1007 // now we restore global variables
1008 for (i = 0; i < n; i ++)
1009 global_list.insert(global_list.end(), gv_array[i]);
1015 //bool Result = AsmPrinter::doFinalization(M);
1016 // Instead of calling the parents doFinalization, we may
1017 // clone parents doFinalization and customize here.
1018 // Currently, we if NVISA out the EmitGlobals() in
1019 // parent's doFinalization, which is too intrusive.
1021 // Same for the doInitialization.
1025 // This function emits appropriate linkage directives for
1026 // functions and global variables.
1028 // extern function declaration -> .extern
1029 // extern function definition -> .visible
1030 // external global variable with init -> .visible
1031 // external without init -> .extern
1032 // appending -> not allowed, assert.
1034 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
1036 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1037 if (V->hasExternalLinkage()) {
1038 if (isa<GlobalVariable>(V)) {
1039 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1041 if (GVar->hasInitializer())
1046 } else if (V->isDeclaration())
1050 } else if (V->hasAppendingLinkage()) {
1052 msg.append("Error: ");
1053 msg.append("Symbol ");
1055 msg.append(V->getName().str());
1056 msg.append("has unsupported appending linkage type");
1057 llvm_unreachable(msg.c_str());
1063 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1064 bool processDemoted) {
1067 if (GVar->hasSection()) {
1068 if (GVar->getSection() == "llvm.metadata")
1072 const DataLayout *TD = TM.getDataLayout();
1074 // GlobalVariables are always constant pointers themselves.
1075 const PointerType *PTy = GVar->getType();
1076 Type *ETy = PTy->getElementType();
1078 if (GVar->hasExternalLinkage()) {
1079 if (GVar->hasInitializer())
1085 if (llvm::isTexture(*GVar)) {
1086 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1090 if (llvm::isSurface(*GVar)) {
1091 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1095 if (GVar->isDeclaration()) {
1096 // (extern) declarations, no definition or initializer
1097 // Currently the only known declaration is for an automatic __local
1098 // (.shared) promoted to global.
1099 emitPTXGlobalVariable(GVar, O);
1104 if (llvm::isSampler(*GVar)) {
1105 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1107 Constant *Initializer = NULL;
1108 if (GVar->hasInitializer())
1109 Initializer = GVar->getInitializer();
1110 ConstantInt *CI = NULL;
1112 CI = dyn_cast<ConstantInt>(Initializer);
1114 unsigned sample=CI->getZExtValue();
1118 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1119 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1120 O << "addr_mode_" << i << " = ";
1122 case 0: O << "wrap"; break;
1123 case 1: O << "clamp_to_border"; break;
1124 case 2: O << "clamp_to_edge"; break;
1125 case 3: O << "wrap"; break;
1126 case 4: O << "mirror"; break;
1130 O << "filter_mode = ";
1131 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1132 case 0: O << "nearest"; break;
1133 case 1: O << "linear"; break;
1134 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1135 default: O << "nearest"; break;
1137 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1138 O << ", force_unnormalized_coords = 1";
1147 if (GVar->hasPrivateLinkage()) {
1149 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1152 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1153 if (!strncmp(GVar->getName().data(), "filename", 8))
1155 if (GVar->use_empty())
1159 const Function *demotedFunc = 0;
1160 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1161 O << "// " << GVar->getName().str() << " has been demoted\n";
1162 if (localDecls.find(demotedFunc) != localDecls.end())
1163 localDecls[demotedFunc].push_back(GVar);
1165 std::vector<GlobalVariable *> temp;
1166 temp.push_back(GVar);
1167 localDecls[demotedFunc] = temp;
1173 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1174 if (GVar->getAlignment() == 0)
1175 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1177 O << " .align " << GVar->getAlignment();
1180 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1182 O << getPTXFundamentalTypeStr(ETy, false);
1184 O << *Mang->getSymbol(GVar);
1186 // Ptx allows variable initilization only for constant and global state
1188 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1189 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1190 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1191 && GVar->hasInitializer()) {
1192 Constant *Initializer = GVar->getInitializer();
1193 if (!Initializer->isNullValue()) {
1195 printScalarConstant(Initializer, O);
1199 unsigned int ElementSize =0;
1201 // Although PTX has direct support for struct type and array type and
1202 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1203 // targets that support these high level field accesses. Structs, arrays
1204 // and vectors are lowered into arrays of bytes.
1205 switch (ETy->getTypeID()) {
1206 case Type::StructTyID:
1207 case Type::ArrayTyID:
1208 case Type::VectorTyID:
1209 ElementSize = TD->getTypeStoreSize(ETy);
1210 // Ptx allows variable initilization only for constant and
1211 // global state spaces.
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 (!isa<UndefValue>(Initializer) &&
1218 !Initializer->isNullValue()) {
1219 AggBuffer aggBuffer(ElementSize, O, *this);
1220 bufferAggregateConstant(Initializer, &aggBuffer);
1221 if (aggBuffer.numSymbols) {
1222 if (nvptxSubtarget.is64Bit()) {
1223 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1227 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1233 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1242 O << " .b8 " << *Mang->getSymbol(GVar) ;
1251 O << " .b8 " << *Mang->getSymbol(GVar);
1260 assert( 0 && "type not supported yet");
1267 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1268 if (localDecls.find(f) == localDecls.end())
1271 std::vector<GlobalVariable *> &gvars = localDecls[f];
1273 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1274 O << "\t// demoted variable\n\t";
1275 printModuleLevelGV(gvars[i], O, true);
1279 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1280 raw_ostream &O) const {
1281 switch (AddressSpace) {
1282 case llvm::ADDRESS_SPACE_LOCAL:
1285 case llvm::ADDRESS_SPACE_GLOBAL:
1288 case llvm::ADDRESS_SPACE_CONST:
1289 // This logic should be consistent with that in
1290 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1291 if (nvptxSubtarget.hasGenericLdSt())
1296 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1299 case llvm::ADDRESS_SPACE_SHARED:
1303 report_fatal_error("Bad address space found while emitting PTX");
1308 std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1309 bool useB4PTR) const {
1310 switch (Ty->getTypeID()) {
1312 llvm_unreachable("unexpected type");
1314 case Type::IntegerTyID: {
1315 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1318 else if (NumBits <= 64) {
1319 std::string name = "u";
1320 return name + utostr(NumBits);
1322 llvm_unreachable("Integer too large");
1327 case Type::FloatTyID:
1329 case Type::DoubleTyID:
1331 case Type::PointerTyID:
1332 if (nvptxSubtarget.is64Bit())
1333 if (useB4PTR) return "b64";
1336 if (useB4PTR) return "b32";
1339 llvm_unreachable("unexpected type");
1343 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1346 const DataLayout *TD = TM.getDataLayout();
1348 // GlobalVariables are always constant pointers themselves.
1349 const PointerType *PTy = GVar->getType();
1350 Type *ETy = PTy->getElementType();
1353 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1354 if (GVar->getAlignment() == 0)
1355 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1357 O << " .align " << GVar->getAlignment();
1359 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1361 O << getPTXFundamentalTypeStr(ETy);
1363 O << *Mang->getSymbol(GVar);
1367 int64_t ElementSize =0;
1369 // Although PTX has direct support for struct type and array type and LLVM IR
1370 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1371 // support these high level field accesses. Structs and arrays are lowered
1372 // into arrays of bytes.
1373 switch (ETy->getTypeID()) {
1374 case Type::StructTyID:
1375 case Type::ArrayTyID:
1376 case Type::VectorTyID:
1377 ElementSize = TD->getTypeStoreSize(ETy);
1378 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1380 O << itostr(ElementSize) ;
1385 assert( 0 && "type not supported yet");
1392 getOpenCLAlignment(const DataLayout *TD,
1394 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1395 return TD->getPrefTypeAlignment(Ty);
1397 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1399 return getOpenCLAlignment(TD, ATy->getElementType());
1401 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1403 Type *ETy = VTy->getElementType();
1404 unsigned int numE = VTy->getNumElements();
1405 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1412 const StructType *STy = dyn_cast<StructType>(Ty);
1414 unsigned int alignStruct = 1;
1415 // Go through each element of the struct and find the
1416 // largest alignment.
1417 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1418 Type *ETy = STy->getElementType(i);
1419 unsigned int align = getOpenCLAlignment(TD, ETy);
1420 if (align > alignStruct)
1421 alignStruct = align;
1426 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1428 return TD->getPointerPrefAlignment();
1429 return TD->getPrefTypeAlignment(Ty);
1432 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1433 int paramIndex, raw_ostream &O) {
1434 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1435 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1436 O << *CurrentFnSym << "_param_" << paramIndex;
1438 std::string argName = I->getName();
1439 const char *p = argName.c_str();
1450 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1451 Function::const_arg_iterator I, E;
1454 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1455 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1456 O << *CurrentFnSym << "_param_" << paramIndex;
1460 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1461 if (i==paramIndex) {
1462 printParamName(I, paramIndex, O);
1466 llvm_unreachable("paramIndex out of bound");
1469 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1471 const DataLayout *TD = TM.getDataLayout();
1472 const AttributeSet &PAL = F->getAttributes();
1473 const TargetLowering *TLI = TM.getTargetLowering();
1474 Function::const_arg_iterator I, E;
1475 unsigned paramIndex = 0;
1477 bool isKernelFunc = llvm::isKernelFunction(*F);
1478 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1479 MVT thePointerTy = TLI->getPointerTy();
1483 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1484 const Type *Ty = I->getType();
1491 // Handle image/sampler parameters
1492 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1493 if (llvm::isImage(*I)) {
1494 std::string sname = I->getName();
1495 if (llvm::isImageWriteOnly(*I))
1496 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1497 else // Default image is read_only
1498 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1500 else // Should be llvm::isSampler(*I)
1501 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1506 if (PAL.hasAttribute(paramIndex+1, Attribute::ByVal) == false) {
1508 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1511 // Special handling for pointer arguments to kernel
1512 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1514 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1515 Type *ETy = PTy->getElementType();
1516 int addrSpace = PTy->getAddressSpace();
1521 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1522 O << ".ptr .const ";
1524 case llvm::ADDRESS_SPACE_SHARED:
1525 O << ".ptr .shared ";
1527 case llvm::ADDRESS_SPACE_GLOBAL:
1528 case llvm::ADDRESS_SPACE_CONST:
1529 O << ".ptr .global ";
1532 O << ".align " << (int)getOpenCLAlignment(TD, ETy) << " ";
1534 printParamName(I, paramIndex, O);
1538 // non-pointer scalar to kernel func
1540 << getPTXFundamentalTypeStr(Ty) << " ";
1541 printParamName(I, paramIndex, O);
1544 // Non-kernel function, just print .param .b<size> for ABI
1545 // and .reg .b<size> for non ABY
1547 if (isa<IntegerType>(Ty)) {
1548 sz = cast<IntegerType>(Ty)->getBitWidth();
1549 if (sz < 32) sz = 32;
1551 else if (isa<PointerType>(Ty))
1552 sz = thePointerTy.getSizeInBits();
1554 sz = Ty->getPrimitiveSizeInBits();
1556 O << "\t.param .b" << sz << " ";
1558 O << "\t.reg .b" << sz << " ";
1559 printParamName(I, paramIndex, O);
1563 // param has byVal attribute. So should be a pointer
1564 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1566 "Param with byval attribute should be a pointer type");
1567 Type *ETy = PTy->getElementType();
1569 if (isABI || isKernelFunc) {
1570 // Just print .param .b8 .align <a> .param[size];
1571 // <a> = PAL.getparamalignment
1572 // size = typeallocsize of element type
1573 unsigned align = PAL.getParamAlignment(paramIndex+1);
1575 align = TD->getABITypeAlignment(ETy);
1577 unsigned sz = TD->getTypeAllocSize(ETy);
1578 O << "\t.param .align " << align
1580 printParamName(I, paramIndex, O);
1581 O << "[" << sz << "]";
1584 // Split the ETy into constituent parts and
1585 // print .param .b<size> <name> for each part.
1586 // Further, if a part is vector, print the above for
1587 // each vector element.
1588 SmallVector<EVT, 16> vtparts;
1589 ComputeValueVTs(*TLI, ETy, vtparts);
1590 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
1592 EVT elemtype = vtparts[i];
1593 if (vtparts[i].isVector()) {
1594 elems = vtparts[i].getVectorNumElements();
1595 elemtype = vtparts[i].getVectorElementType();
1598 for (unsigned j=0,je=elems; j!=je; ++j) {
1599 unsigned sz = elemtype.getSizeInBits();
1600 if (elemtype.isInteger() && (sz < 32)) sz = 32;
1601 O << "\t.reg .b" << sz << " ";
1602 printParamName(I, paramIndex, O);
1603 if (j<je-1) O << ",\n";
1617 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1619 const Function *F = MF.getFunction();
1620 emitFunctionParamList(F, O);
1624 void NVPTXAsmPrinter::
1625 setAndEmitFunctionVirtualRegisters(const MachineFunction &MF) {
1626 SmallString<128> Str;
1627 raw_svector_ostream O(Str);
1629 // Map the global virtual register number to a register class specific
1630 // virtual register number starting from 1 with that class.
1631 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1632 //unsigned numRegClasses = TRI->getNumRegClasses();
1634 // Emit the Fake Stack Object
1635 const MachineFrameInfo *MFI = MF.getFrameInfo();
1636 int NumBytes = (int) MFI->getStackSize();
1638 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t"
1640 << getFunctionNumber() << "[" << NumBytes << "];\n";
1641 if (nvptxSubtarget.is64Bit()) {
1642 O << "\t.reg .b64 \t%SP;\n";
1643 O << "\t.reg .b64 \t%SPL;\n";
1646 O << "\t.reg .b32 \t%SP;\n";
1647 O << "\t.reg .b32 \t%SPL;\n";
1651 // Go through all virtual registers to establish the mapping between the
1653 // register number and the per class virtual register number.
1654 // We use the per class virtual register number in the ptx output.
1655 unsigned int numVRs = MRI->getNumVirtRegs();
1656 for (unsigned i=0; i< numVRs; i++) {
1657 unsigned int vr = TRI->index2VirtReg(i);
1658 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1659 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[RC->getID()];
1660 int n = regmap.size();
1661 regmap.insert(std::make_pair(vr, n+1));
1664 // Emit register declarations
1665 // @TODO: Extract out the real register usage
1666 O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1667 O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1668 O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1669 O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1670 O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1671 O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1672 O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1674 // Emit declaration of the virtual registers or 'physical' registers for
1675 // each register class
1676 //for (unsigned i=0; i< numRegClasses; i++) {
1677 // std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[i];
1678 // const TargetRegisterClass *RC = TRI->getRegClass(i);
1679 // std::string rcname = getNVPTXRegClassName(RC);
1680 // std::string rcStr = getNVPTXRegClassStr(RC);
1681 // //int n = regmap.size();
1682 // if (!isNVPTXVectorRegClass(RC)) {
1683 // O << "\t.reg " << rcname << " \t" << rcStr << "<"
1684 // << NVPTXNumRegisters << ">;\n";
1687 // Only declare those registers that may be used. And do not emit vector
1689 // they are all elementized to scalar registers.
1690 //if (n && !isNVPTXVectorRegClass(RC)) {
1691 // if (RegAllocNilUsed) {
1692 // O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1696 // O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1697 // << "<" << 32 << ">;\n";
1702 OutStreamer.EmitRawText(O.str());
1706 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1707 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1709 unsigned int numHex;
1712 if (Fp->getType()->getTypeID()==Type::FloatTyID) {
1715 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1717 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1720 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1723 llvm_unreachable("unsupported fp type");
1725 APInt API = APF.bitcastToAPInt();
1726 std::string hexstr(utohexstr(API.getZExtValue()));
1728 if (hexstr.length() < numHex)
1729 O << std::string(numHex - hexstr.length(), '0');
1730 O << utohexstr(API.getZExtValue());
1733 void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1734 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1735 O << CI->getValue();
1738 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1739 printFPConstant(CFP, O);
1742 if (isa<ConstantPointerNull>(CPV)) {
1746 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1747 O << *Mang->getSymbol(GVar);
1750 if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1751 Value *v = Cexpr->stripPointerCasts();
1752 if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1753 O << *Mang->getSymbol(GVar);
1756 O << *LowerConstant(CPV, *this);
1760 llvm_unreachable("Not scalar type found in printScalarConstant()");
1764 void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1765 AggBuffer *aggBuffer) {
1767 const DataLayout *TD = TM.getDataLayout();
1769 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1770 int s = TD->getTypeAllocSize(CPV->getType());
1773 aggBuffer->addZeros(s);
1778 switch (CPV->getType()->getTypeID()) {
1780 case Type::IntegerTyID: {
1781 const Type *ETy = CPV->getType();
1782 if ( ETy == Type::getInt8Ty(CPV->getContext()) ){
1784 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1786 aggBuffer->addBytes(ptr, 1, Bytes);
1787 } else if ( ETy == Type::getInt16Ty(CPV->getContext()) ) {
1789 (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1790 ptr = (unsigned char*)&int16;
1791 aggBuffer->addBytes(ptr, 2, Bytes);
1792 } else if ( ETy == Type::getInt32Ty(CPV->getContext()) ) {
1793 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1794 int int32 =(int)(constInt->getZExtValue());
1795 ptr = (unsigned char*)&int32;
1796 aggBuffer->addBytes(ptr, 4, Bytes);
1798 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1799 if (ConstantInt *constInt =
1800 dyn_cast<ConstantInt>(ConstantFoldConstantExpression(
1802 int int32 =(int)(constInt->getZExtValue());
1803 ptr = (unsigned char*)&int32;
1804 aggBuffer->addBytes(ptr, 4, Bytes);
1807 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1808 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1809 aggBuffer->addSymbol(v);
1810 aggBuffer->addZeros(4);
1814 llvm_unreachable("unsupported integer const type");
1815 } else if (ETy == Type::getInt64Ty(CPV->getContext()) ) {
1816 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1817 long long int64 =(long long)(constInt->getZExtValue());
1818 ptr = (unsigned char*)&int64;
1819 aggBuffer->addBytes(ptr, 8, Bytes);
1821 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1822 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1823 ConstantFoldConstantExpression(Cexpr, TD))) {
1824 long long int64 =(long long)(constInt->getZExtValue());
1825 ptr = (unsigned char*)&int64;
1826 aggBuffer->addBytes(ptr, 8, Bytes);
1829 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1830 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1831 aggBuffer->addSymbol(v);
1832 aggBuffer->addZeros(8);
1836 llvm_unreachable("unsupported integer const type");
1838 llvm_unreachable("unsupported integer const type");
1841 case Type::FloatTyID:
1842 case Type::DoubleTyID: {
1843 ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1844 const Type* Ty = CFP->getType();
1845 if (Ty == Type::getFloatTy(CPV->getContext())) {
1846 float float32 = (float)CFP->getValueAPF().convertToFloat();
1847 ptr = (unsigned char*)&float32;
1848 aggBuffer->addBytes(ptr, 4, Bytes);
1849 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1850 double float64 = CFP->getValueAPF().convertToDouble();
1851 ptr = (unsigned char*)&float64;
1852 aggBuffer->addBytes(ptr, 8, Bytes);
1855 llvm_unreachable("unsupported fp const type");
1859 case Type::PointerTyID: {
1860 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1861 aggBuffer->addSymbol(GVar);
1863 else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1864 Value *v = Cexpr->stripPointerCasts();
1865 aggBuffer->addSymbol(v);
1867 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1868 aggBuffer->addZeros(s);
1872 case Type::ArrayTyID:
1873 case Type::VectorTyID:
1874 case Type::StructTyID: {
1875 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1876 isa<ConstantStruct>(CPV)) {
1877 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1878 bufferAggregateConstant(CPV, aggBuffer);
1879 if ( Bytes > ElementSize )
1880 aggBuffer->addZeros(Bytes-ElementSize);
1882 else if (isa<ConstantAggregateZero>(CPV))
1883 aggBuffer->addZeros(Bytes);
1885 llvm_unreachable("Unexpected Constant type");
1890 llvm_unreachable("unsupported type");
1894 void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1895 AggBuffer *aggBuffer) {
1896 const DataLayout *TD = TM.getDataLayout();
1900 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1901 if (CPV->getNumOperands())
1902 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1903 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1907 if (const ConstantDataSequential *CDS =
1908 dyn_cast<ConstantDataSequential>(CPV)) {
1909 if (CDS->getNumElements())
1910 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1911 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1917 if (isa<ConstantStruct>(CPV)) {
1918 if (CPV->getNumOperands()) {
1919 StructType *ST = cast<StructType>(CPV->getType());
1920 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1922 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1923 TD->getTypeAllocSize(ST)
1924 - TD->getStructLayout(ST)->getElementOffset(i);
1926 Bytes = TD->getStructLayout(ST)->getElementOffset(i+1) -
1927 TD->getStructLayout(ST)->getElementOffset(i);
1928 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes,
1934 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1937 // buildTypeNameMap - Run through symbol table looking for type names.
1941 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1943 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1945 if (PI != TypeNameMap.end() &&
1946 (!PI->second.compare("struct._image1d_t") ||
1947 !PI->second.compare("struct._image2d_t") ||
1948 !PI->second.compare("struct._image3d_t")))
1954 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1956 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1957 unsigned AsmVariant,
1958 const char *ExtraCode,
1960 if (ExtraCode && ExtraCode[0]) {
1961 if (ExtraCode[1] != 0) return true; // Unknown modifier.
1963 switch (ExtraCode[0]) {
1965 // See if this is a generic print operand
1966 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1972 printOperand(MI, OpNo, O);
1977 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1979 unsigned AsmVariant,
1980 const char *ExtraCode,
1982 if (ExtraCode && ExtraCode[0])
1983 return true; // Unknown modifier
1986 printMemOperand(MI, OpNo, O);
1992 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
1994 switch(MI.getOpcode()) {
1997 case NVPTX::CallArgBeginInst: case NVPTX::CallArgEndInst0:
1998 case NVPTX::CallArgEndInst1: case NVPTX::CallArgF32:
1999 case NVPTX::CallArgF64: case NVPTX::CallArgI16:
2000 case NVPTX::CallArgI32: case NVPTX::CallArgI32imm:
2001 case NVPTX::CallArgI64: case NVPTX::CallArgI8:
2002 case NVPTX::CallArgParam: case NVPTX::CallVoidInst:
2003 case NVPTX::CallVoidInstReg: case NVPTX::Callseq_End:
2004 case NVPTX::CallVoidInstReg64:
2005 case NVPTX::DeclareParamInst: case NVPTX::DeclareRetMemInst:
2006 case NVPTX::DeclareRetRegInst: case NVPTX::DeclareRetScalarInst:
2007 case NVPTX::DeclareScalarParamInst: case NVPTX::DeclareScalarRegInst:
2008 case NVPTX::StoreParamF32: case NVPTX::StoreParamF64:
2009 case NVPTX::StoreParamI16: case NVPTX::StoreParamI32:
2010 case NVPTX::StoreParamI64: case NVPTX::StoreParamI8:
2011 case NVPTX::StoreParamS32I8: case NVPTX::StoreParamU32I8:
2012 case NVPTX::StoreParamS32I16: case NVPTX::StoreParamU32I16:
2013 case NVPTX::StoreRetvalF32: case NVPTX::StoreRetvalF64:
2014 case NVPTX::StoreRetvalI16: case NVPTX::StoreRetvalI32:
2015 case NVPTX::StoreRetvalI64: case NVPTX::StoreRetvalI8:
2016 case NVPTX::LastCallArgF32: case NVPTX::LastCallArgF64:
2017 case NVPTX::LastCallArgI16: case NVPTX::LastCallArgI32:
2018 case NVPTX::LastCallArgI32imm: case NVPTX::LastCallArgI64:
2019 case NVPTX::LastCallArgI8: case NVPTX::LastCallArgParam:
2020 case NVPTX::LoadParamMemF32: case NVPTX::LoadParamMemF64:
2021 case NVPTX::LoadParamMemI16: case NVPTX::LoadParamMemI32:
2022 case NVPTX::LoadParamMemI64: case NVPTX::LoadParamMemI8:
2023 case NVPTX::LoadParamRegF32: case NVPTX::LoadParamRegF64:
2024 case NVPTX::LoadParamRegI16: case NVPTX::LoadParamRegI32:
2025 case NVPTX::LoadParamRegI64: case NVPTX::LoadParamRegI8:
2026 case NVPTX::PrototypeInst: case NVPTX::DBG_VALUE:
2032 // Force static initialization.
2033 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2034 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2035 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2039 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2040 std::stringstream temp;
2041 LineReader * reader = this->getReader(filename.str());
2043 temp << filename.str();
2047 temp << reader->readLine(line);
2049 this->OutStreamer.EmitRawText(Twine(temp.str()));
2053 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2054 if (reader == NULL) {
2055 reader = new LineReader(filename);
2058 if (reader->fileName() != filename) {
2060 reader = new LineReader(filename);
2068 LineReader::readLine(unsigned lineNum) {
2069 if (lineNum < theCurLine) {
2071 fstr.seekg(0,std::ios::beg);
2073 while (theCurLine < lineNum) {
2074 fstr.getline(buff,500);
2080 // Force static initialization.
2081 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2082 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2083 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);