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 "NVPTXRegisterInfo.h"
20 #include "NVPTXTargetMachine.h"
21 #include "NVPTXUtilities.h"
22 #include "cl_common_defines.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/Analysis.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/DebugInfo.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TimeValue.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "NVPTXGenAsmWriter.inc"
51 bool RegAllocNilUsed = true;
53 #define DEPOTNAME "__local_depot"
56 EmitLineNumbers("nvptx-emit-line-numbers",
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
60 namespace llvm { bool InterleaveSrcInPtx = false; }
62 static cl::opt<bool, true>
63 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
64 cl::desc("NVPTX Specific: Emit source line in ptx file"),
65 cl::location(llvm::InterleaveSrcInPtx));
68 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
70 void DiscoverDependentGlobals(const Value *V,
71 DenseSet<const GlobalVariable *> &Globals) {
72 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
75 if (const User *U = dyn_cast<User>(V)) {
76 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
77 DiscoverDependentGlobals(U->getOperand(i), Globals);
83 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
84 /// instances to be emitted, but only after any dependents have been added
86 void VisitGlobalVariableForEmission(
87 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
88 DenseSet<const GlobalVariable *> &Visited,
89 DenseSet<const GlobalVariable *> &Visiting) {
90 // Have we already visited this one?
91 if (Visited.count(GV))
94 // Do we have a circular dependency?
95 if (Visiting.count(GV))
96 report_fatal_error("Circular dependency found in global variable set");
98 // Start visiting this global
101 // Make sure we visit all dependents first
102 DenseSet<const GlobalVariable *> Others;
103 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
104 DiscoverDependentGlobals(GV->getOperand(i), Others);
106 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
109 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
111 // Now we can visit ourself
118 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
119 // cannot just link to the existing version.
120 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
122 using namespace nvptx;
123 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
124 MCContext &Ctx = AP.OutContext;
126 if (CV->isNullValue() || isa<UndefValue>(CV))
127 return MCConstantExpr::Create(0, Ctx);
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
130 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
133 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
135 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
136 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
140 llvm_unreachable("Unknown constant value to lower!");
142 switch (CE->getOpcode()) {
144 // If the code isn't optimized, there may be outstanding folding
145 // opportunities. Attempt to fold the expression using DataLayout as a
146 // last resort before giving up.
147 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
149 return LowerConstant(C, AP);
151 // Otherwise report the problem to the user.
154 raw_string_ostream OS(S);
155 OS << "Unsupported expression in static initializer: ";
156 WriteAsOperand(OS, CE, /*PrintType=*/ false,
157 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
158 report_fatal_error(OS.str());
160 case Instruction::GetElementPtr: {
161 const DataLayout &TD = *AP.TM.getDataLayout();
162 // Generate a symbolic expression for the byte address
163 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
164 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
166 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
170 int64_t Offset = OffsetAI.getSExtValue();
171 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
175 case Instruction::Trunc:
176 // We emit the value and depend on the assembler to truncate the generated
177 // expression properly. This is important for differences between
178 // blockaddress labels. Since the two labels are in the same function, it
179 // is reasonable to treat their delta as a 32-bit value.
181 case Instruction::BitCast:
182 return LowerConstant(CE->getOperand(0), AP);
184 case Instruction::IntToPtr: {
185 const DataLayout &TD = *AP.TM.getDataLayout();
186 // Handle casts to pointers by changing them into casts to the appropriate
187 // integer type. This promotes constant folding and simplifies this code.
188 Constant *Op = CE->getOperand(0);
189 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
191 return LowerConstant(Op, AP);
194 case Instruction::PtrToInt: {
195 const DataLayout &TD = *AP.TM.getDataLayout();
196 // Support only foldable casts to/from pointers that can be eliminated by
197 // changing the pointer to the appropriately sized integer type.
198 Constant *Op = CE->getOperand(0);
199 Type *Ty = CE->getType();
201 const MCExpr *OpExpr = LowerConstant(Op, AP);
203 // We can emit the pointer value into this slot if the slot is an
204 // integer slot equal to the size of the pointer.
205 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
208 // Otherwise the pointer is smaller than the resultant integer, mask off
209 // the high bits so we are sure to get a proper truncation if the input is
211 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
212 const MCExpr *MaskExpr =
213 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
214 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
217 // The MC library also has a right-shift operator, but it isn't consistently
218 // signed or unsigned between different targets.
219 case Instruction::Add:
220 case Instruction::Sub:
221 case Instruction::Mul:
222 case Instruction::SDiv:
223 case Instruction::SRem:
224 case Instruction::Shl:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor: {
228 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
229 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
230 switch (CE->getOpcode()) {
232 llvm_unreachable("Unknown binary operator constant cast expr");
233 case Instruction::Add:
234 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
235 case Instruction::Sub:
236 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
237 case Instruction::Mul:
238 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
239 case Instruction::SDiv:
240 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
241 case Instruction::SRem:
242 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
243 case Instruction::Shl:
244 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
245 case Instruction::And:
246 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
247 case Instruction::Or:
248 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
249 case Instruction::Xor:
250 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
256 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
257 if (!EmitLineNumbers)
262 DebugLoc curLoc = MI.getDebugLoc();
264 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
267 if (prevDebugLoc == curLoc)
270 prevDebugLoc = curLoc;
272 if (curLoc.isUnknown())
275 const MachineFunction *MF = MI.getParent()->getParent();
276 //const TargetMachine &TM = MF->getTarget();
278 const LLVMContext &ctx = MF->getFunction()->getContext();
279 DIScope Scope(curLoc.getScope(ctx));
281 assert((!Scope || Scope.isScope()) &&
282 "Scope of a DebugLoc should be null or a DIScope.");
286 StringRef fileName(Scope.getFilename());
287 StringRef dirName(Scope.getDirectory());
288 SmallString<128> FullPathName = dirName;
289 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
290 sys::path::append(FullPathName, fileName);
291 fileName = FullPathName.str();
294 if (filenameMap.find(fileName.str()) == filenameMap.end())
297 // Emit the line from the source file.
298 if (llvm::InterleaveSrcInPtx)
299 this->emitSrcInText(fileName.str(), curLoc.getLine());
301 std::stringstream temp;
302 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
303 << " " << curLoc.getCol();
304 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
307 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
308 SmallString<128> Str;
309 raw_svector_ostream OS(Str);
310 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
311 emitLineNumberAsDotLoc(*MI);
312 printInstruction(MI, OS);
313 OutStreamer.EmitRawText(OS.str());
316 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
317 const DataLayout *TD = TM.getDataLayout();
318 const TargetLowering *TLI = TM.getTargetLowering();
320 Type *Ty = F->getReturnType();
322 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
324 if (Ty->getTypeID() == Type::VoidTyID)
330 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
332 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
333 size = ITy->getBitWidth();
337 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
338 size = Ty->getPrimitiveSizeInBits();
341 O << ".param .b" << size << " func_retval0";
342 } else if (isa<PointerType>(Ty)) {
343 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
346 if ((Ty->getTypeID() == Type::StructTyID) || 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))
364 unsigned retAlignment = 0;
365 if (!llvm::getAlign(*F, 0, retAlignment))
366 retAlignment = TD->getABITypeAlignment(Ty);
367 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
370 assert(false && "Unknown return type");
373 SmallVector<EVT, 16> vtparts;
374 ComputeValueVTs(*TLI, Ty, vtparts);
376 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
378 EVT elemtype = vtparts[i];
379 if (vtparts[i].isVector()) {
380 elems = vtparts[i].getVectorNumElements();
381 elemtype = vtparts[i].getVectorElementType();
384 for (unsigned j = 0, je = elems; j != je; ++j) {
385 unsigned sz = elemtype.getSizeInBits();
386 if (elemtype.isInteger() && (sz < 32))
388 O << ".reg .b" << sz << " func_retval" << idx;
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);
411 if (!GlobalsEmitted) {
412 emitGlobals(*MF->getFunction()->getParent());
413 GlobalsEmitted = true;
417 MRI = &MF->getRegInfo();
418 F = MF->getFunction();
419 emitLinkageDirective(F, O);
420 if (llvm::isKernelFunction(*F))
424 printReturnValStr(*MF, O);
429 emitFunctionParamList(*MF, O);
431 if (llvm::isKernelFunction(*F))
432 emitKernelFunctionDirectives(*F, O);
434 OutStreamer.EmitRawText(O.str());
436 prevDebugLoc = DebugLoc();
439 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
441 OutStreamer.EmitRawText(StringRef("{\n"));
442 setAndEmitFunctionVirtualRegisters(*MF);
444 SmallString<128> Str;
445 raw_svector_ostream O(Str);
446 emitDemotedVars(MF->getFunction(), O);
447 OutStreamer.EmitRawText(O.str());
450 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
451 OutStreamer.EmitRawText(StringRef("}\n"));
455 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
456 raw_ostream &O) const {
457 // If the NVVM IR has some of reqntid* specified, then output
458 // the reqntid directive, and set the unspecified ones to 1.
459 // If none of reqntid* is specified, don't output reqntid directive.
460 unsigned reqntidx, reqntidy, reqntidz;
461 bool specified = false;
462 if (llvm::getReqNTIDx(F, reqntidx) == false)
466 if (llvm::getReqNTIDy(F, reqntidy) == false)
470 if (llvm::getReqNTIDz(F, reqntidz) == false)
476 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
479 // If the NVVM IR has some of maxntid* specified, then output
480 // the maxntid directive, and set the unspecified ones to 1.
481 // If none of maxntid* is specified, don't output maxntid directive.
482 unsigned maxntidx, maxntidy, maxntidz;
484 if (llvm::getMaxNTIDx(F, maxntidx) == false)
488 if (llvm::getMaxNTIDy(F, maxntidy) == false)
492 if (llvm::getMaxNTIDz(F, maxntidz) == false)
498 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
502 if (llvm::getMinCTASm(F, mincta))
503 O << ".minnctapersm " << mincta << "\n";
506 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
508 const TargetRegisterClass *RC = MRI->getRegClass(vr);
510 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
511 unsigned mapped_vr = regmap[vr];
514 O << getNVPTXRegClassStr(RC) << mapped_vr;
517 report_fatal_error("Bad register!");
520 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
522 getVirtualRegisterName(vr, isVec, O);
525 void NVPTXAsmPrinter::printVecModifiedImmediate(
526 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
527 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
528 int Imm = (int) MO.getImm();
529 if (0 == strcmp(Modifier, "vecelem"))
530 O << "_" << vecelem[Imm];
531 else if (0 == strcmp(Modifier, "vecv4comm1")) {
532 if ((Imm < 0) || (Imm > 3))
534 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
535 if ((Imm < 4) || (Imm > 7))
537 } else if (0 == strcmp(Modifier, "vecv4pos")) {
540 O << "_" << vecelem[Imm % 4];
541 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
542 if ((Imm < 0) || (Imm > 1))
544 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
545 if ((Imm < 2) || (Imm > 3))
547 } else if (0 == strcmp(Modifier, "vecv2pos")) {
550 O << "_" << vecelem[Imm % 2];
552 llvm_unreachable("Unknown Modifier on immediate operand");
555 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
556 raw_ostream &O, const char *Modifier) {
557 const MachineOperand &MO = MI->getOperand(opNum);
558 switch (MO.getType()) {
559 case MachineOperand::MO_Register:
560 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
561 if (MO.getReg() == NVPTX::VRDepot)
562 O << DEPOTNAME << getFunctionNumber();
564 O << getRegisterName(MO.getReg());
567 emitVirtualRegister(MO.getReg(), false, O);
569 if (strcmp(Modifier, "vecfull") == 0)
570 emitVirtualRegister(MO.getReg(), true, O);
573 "Don't know how to handle the modifier on virtual register.");
578 case MachineOperand::MO_Immediate:
581 else if (strstr(Modifier, "vec") == Modifier)
582 printVecModifiedImmediate(MO, Modifier, O);
585 "Don't know how to handle modifier on immediate operand");
588 case MachineOperand::MO_FPImmediate:
589 printFPConstant(MO.getFPImm(), O);
592 case MachineOperand::MO_GlobalAddress:
593 O << *Mang->getSymbol(MO.getGlobal());
596 case MachineOperand::MO_ExternalSymbol: {
597 const char *symbname = MO.getSymbolName();
598 if (strstr(symbname, ".PARAM") == symbname) {
600 sscanf(symbname + 6, "%u[];", &index);
601 printParamName(index, O);
602 } else if (strstr(symbname, ".HLPPARAM") == symbname) {
604 sscanf(symbname + 9, "%u[];", &index);
605 O << *CurrentFnSym << "_param_" << index << "_offset";
611 case MachineOperand::MO_MachineBasicBlock:
612 O << *MO.getMBB()->getSymbol();
616 llvm_unreachable("Operand type not supported.");
620 void NVPTXAsmPrinter::printImplicitDef(const MachineInstr *MI,
621 raw_ostream &O) const {
623 O << "\t// Implicit def :";
624 //printOperand(MI, 0);
629 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
630 raw_ostream &O, const char *Modifier) {
631 printOperand(MI, opNum, O);
633 if (Modifier && !strcmp(Modifier, "add")) {
635 printOperand(MI, opNum + 1, O);
637 if (MI->getOperand(opNum + 1).isImm() &&
638 MI->getOperand(opNum + 1).getImm() == 0)
639 return; // don't print ',0' or '+0'
641 printOperand(MI, opNum + 1, O);
645 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
646 raw_ostream &O, const char *Modifier) {
648 const MachineOperand &MO = MI->getOperand(opNum);
649 int Imm = (int) MO.getImm();
650 if (!strcmp(Modifier, "volatile")) {
653 } else if (!strcmp(Modifier, "addsp")) {
655 case NVPTX::PTXLdStInstCode::GLOBAL:
658 case NVPTX::PTXLdStInstCode::SHARED:
661 case NVPTX::PTXLdStInstCode::LOCAL:
664 case NVPTX::PTXLdStInstCode::PARAM:
667 case NVPTX::PTXLdStInstCode::CONSTANT:
670 case NVPTX::PTXLdStInstCode::GENERIC:
671 if (!nvptxSubtarget.hasGenericLdSt())
675 llvm_unreachable("Wrong Address Space");
677 } else if (!strcmp(Modifier, "sign")) {
678 if (Imm == NVPTX::PTXLdStInstCode::Signed)
680 else if (Imm == NVPTX::PTXLdStInstCode::Unsigned)
684 } else if (!strcmp(Modifier, "vec")) {
685 if (Imm == NVPTX::PTXLdStInstCode::V2)
687 else if (Imm == NVPTX::PTXLdStInstCode::V4)
690 llvm_unreachable("Unknown Modifier");
692 llvm_unreachable("Empty Modifier");
695 void NVPTXAsmPrinter::printCvtMode(const MachineInstr *MI, int OpNum,
696 raw_ostream &O, const char *Modifier) {
697 const MachineOperand &MO = MI->getOperand(OpNum);
698 int64_t Imm = MO.getImm();
700 if (strcmp(Modifier, "ftz") == 0) {
702 if (Imm & NVPTX::PTXCvtMode::FTZ_FLAG)
704 } else if (strcmp(Modifier, "sat") == 0) {
706 if (Imm & NVPTX::PTXCvtMode::SAT_FLAG)
708 } else if (strcmp(Modifier, "base") == 0) {
710 switch (Imm & NVPTX::PTXCvtMode::BASE_MASK) {
713 case NVPTX::PTXCvtMode::NONE:
715 case NVPTX::PTXCvtMode::RNI:
718 case NVPTX::PTXCvtMode::RZI:
721 case NVPTX::PTXCvtMode::RMI:
724 case NVPTX::PTXCvtMode::RPI:
727 case NVPTX::PTXCvtMode::RN:
730 case NVPTX::PTXCvtMode::RZ:
733 case NVPTX::PTXCvtMode::RM:
736 case NVPTX::PTXCvtMode::RP:
741 llvm_unreachable("Invalid conversion modifier");
745 void NVPTXAsmPrinter::printCmpMode(const MachineInstr *MI, int OpNum,
746 raw_ostream &O, const char *Modifier) {
747 const MachineOperand &MO = MI->getOperand(OpNum);
748 int64_t Imm = MO.getImm();
750 if (strcmp(Modifier, "ftz") == 0) {
752 if (Imm & NVPTX::PTXCmpMode::FTZ_FLAG)
754 } else if (strcmp(Modifier, "base") == 0) {
755 switch (Imm & NVPTX::PTXCmpMode::BASE_MASK) {
758 case NVPTX::PTXCmpMode::EQ:
761 case NVPTX::PTXCmpMode::NE:
764 case NVPTX::PTXCmpMode::LT:
767 case NVPTX::PTXCmpMode::LE:
770 case NVPTX::PTXCmpMode::GT:
773 case NVPTX::PTXCmpMode::GE:
776 case NVPTX::PTXCmpMode::LO:
779 case NVPTX::PTXCmpMode::LS:
782 case NVPTX::PTXCmpMode::HI:
785 case NVPTX::PTXCmpMode::HS:
788 case NVPTX::PTXCmpMode::EQU:
791 case NVPTX::PTXCmpMode::NEU:
794 case NVPTX::PTXCmpMode::LTU:
797 case NVPTX::PTXCmpMode::LEU:
800 case NVPTX::PTXCmpMode::GTU:
803 case NVPTX::PTXCmpMode::GEU:
806 case NVPTX::PTXCmpMode::NUM:
809 case NVPTX::PTXCmpMode::NotANumber:
814 llvm_unreachable("Empty Modifier");
819 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
821 emitLinkageDirective(F, O);
822 if (llvm::isKernelFunction(*F))
826 printReturnValStr(F, O);
827 O << *Mang->getSymbol(F) << "\n";
828 emitFunctionParamList(F, O);
832 static bool usedInGlobalVarDef(const Constant *C) {
836 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
837 if (GV->getName().str() == "llvm.used")
842 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
844 const Constant *C = dyn_cast<Constant>(*ui);
845 if (usedInGlobalVarDef(C))
851 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
852 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
853 if (othergv->getName().str() == "llvm.used")
857 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
858 if (instr->getParent() && instr->getParent()->getParent()) {
859 const Function *curFunc = instr->getParent()->getParent();
860 if (oneFunc && (curFunc != oneFunc))
868 if (const MDNode *md = dyn_cast<MDNode>(U))
869 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
870 (md->getName().str() == "llvm.dbg.sp")))
873 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
875 if (usedInOneFunc(*ui, oneFunc) == false)
881 /* Find out if a global variable can be demoted to local scope.
882 * Currently, this is valid for CUDA shared variables, which have local
883 * scope and global lifetime. So the conditions to check are :
884 * 1. Is the global variable in shared address space?
885 * 2. Does it have internal linkage?
886 * 3. Is the global variable referenced only in one function?
888 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
889 if (gv->hasInternalLinkage() == false)
891 const PointerType *Pty = gv->getType();
892 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
895 const Function *oneFunc = 0;
897 bool flag = usedInOneFunc(gv, oneFunc);
906 static bool useFuncSeen(const Constant *C,
907 llvm::DenseMap<const Function *, bool> &seenMap) {
908 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
910 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
911 if (useFuncSeen(cu, seenMap))
913 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
914 const BasicBlock *bb = I->getParent();
917 const Function *caller = bb->getParent();
920 if (seenMap.find(caller) != seenMap.end())
927 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
928 llvm::DenseMap<const Function *, bool> seenMap;
929 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
930 const Function *F = FI;
932 if (F->isDeclaration()) {
935 if (F->getIntrinsicID())
937 emitDeclaration(F, O);
940 for (Value::const_use_iterator iter = F->use_begin(),
941 iterEnd = F->use_end();
942 iter != iterEnd; ++iter) {
943 if (const Constant *C = dyn_cast<Constant>(*iter)) {
944 if (usedInGlobalVarDef(C)) {
945 // The use is in the initialization of a global variable
946 // that is a function pointer, so print a declaration
947 // for the original function
948 emitDeclaration(F, O);
951 // Emit a declaration of this function if the function that
952 // uses this constant expr has already been seen.
953 if (useFuncSeen(C, seenMap)) {
954 emitDeclaration(F, O);
959 if (!isa<Instruction>(*iter))
961 const Instruction *instr = cast<Instruction>(*iter);
962 const BasicBlock *bb = instr->getParent();
965 const Function *caller = bb->getParent();
969 // If a caller has already been seen, then the caller is
970 // appearing in the module before the callee. so print out
971 // a declaration for the callee.
972 if (seenMap.find(caller) != seenMap.end()) {
973 emitDeclaration(F, O);
981 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
982 DebugInfoFinder DbgFinder;
983 DbgFinder.processModule(M);
986 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
987 E = DbgFinder.compile_unit_end();
989 DICompileUnit DIUnit(*I);
990 StringRef Filename(DIUnit.getFilename());
991 StringRef Dirname(DIUnit.getDirectory());
992 SmallString<128> FullPathName = Dirname;
993 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
994 sys::path::append(FullPathName, Filename);
995 Filename = FullPathName.str();
997 if (filenameMap.find(Filename.str()) != filenameMap.end())
999 filenameMap[Filename.str()] = i;
1000 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
1004 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1005 E = DbgFinder.subprogram_end();
1007 DISubprogram SP(*I);
1008 StringRef Filename(SP.getFilename());
1009 StringRef Dirname(SP.getDirectory());
1010 SmallString<128> FullPathName = Dirname;
1011 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1012 sys::path::append(FullPathName, Filename);
1013 Filename = FullPathName.str();
1015 if (filenameMap.find(Filename.str()) != filenameMap.end())
1017 filenameMap[Filename.str()] = i;
1022 bool NVPTXAsmPrinter::doInitialization(Module &M) {
1024 SmallString<128> Str1;
1025 raw_svector_ostream OS1(Str1);
1027 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
1028 MMI->AnalyzeModule(M);
1030 // We need to call the parent's one explicitly.
1031 //bool Result = AsmPrinter::doInitialization(M);
1033 // Initialize TargetLoweringObjectFile.
1034 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
1035 .Initialize(OutContext, TM);
1037 Mang = new Mangler(OutContext, &TM);
1039 // Emit header before any dwarf directives are emitted below.
1041 OutStreamer.EmitRawText(OS1.str());
1043 // Already commented out
1044 //bool Result = AsmPrinter::doInitialization(M);
1046 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
1047 recordAndEmitFilenames(M);
1049 GlobalsEmitted = false;
1051 return false; // success
1054 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
1055 SmallString<128> Str2;
1056 raw_svector_ostream OS2(Str2);
1058 emitDeclarations(M, OS2);
1060 // As ptxas does not support forward references of globals, we need to first
1061 // sort the list of module-level globals in def-use order. We visit each
1062 // global variable in order, and ensure that we emit it *after* its dependent
1063 // globals. We use a little extra memory maintaining both a set and a list to
1064 // have fast searches while maintaining a strict ordering.
1065 SmallVector<const GlobalVariable *, 8> Globals;
1066 DenseSet<const GlobalVariable *> GVVisited;
1067 DenseSet<const GlobalVariable *> GVVisiting;
1069 // Visit each global variable, in order
1070 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1072 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1074 assert(GVVisited.size() == M.getGlobalList().size() &&
1075 "Missed a global variable");
1076 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1078 // Print out module-level global variables in proper order
1079 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1080 printModuleLevelGV(Globals[i], OS2);
1084 OutStreamer.EmitRawText(OS2.str());
1087 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1089 O << "// Generated by LLVM NVPTX Back-End\n";
1093 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1094 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1097 O << nvptxSubtarget.getTargetName();
1099 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1100 O << ", texmode_independent";
1101 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1102 if (!nvptxSubtarget.hasDouble())
1103 O << ", map_f64_to_f32";
1106 if (MAI->doesSupportDebugInformation())
1111 O << ".address_size ";
1112 if (nvptxSubtarget.is64Bit())
1121 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1123 // If we did not emit any functions, then the global declarations have not
1124 // yet been emitted.
1125 if (!GlobalsEmitted) {
1127 GlobalsEmitted = true;
1130 // XXX Temproarily remove global variables so that doFinalization() will not
1131 // emit them again (global variables are emitted at beginning).
1133 Module::GlobalListType &global_list = M.getGlobalList();
1134 int i, n = global_list.size();
1135 GlobalVariable **gv_array = new GlobalVariable *[n];
1137 // first, back-up GlobalVariable in gv_array
1139 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1141 gv_array[i++] = &*I;
1143 // second, empty global_list
1144 while (!global_list.empty())
1145 global_list.remove(global_list.begin());
1147 // call doFinalization
1148 bool ret = AsmPrinter::doFinalization(M);
1150 // now we restore global variables
1151 for (i = 0; i < n; i++)
1152 global_list.insert(global_list.end(), gv_array[i]);
1157 //bool Result = AsmPrinter::doFinalization(M);
1158 // Instead of calling the parents doFinalization, we may
1159 // clone parents doFinalization and customize here.
1160 // Currently, we if NVISA out the EmitGlobals() in
1161 // parent's doFinalization, which is too intrusive.
1163 // Same for the doInitialization.
1167 // This function emits appropriate linkage directives for
1168 // functions and global variables.
1170 // extern function declaration -> .extern
1171 // extern function definition -> .visible
1172 // external global variable with init -> .visible
1173 // external without init -> .extern
1174 // appending -> not allowed, assert.
1176 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1178 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1179 if (V->hasExternalLinkage()) {
1180 if (isa<GlobalVariable>(V)) {
1181 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1183 if (GVar->hasInitializer())
1188 } else if (V->isDeclaration())
1192 } else if (V->hasAppendingLinkage()) {
1194 msg.append("Error: ");
1195 msg.append("Symbol ");
1197 msg.append(V->getName().str());
1198 msg.append("has unsupported appending linkage type");
1199 llvm_unreachable(msg.c_str());
1204 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1206 bool processDemoted) {
1209 if (GVar->hasSection()) {
1210 if (GVar->getSection() == "llvm.metadata")
1214 const DataLayout *TD = TM.getDataLayout();
1216 // GlobalVariables are always constant pointers themselves.
1217 const PointerType *PTy = GVar->getType();
1218 Type *ETy = PTy->getElementType();
1220 if (GVar->hasExternalLinkage()) {
1221 if (GVar->hasInitializer())
1227 if (llvm::isTexture(*GVar)) {
1228 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1232 if (llvm::isSurface(*GVar)) {
1233 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1237 if (GVar->isDeclaration()) {
1238 // (extern) declarations, no definition or initializer
1239 // Currently the only known declaration is for an automatic __local
1240 // (.shared) promoted to global.
1241 emitPTXGlobalVariable(GVar, O);
1246 if (llvm::isSampler(*GVar)) {
1247 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1249 const Constant *Initializer = NULL;
1250 if (GVar->hasInitializer())
1251 Initializer = GVar->getInitializer();
1252 const ConstantInt *CI = NULL;
1254 CI = dyn_cast<ConstantInt>(Initializer);
1256 unsigned sample = CI->getZExtValue();
1261 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1263 O << "addr_mode_" << i << " = ";
1269 O << "clamp_to_border";
1272 O << "clamp_to_edge";
1283 O << "filter_mode = ";
1284 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1292 assert(0 && "Anisotropic filtering is not supported");
1297 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1298 O << ", force_unnormalized_coords = 1";
1307 if (GVar->hasPrivateLinkage()) {
1309 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1312 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1313 if (!strncmp(GVar->getName().data(), "filename", 8))
1315 if (GVar->use_empty())
1319 const Function *demotedFunc = 0;
1320 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1321 O << "// " << GVar->getName().str() << " has been demoted\n";
1322 if (localDecls.find(demotedFunc) != localDecls.end())
1323 localDecls[demotedFunc].push_back(GVar);
1325 std::vector<const GlobalVariable *> temp;
1326 temp.push_back(GVar);
1327 localDecls[demotedFunc] = temp;
1333 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1334 if (GVar->getAlignment() == 0)
1335 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1337 O << " .align " << GVar->getAlignment();
1339 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1341 // Special case: ABI requires that we use .u8 for predicates
1342 if (ETy->isIntegerTy(1))
1345 O << getPTXFundamentalTypeStr(ETy, false);
1347 O << *Mang->getSymbol(GVar);
1349 // Ptx allows variable initilization only for constant and global state
1351 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1352 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1353 GVar->hasInitializer()) {
1354 const Constant *Initializer = GVar->getInitializer();
1355 if (!Initializer->isNullValue()) {
1357 printScalarConstant(Initializer, O);
1361 unsigned int ElementSize = 0;
1363 // Although PTX has direct support for struct type and array type and
1364 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1365 // targets that support these high level field accesses. Structs, arrays
1366 // and vectors are lowered into arrays of bytes.
1367 switch (ETy->getTypeID()) {
1368 case Type::StructTyID:
1369 case Type::ArrayTyID:
1370 case Type::VectorTyID:
1371 ElementSize = TD->getTypeStoreSize(ETy);
1372 // Ptx allows variable initilization only for constant and
1373 // global state spaces.
1374 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1375 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1376 GVar->hasInitializer()) {
1377 const Constant *Initializer = GVar->getInitializer();
1378 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1379 AggBuffer aggBuffer(ElementSize, O, *this);
1380 bufferAggregateConstant(Initializer, &aggBuffer);
1381 if (aggBuffer.numSymbols) {
1382 if (nvptxSubtarget.is64Bit()) {
1383 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1384 O << ElementSize / 8;
1386 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1387 O << ElementSize / 4;
1391 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1399 O << " .b8 " << *Mang->getSymbol(GVar);
1407 O << " .b8 " << *Mang->getSymbol(GVar);
1416 assert(0 && "type not supported yet");
1423 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1424 if (localDecls.find(f) == localDecls.end())
1427 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1429 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1430 O << "\t// demoted variable\n\t";
1431 printModuleLevelGV(gvars[i], O, true);
1435 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1436 raw_ostream &O) const {
1437 switch (AddressSpace) {
1438 case llvm::ADDRESS_SPACE_LOCAL:
1441 case llvm::ADDRESS_SPACE_GLOBAL:
1444 case llvm::ADDRESS_SPACE_CONST:
1447 case llvm::ADDRESS_SPACE_SHARED:
1451 report_fatal_error("Bad address space found while emitting PTX");
1457 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1458 switch (Ty->getTypeID()) {
1460 llvm_unreachable("unexpected type");
1462 case Type::IntegerTyID: {
1463 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1466 else if (NumBits <= 64) {
1467 std::string name = "u";
1468 return name + utostr(NumBits);
1470 llvm_unreachable("Integer too large");
1475 case Type::FloatTyID:
1477 case Type::DoubleTyID:
1479 case Type::PointerTyID:
1480 if (nvptxSubtarget.is64Bit())
1490 llvm_unreachable("unexpected type");
1494 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1497 const DataLayout *TD = TM.getDataLayout();
1499 // GlobalVariables are always constant pointers themselves.
1500 const PointerType *PTy = GVar->getType();
1501 Type *ETy = PTy->getElementType();
1504 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1505 if (GVar->getAlignment() == 0)
1506 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1508 O << " .align " << GVar->getAlignment();
1510 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1512 O << getPTXFundamentalTypeStr(ETy);
1514 O << *Mang->getSymbol(GVar);
1518 int64_t ElementSize = 0;
1520 // Although PTX has direct support for struct type and array type and LLVM IR
1521 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1522 // support these high level field accesses. Structs and arrays are lowered
1523 // into arrays of bytes.
1524 switch (ETy->getTypeID()) {
1525 case Type::StructTyID:
1526 case Type::ArrayTyID:
1527 case Type::VectorTyID:
1528 ElementSize = TD->getTypeStoreSize(ETy);
1529 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1531 O << itostr(ElementSize);
1536 assert(0 && "type not supported yet");
1541 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1542 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1543 return TD->getPrefTypeAlignment(Ty);
1545 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1547 return getOpenCLAlignment(TD, ATy->getElementType());
1549 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1551 Type *ETy = VTy->getElementType();
1552 unsigned int numE = VTy->getNumElements();
1553 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1557 return numE * alignE;
1560 const StructType *STy = dyn_cast<StructType>(Ty);
1562 unsigned int alignStruct = 1;
1563 // Go through each element of the struct and find the
1564 // largest alignment.
1565 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1566 Type *ETy = STy->getElementType(i);
1567 unsigned int align = getOpenCLAlignment(TD, ETy);
1568 if (align > alignStruct)
1569 alignStruct = align;
1574 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1576 return TD->getPointerPrefAlignment();
1577 return TD->getPrefTypeAlignment(Ty);
1580 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1581 int paramIndex, raw_ostream &O) {
1582 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1583 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1584 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1586 std::string argName = I->getName();
1587 const char *p = argName.c_str();
1598 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1599 Function::const_arg_iterator I, E;
1602 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1603 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1604 O << *CurrentFnSym << "_param_" << paramIndex;
1608 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1609 if (i == paramIndex) {
1610 printParamName(I, paramIndex, O);
1614 llvm_unreachable("paramIndex out of bound");
1617 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1618 const DataLayout *TD = TM.getDataLayout();
1619 const AttributeSet &PAL = F->getAttributes();
1620 const TargetLowering *TLI = TM.getTargetLowering();
1621 Function::const_arg_iterator I, E;
1622 unsigned paramIndex = 0;
1624 bool isKernelFunc = llvm::isKernelFunction(*F);
1625 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1626 MVT thePointerTy = TLI->getPointerTy();
1630 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1631 Type *Ty = I->getType();
1638 // Handle image/sampler parameters
1639 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1640 if (llvm::isImage(*I)) {
1641 std::string sname = I->getName();
1642 if (llvm::isImageWriteOnly(*I))
1643 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1645 else // Default image is read_only
1646 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1648 } else // Should be llvm::isSampler(*I)
1649 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1654 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1655 if (Ty->isVectorTy()) {
1656 // Just print .param .b8 .align <a> .param[size];
1657 // <a> = PAL.getparamalignment
1658 // size = typeallocsize of element type
1659 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1661 align = TD->getABITypeAlignment(Ty);
1663 unsigned sz = TD->getTypeAllocSize(Ty);
1664 O << "\t.param .align " << align << " .b8 ";
1665 printParamName(I, paramIndex, O);
1666 O << "[" << sz << "]";
1671 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1674 // Special handling for pointer arguments to kernel
1675 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1677 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1678 Type *ETy = PTy->getElementType();
1679 int addrSpace = PTy->getAddressSpace();
1680 switch (addrSpace) {
1684 case llvm::ADDRESS_SPACE_CONST:
1685 O << ".ptr .const ";
1687 case llvm::ADDRESS_SPACE_SHARED:
1688 O << ".ptr .shared ";
1690 case llvm::ADDRESS_SPACE_GLOBAL:
1691 O << ".ptr .global ";
1694 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1696 printParamName(I, paramIndex, O);
1700 // non-pointer scalar to kernel func
1702 // Special case: predicate operands become .u8 types
1703 if (Ty->isIntegerTy(1))
1706 O << getPTXFundamentalTypeStr(Ty);
1708 printParamName(I, paramIndex, O);
1711 // Non-kernel function, just print .param .b<size> for ABI
1712 // and .reg .b<size> for non ABY
1714 if (isa<IntegerType>(Ty)) {
1715 sz = cast<IntegerType>(Ty)->getBitWidth();
1718 } else if (isa<PointerType>(Ty))
1719 sz = thePointerTy.getSizeInBits();
1721 sz = Ty->getPrimitiveSizeInBits();
1723 O << "\t.param .b" << sz << " ";
1725 O << "\t.reg .b" << sz << " ";
1726 printParamName(I, paramIndex, O);
1730 // param has byVal attribute. So should be a pointer
1731 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1732 assert(PTy && "Param with byval attribute should be a pointer type");
1733 Type *ETy = PTy->getElementType();
1735 if (isABI || isKernelFunc) {
1736 // Just print .param .b8 .align <a> .param[size];
1737 // <a> = PAL.getparamalignment
1738 // size = typeallocsize of element type
1739 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1741 align = TD->getABITypeAlignment(ETy);
1743 unsigned sz = TD->getTypeAllocSize(ETy);
1744 O << "\t.param .align " << align << " .b8 ";
1745 printParamName(I, paramIndex, O);
1746 O << "[" << sz << "]";
1749 // Split the ETy into constituent parts and
1750 // print .param .b<size> <name> for each part.
1751 // Further, if a part is vector, print the above for
1752 // each vector element.
1753 SmallVector<EVT, 16> vtparts;
1754 ComputeValueVTs(*TLI, ETy, vtparts);
1755 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1757 EVT elemtype = vtparts[i];
1758 if (vtparts[i].isVector()) {
1759 elems = vtparts[i].getVectorNumElements();
1760 elemtype = vtparts[i].getVectorElementType();
1763 for (unsigned j = 0, je = elems; j != je; ++j) {
1764 unsigned sz = elemtype.getSizeInBits();
1765 if (elemtype.isInteger() && (sz < 32))
1767 O << "\t.reg .b" << sz << " ";
1768 printParamName(I, paramIndex, O);
1784 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1786 const Function *F = MF.getFunction();
1787 emitFunctionParamList(F, O);
1790 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1791 const MachineFunction &MF) {
1792 SmallString<128> Str;
1793 raw_svector_ostream O(Str);
1795 // Map the global virtual register number to a register class specific
1796 // virtual register number starting from 1 with that class.
1797 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1798 //unsigned numRegClasses = TRI->getNumRegClasses();
1800 // Emit the Fake Stack Object
1801 const MachineFrameInfo *MFI = MF.getFrameInfo();
1802 int NumBytes = (int) MFI->getStackSize();
1804 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1805 << getFunctionNumber() << "[" << NumBytes << "];\n";
1806 if (nvptxSubtarget.is64Bit()) {
1807 O << "\t.reg .b64 \t%SP;\n";
1808 O << "\t.reg .b64 \t%SPL;\n";
1810 O << "\t.reg .b32 \t%SP;\n";
1811 O << "\t.reg .b32 \t%SPL;\n";
1815 // Go through all virtual registers to establish the mapping between the
1817 // register number and the per class virtual register number.
1818 // We use the per class virtual register number in the ptx output.
1819 unsigned int numVRs = MRI->getNumVirtRegs();
1820 for (unsigned i = 0; i < numVRs; i++) {
1821 unsigned int vr = TRI->index2VirtReg(i);
1822 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1823 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1824 int n = regmap.size();
1825 regmap.insert(std::make_pair(vr, n + 1));
1828 // Emit register declarations
1829 // @TODO: Extract out the real register usage
1830 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1831 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1832 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1833 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1834 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1835 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1836 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1838 // Emit declaration of the virtual registers or 'physical' registers for
1839 // each register class
1840 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1841 const TargetRegisterClass *RC = TRI->getRegClass(i);
1842 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1843 std::string rcname = getNVPTXRegClassName(RC);
1844 std::string rcStr = getNVPTXRegClassStr(RC);
1845 int n = regmap.size();
1847 // Only declare those registers that may be used.
1849 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1854 OutStreamer.EmitRawText(O.str());
1857 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1858 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1860 unsigned int numHex;
1863 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1866 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1867 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1870 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1872 llvm_unreachable("unsupported fp type");
1874 APInt API = APF.bitcastToAPInt();
1875 std::string hexstr(utohexstr(API.getZExtValue()));
1877 if (hexstr.length() < numHex)
1878 O << std::string(numHex - hexstr.length(), '0');
1879 O << utohexstr(API.getZExtValue());
1882 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1883 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1884 O << CI->getValue();
1887 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1888 printFPConstant(CFP, O);
1891 if (isa<ConstantPointerNull>(CPV)) {
1895 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1896 O << *Mang->getSymbol(GVar);
1899 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1900 const Value *v = Cexpr->stripPointerCasts();
1901 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1902 O << *Mang->getSymbol(GVar);
1905 O << *LowerConstant(CPV, *this);
1909 llvm_unreachable("Not scalar type found in printScalarConstant()");
1912 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1913 AggBuffer *aggBuffer) {
1915 const DataLayout *TD = TM.getDataLayout();
1917 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1918 int s = TD->getTypeAllocSize(CPV->getType());
1921 aggBuffer->addZeros(s);
1926 switch (CPV->getType()->getTypeID()) {
1928 case Type::IntegerTyID: {
1929 const Type *ETy = CPV->getType();
1930 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1932 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1934 aggBuffer->addBytes(ptr, 1, Bytes);
1935 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1936 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1937 ptr = (unsigned char *)&int16;
1938 aggBuffer->addBytes(ptr, 2, Bytes);
1939 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1940 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1941 int int32 = (int)(constInt->getZExtValue());
1942 ptr = (unsigned char *)&int32;
1943 aggBuffer->addBytes(ptr, 4, Bytes);
1945 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1946 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1947 ConstantFoldConstantExpression(Cexpr, TD))) {
1948 int int32 = (int)(constInt->getZExtValue());
1949 ptr = (unsigned char *)&int32;
1950 aggBuffer->addBytes(ptr, 4, Bytes);
1953 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1954 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1955 aggBuffer->addSymbol(v);
1956 aggBuffer->addZeros(4);
1960 llvm_unreachable("unsupported integer const type");
1961 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1962 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1963 long long int64 = (long long)(constInt->getZExtValue());
1964 ptr = (unsigned char *)&int64;
1965 aggBuffer->addBytes(ptr, 8, Bytes);
1967 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1968 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1969 ConstantFoldConstantExpression(Cexpr, TD))) {
1970 long long int64 = (long long)(constInt->getZExtValue());
1971 ptr = (unsigned char *)&int64;
1972 aggBuffer->addBytes(ptr, 8, Bytes);
1975 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1976 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1977 aggBuffer->addSymbol(v);
1978 aggBuffer->addZeros(8);
1982 llvm_unreachable("unsupported integer const type");
1984 llvm_unreachable("unsupported integer const type");
1987 case Type::FloatTyID:
1988 case Type::DoubleTyID: {
1989 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1990 const Type *Ty = CFP->getType();
1991 if (Ty == Type::getFloatTy(CPV->getContext())) {
1992 float float32 = (float) CFP->getValueAPF().convertToFloat();
1993 ptr = (unsigned char *)&float32;
1994 aggBuffer->addBytes(ptr, 4, Bytes);
1995 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1996 double float64 = CFP->getValueAPF().convertToDouble();
1997 ptr = (unsigned char *)&float64;
1998 aggBuffer->addBytes(ptr, 8, Bytes);
2000 llvm_unreachable("unsupported fp const type");
2004 case Type::PointerTyID: {
2005 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2006 aggBuffer->addSymbol(GVar);
2007 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2008 const Value *v = Cexpr->stripPointerCasts();
2009 aggBuffer->addSymbol(v);
2011 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2012 aggBuffer->addZeros(s);
2016 case Type::ArrayTyID:
2017 case Type::VectorTyID:
2018 case Type::StructTyID: {
2019 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2020 isa<ConstantStruct>(CPV)) {
2021 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2022 bufferAggregateConstant(CPV, aggBuffer);
2023 if (Bytes > ElementSize)
2024 aggBuffer->addZeros(Bytes - ElementSize);
2025 } else if (isa<ConstantAggregateZero>(CPV))
2026 aggBuffer->addZeros(Bytes);
2028 llvm_unreachable("Unexpected Constant type");
2033 llvm_unreachable("unsupported type");
2037 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2038 AggBuffer *aggBuffer) {
2039 const DataLayout *TD = TM.getDataLayout();
2043 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2044 if (CPV->getNumOperands())
2045 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2046 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2050 if (const ConstantDataSequential *CDS =
2051 dyn_cast<ConstantDataSequential>(CPV)) {
2052 if (CDS->getNumElements())
2053 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2054 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2059 if (isa<ConstantStruct>(CPV)) {
2060 if (CPV->getNumOperands()) {
2061 StructType *ST = cast<StructType>(CPV->getType());
2062 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2064 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2065 TD->getTypeAllocSize(ST) -
2066 TD->getStructLayout(ST)->getElementOffset(i);
2068 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2069 TD->getStructLayout(ST)->getElementOffset(i);
2070 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2075 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2078 // buildTypeNameMap - Run through symbol table looking for type names.
2081 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2083 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2085 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2086 !PI->second.compare("struct._image2d_t") ||
2087 !PI->second.compare("struct._image3d_t")))
2093 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2095 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2096 unsigned AsmVariant,
2097 const char *ExtraCode, raw_ostream &O) {
2098 if (ExtraCode && ExtraCode[0]) {
2099 if (ExtraCode[1] != 0)
2100 return true; // Unknown modifier.
2102 switch (ExtraCode[0]) {
2104 // See if this is a generic print operand
2105 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2111 printOperand(MI, OpNo, O);
2116 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2117 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2118 const char *ExtraCode, raw_ostream &O) {
2119 if (ExtraCode && ExtraCode[0])
2120 return true; // Unknown modifier
2123 printMemOperand(MI, OpNo, O);
2129 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2130 switch (MI.getOpcode()) {
2133 case NVPTX::CallArgBeginInst:
2134 case NVPTX::CallArgEndInst0:
2135 case NVPTX::CallArgEndInst1:
2136 case NVPTX::CallArgF32:
2137 case NVPTX::CallArgF64:
2138 case NVPTX::CallArgI16:
2139 case NVPTX::CallArgI32:
2140 case NVPTX::CallArgI32imm:
2141 case NVPTX::CallArgI64:
2142 case NVPTX::CallArgParam:
2143 case NVPTX::CallVoidInst:
2144 case NVPTX::CallVoidInstReg:
2145 case NVPTX::Callseq_End:
2146 case NVPTX::CallVoidInstReg64:
2147 case NVPTX::DeclareParamInst:
2148 case NVPTX::DeclareRetMemInst:
2149 case NVPTX::DeclareRetRegInst:
2150 case NVPTX::DeclareRetScalarInst:
2151 case NVPTX::DeclareScalarParamInst:
2152 case NVPTX::DeclareScalarRegInst:
2153 case NVPTX::StoreParamF32:
2154 case NVPTX::StoreParamF64:
2155 case NVPTX::StoreParamI16:
2156 case NVPTX::StoreParamI32:
2157 case NVPTX::StoreParamI64:
2158 case NVPTX::StoreParamI8:
2159 case NVPTX::StoreRetvalF32:
2160 case NVPTX::StoreRetvalF64:
2161 case NVPTX::StoreRetvalI16:
2162 case NVPTX::StoreRetvalI32:
2163 case NVPTX::StoreRetvalI64:
2164 case NVPTX::StoreRetvalI8:
2165 case NVPTX::LastCallArgF32:
2166 case NVPTX::LastCallArgF64:
2167 case NVPTX::LastCallArgI16:
2168 case NVPTX::LastCallArgI32:
2169 case NVPTX::LastCallArgI32imm:
2170 case NVPTX::LastCallArgI64:
2171 case NVPTX::LastCallArgParam:
2172 case NVPTX::LoadParamMemF32:
2173 case NVPTX::LoadParamMemF64:
2174 case NVPTX::LoadParamMemI16:
2175 case NVPTX::LoadParamMemI32:
2176 case NVPTX::LoadParamMemI64:
2177 case NVPTX::LoadParamMemI8:
2178 case NVPTX::PrototypeInst:
2179 case NVPTX::DBG_VALUE:
2185 // Force static initialization.
2186 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2187 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2188 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2191 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2192 std::stringstream temp;
2193 LineReader *reader = this->getReader(filename.str());
2195 temp << filename.str();
2199 temp << reader->readLine(line);
2201 this->OutStreamer.EmitRawText(Twine(temp.str()));
2204 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2205 if (reader == NULL) {
2206 reader = new LineReader(filename);
2209 if (reader->fileName() != filename) {
2211 reader = new LineReader(filename);
2217 std::string LineReader::readLine(unsigned lineNum) {
2218 if (lineNum < theCurLine) {
2220 fstr.seekg(0, std::ios::beg);
2222 while (theCurLine < lineNum) {
2223 fstr.getline(buff, 500);
2229 // Force static initialization.
2230 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2231 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2232 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);