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 // Emit module-level inline asm if it exists.
1047 if (!M.getModuleInlineAsm().empty()) {
1048 OutStreamer.AddComment("Start of file scope inline assembly");
1049 OutStreamer.AddBlankLine();
1050 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
1051 OutStreamer.AddBlankLine();
1052 OutStreamer.AddComment("End of file scope inline assembly");
1053 OutStreamer.AddBlankLine();
1056 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
1057 recordAndEmitFilenames(M);
1059 GlobalsEmitted = false;
1061 return false; // success
1064 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
1065 SmallString<128> Str2;
1066 raw_svector_ostream OS2(Str2);
1068 emitDeclarations(M, OS2);
1070 // As ptxas does not support forward references of globals, we need to first
1071 // sort the list of module-level globals in def-use order. We visit each
1072 // global variable in order, and ensure that we emit it *after* its dependent
1073 // globals. We use a little extra memory maintaining both a set and a list to
1074 // have fast searches while maintaining a strict ordering.
1075 SmallVector<const GlobalVariable *, 8> Globals;
1076 DenseSet<const GlobalVariable *> GVVisited;
1077 DenseSet<const GlobalVariable *> GVVisiting;
1079 // Visit each global variable, in order
1080 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1082 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1084 assert(GVVisited.size() == M.getGlobalList().size() &&
1085 "Missed a global variable");
1086 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1088 // Print out module-level global variables in proper order
1089 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1090 printModuleLevelGV(Globals[i], OS2);
1094 OutStreamer.EmitRawText(OS2.str());
1097 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1099 O << "// Generated by LLVM NVPTX Back-End\n";
1103 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1104 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1107 O << nvptxSubtarget.getTargetName();
1109 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1110 O << ", texmode_independent";
1111 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1112 if (!nvptxSubtarget.hasDouble())
1113 O << ", map_f64_to_f32";
1116 if (MAI->doesSupportDebugInformation())
1121 O << ".address_size ";
1122 if (nvptxSubtarget.is64Bit())
1131 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1133 // If we did not emit any functions, then the global declarations have not
1134 // yet been emitted.
1135 if (!GlobalsEmitted) {
1137 GlobalsEmitted = true;
1140 // XXX Temproarily remove global variables so that doFinalization() will not
1141 // emit them again (global variables are emitted at beginning).
1143 Module::GlobalListType &global_list = M.getGlobalList();
1144 int i, n = global_list.size();
1145 GlobalVariable **gv_array = new GlobalVariable *[n];
1147 // first, back-up GlobalVariable in gv_array
1149 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1151 gv_array[i++] = &*I;
1153 // second, empty global_list
1154 while (!global_list.empty())
1155 global_list.remove(global_list.begin());
1157 // call doFinalization
1158 bool ret = AsmPrinter::doFinalization(M);
1160 // now we restore global variables
1161 for (i = 0; i < n; i++)
1162 global_list.insert(global_list.end(), gv_array[i]);
1167 //bool Result = AsmPrinter::doFinalization(M);
1168 // Instead of calling the parents doFinalization, we may
1169 // clone parents doFinalization and customize here.
1170 // Currently, we if NVISA out the EmitGlobals() in
1171 // parent's doFinalization, which is too intrusive.
1173 // Same for the doInitialization.
1177 // This function emits appropriate linkage directives for
1178 // functions and global variables.
1180 // extern function declaration -> .extern
1181 // extern function definition -> .visible
1182 // external global variable with init -> .visible
1183 // external without init -> .extern
1184 // appending -> not allowed, assert.
1186 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1188 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1189 if (V->hasExternalLinkage()) {
1190 if (isa<GlobalVariable>(V)) {
1191 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1193 if (GVar->hasInitializer())
1198 } else if (V->isDeclaration())
1202 } else if (V->hasAppendingLinkage()) {
1204 msg.append("Error: ");
1205 msg.append("Symbol ");
1207 msg.append(V->getName().str());
1208 msg.append("has unsupported appending linkage type");
1209 llvm_unreachable(msg.c_str());
1214 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1216 bool processDemoted) {
1219 if (GVar->hasSection()) {
1220 if (GVar->getSection() == "llvm.metadata")
1224 const DataLayout *TD = TM.getDataLayout();
1226 // GlobalVariables are always constant pointers themselves.
1227 const PointerType *PTy = GVar->getType();
1228 Type *ETy = PTy->getElementType();
1230 if (GVar->hasExternalLinkage()) {
1231 if (GVar->hasInitializer())
1237 if (llvm::isTexture(*GVar)) {
1238 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1242 if (llvm::isSurface(*GVar)) {
1243 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1247 if (GVar->isDeclaration()) {
1248 // (extern) declarations, no definition or initializer
1249 // Currently the only known declaration is for an automatic __local
1250 // (.shared) promoted to global.
1251 emitPTXGlobalVariable(GVar, O);
1256 if (llvm::isSampler(*GVar)) {
1257 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1259 const Constant *Initializer = NULL;
1260 if (GVar->hasInitializer())
1261 Initializer = GVar->getInitializer();
1262 const ConstantInt *CI = NULL;
1264 CI = dyn_cast<ConstantInt>(Initializer);
1266 unsigned sample = CI->getZExtValue();
1271 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1273 O << "addr_mode_" << i << " = ";
1279 O << "clamp_to_border";
1282 O << "clamp_to_edge";
1293 O << "filter_mode = ";
1294 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1302 assert(0 && "Anisotropic filtering is not supported");
1307 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1308 O << ", force_unnormalized_coords = 1";
1317 if (GVar->hasPrivateLinkage()) {
1319 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1322 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1323 if (!strncmp(GVar->getName().data(), "filename", 8))
1325 if (GVar->use_empty())
1329 const Function *demotedFunc = 0;
1330 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1331 O << "// " << GVar->getName().str() << " has been demoted\n";
1332 if (localDecls.find(demotedFunc) != localDecls.end())
1333 localDecls[demotedFunc].push_back(GVar);
1335 std::vector<const GlobalVariable *> temp;
1336 temp.push_back(GVar);
1337 localDecls[demotedFunc] = temp;
1343 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1344 if (GVar->getAlignment() == 0)
1345 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1347 O << " .align " << GVar->getAlignment();
1349 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1351 // Special case: ABI requires that we use .u8 for predicates
1352 if (ETy->isIntegerTy(1))
1355 O << getPTXFundamentalTypeStr(ETy, false);
1357 O << *Mang->getSymbol(GVar);
1359 // Ptx allows variable initilization only for constant and global state
1361 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1362 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1363 GVar->hasInitializer()) {
1364 const Constant *Initializer = GVar->getInitializer();
1365 if (!Initializer->isNullValue()) {
1367 printScalarConstant(Initializer, O);
1371 unsigned int ElementSize = 0;
1373 // Although PTX has direct support for struct type and array type and
1374 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1375 // targets that support these high level field accesses. Structs, arrays
1376 // and vectors are lowered into arrays of bytes.
1377 switch (ETy->getTypeID()) {
1378 case Type::StructTyID:
1379 case Type::ArrayTyID:
1380 case Type::VectorTyID:
1381 ElementSize = TD->getTypeStoreSize(ETy);
1382 // Ptx allows variable initilization only for constant and
1383 // global state spaces.
1384 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1385 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1386 GVar->hasInitializer()) {
1387 const Constant *Initializer = GVar->getInitializer();
1388 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1389 AggBuffer aggBuffer(ElementSize, O, *this);
1390 bufferAggregateConstant(Initializer, &aggBuffer);
1391 if (aggBuffer.numSymbols) {
1392 if (nvptxSubtarget.is64Bit()) {
1393 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1394 O << ElementSize / 8;
1396 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1397 O << ElementSize / 4;
1401 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1409 O << " .b8 " << *Mang->getSymbol(GVar);
1417 O << " .b8 " << *Mang->getSymbol(GVar);
1426 assert(0 && "type not supported yet");
1433 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1434 if (localDecls.find(f) == localDecls.end())
1437 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1439 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1440 O << "\t// demoted variable\n\t";
1441 printModuleLevelGV(gvars[i], O, true);
1445 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1446 raw_ostream &O) const {
1447 switch (AddressSpace) {
1448 case llvm::ADDRESS_SPACE_LOCAL:
1451 case llvm::ADDRESS_SPACE_GLOBAL:
1454 case llvm::ADDRESS_SPACE_CONST:
1457 case llvm::ADDRESS_SPACE_SHARED:
1461 report_fatal_error("Bad address space found while emitting PTX");
1467 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1468 switch (Ty->getTypeID()) {
1470 llvm_unreachable("unexpected type");
1472 case Type::IntegerTyID: {
1473 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1476 else if (NumBits <= 64) {
1477 std::string name = "u";
1478 return name + utostr(NumBits);
1480 llvm_unreachable("Integer too large");
1485 case Type::FloatTyID:
1487 case Type::DoubleTyID:
1489 case Type::PointerTyID:
1490 if (nvptxSubtarget.is64Bit())
1500 llvm_unreachable("unexpected type");
1504 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1507 const DataLayout *TD = TM.getDataLayout();
1509 // GlobalVariables are always constant pointers themselves.
1510 const PointerType *PTy = GVar->getType();
1511 Type *ETy = PTy->getElementType();
1514 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1515 if (GVar->getAlignment() == 0)
1516 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1518 O << " .align " << GVar->getAlignment();
1520 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1522 O << getPTXFundamentalTypeStr(ETy);
1524 O << *Mang->getSymbol(GVar);
1528 int64_t ElementSize = 0;
1530 // Although PTX has direct support for struct type and array type and LLVM IR
1531 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1532 // support these high level field accesses. Structs and arrays are lowered
1533 // into arrays of bytes.
1534 switch (ETy->getTypeID()) {
1535 case Type::StructTyID:
1536 case Type::ArrayTyID:
1537 case Type::VectorTyID:
1538 ElementSize = TD->getTypeStoreSize(ETy);
1539 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1541 O << itostr(ElementSize);
1546 assert(0 && "type not supported yet");
1551 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1552 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1553 return TD->getPrefTypeAlignment(Ty);
1555 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1557 return getOpenCLAlignment(TD, ATy->getElementType());
1559 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1561 Type *ETy = VTy->getElementType();
1562 unsigned int numE = VTy->getNumElements();
1563 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1567 return numE * alignE;
1570 const StructType *STy = dyn_cast<StructType>(Ty);
1572 unsigned int alignStruct = 1;
1573 // Go through each element of the struct and find the
1574 // largest alignment.
1575 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1576 Type *ETy = STy->getElementType(i);
1577 unsigned int align = getOpenCLAlignment(TD, ETy);
1578 if (align > alignStruct)
1579 alignStruct = align;
1584 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1586 return TD->getPointerPrefAlignment();
1587 return TD->getPrefTypeAlignment(Ty);
1590 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1591 int paramIndex, raw_ostream &O) {
1592 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1593 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1594 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1596 std::string argName = I->getName();
1597 const char *p = argName.c_str();
1608 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1609 Function::const_arg_iterator I, E;
1612 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1613 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1614 O << *CurrentFnSym << "_param_" << paramIndex;
1618 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1619 if (i == paramIndex) {
1620 printParamName(I, paramIndex, O);
1624 llvm_unreachable("paramIndex out of bound");
1627 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1628 const DataLayout *TD = TM.getDataLayout();
1629 const AttributeSet &PAL = F->getAttributes();
1630 const TargetLowering *TLI = TM.getTargetLowering();
1631 Function::const_arg_iterator I, E;
1632 unsigned paramIndex = 0;
1634 bool isKernelFunc = llvm::isKernelFunction(*F);
1635 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1636 MVT thePointerTy = TLI->getPointerTy();
1640 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1641 Type *Ty = I->getType();
1648 // Handle image/sampler parameters
1649 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1650 if (llvm::isImage(*I)) {
1651 std::string sname = I->getName();
1652 if (llvm::isImageWriteOnly(*I))
1653 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1655 else // Default image is read_only
1656 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1658 } else // Should be llvm::isSampler(*I)
1659 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1664 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1665 if (Ty->isVectorTy()) {
1666 // Just print .param .b8 .align <a> .param[size];
1667 // <a> = PAL.getparamalignment
1668 // size = typeallocsize of element type
1669 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1671 align = TD->getABITypeAlignment(Ty);
1673 unsigned sz = TD->getTypeAllocSize(Ty);
1674 O << "\t.param .align " << align << " .b8 ";
1675 printParamName(I, paramIndex, O);
1676 O << "[" << sz << "]";
1681 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1684 // Special handling for pointer arguments to kernel
1685 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1687 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1688 Type *ETy = PTy->getElementType();
1689 int addrSpace = PTy->getAddressSpace();
1690 switch (addrSpace) {
1694 case llvm::ADDRESS_SPACE_CONST:
1695 O << ".ptr .const ";
1697 case llvm::ADDRESS_SPACE_SHARED:
1698 O << ".ptr .shared ";
1700 case llvm::ADDRESS_SPACE_GLOBAL:
1701 O << ".ptr .global ";
1704 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1706 printParamName(I, paramIndex, O);
1710 // non-pointer scalar to kernel func
1712 // Special case: predicate operands become .u8 types
1713 if (Ty->isIntegerTy(1))
1716 O << getPTXFundamentalTypeStr(Ty);
1718 printParamName(I, paramIndex, O);
1721 // Non-kernel function, just print .param .b<size> for ABI
1722 // and .reg .b<size> for non ABY
1724 if (isa<IntegerType>(Ty)) {
1725 sz = cast<IntegerType>(Ty)->getBitWidth();
1728 } else if (isa<PointerType>(Ty))
1729 sz = thePointerTy.getSizeInBits();
1731 sz = Ty->getPrimitiveSizeInBits();
1733 O << "\t.param .b" << sz << " ";
1735 O << "\t.reg .b" << sz << " ";
1736 printParamName(I, paramIndex, O);
1740 // param has byVal attribute. So should be a pointer
1741 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1742 assert(PTy && "Param with byval attribute should be a pointer type");
1743 Type *ETy = PTy->getElementType();
1745 if (isABI || isKernelFunc) {
1746 // Just print .param .b8 .align <a> .param[size];
1747 // <a> = PAL.getparamalignment
1748 // size = typeallocsize of element type
1749 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1751 align = TD->getABITypeAlignment(ETy);
1753 unsigned sz = TD->getTypeAllocSize(ETy);
1754 O << "\t.param .align " << align << " .b8 ";
1755 printParamName(I, paramIndex, O);
1756 O << "[" << sz << "]";
1759 // Split the ETy into constituent parts and
1760 // print .param .b<size> <name> for each part.
1761 // Further, if a part is vector, print the above for
1762 // each vector element.
1763 SmallVector<EVT, 16> vtparts;
1764 ComputeValueVTs(*TLI, ETy, vtparts);
1765 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1767 EVT elemtype = vtparts[i];
1768 if (vtparts[i].isVector()) {
1769 elems = vtparts[i].getVectorNumElements();
1770 elemtype = vtparts[i].getVectorElementType();
1773 for (unsigned j = 0, je = elems; j != je; ++j) {
1774 unsigned sz = elemtype.getSizeInBits();
1775 if (elemtype.isInteger() && (sz < 32))
1777 O << "\t.reg .b" << sz << " ";
1778 printParamName(I, paramIndex, O);
1794 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1796 const Function *F = MF.getFunction();
1797 emitFunctionParamList(F, O);
1800 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1801 const MachineFunction &MF) {
1802 SmallString<128> Str;
1803 raw_svector_ostream O(Str);
1805 // Map the global virtual register number to a register class specific
1806 // virtual register number starting from 1 with that class.
1807 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1808 //unsigned numRegClasses = TRI->getNumRegClasses();
1810 // Emit the Fake Stack Object
1811 const MachineFrameInfo *MFI = MF.getFrameInfo();
1812 int NumBytes = (int) MFI->getStackSize();
1814 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1815 << getFunctionNumber() << "[" << NumBytes << "];\n";
1816 if (nvptxSubtarget.is64Bit()) {
1817 O << "\t.reg .b64 \t%SP;\n";
1818 O << "\t.reg .b64 \t%SPL;\n";
1820 O << "\t.reg .b32 \t%SP;\n";
1821 O << "\t.reg .b32 \t%SPL;\n";
1825 // Go through all virtual registers to establish the mapping between the
1827 // register number and the per class virtual register number.
1828 // We use the per class virtual register number in the ptx output.
1829 unsigned int numVRs = MRI->getNumVirtRegs();
1830 for (unsigned i = 0; i < numVRs; i++) {
1831 unsigned int vr = TRI->index2VirtReg(i);
1832 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1833 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1834 int n = regmap.size();
1835 regmap.insert(std::make_pair(vr, n + 1));
1838 // Emit register declarations
1839 // @TODO: Extract out the real register usage
1840 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1841 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1842 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1843 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1844 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1845 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1846 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1848 // Emit declaration of the virtual registers or 'physical' registers for
1849 // each register class
1850 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1851 const TargetRegisterClass *RC = TRI->getRegClass(i);
1852 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1853 std::string rcname = getNVPTXRegClassName(RC);
1854 std::string rcStr = getNVPTXRegClassStr(RC);
1855 int n = regmap.size();
1857 // Only declare those registers that may be used.
1859 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1864 OutStreamer.EmitRawText(O.str());
1867 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1868 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1870 unsigned int numHex;
1873 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1876 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1877 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1880 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1882 llvm_unreachable("unsupported fp type");
1884 APInt API = APF.bitcastToAPInt();
1885 std::string hexstr(utohexstr(API.getZExtValue()));
1887 if (hexstr.length() < numHex)
1888 O << std::string(numHex - hexstr.length(), '0');
1889 O << utohexstr(API.getZExtValue());
1892 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1893 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1894 O << CI->getValue();
1897 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1898 printFPConstant(CFP, O);
1901 if (isa<ConstantPointerNull>(CPV)) {
1905 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1906 O << *Mang->getSymbol(GVar);
1909 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1910 const Value *v = Cexpr->stripPointerCasts();
1911 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1912 O << *Mang->getSymbol(GVar);
1915 O << *LowerConstant(CPV, *this);
1919 llvm_unreachable("Not scalar type found in printScalarConstant()");
1922 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1923 AggBuffer *aggBuffer) {
1925 const DataLayout *TD = TM.getDataLayout();
1927 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1928 int s = TD->getTypeAllocSize(CPV->getType());
1931 aggBuffer->addZeros(s);
1936 switch (CPV->getType()->getTypeID()) {
1938 case Type::IntegerTyID: {
1939 const Type *ETy = CPV->getType();
1940 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1942 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1944 aggBuffer->addBytes(ptr, 1, Bytes);
1945 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1946 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1947 ptr = (unsigned char *)&int16;
1948 aggBuffer->addBytes(ptr, 2, Bytes);
1949 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1950 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1951 int int32 = (int)(constInt->getZExtValue());
1952 ptr = (unsigned char *)&int32;
1953 aggBuffer->addBytes(ptr, 4, Bytes);
1955 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1956 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1957 ConstantFoldConstantExpression(Cexpr, TD))) {
1958 int int32 = (int)(constInt->getZExtValue());
1959 ptr = (unsigned char *)&int32;
1960 aggBuffer->addBytes(ptr, 4, Bytes);
1963 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1964 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1965 aggBuffer->addSymbol(v);
1966 aggBuffer->addZeros(4);
1970 llvm_unreachable("unsupported integer const type");
1971 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1972 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1973 long long int64 = (long long)(constInt->getZExtValue());
1974 ptr = (unsigned char *)&int64;
1975 aggBuffer->addBytes(ptr, 8, Bytes);
1977 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1978 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1979 ConstantFoldConstantExpression(Cexpr, TD))) {
1980 long long int64 = (long long)(constInt->getZExtValue());
1981 ptr = (unsigned char *)&int64;
1982 aggBuffer->addBytes(ptr, 8, Bytes);
1985 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1986 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1987 aggBuffer->addSymbol(v);
1988 aggBuffer->addZeros(8);
1992 llvm_unreachable("unsupported integer const type");
1994 llvm_unreachable("unsupported integer const type");
1997 case Type::FloatTyID:
1998 case Type::DoubleTyID: {
1999 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
2000 const Type *Ty = CFP->getType();
2001 if (Ty == Type::getFloatTy(CPV->getContext())) {
2002 float float32 = (float) CFP->getValueAPF().convertToFloat();
2003 ptr = (unsigned char *)&float32;
2004 aggBuffer->addBytes(ptr, 4, Bytes);
2005 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
2006 double float64 = CFP->getValueAPF().convertToDouble();
2007 ptr = (unsigned char *)&float64;
2008 aggBuffer->addBytes(ptr, 8, Bytes);
2010 llvm_unreachable("unsupported fp const type");
2014 case Type::PointerTyID: {
2015 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2016 aggBuffer->addSymbol(GVar);
2017 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2018 const Value *v = Cexpr->stripPointerCasts();
2019 aggBuffer->addSymbol(v);
2021 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2022 aggBuffer->addZeros(s);
2026 case Type::ArrayTyID:
2027 case Type::VectorTyID:
2028 case Type::StructTyID: {
2029 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2030 isa<ConstantStruct>(CPV)) {
2031 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2032 bufferAggregateConstant(CPV, aggBuffer);
2033 if (Bytes > ElementSize)
2034 aggBuffer->addZeros(Bytes - ElementSize);
2035 } else if (isa<ConstantAggregateZero>(CPV))
2036 aggBuffer->addZeros(Bytes);
2038 llvm_unreachable("Unexpected Constant type");
2043 llvm_unreachable("unsupported type");
2047 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2048 AggBuffer *aggBuffer) {
2049 const DataLayout *TD = TM.getDataLayout();
2053 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2054 if (CPV->getNumOperands())
2055 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2056 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2060 if (const ConstantDataSequential *CDS =
2061 dyn_cast<ConstantDataSequential>(CPV)) {
2062 if (CDS->getNumElements())
2063 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2064 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2069 if (isa<ConstantStruct>(CPV)) {
2070 if (CPV->getNumOperands()) {
2071 StructType *ST = cast<StructType>(CPV->getType());
2072 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2074 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2075 TD->getTypeAllocSize(ST) -
2076 TD->getStructLayout(ST)->getElementOffset(i);
2078 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2079 TD->getStructLayout(ST)->getElementOffset(i);
2080 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2085 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2088 // buildTypeNameMap - Run through symbol table looking for type names.
2091 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2093 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2095 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2096 !PI->second.compare("struct._image2d_t") ||
2097 !PI->second.compare("struct._image3d_t")))
2103 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2105 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2106 unsigned AsmVariant,
2107 const char *ExtraCode, raw_ostream &O) {
2108 if (ExtraCode && ExtraCode[0]) {
2109 if (ExtraCode[1] != 0)
2110 return true; // Unknown modifier.
2112 switch (ExtraCode[0]) {
2114 // See if this is a generic print operand
2115 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2121 printOperand(MI, OpNo, O);
2126 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2127 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2128 const char *ExtraCode, raw_ostream &O) {
2129 if (ExtraCode && ExtraCode[0])
2130 return true; // Unknown modifier
2133 printMemOperand(MI, OpNo, O);
2139 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2140 switch (MI.getOpcode()) {
2143 case NVPTX::CallArgBeginInst:
2144 case NVPTX::CallArgEndInst0:
2145 case NVPTX::CallArgEndInst1:
2146 case NVPTX::CallArgF32:
2147 case NVPTX::CallArgF64:
2148 case NVPTX::CallArgI16:
2149 case NVPTX::CallArgI32:
2150 case NVPTX::CallArgI32imm:
2151 case NVPTX::CallArgI64:
2152 case NVPTX::CallArgParam:
2153 case NVPTX::CallVoidInst:
2154 case NVPTX::CallVoidInstReg:
2155 case NVPTX::Callseq_End:
2156 case NVPTX::CallVoidInstReg64:
2157 case NVPTX::DeclareParamInst:
2158 case NVPTX::DeclareRetMemInst:
2159 case NVPTX::DeclareRetRegInst:
2160 case NVPTX::DeclareRetScalarInst:
2161 case NVPTX::DeclareScalarParamInst:
2162 case NVPTX::DeclareScalarRegInst:
2163 case NVPTX::StoreParamF32:
2164 case NVPTX::StoreParamF64:
2165 case NVPTX::StoreParamI16:
2166 case NVPTX::StoreParamI32:
2167 case NVPTX::StoreParamI64:
2168 case NVPTX::StoreParamI8:
2169 case NVPTX::StoreRetvalF32:
2170 case NVPTX::StoreRetvalF64:
2171 case NVPTX::StoreRetvalI16:
2172 case NVPTX::StoreRetvalI32:
2173 case NVPTX::StoreRetvalI64:
2174 case NVPTX::StoreRetvalI8:
2175 case NVPTX::LastCallArgF32:
2176 case NVPTX::LastCallArgF64:
2177 case NVPTX::LastCallArgI16:
2178 case NVPTX::LastCallArgI32:
2179 case NVPTX::LastCallArgI32imm:
2180 case NVPTX::LastCallArgI64:
2181 case NVPTX::LastCallArgParam:
2182 case NVPTX::LoadParamMemF32:
2183 case NVPTX::LoadParamMemF64:
2184 case NVPTX::LoadParamMemI16:
2185 case NVPTX::LoadParamMemI32:
2186 case NVPTX::LoadParamMemI64:
2187 case NVPTX::LoadParamMemI8:
2188 case NVPTX::PrototypeInst:
2189 case NVPTX::DBG_VALUE:
2195 // Force static initialization.
2196 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2197 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2198 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2201 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2202 std::stringstream temp;
2203 LineReader *reader = this->getReader(filename.str());
2205 temp << filename.str();
2209 temp << reader->readLine(line);
2211 this->OutStreamer.EmitRawText(Twine(temp.str()));
2214 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2215 if (reader == NULL) {
2216 reader = new LineReader(filename);
2219 if (reader->fileName() != filename) {
2221 reader = new LineReader(filename);
2227 std::string LineReader::readLine(unsigned lineNum) {
2228 if (lineNum < theCurLine) {
2230 fstr.seekg(0, std::ios::beg);
2232 while (theCurLine < lineNum) {
2233 fstr.getline(buff, 500);
2239 // Force static initialization.
2240 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2241 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2242 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);