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 // Vector virtual register
507 if (getNVPTXVectorSize(RC) == 4)
509 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
510 << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
511 << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
512 << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
514 else if (getNVPTXVectorSize(RC) == 2)
516 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
517 << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
520 llvm_unreachable("Unsupported vector size");
524 NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
526 getVirtualRegisterName(vr, isVec, O);
529 void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
530 const char *Modifier,
532 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
533 int Imm = (int)MO.getImm();
534 if(0 == strcmp(Modifier, "vecelem"))
535 O << "_" << vecelem[Imm];
536 else if(0 == strcmp(Modifier, "vecv4comm1")) {
537 if((Imm < 0) || (Imm > 3))
540 else if(0 == strcmp(Modifier, "vecv4comm2")) {
541 if((Imm < 4) || (Imm > 7))
544 else if(0 == strcmp(Modifier, "vecv4pos")) {
546 O << "_" << vecelem[Imm%4];
548 else if(0 == strcmp(Modifier, "vecv2comm1")) {
549 if((Imm < 0) || (Imm > 1))
552 else if(0 == strcmp(Modifier, "vecv2comm2")) {
553 if((Imm < 2) || (Imm > 3))
556 else if(0 == strcmp(Modifier, "vecv2pos")) {
558 O << "_" << vecelem[Imm%2];
561 llvm_unreachable("Unknown Modifier on immediate operand");
564 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
565 raw_ostream &O, const char *Modifier) {
566 const MachineOperand &MO = MI->getOperand(opNum);
567 switch (MO.getType()) {
568 case MachineOperand::MO_Register:
569 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
570 if (MO.getReg() == NVPTX::VRDepot)
571 O << DEPOTNAME << getFunctionNumber();
573 O << getRegisterName(MO.getReg());
576 emitVirtualRegister(MO.getReg(), false, O);
578 if (strcmp(Modifier, "vecfull") == 0)
579 emitVirtualRegister(MO.getReg(), true, O);
582 "Don't know how to handle the modifier on virtual register.");
587 case MachineOperand::MO_Immediate:
590 else if (strstr(Modifier, "vec") == Modifier)
591 printVecModifiedImmediate(MO, Modifier, O);
593 llvm_unreachable("Don't know how to handle modifier on immediate operand");
596 case MachineOperand::MO_FPImmediate:
597 printFPConstant(MO.getFPImm(), O);
600 case MachineOperand::MO_GlobalAddress:
601 O << *Mang->getSymbol(MO.getGlobal());
604 case MachineOperand::MO_ExternalSymbol: {
605 const char * symbname = MO.getSymbolName();
606 if (strstr(symbname, ".PARAM") == symbname) {
608 sscanf(symbname+6, "%u[];", &index);
609 printParamName(index, O);
611 else if (strstr(symbname, ".HLPPARAM") == symbname) {
613 sscanf(symbname+9, "%u[];", &index);
614 O << *CurrentFnSym << "_param_" << index << "_offset";
621 case MachineOperand::MO_MachineBasicBlock:
622 O << *MO.getMBB()->getSymbol();
626 llvm_unreachable("Operand type not supported.");
630 void NVPTXAsmPrinter::
631 printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
633 O << "\t// Implicit def :";
634 //printOperand(MI, 0);
639 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
640 raw_ostream &O, const char *Modifier) {
641 printOperand(MI, opNum, O);
643 if (Modifier && !strcmp(Modifier, "add")) {
645 printOperand(MI, opNum+1, O);
647 if (MI->getOperand(opNum+1).isImm() &&
648 MI->getOperand(opNum+1).getImm() == 0)
649 return; // don't print ',0' or '+0'
651 printOperand(MI, opNum+1, O);
655 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
656 raw_ostream &O, const char *Modifier)
659 const MachineOperand &MO = MI->getOperand(opNum);
660 int Imm = (int)MO.getImm();
661 if (!strcmp(Modifier, "volatile")) {
664 } else if (!strcmp(Modifier, "addsp")) {
666 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
667 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
668 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
669 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
670 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
671 case NVPTX::PTXLdStInstCode::GENERIC:
672 if (!nvptxSubtarget.hasGenericLdSt())
676 llvm_unreachable("Wrong Address Space");
679 else if (!strcmp(Modifier, "sign")) {
680 if (Imm==NVPTX::PTXLdStInstCode::Signed)
682 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
687 else if (!strcmp(Modifier, "vec")) {
688 if (Imm==NVPTX::PTXLdStInstCode::V2)
690 else if (Imm==NVPTX::PTXLdStInstCode::V4)
694 llvm_unreachable("Unknown Modifier");
697 llvm_unreachable("Empty Modifier");
700 void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
702 emitLinkageDirective(F,O);
703 if (llvm::isKernelFunction(*F))
707 printReturnValStr(F, O);
708 O << *CurrentFnSym << "\n";
709 emitFunctionParamList(F, O);
713 static bool usedInGlobalVarDef(const Constant *C)
718 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
719 if (GV->getName().str() == "llvm.used")
724 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
726 const Constant *C = dyn_cast<Constant>(*ui);
727 if (usedInGlobalVarDef(C))
733 static bool usedInOneFunc(const User *U, Function const *&oneFunc)
735 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
736 if (othergv->getName().str() == "llvm.used")
740 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
741 if (instr->getParent() && instr->getParent()->getParent()) {
742 const Function *curFunc = instr->getParent()->getParent();
743 if (oneFunc && (curFunc != oneFunc))
752 if (const MDNode *md = dyn_cast<MDNode>(U))
753 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
754 (md->getName().str() == "llvm.dbg.sp")))
758 for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
760 if (usedInOneFunc(*ui, oneFunc) == false)
766 /* Find out if a global variable can be demoted to local scope.
767 * Currently, this is valid for CUDA shared variables, which have local
768 * scope and global lifetime. So the conditions to check are :
769 * 1. Is the global variable in shared address space?
770 * 2. Does it have internal linkage?
771 * 3. Is the global variable referenced only in one function?
773 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
774 if (gv->hasInternalLinkage() == false)
776 const PointerType *Pty = gv->getType();
777 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
780 const Function *oneFunc = 0;
782 bool flag = usedInOneFunc(gv, oneFunc);
791 static bool useFuncSeen(const Constant *C,
792 llvm::DenseMap<const Function *, bool> &seenMap) {
793 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
795 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
796 if (useFuncSeen(cu, seenMap))
798 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
799 const BasicBlock *bb = I->getParent();
801 const Function *caller = bb->getParent();
802 if (!caller) continue;
803 if (seenMap.find(caller) != seenMap.end())
810 void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
811 llvm::DenseMap<const Function *, bool> seenMap;
812 for (Module::const_iterator FI=M.begin(), FE=M.end();
814 const Function *F = FI;
816 if (F->isDeclaration()) {
819 if (F->getIntrinsicID())
821 CurrentFnSym = Mang->getSymbol(F);
822 emitDeclaration(F, O);
825 for (Value::const_use_iterator iter=F->use_begin(),
826 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
827 if (const Constant *C = dyn_cast<Constant>(*iter)) {
828 if (usedInGlobalVarDef(C)) {
829 // The use is in the initialization of a global variable
830 // that is a function pointer, so print a declaration
831 // for the original function
832 CurrentFnSym = Mang->getSymbol(F);
833 emitDeclaration(F, O);
836 // Emit a declaration of this function if the function that
837 // uses this constant expr has already been seen.
838 if (useFuncSeen(C, seenMap)) {
839 CurrentFnSym = Mang->getSymbol(F);
840 emitDeclaration(F, O);
845 if (!isa<Instruction>(*iter)) continue;
846 const Instruction *instr = cast<Instruction>(*iter);
847 const BasicBlock *bb = instr->getParent();
849 const Function *caller = bb->getParent();
850 if (!caller) continue;
852 // If a caller has already been seen, then the caller is
853 // appearing in the module before the callee. so print out
854 // a declaration for the callee.
855 if (seenMap.find(caller) != seenMap.end()) {
856 CurrentFnSym = Mang->getSymbol(F);
857 emitDeclaration(F, O);
865 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
866 DebugInfoFinder DbgFinder;
867 DbgFinder.processModule(M);
870 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
871 E = DbgFinder.compile_unit_end(); I != E; ++I) {
872 DICompileUnit DIUnit(*I);
873 StringRef Filename(DIUnit.getFilename());
874 StringRef Dirname(DIUnit.getDirectory());
875 SmallString<128> FullPathName = Dirname;
876 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
877 sys::path::append(FullPathName, Filename);
878 Filename = FullPathName.str();
880 if (filenameMap.find(Filename.str()) != filenameMap.end())
882 filenameMap[Filename.str()] = i;
883 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
887 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
888 E = DbgFinder.subprogram_end(); I != E; ++I) {
890 StringRef Filename(SP.getFilename());
891 StringRef Dirname(SP.getDirectory());
892 SmallString<128> FullPathName = Dirname;
893 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
894 sys::path::append(FullPathName, Filename);
895 Filename = FullPathName.str();
897 if (filenameMap.find(Filename.str()) != filenameMap.end())
899 filenameMap[Filename.str()] = i;
904 bool NVPTXAsmPrinter::doInitialization (Module &M) {
906 SmallString<128> Str1;
907 raw_svector_ostream OS1(Str1);
909 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
910 MMI->AnalyzeModule(M);
912 // We need to call the parent's one explicitly.
913 //bool Result = AsmPrinter::doInitialization(M);
915 // Initialize TargetLoweringObjectFile.
916 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
917 .Initialize(OutContext, TM);
919 Mang = new Mangler(OutContext, *TM.getDataLayout());
921 // Emit header before any dwarf directives are emitted below.
923 OutStreamer.EmitRawText(OS1.str());
926 // Already commented out
927 //bool Result = AsmPrinter::doInitialization(M);
930 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
931 recordAndEmitFilenames(M);
933 SmallString<128> Str2;
934 raw_svector_ostream OS2(Str2);
936 emitDeclarations(M, OS2);
938 // As ptxas does not support forward references of globals, we need to first
939 // sort the list of module-level globals in def-use order. We visit each
940 // global variable in order, and ensure that we emit it *after* its dependent
941 // globals. We use a little extra memory maintaining both a set and a list to
942 // have fast searches while maintaining a strict ordering.
943 SmallVector<GlobalVariable*,8> Globals;
944 DenseSet<GlobalVariable*> GVVisited;
945 DenseSet<GlobalVariable*> GVVisiting;
947 // Visit each global variable, in order
948 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
950 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
952 assert(GVVisited.size() == M.getGlobalList().size() &&
953 "Missed a global variable");
954 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
956 // Print out module-level global variables in proper order
957 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
958 printModuleLevelGV(Globals[i], OS2);
962 OutStreamer.EmitRawText(OS2.str());
963 return false; // success
966 void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
968 O << "// Generated by LLVM NVPTX Back-End\n";
972 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
973 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
976 O << nvptxSubtarget.getTargetName();
978 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
979 O << ", texmode_independent";
980 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
981 if (!nvptxSubtarget.hasDouble())
982 O << ", map_f64_to_f32";
985 if (MAI->doesSupportDebugInformation())
990 O << ".address_size ";
991 if (nvptxSubtarget.is64Bit())
1000 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1001 // XXX Temproarily remove global variables so that doFinalization() will not
1002 // emit them again (global variables are emitted at beginning).
1004 Module::GlobalListType &global_list = M.getGlobalList();
1005 int i, n = global_list.size();
1006 GlobalVariable **gv_array = new GlobalVariable* [n];
1008 // first, back-up GlobalVariable in gv_array
1010 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1012 gv_array[i++] = &*I;
1014 // second, empty global_list
1015 while (!global_list.empty())
1016 global_list.remove(global_list.begin());
1018 // call doFinalization
1019 bool ret = AsmPrinter::doFinalization(M);
1021 // now we restore global variables
1022 for (i = 0; i < n; i ++)
1023 global_list.insert(global_list.end(), gv_array[i]);
1029 //bool Result = AsmPrinter::doFinalization(M);
1030 // Instead of calling the parents doFinalization, we may
1031 // clone parents doFinalization and customize here.
1032 // Currently, we if NVISA out the EmitGlobals() in
1033 // parent's doFinalization, which is too intrusive.
1035 // Same for the doInitialization.
1039 // This function emits appropriate linkage directives for
1040 // functions and global variables.
1042 // extern function declaration -> .extern
1043 // extern function definition -> .visible
1044 // external global variable with init -> .visible
1045 // external without init -> .extern
1046 // appending -> not allowed, assert.
1048 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
1050 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1051 if (V->hasExternalLinkage()) {
1052 if (isa<GlobalVariable>(V)) {
1053 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1055 if (GVar->hasInitializer())
1060 } else if (V->isDeclaration())
1064 } else if (V->hasAppendingLinkage()) {
1066 msg.append("Error: ");
1067 msg.append("Symbol ");
1069 msg.append(V->getName().str());
1070 msg.append("has unsupported appending linkage type");
1071 llvm_unreachable(msg.c_str());
1077 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1078 bool processDemoted) {
1081 if (GVar->hasSection()) {
1082 if (GVar->getSection() == "llvm.metadata")
1086 const DataLayout *TD = TM.getDataLayout();
1088 // GlobalVariables are always constant pointers themselves.
1089 const PointerType *PTy = GVar->getType();
1090 Type *ETy = PTy->getElementType();
1092 if (GVar->hasExternalLinkage()) {
1093 if (GVar->hasInitializer())
1099 if (llvm::isTexture(*GVar)) {
1100 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1104 if (llvm::isSurface(*GVar)) {
1105 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1109 if (GVar->isDeclaration()) {
1110 // (extern) declarations, no definition or initializer
1111 // Currently the only known declaration is for an automatic __local
1112 // (.shared) promoted to global.
1113 emitPTXGlobalVariable(GVar, O);
1118 if (llvm::isSampler(*GVar)) {
1119 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1121 Constant *Initializer = NULL;
1122 if (GVar->hasInitializer())
1123 Initializer = GVar->getInitializer();
1124 ConstantInt *CI = NULL;
1126 CI = dyn_cast<ConstantInt>(Initializer);
1128 unsigned sample=CI->getZExtValue();
1132 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1133 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1134 O << "addr_mode_" << i << " = ";
1136 case 0: O << "wrap"; break;
1137 case 1: O << "clamp_to_border"; break;
1138 case 2: O << "clamp_to_edge"; break;
1139 case 3: O << "wrap"; break;
1140 case 4: O << "mirror"; break;
1144 O << "filter_mode = ";
1145 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1146 case 0: O << "nearest"; break;
1147 case 1: O << "linear"; break;
1148 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1149 default: O << "nearest"; break;
1151 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1152 O << ", force_unnormalized_coords = 1";
1161 if (GVar->hasPrivateLinkage()) {
1163 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1166 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1167 if (!strncmp(GVar->getName().data(), "filename", 8))
1169 if (GVar->use_empty())
1173 const Function *demotedFunc = 0;
1174 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1175 O << "// " << GVar->getName().str() << " has been demoted\n";
1176 if (localDecls.find(demotedFunc) != localDecls.end())
1177 localDecls[demotedFunc].push_back(GVar);
1179 std::vector<GlobalVariable *> temp;
1180 temp.push_back(GVar);
1181 localDecls[demotedFunc] = temp;
1187 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1188 if (GVar->getAlignment() == 0)
1189 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1191 O << " .align " << GVar->getAlignment();
1194 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1196 O << getPTXFundamentalTypeStr(ETy, false);
1198 O << *Mang->getSymbol(GVar);
1200 // Ptx allows variable initilization only for constant and global state
1202 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1203 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1204 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1205 && GVar->hasInitializer()) {
1206 Constant *Initializer = GVar->getInitializer();
1207 if (!Initializer->isNullValue()) {
1209 printScalarConstant(Initializer, O);
1213 unsigned int ElementSize =0;
1215 // Although PTX has direct support for struct type and array type and
1216 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1217 // targets that support these high level field accesses. Structs, arrays
1218 // and vectors are lowered into arrays of bytes.
1219 switch (ETy->getTypeID()) {
1220 case Type::StructTyID:
1221 case Type::ArrayTyID:
1222 case Type::VectorTyID:
1223 ElementSize = TD->getTypeStoreSize(ETy);
1224 // Ptx allows variable initilization only for constant and
1225 // global state spaces.
1226 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1227 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1228 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1229 && GVar->hasInitializer()) {
1230 Constant *Initializer = GVar->getInitializer();
1231 if (!isa<UndefValue>(Initializer) &&
1232 !Initializer->isNullValue()) {
1233 AggBuffer aggBuffer(ElementSize, O, *this);
1234 bufferAggregateConstant(Initializer, &aggBuffer);
1235 if (aggBuffer.numSymbols) {
1236 if (nvptxSubtarget.is64Bit()) {
1237 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1241 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1247 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1256 O << " .b8 " << *Mang->getSymbol(GVar) ;
1265 O << " .b8 " << *Mang->getSymbol(GVar);
1274 assert( 0 && "type not supported yet");
1281 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1282 if (localDecls.find(f) == localDecls.end())
1285 std::vector<GlobalVariable *> &gvars = localDecls[f];
1287 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1288 O << "\t// demoted variable\n\t";
1289 printModuleLevelGV(gvars[i], O, true);
1293 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1294 raw_ostream &O) const {
1295 switch (AddressSpace) {
1296 case llvm::ADDRESS_SPACE_LOCAL:
1299 case llvm::ADDRESS_SPACE_GLOBAL:
1302 case llvm::ADDRESS_SPACE_CONST:
1303 // This logic should be consistent with that in
1304 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1305 if (nvptxSubtarget.hasGenericLdSt())
1310 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1313 case llvm::ADDRESS_SPACE_SHARED:
1317 report_fatal_error("Bad address space found while emitting PTX");
1322 std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1323 bool useB4PTR) const {
1324 switch (Ty->getTypeID()) {
1326 llvm_unreachable("unexpected type");
1328 case Type::IntegerTyID: {
1329 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1332 else if (NumBits <= 64) {
1333 std::string name = "u";
1334 return name + utostr(NumBits);
1336 llvm_unreachable("Integer too large");
1341 case Type::FloatTyID:
1343 case Type::DoubleTyID:
1345 case Type::PointerTyID:
1346 if (nvptxSubtarget.is64Bit())
1347 if (useB4PTR) return "b64";
1350 if (useB4PTR) return "b32";
1353 llvm_unreachable("unexpected type");
1357 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1360 const DataLayout *TD = TM.getDataLayout();
1362 // GlobalVariables are always constant pointers themselves.
1363 const PointerType *PTy = GVar->getType();
1364 Type *ETy = PTy->getElementType();
1367 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1368 if (GVar->getAlignment() == 0)
1369 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1371 O << " .align " << GVar->getAlignment();
1373 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1375 O << getPTXFundamentalTypeStr(ETy);
1377 O << *Mang->getSymbol(GVar);
1381 int64_t ElementSize =0;
1383 // Although PTX has direct support for struct type and array type and LLVM IR
1384 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1385 // support these high level field accesses. Structs and arrays are lowered
1386 // into arrays of bytes.
1387 switch (ETy->getTypeID()) {
1388 case Type::StructTyID:
1389 case Type::ArrayTyID:
1390 case Type::VectorTyID:
1391 ElementSize = TD->getTypeStoreSize(ETy);
1392 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1394 O << itostr(ElementSize) ;
1399 assert( 0 && "type not supported yet");
1406 getOpenCLAlignment(const DataLayout *TD,
1408 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1409 return TD->getPrefTypeAlignment(Ty);
1411 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1413 return getOpenCLAlignment(TD, ATy->getElementType());
1415 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1417 Type *ETy = VTy->getElementType();
1418 unsigned int numE = VTy->getNumElements();
1419 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1426 const StructType *STy = dyn_cast<StructType>(Ty);
1428 unsigned int alignStruct = 1;
1429 // Go through each element of the struct and find the
1430 // largest alignment.
1431 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1432 Type *ETy = STy->getElementType(i);
1433 unsigned int align = getOpenCLAlignment(TD, ETy);
1434 if (align > alignStruct)
1435 alignStruct = align;
1440 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1442 return TD->getPointerPrefAlignment();
1443 return TD->getPrefTypeAlignment(Ty);
1446 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1447 int paramIndex, raw_ostream &O) {
1448 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1449 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1450 O << *CurrentFnSym << "_param_" << paramIndex;
1452 std::string argName = I->getName();
1453 const char *p = argName.c_str();
1464 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1465 Function::const_arg_iterator I, E;
1468 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1469 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1470 O << *CurrentFnSym << "_param_" << paramIndex;
1474 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1475 if (i==paramIndex) {
1476 printParamName(I, paramIndex, O);
1480 llvm_unreachable("paramIndex out of bound");
1483 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1485 const DataLayout *TD = TM.getDataLayout();
1486 const AttributeSet &PAL = F->getAttributes();
1487 const TargetLowering *TLI = TM.getTargetLowering();
1488 Function::const_arg_iterator I, E;
1489 unsigned paramIndex = 0;
1491 bool isKernelFunc = llvm::isKernelFunction(*F);
1492 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1493 MVT thePointerTy = TLI->getPointerTy();
1497 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1498 const Type *Ty = I->getType();
1505 // Handle image/sampler parameters
1506 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1507 if (llvm::isImage(*I)) {
1508 std::string sname = I->getName();
1509 if (llvm::isImageWriteOnly(*I))
1510 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1511 else // Default image is read_only
1512 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1514 else // Should be llvm::isSampler(*I)
1515 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1520 if (PAL.hasAttribute(paramIndex+1, Attribute::ByVal) == false) {
1522 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1525 // Special handling for pointer arguments to kernel
1526 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1528 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1529 Type *ETy = PTy->getElementType();
1530 int addrSpace = PTy->getAddressSpace();
1535 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1536 O << ".ptr .const ";
1538 case llvm::ADDRESS_SPACE_SHARED:
1539 O << ".ptr .shared ";
1541 case llvm::ADDRESS_SPACE_GLOBAL:
1542 case llvm::ADDRESS_SPACE_CONST:
1543 O << ".ptr .global ";
1546 O << ".align " << (int)getOpenCLAlignment(TD, ETy) << " ";
1548 printParamName(I, paramIndex, O);
1552 // non-pointer scalar to kernel func
1554 << getPTXFundamentalTypeStr(Ty) << " ";
1555 printParamName(I, paramIndex, O);
1558 // Non-kernel function, just print .param .b<size> for ABI
1559 // and .reg .b<size> for non ABY
1561 if (isa<IntegerType>(Ty)) {
1562 sz = cast<IntegerType>(Ty)->getBitWidth();
1563 if (sz < 32) sz = 32;
1565 else if (isa<PointerType>(Ty))
1566 sz = thePointerTy.getSizeInBits();
1568 sz = Ty->getPrimitiveSizeInBits();
1570 O << "\t.param .b" << sz << " ";
1572 O << "\t.reg .b" << sz << " ";
1573 printParamName(I, paramIndex, O);
1577 // param has byVal attribute. So should be a pointer
1578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1580 "Param with byval attribute should be a pointer type");
1581 Type *ETy = PTy->getElementType();
1583 if (isABI || isKernelFunc) {
1584 // Just print .param .b8 .align <a> .param[size];
1585 // <a> = PAL.getparamalignment
1586 // size = typeallocsize of element type
1587 unsigned align = PAL.getParamAlignment(paramIndex+1);
1589 align = TD->getABITypeAlignment(ETy);
1591 unsigned sz = TD->getTypeAllocSize(ETy);
1592 O << "\t.param .align " << align
1594 printParamName(I, paramIndex, O);
1595 O << "[" << sz << "]";
1598 // Split the ETy into constituent parts and
1599 // print .param .b<size> <name> for each part.
1600 // Further, if a part is vector, print the above for
1601 // each vector element.
1602 SmallVector<EVT, 16> vtparts;
1603 ComputeValueVTs(*TLI, ETy, vtparts);
1604 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
1606 EVT elemtype = vtparts[i];
1607 if (vtparts[i].isVector()) {
1608 elems = vtparts[i].getVectorNumElements();
1609 elemtype = vtparts[i].getVectorElementType();
1612 for (unsigned j=0,je=elems; j!=je; ++j) {
1613 unsigned sz = elemtype.getSizeInBits();
1614 if (elemtype.isInteger() && (sz < 32)) sz = 32;
1615 O << "\t.reg .b" << sz << " ";
1616 printParamName(I, paramIndex, O);
1617 if (j<je-1) O << ",\n";
1631 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1633 const Function *F = MF.getFunction();
1634 emitFunctionParamList(F, O);
1638 void NVPTXAsmPrinter::
1639 setAndEmitFunctionVirtualRegisters(const MachineFunction &MF) {
1640 SmallString<128> Str;
1641 raw_svector_ostream O(Str);
1643 // Map the global virtual register number to a register class specific
1644 // virtual register number starting from 1 with that class.
1645 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1646 //unsigned numRegClasses = TRI->getNumRegClasses();
1648 // Emit the Fake Stack Object
1649 const MachineFrameInfo *MFI = MF.getFrameInfo();
1650 int NumBytes = (int) MFI->getStackSize();
1652 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t"
1654 << getFunctionNumber() << "[" << NumBytes << "];\n";
1655 if (nvptxSubtarget.is64Bit()) {
1656 O << "\t.reg .b64 \t%SP;\n";
1657 O << "\t.reg .b64 \t%SPL;\n";
1660 O << "\t.reg .b32 \t%SP;\n";
1661 O << "\t.reg .b32 \t%SPL;\n";
1665 // Go through all virtual registers to establish the mapping between the
1667 // register number and the per class virtual register number.
1668 // We use the per class virtual register number in the ptx output.
1669 unsigned int numVRs = MRI->getNumVirtRegs();
1670 for (unsigned i=0; i< numVRs; i++) {
1671 unsigned int vr = TRI->index2VirtReg(i);
1672 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1673 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[RC->getID()];
1674 int n = regmap.size();
1675 regmap.insert(std::make_pair(vr, n+1));
1678 // Emit register declarations
1679 // @TODO: Extract out the real register usage
1680 O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1681 O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1682 O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1683 O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1684 O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1685 O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1686 O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1688 // Emit declaration of the virtual registers or 'physical' registers for
1689 // each register class
1690 //for (unsigned i=0; i< numRegClasses; i++) {
1691 // std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[i];
1692 // const TargetRegisterClass *RC = TRI->getRegClass(i);
1693 // std::string rcname = getNVPTXRegClassName(RC);
1694 // std::string rcStr = getNVPTXRegClassStr(RC);
1695 // //int n = regmap.size();
1696 // if (!isNVPTXVectorRegClass(RC)) {
1697 // O << "\t.reg " << rcname << " \t" << rcStr << "<"
1698 // << NVPTXNumRegisters << ">;\n";
1701 // Only declare those registers that may be used. And do not emit vector
1703 // they are all elementized to scalar registers.
1704 //if (n && !isNVPTXVectorRegClass(RC)) {
1705 // if (RegAllocNilUsed) {
1706 // O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1710 // O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1711 // << "<" << 32 << ">;\n";
1716 OutStreamer.EmitRawText(O.str());
1720 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1721 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1723 unsigned int numHex;
1726 if (Fp->getType()->getTypeID()==Type::FloatTyID) {
1729 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1731 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1734 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1737 llvm_unreachable("unsupported fp type");
1739 APInt API = APF.bitcastToAPInt();
1740 std::string hexstr(utohexstr(API.getZExtValue()));
1742 if (hexstr.length() < numHex)
1743 O << std::string(numHex - hexstr.length(), '0');
1744 O << utohexstr(API.getZExtValue());
1747 void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1748 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1749 O << CI->getValue();
1752 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1753 printFPConstant(CFP, O);
1756 if (isa<ConstantPointerNull>(CPV)) {
1760 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1761 O << *Mang->getSymbol(GVar);
1764 if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1765 Value *v = Cexpr->stripPointerCasts();
1766 if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1767 O << *Mang->getSymbol(GVar);
1770 O << *LowerConstant(CPV, *this);
1774 llvm_unreachable("Not scalar type found in printScalarConstant()");
1778 void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1779 AggBuffer *aggBuffer) {
1781 const DataLayout *TD = TM.getDataLayout();
1783 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1784 int s = TD->getTypeAllocSize(CPV->getType());
1787 aggBuffer->addZeros(s);
1792 switch (CPV->getType()->getTypeID()) {
1794 case Type::IntegerTyID: {
1795 const Type *ETy = CPV->getType();
1796 if ( ETy == Type::getInt8Ty(CPV->getContext()) ){
1798 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1800 aggBuffer->addBytes(ptr, 1, Bytes);
1801 } else if ( ETy == Type::getInt16Ty(CPV->getContext()) ) {
1803 (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1804 ptr = (unsigned char*)&int16;
1805 aggBuffer->addBytes(ptr, 2, Bytes);
1806 } else if ( ETy == Type::getInt32Ty(CPV->getContext()) ) {
1807 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1808 int int32 =(int)(constInt->getZExtValue());
1809 ptr = (unsigned char*)&int32;
1810 aggBuffer->addBytes(ptr, 4, Bytes);
1812 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1813 if (ConstantInt *constInt =
1814 dyn_cast<ConstantInt>(ConstantFoldConstantExpression(
1816 int int32 =(int)(constInt->getZExtValue());
1817 ptr = (unsigned char*)&int32;
1818 aggBuffer->addBytes(ptr, 4, Bytes);
1821 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1822 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1823 aggBuffer->addSymbol(v);
1824 aggBuffer->addZeros(4);
1828 llvm_unreachable("unsupported integer const type");
1829 } else if (ETy == Type::getInt64Ty(CPV->getContext()) ) {
1830 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1831 long long int64 =(long long)(constInt->getZExtValue());
1832 ptr = (unsigned char*)&int64;
1833 aggBuffer->addBytes(ptr, 8, Bytes);
1835 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1836 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1837 ConstantFoldConstantExpression(Cexpr, TD))) {
1838 long long int64 =(long long)(constInt->getZExtValue());
1839 ptr = (unsigned char*)&int64;
1840 aggBuffer->addBytes(ptr, 8, Bytes);
1843 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1844 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1845 aggBuffer->addSymbol(v);
1846 aggBuffer->addZeros(8);
1850 llvm_unreachable("unsupported integer const type");
1852 llvm_unreachable("unsupported integer const type");
1855 case Type::FloatTyID:
1856 case Type::DoubleTyID: {
1857 ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1858 const Type* Ty = CFP->getType();
1859 if (Ty == Type::getFloatTy(CPV->getContext())) {
1860 float float32 = (float)CFP->getValueAPF().convertToFloat();
1861 ptr = (unsigned char*)&float32;
1862 aggBuffer->addBytes(ptr, 4, Bytes);
1863 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1864 double float64 = CFP->getValueAPF().convertToDouble();
1865 ptr = (unsigned char*)&float64;
1866 aggBuffer->addBytes(ptr, 8, Bytes);
1869 llvm_unreachable("unsupported fp const type");
1873 case Type::PointerTyID: {
1874 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1875 aggBuffer->addSymbol(GVar);
1877 else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1878 Value *v = Cexpr->stripPointerCasts();
1879 aggBuffer->addSymbol(v);
1881 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1882 aggBuffer->addZeros(s);
1886 case Type::ArrayTyID:
1887 case Type::VectorTyID:
1888 case Type::StructTyID: {
1889 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1890 isa<ConstantStruct>(CPV)) {
1891 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1892 bufferAggregateConstant(CPV, aggBuffer);
1893 if ( Bytes > ElementSize )
1894 aggBuffer->addZeros(Bytes-ElementSize);
1896 else if (isa<ConstantAggregateZero>(CPV))
1897 aggBuffer->addZeros(Bytes);
1899 llvm_unreachable("Unexpected Constant type");
1904 llvm_unreachable("unsupported type");
1908 void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1909 AggBuffer *aggBuffer) {
1910 const DataLayout *TD = TM.getDataLayout();
1914 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1915 if (CPV->getNumOperands())
1916 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1917 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1921 if (const ConstantDataSequential *CDS =
1922 dyn_cast<ConstantDataSequential>(CPV)) {
1923 if (CDS->getNumElements())
1924 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1925 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1931 if (isa<ConstantStruct>(CPV)) {
1932 if (CPV->getNumOperands()) {
1933 StructType *ST = cast<StructType>(CPV->getType());
1934 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1936 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1937 TD->getTypeAllocSize(ST)
1938 - TD->getStructLayout(ST)->getElementOffset(i);
1940 Bytes = TD->getStructLayout(ST)->getElementOffset(i+1) -
1941 TD->getStructLayout(ST)->getElementOffset(i);
1942 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes,
1948 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1951 // buildTypeNameMap - Run through symbol table looking for type names.
1955 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1957 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1959 if (PI != TypeNameMap.end() &&
1960 (!PI->second.compare("struct._image1d_t") ||
1961 !PI->second.compare("struct._image2d_t") ||
1962 !PI->second.compare("struct._image3d_t")))
1968 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1970 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1971 unsigned AsmVariant,
1972 const char *ExtraCode,
1974 if (ExtraCode && ExtraCode[0]) {
1975 if (ExtraCode[1] != 0) return true; // Unknown modifier.
1977 switch (ExtraCode[0]) {
1979 // See if this is a generic print operand
1980 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1986 printOperand(MI, OpNo, O);
1991 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1993 unsigned AsmVariant,
1994 const char *ExtraCode,
1996 if (ExtraCode && ExtraCode[0])
1997 return true; // Unknown modifier
2000 printMemOperand(MI, OpNo, O);
2006 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
2008 switch(MI.getOpcode()) {
2011 case NVPTX::CallArgBeginInst: case NVPTX::CallArgEndInst0:
2012 case NVPTX::CallArgEndInst1: case NVPTX::CallArgF32:
2013 case NVPTX::CallArgF64: case NVPTX::CallArgI16:
2014 case NVPTX::CallArgI32: case NVPTX::CallArgI32imm:
2015 case NVPTX::CallArgI64: case NVPTX::CallArgI8:
2016 case NVPTX::CallArgParam: case NVPTX::CallVoidInst:
2017 case NVPTX::CallVoidInstReg: case NVPTX::Callseq_End:
2018 case NVPTX::CallVoidInstReg64:
2019 case NVPTX::DeclareParamInst: case NVPTX::DeclareRetMemInst:
2020 case NVPTX::DeclareRetRegInst: case NVPTX::DeclareRetScalarInst:
2021 case NVPTX::DeclareScalarParamInst: case NVPTX::DeclareScalarRegInst:
2022 case NVPTX::StoreParamF32: case NVPTX::StoreParamF64:
2023 case NVPTX::StoreParamI16: case NVPTX::StoreParamI32:
2024 case NVPTX::StoreParamI64: case NVPTX::StoreParamI8:
2025 case NVPTX::StoreParamS32I8: case NVPTX::StoreParamU32I8:
2026 case NVPTX::StoreParamS32I16: case NVPTX::StoreParamU32I16:
2027 case NVPTX::StoreParamScalar2F32: case NVPTX::StoreParamScalar2F64:
2028 case NVPTX::StoreParamScalar2I16: case NVPTX::StoreParamScalar2I32:
2029 case NVPTX::StoreParamScalar2I64: case NVPTX::StoreParamScalar2I8:
2030 case NVPTX::StoreParamScalar4F32: case NVPTX::StoreParamScalar4I16:
2031 case NVPTX::StoreParamScalar4I32: case NVPTX::StoreParamScalar4I8:
2032 case NVPTX::StoreParamV2F32: case NVPTX::StoreParamV2F64:
2033 case NVPTX::StoreParamV2I16: case NVPTX::StoreParamV2I32:
2034 case NVPTX::StoreParamV2I64: case NVPTX::StoreParamV2I8:
2035 case NVPTX::StoreParamV4F32: case NVPTX::StoreParamV4I16:
2036 case NVPTX::StoreParamV4I32: case NVPTX::StoreParamV4I8:
2037 case NVPTX::StoreRetvalF32: case NVPTX::StoreRetvalF64:
2038 case NVPTX::StoreRetvalI16: case NVPTX::StoreRetvalI32:
2039 case NVPTX::StoreRetvalI64: case NVPTX::StoreRetvalI8:
2040 case NVPTX::StoreRetvalScalar2F32: case NVPTX::StoreRetvalScalar2F64:
2041 case NVPTX::StoreRetvalScalar2I16: case NVPTX::StoreRetvalScalar2I32:
2042 case NVPTX::StoreRetvalScalar2I64: case NVPTX::StoreRetvalScalar2I8:
2043 case NVPTX::StoreRetvalScalar4F32: case NVPTX::StoreRetvalScalar4I16:
2044 case NVPTX::StoreRetvalScalar4I32: case NVPTX::StoreRetvalScalar4I8:
2045 case NVPTX::StoreRetvalV2F32: case NVPTX::StoreRetvalV2F64:
2046 case NVPTX::StoreRetvalV2I16: case NVPTX::StoreRetvalV2I32:
2047 case NVPTX::StoreRetvalV2I64: case NVPTX::StoreRetvalV2I8:
2048 case NVPTX::StoreRetvalV4F32: case NVPTX::StoreRetvalV4I16:
2049 case NVPTX::StoreRetvalV4I32: case NVPTX::StoreRetvalV4I8:
2050 case NVPTX::LastCallArgF32: case NVPTX::LastCallArgF64:
2051 case NVPTX::LastCallArgI16: case NVPTX::LastCallArgI32:
2052 case NVPTX::LastCallArgI32imm: case NVPTX::LastCallArgI64:
2053 case NVPTX::LastCallArgI8: case NVPTX::LastCallArgParam:
2054 case NVPTX::LoadParamMemF32: case NVPTX::LoadParamMemF64:
2055 case NVPTX::LoadParamMemI16: case NVPTX::LoadParamMemI32:
2056 case NVPTX::LoadParamMemI64: case NVPTX::LoadParamMemI8:
2057 case NVPTX::LoadParamRegF32: case NVPTX::LoadParamRegF64:
2058 case NVPTX::LoadParamRegI16: case NVPTX::LoadParamRegI32:
2059 case NVPTX::LoadParamRegI64: case NVPTX::LoadParamRegI8:
2060 case NVPTX::LoadParamScalar2F32: case NVPTX::LoadParamScalar2F64:
2061 case NVPTX::LoadParamScalar2I16: case NVPTX::LoadParamScalar2I32:
2062 case NVPTX::LoadParamScalar2I64: case NVPTX::LoadParamScalar2I8:
2063 case NVPTX::LoadParamScalar4F32: case NVPTX::LoadParamScalar4I16:
2064 case NVPTX::LoadParamScalar4I32: case NVPTX::LoadParamScalar4I8:
2065 case NVPTX::LoadParamV2F32: case NVPTX::LoadParamV2F64:
2066 case NVPTX::LoadParamV2I16: case NVPTX::LoadParamV2I32:
2067 case NVPTX::LoadParamV2I64: case NVPTX::LoadParamV2I8:
2068 case NVPTX::LoadParamV4F32: case NVPTX::LoadParamV4I16:
2069 case NVPTX::LoadParamV4I32: case NVPTX::LoadParamV4I8:
2070 case NVPTX::PrototypeInst: case NVPTX::DBG_VALUE:
2076 // Force static initialization.
2077 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2078 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2079 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2083 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2084 std::stringstream temp;
2085 LineReader * reader = this->getReader(filename.str());
2087 temp << filename.str();
2091 temp << reader->readLine(line);
2093 this->OutStreamer.EmitRawText(Twine(temp.str()));
2097 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2098 if (reader == NULL) {
2099 reader = new LineReader(filename);
2102 if (reader->fileName() != filename) {
2104 reader = new LineReader(filename);
2112 LineReader::readLine(unsigned lineNum) {
2113 if (lineNum < theCurLine) {
2115 fstr.seekg(0,std::ios::beg);
2117 while (theCurLine < lineNum) {
2118 fstr.getline(buff,500);
2124 // Force static initialization.
2125 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2126 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2127 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);