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 "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMachineFunctionInfo.h"
21 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeValue.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #define DEPOTNAME "__local_depot"
54 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
55 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
60 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
66 void DiscoverDependentGlobals(const Value *V,
67 DenseSet<const GlobalVariable *> &Globals) {
68 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
71 if (const User *U = dyn_cast<User>(V)) {
72 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73 DiscoverDependentGlobals(U->getOperand(i), Globals);
79 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80 /// instances to be emitted, but only after any dependents have been added
82 void VisitGlobalVariableForEmission(
83 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84 DenseSet<const GlobalVariable *> &Visited,
85 DenseSet<const GlobalVariable *> &Visiting) {
86 // Have we already visited this one?
87 if (Visited.count(GV))
90 // Do we have a circular dependency?
91 if (!Visiting.insert(GV).second)
92 report_fatal_error("Circular dependency found in global variable set");
94 // Make sure we visit all dependents first
95 DenseSet<const GlobalVariable *> Others;
96 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
97 DiscoverDependentGlobals(GV->getOperand(i), Others);
99 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
102 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
104 // Now we can visit ourself
111 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
112 // cannot just link to the existing version.
113 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
115 using namespace nvptx;
116 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
117 MCContext &Ctx = AP.OutContext;
119 if (CV->isNullValue() || isa<UndefValue>(CV))
120 return MCConstantExpr::Create(0, Ctx);
122 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
123 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
125 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
126 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
128 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
129 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
131 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
133 llvm_unreachable("Unknown constant value to lower!");
135 switch (CE->getOpcode()) {
137 // If the code isn't optimized, there may be outstanding folding
138 // opportunities. Attempt to fold the expression using DataLayout as a
139 // last resort before giving up.
140 if (Constant *C = ConstantFoldConstantExpression(
141 CE, AP.TM.getSubtargetImpl()->getDataLayout()))
143 return LowerConstant(C, AP);
145 // Otherwise report the problem to the user.
148 raw_string_ostream OS(S);
149 OS << "Unsupported expression in static initializer: ";
150 CE->printAsOperand(OS, /*PrintType=*/ false,
151 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
152 report_fatal_error(OS.str());
154 case Instruction::AddrSpaceCast: {
155 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
156 // handled by the generic() logic in the MCExpr printer
157 PointerType *DstTy = cast<PointerType>(CE->getType());
158 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
159 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
160 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
163 raw_string_ostream OS(S);
164 OS << "Unsupported expression in static initializer: ";
165 CE->printAsOperand(OS, /*PrintType=*/ false,
166 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
167 report_fatal_error(OS.str());
169 case Instruction::GetElementPtr: {
170 const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
171 // Generate a symbolic expression for the byte address
172 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
173 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
175 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
179 int64_t Offset = OffsetAI.getSExtValue();
180 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
184 case Instruction::Trunc:
185 // We emit the value and depend on the assembler to truncate the generated
186 // expression properly. This is important for differences between
187 // blockaddress labels. Since the two labels are in the same function, it
188 // is reasonable to treat their delta as a 32-bit value.
190 case Instruction::BitCast:
191 return LowerConstant(CE->getOperand(0), AP);
193 case Instruction::IntToPtr: {
194 const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
195 // Handle casts to pointers by changing them into casts to the appropriate
196 // integer type. This promotes constant folding and simplifies this code.
197 Constant *Op = CE->getOperand(0);
198 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
200 return LowerConstant(Op, AP);
203 case Instruction::PtrToInt: {
204 const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
205 // Support only foldable casts to/from pointers that can be eliminated by
206 // changing the pointer to the appropriately sized integer type.
207 Constant *Op = CE->getOperand(0);
208 Type *Ty = CE->getType();
210 const MCExpr *OpExpr = LowerConstant(Op, AP);
212 // We can emit the pointer value into this slot if the slot is an
213 // integer slot equal to the size of the pointer.
214 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
217 // Otherwise the pointer is smaller than the resultant integer, mask off
218 // the high bits so we are sure to get a proper truncation if the input is
220 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
221 const MCExpr *MaskExpr =
222 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
223 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
226 // The MC library also has a right-shift operator, but it isn't consistently
227 // signed or unsigned between different targets.
228 case Instruction::Add:
229 case Instruction::Sub:
230 case Instruction::Mul:
231 case Instruction::SDiv:
232 case Instruction::SRem:
233 case Instruction::Shl:
234 case Instruction::And:
235 case Instruction::Or:
236 case Instruction::Xor: {
237 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
238 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
239 switch (CE->getOpcode()) {
241 llvm_unreachable("Unknown binary operator constant cast expr");
242 case Instruction::Add:
243 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
244 case Instruction::Sub:
245 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
246 case Instruction::Mul:
247 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
248 case Instruction::SDiv:
249 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
250 case Instruction::SRem:
251 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
252 case Instruction::Shl:
253 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
254 case Instruction::And:
255 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
256 case Instruction::Or:
257 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
258 case Instruction::Xor:
259 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
265 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
266 if (!EmitLineNumbers)
271 DebugLoc curLoc = MI.getDebugLoc();
273 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
276 if (prevDebugLoc == curLoc)
279 prevDebugLoc = curLoc;
281 if (curLoc.isUnknown())
284 const MachineFunction *MF = MI.getParent()->getParent();
285 //const TargetMachine &TM = MF->getTarget();
287 const LLVMContext &ctx = MF->getFunction()->getContext();
288 DIScope Scope(curLoc.getScope(ctx));
290 assert((!Scope || Scope.isScope()) &&
291 "Scope of a DebugLoc should be null or a DIScope.");
295 StringRef fileName(Scope.getFilename());
296 StringRef dirName(Scope.getDirectory());
297 SmallString<128> FullPathName = dirName;
298 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
299 sys::path::append(FullPathName, fileName);
300 fileName = FullPathName.str();
303 if (filenameMap.find(fileName.str()) == filenameMap.end())
306 // Emit the line from the source file.
308 this->emitSrcInText(fileName.str(), curLoc.getLine());
310 std::stringstream temp;
311 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
312 << " " << curLoc.getCol();
313 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
316 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
317 SmallString<128> Str;
318 raw_svector_ostream OS(Str);
319 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
320 emitLineNumberAsDotLoc(*MI);
323 lowerToMCInst(MI, Inst);
324 EmitToStreamer(OutStreamer, Inst);
327 // Handle symbol backtracking for targets that do not support image handles
328 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
329 unsigned OpNo, MCOperand &MCOp) {
330 const MachineOperand &MO = MI->getOperand(OpNo);
331 const MCInstrDesc &MCID = MI->getDesc();
333 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
334 // This is a texture fetch, so operand 4 is a texref and operand 5 is
336 if (OpNo == 4 && MO.isImm()) {
337 lowerImageHandleSymbol(MO.getImm(), MCOp);
340 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
341 lowerImageHandleSymbol(MO.getImm(), MCOp);
346 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
348 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
350 // For a surface load of vector size N, the Nth operand will be the surfref
351 if (OpNo == VecSize && MO.isImm()) {
352 lowerImageHandleSymbol(MO.getImm(), MCOp);
357 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
358 // This is a surface store, so operand 0 is a surfref
359 if (OpNo == 0 && MO.isImm()) {
360 lowerImageHandleSymbol(MO.getImm(), MCOp);
365 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
366 // This is a query, so operand 1 is a surfref/texref
367 if (OpNo == 1 && MO.isImm()) {
368 lowerImageHandleSymbol(MO.getImm(), MCOp);
378 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
380 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
381 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
382 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
383 const char *Sym = MFI->getImageHandleSymbol(Index);
384 std::string *SymNamePtr =
385 nvTM.getManagedStrPool()->getManagedString(Sym);
386 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
387 StringRef(SymNamePtr->c_str())));
390 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
391 OutMI.setOpcode(MI->getOpcode());
392 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
394 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
395 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
396 const MachineOperand &MO = MI->getOperand(0);
397 OutMI.addOperand(GetSymbolRef(
398 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
402 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
403 const MachineOperand &MO = MI->getOperand(i);
406 if (!ST.hasImageHandles()) {
407 if (lowerImageHandleOperand(MI, i, MCOp)) {
408 OutMI.addOperand(MCOp);
413 if (lowerOperand(MO, MCOp))
414 OutMI.addOperand(MCOp);
418 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
420 switch (MO.getType()) {
421 default: llvm_unreachable("unknown operand type");
422 case MachineOperand::MO_Register:
423 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
425 case MachineOperand::MO_Immediate:
426 MCOp = MCOperand::CreateImm(MO.getImm());
428 case MachineOperand::MO_MachineBasicBlock:
429 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
430 MO.getMBB()->getSymbol(), OutContext));
432 case MachineOperand::MO_ExternalSymbol:
433 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
435 case MachineOperand::MO_GlobalAddress:
436 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
438 case MachineOperand::MO_FPImmediate: {
439 const ConstantFP *Cnt = MO.getFPImm();
440 APFloat Val = Cnt->getValueAPF();
442 switch (Cnt->getType()->getTypeID()) {
443 default: report_fatal_error("Unsupported FP type"); break;
444 case Type::FloatTyID:
445 MCOp = MCOperand::CreateExpr(
446 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
448 case Type::DoubleTyID:
449 MCOp = MCOperand::CreateExpr(
450 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
459 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
460 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
461 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
463 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
464 unsigned RegNum = RegMap[Reg];
466 // Encode the register class in the upper 4 bits
467 // Must be kept in sync with NVPTXInstPrinter::printRegName
469 if (RC == &NVPTX::Int1RegsRegClass) {
471 } else if (RC == &NVPTX::Int16RegsRegClass) {
473 } else if (RC == &NVPTX::Int32RegsRegClass) {
475 } else if (RC == &NVPTX::Int64RegsRegClass) {
477 } else if (RC == &NVPTX::Float32RegsRegClass) {
479 } else if (RC == &NVPTX::Float64RegsRegClass) {
482 report_fatal_error("Bad register class");
485 // Insert the vreg number
486 Ret |= (RegNum & 0x0FFFFFFF);
489 // Some special-use registers are actually physical registers.
490 // Encode this as the register class ID of 0 and the real register ID.
491 return Reg & 0x0FFFFFFF;
495 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
497 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
499 return MCOperand::CreateExpr(Expr);
502 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
503 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
504 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
506 Type *Ty = F->getReturnType();
508 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
510 if (Ty->getTypeID() == Type::VoidTyID)
516 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
518 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
519 size = ITy->getBitWidth();
523 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
524 size = Ty->getPrimitiveSizeInBits();
527 O << ".param .b" << size << " func_retval0";
528 } else if (isa<PointerType>(Ty)) {
529 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
532 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
533 unsigned totalsz = TD->getTypeAllocSize(Ty);
534 unsigned retAlignment = 0;
535 if (!llvm::getAlign(*F, 0, retAlignment))
536 retAlignment = TD->getABITypeAlignment(Ty);
537 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
540 assert(false && "Unknown return type");
543 SmallVector<EVT, 16> vtparts;
544 ComputeValueVTs(*TLI, Ty, vtparts);
546 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
548 EVT elemtype = vtparts[i];
549 if (vtparts[i].isVector()) {
550 elems = vtparts[i].getVectorNumElements();
551 elemtype = vtparts[i].getVectorElementType();
554 for (unsigned j = 0, je = elems; j != je; ++j) {
555 unsigned sz = elemtype.getSizeInBits();
556 if (elemtype.isInteger() && (sz < 32))
558 O << ".reg .b" << sz << " func_retval" << idx;
571 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
573 const Function *F = MF.getFunction();
574 printReturnValStr(F, O);
577 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
578 SmallString<128> Str;
579 raw_svector_ostream O(Str);
581 if (!GlobalsEmitted) {
582 emitGlobals(*MF->getFunction()->getParent());
583 GlobalsEmitted = true;
587 MRI = &MF->getRegInfo();
588 F = MF->getFunction();
589 emitLinkageDirective(F, O);
590 if (llvm::isKernelFunction(*F))
594 printReturnValStr(*MF, O);
599 emitFunctionParamList(*MF, O);
601 if (llvm::isKernelFunction(*F))
602 emitKernelFunctionDirectives(*F, O);
604 OutStreamer.EmitRawText(O.str());
606 prevDebugLoc = DebugLoc();
609 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
611 OutStreamer.EmitRawText(StringRef("{\n"));
612 setAndEmitFunctionVirtualRegisters(*MF);
614 SmallString<128> Str;
615 raw_svector_ostream O(Str);
616 emitDemotedVars(MF->getFunction(), O);
617 OutStreamer.EmitRawText(O.str());
620 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
621 OutStreamer.EmitRawText(StringRef("}\n"));
625 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
626 unsigned RegNo = MI->getOperand(0).getReg();
627 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
628 if (TRI->isVirtualRegister(RegNo)) {
629 OutStreamer.AddComment(Twine("implicit-def: ") +
630 getVirtualRegisterName(RegNo));
632 OutStreamer.AddComment(
633 Twine("implicit-def: ") +
634 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
636 OutStreamer.AddBlankLine();
639 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
640 raw_ostream &O) const {
641 // If the NVVM IR has some of reqntid* specified, then output
642 // the reqntid directive, and set the unspecified ones to 1.
643 // If none of reqntid* is specified, don't output reqntid directive.
644 unsigned reqntidx, reqntidy, reqntidz;
645 bool specified = false;
646 if (llvm::getReqNTIDx(F, reqntidx) == false)
650 if (llvm::getReqNTIDy(F, reqntidy) == false)
654 if (llvm::getReqNTIDz(F, reqntidz) == false)
660 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
663 // If the NVVM IR has some of maxntid* specified, then output
664 // the maxntid directive, and set the unspecified ones to 1.
665 // If none of maxntid* is specified, don't output maxntid directive.
666 unsigned maxntidx, maxntidy, maxntidz;
668 if (llvm::getMaxNTIDx(F, maxntidx) == false)
672 if (llvm::getMaxNTIDy(F, maxntidy) == false)
676 if (llvm::getMaxNTIDz(F, maxntidz) == false)
682 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
686 if (llvm::getMinCTASm(F, mincta))
687 O << ".minnctapersm " << mincta << "\n";
691 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
692 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
695 raw_string_ostream NameStr(Name);
697 VRegRCMap::const_iterator I = VRegMapping.find(RC);
698 assert(I != VRegMapping.end() && "Bad register class");
699 const DenseMap<unsigned, unsigned> &RegMap = I->second;
701 VRegMap::const_iterator VI = RegMap.find(Reg);
702 assert(VI != RegMap.end() && "Bad virtual register");
703 unsigned MappedVR = VI->second;
705 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
711 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
713 O << getVirtualRegisterName(vr);
716 void NVPTXAsmPrinter::printVecModifiedImmediate(
717 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
718 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
719 int Imm = (int) MO.getImm();
720 if (0 == strcmp(Modifier, "vecelem"))
721 O << "_" << vecelem[Imm];
722 else if (0 == strcmp(Modifier, "vecv4comm1")) {
723 if ((Imm < 0) || (Imm > 3))
725 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
726 if ((Imm < 4) || (Imm > 7))
728 } else if (0 == strcmp(Modifier, "vecv4pos")) {
731 O << "_" << vecelem[Imm % 4];
732 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
733 if ((Imm < 0) || (Imm > 1))
735 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
736 if ((Imm < 2) || (Imm > 3))
738 } else if (0 == strcmp(Modifier, "vecv2pos")) {
741 O << "_" << vecelem[Imm % 2];
743 llvm_unreachable("Unknown Modifier on immediate operand");
748 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
750 emitLinkageDirective(F, O);
751 if (llvm::isKernelFunction(*F))
755 printReturnValStr(F, O);
756 O << *getSymbol(F) << "\n";
757 emitFunctionParamList(F, O);
761 static bool usedInGlobalVarDef(const Constant *C) {
765 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
766 if (GV->getName().str() == "llvm.used")
771 for (const User *U : C->users())
772 if (const Constant *C = dyn_cast<Constant>(U))
773 if (usedInGlobalVarDef(C))
779 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
780 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
781 if (othergv->getName().str() == "llvm.used")
785 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
786 if (instr->getParent() && instr->getParent()->getParent()) {
787 const Function *curFunc = instr->getParent()->getParent();
788 if (oneFunc && (curFunc != oneFunc))
796 for (const User *UU : U->users())
797 if (usedInOneFunc(UU, oneFunc) == false)
803 /* Find out if a global variable can be demoted to local scope.
804 * Currently, this is valid for CUDA shared variables, which have local
805 * scope and global lifetime. So the conditions to check are :
806 * 1. Is the global variable in shared address space?
807 * 2. Does it have internal linkage?
808 * 3. Is the global variable referenced only in one function?
810 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
811 if (gv->hasInternalLinkage() == false)
813 const PointerType *Pty = gv->getType();
814 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
817 const Function *oneFunc = nullptr;
819 bool flag = usedInOneFunc(gv, oneFunc);
828 static bool useFuncSeen(const Constant *C,
829 llvm::DenseMap<const Function *, bool> &seenMap) {
830 for (const User *U : C->users()) {
831 if (const Constant *cu = dyn_cast<Constant>(U)) {
832 if (useFuncSeen(cu, seenMap))
834 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
835 const BasicBlock *bb = I->getParent();
838 const Function *caller = bb->getParent();
841 if (seenMap.find(caller) != seenMap.end())
848 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
849 llvm::DenseMap<const Function *, bool> seenMap;
850 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
851 const Function *F = FI;
853 if (F->isDeclaration()) {
856 if (F->getIntrinsicID())
858 emitDeclaration(F, O);
861 for (const User *U : F->users()) {
862 if (const Constant *C = dyn_cast<Constant>(U)) {
863 if (usedInGlobalVarDef(C)) {
864 // The use is in the initialization of a global variable
865 // that is a function pointer, so print a declaration
866 // for the original function
867 emitDeclaration(F, O);
870 // Emit a declaration of this function if the function that
871 // uses this constant expr has already been seen.
872 if (useFuncSeen(C, seenMap)) {
873 emitDeclaration(F, O);
878 if (!isa<Instruction>(U))
880 const Instruction *instr = cast<Instruction>(U);
881 const BasicBlock *bb = instr->getParent();
884 const Function *caller = bb->getParent();
888 // If a caller has already been seen, then the caller is
889 // appearing in the module before the callee. so print out
890 // a declaration for the callee.
891 if (seenMap.find(caller) != seenMap.end()) {
892 emitDeclaration(F, O);
900 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
901 DebugInfoFinder DbgFinder;
902 DbgFinder.processModule(M);
905 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
906 StringRef Filename(DIUnit.getFilename());
907 StringRef Dirname(DIUnit.getDirectory());
908 SmallString<128> FullPathName = Dirname;
909 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
910 sys::path::append(FullPathName, Filename);
911 Filename = FullPathName.str();
913 if (filenameMap.find(Filename.str()) != filenameMap.end())
915 filenameMap[Filename.str()] = i;
916 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
920 for (DISubprogram SP : DbgFinder.subprograms()) {
921 StringRef Filename(SP.getFilename());
922 StringRef Dirname(SP.getDirectory());
923 SmallString<128> FullPathName = Dirname;
924 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
925 sys::path::append(FullPathName, Filename);
926 Filename = FullPathName.str();
928 if (filenameMap.find(Filename.str()) != filenameMap.end())
930 filenameMap[Filename.str()] = i;
935 bool NVPTXAsmPrinter::doInitialization(Module &M) {
937 SmallString<128> Str1;
938 raw_svector_ostream OS1(Str1);
940 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
941 MMI->AnalyzeModule(M);
943 // We need to call the parent's one explicitly.
944 //bool Result = AsmPrinter::doInitialization(M);
946 // Initialize TargetLoweringObjectFile.
947 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
948 .Initialize(OutContext, TM);
950 Mang = new Mangler(TM.getSubtargetImpl()->getDataLayout());
952 // Emit header before any dwarf directives are emitted below.
954 OutStreamer.EmitRawText(OS1.str());
956 // Already commented out
957 //bool Result = AsmPrinter::doInitialization(M);
959 // Emit module-level inline asm if it exists.
960 if (!M.getModuleInlineAsm().empty()) {
961 OutStreamer.AddComment("Start of file scope inline assembly");
962 OutStreamer.AddBlankLine();
963 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
964 OutStreamer.AddBlankLine();
965 OutStreamer.AddComment("End of file scope inline assembly");
966 OutStreamer.AddBlankLine();
969 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
970 recordAndEmitFilenames(M);
972 GlobalsEmitted = false;
974 return false; // success
977 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
978 SmallString<128> Str2;
979 raw_svector_ostream OS2(Str2);
981 emitDeclarations(M, OS2);
983 // As ptxas does not support forward references of globals, we need to first
984 // sort the list of module-level globals in def-use order. We visit each
985 // global variable in order, and ensure that we emit it *after* its dependent
986 // globals. We use a little extra memory maintaining both a set and a list to
987 // have fast searches while maintaining a strict ordering.
988 SmallVector<const GlobalVariable *, 8> Globals;
989 DenseSet<const GlobalVariable *> GVVisited;
990 DenseSet<const GlobalVariable *> GVVisiting;
992 // Visit each global variable, in order
993 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
995 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
997 assert(GVVisited.size() == M.getGlobalList().size() &&
998 "Missed a global variable");
999 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1001 // Print out module-level global variables in proper order
1002 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1003 printModuleLevelGV(Globals[i], OS2);
1007 OutStreamer.EmitRawText(OS2.str());
1010 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1012 O << "// Generated by LLVM NVPTX Back-End\n";
1016 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1017 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1020 O << nvptxSubtarget.getTargetName();
1022 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1023 O << ", texmode_independent";
1024 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1025 if (!nvptxSubtarget.hasDouble())
1026 O << ", map_f64_to_f32";
1029 if (MAI->doesSupportDebugInformation())
1034 O << ".address_size ";
1035 if (nvptxSubtarget.is64Bit())
1044 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1046 // If we did not emit any functions, then the global declarations have not
1047 // yet been emitted.
1048 if (!GlobalsEmitted) {
1050 GlobalsEmitted = true;
1053 // XXX Temproarily remove global variables so that doFinalization() will not
1054 // emit them again (global variables are emitted at beginning).
1056 Module::GlobalListType &global_list = M.getGlobalList();
1057 int i, n = global_list.size();
1058 GlobalVariable **gv_array = new GlobalVariable *[n];
1060 // first, back-up GlobalVariable in gv_array
1062 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1064 gv_array[i++] = &*I;
1066 // second, empty global_list
1067 while (!global_list.empty())
1068 global_list.remove(global_list.begin());
1070 // call doFinalization
1071 bool ret = AsmPrinter::doFinalization(M);
1073 // now we restore global variables
1074 for (i = 0; i < n; i++)
1075 global_list.insert(global_list.end(), gv_array[i]);
1077 clearAnnotationCache(&M);
1082 //bool Result = AsmPrinter::doFinalization(M);
1083 // Instead of calling the parents doFinalization, we may
1084 // clone parents doFinalization and customize here.
1085 // Currently, we if NVISA out the EmitGlobals() in
1086 // parent's doFinalization, which is too intrusive.
1088 // Same for the doInitialization.
1092 // This function emits appropriate linkage directives for
1093 // functions and global variables.
1095 // extern function declaration -> .extern
1096 // extern function definition -> .visible
1097 // external global variable with init -> .visible
1098 // external without init -> .extern
1099 // appending -> not allowed, assert.
1100 // for any linkage other than
1101 // internal, private, linker_private,
1102 // linker_private_weak, linker_private_weak_def_auto,
1103 // we emit -> .weak.
1105 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1107 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1108 if (V->hasExternalLinkage()) {
1109 if (isa<GlobalVariable>(V)) {
1110 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1112 if (GVar->hasInitializer())
1117 } else if (V->isDeclaration())
1121 } else if (V->hasAppendingLinkage()) {
1123 msg.append("Error: ");
1124 msg.append("Symbol ");
1126 msg.append(V->getName().str());
1127 msg.append("has unsupported appending linkage type");
1128 llvm_unreachable(msg.c_str());
1129 } else if (!V->hasInternalLinkage() &&
1130 !V->hasPrivateLinkage()) {
1136 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1138 bool processDemoted) {
1141 if (GVar->hasSection()) {
1142 if (GVar->getSection() == StringRef("llvm.metadata"))
1146 // Skip LLVM intrinsic global variables
1147 if (GVar->getName().startswith("llvm.") ||
1148 GVar->getName().startswith("nvvm."))
1151 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1153 // GlobalVariables are always constant pointers themselves.
1154 const PointerType *PTy = GVar->getType();
1155 Type *ETy = PTy->getElementType();
1157 if (GVar->hasExternalLinkage()) {
1158 if (GVar->hasInitializer())
1162 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1163 GVar->hasAvailableExternallyLinkage() ||
1164 GVar->hasCommonLinkage()) {
1168 if (llvm::isTexture(*GVar)) {
1169 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1173 if (llvm::isSurface(*GVar)) {
1174 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1178 if (GVar->isDeclaration()) {
1179 // (extern) declarations, no definition or initializer
1180 // Currently the only known declaration is for an automatic __local
1181 // (.shared) promoted to global.
1182 emitPTXGlobalVariable(GVar, O);
1187 if (llvm::isSampler(*GVar)) {
1188 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1190 const Constant *Initializer = nullptr;
1191 if (GVar->hasInitializer())
1192 Initializer = GVar->getInitializer();
1193 const ConstantInt *CI = nullptr;
1195 CI = dyn_cast<ConstantInt>(Initializer);
1197 unsigned sample = CI->getZExtValue();
1202 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1204 O << "addr_mode_" << i << " = ";
1210 O << "clamp_to_border";
1213 O << "clamp_to_edge";
1224 O << "filter_mode = ";
1225 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1233 llvm_unreachable("Anisotropic filtering is not supported");
1238 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1239 O << ", force_unnormalized_coords = 1";
1248 if (GVar->hasPrivateLinkage()) {
1250 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1253 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1254 if (!strncmp(GVar->getName().data(), "filename", 8))
1256 if (GVar->use_empty())
1260 const Function *demotedFunc = nullptr;
1261 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1262 O << "// " << GVar->getName().str() << " has been demoted\n";
1263 if (localDecls.find(demotedFunc) != localDecls.end())
1264 localDecls[demotedFunc].push_back(GVar);
1266 std::vector<const GlobalVariable *> temp;
1267 temp.push_back(GVar);
1268 localDecls[demotedFunc] = temp;
1274 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1276 if (isManaged(*GVar)) {
1277 O << " .attribute(.managed)";
1280 if (GVar->getAlignment() == 0)
1281 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1283 O << " .align " << GVar->getAlignment();
1285 if (ETy->isSingleValueType()) {
1287 // Special case: ABI requires that we use .u8 for predicates
1288 if (ETy->isIntegerTy(1))
1291 O << getPTXFundamentalTypeStr(ETy, false);
1293 O << *getSymbol(GVar);
1295 // Ptx allows variable initilization only for constant and global state
1297 if (GVar->hasInitializer()) {
1298 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1299 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1300 const Constant *Initializer = GVar->getInitializer();
1301 // 'undef' is treated as there is no value spefied.
1302 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1304 printScalarConstant(Initializer, O);
1307 // The frontend adds zero-initializer to variables that don't have an
1308 // initial value, so skip warning for this case.
1309 if (!GVar->getInitializer()->isNullValue()) {
1310 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1311 "' is not allowed in addrspace(" +
1312 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1313 report_fatal_error(warnMsg.c_str());
1318 unsigned int ElementSize = 0;
1320 // Although PTX has direct support for struct type and array type and
1321 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1322 // targets that support these high level field accesses. Structs, arrays
1323 // and vectors are lowered into arrays of bytes.
1324 switch (ETy->getTypeID()) {
1325 case Type::StructTyID:
1326 case Type::ArrayTyID:
1327 case Type::VectorTyID:
1328 ElementSize = TD->getTypeStoreSize(ETy);
1329 // Ptx allows variable initilization only for constant and
1330 // global state spaces.
1331 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1332 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1333 GVar->hasInitializer()) {
1334 const Constant *Initializer = GVar->getInitializer();
1335 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1336 AggBuffer aggBuffer(ElementSize, O, *this);
1337 bufferAggregateConstant(Initializer, &aggBuffer);
1338 if (aggBuffer.numSymbols) {
1339 if (nvptxSubtarget.is64Bit()) {
1340 O << " .u64 " << *getSymbol(GVar) << "[";
1341 O << ElementSize / 8;
1343 O << " .u32 " << *getSymbol(GVar) << "[";
1344 O << ElementSize / 4;
1348 O << " .b8 " << *getSymbol(GVar) << "[";
1356 O << " .b8 " << *getSymbol(GVar);
1364 O << " .b8 " << *getSymbol(GVar);
1373 llvm_unreachable("type not supported yet");
1380 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1381 if (localDecls.find(f) == localDecls.end())
1384 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1386 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1387 O << "\t// demoted variable\n\t";
1388 printModuleLevelGV(gvars[i], O, true);
1392 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1393 raw_ostream &O) const {
1394 switch (AddressSpace) {
1395 case llvm::ADDRESS_SPACE_LOCAL:
1398 case llvm::ADDRESS_SPACE_GLOBAL:
1401 case llvm::ADDRESS_SPACE_CONST:
1404 case llvm::ADDRESS_SPACE_SHARED:
1408 report_fatal_error("Bad address space found while emitting PTX");
1414 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1415 switch (Ty->getTypeID()) {
1417 llvm_unreachable("unexpected type");
1419 case Type::IntegerTyID: {
1420 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1423 else if (NumBits <= 64) {
1424 std::string name = "u";
1425 return name + utostr(NumBits);
1427 llvm_unreachable("Integer too large");
1432 case Type::FloatTyID:
1434 case Type::DoubleTyID:
1436 case Type::PointerTyID:
1437 if (nvptxSubtarget.is64Bit())
1447 llvm_unreachable("unexpected type");
1451 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1454 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1456 // GlobalVariables are always constant pointers themselves.
1457 const PointerType *PTy = GVar->getType();
1458 Type *ETy = PTy->getElementType();
1461 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1462 if (GVar->getAlignment() == 0)
1463 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1465 O << " .align " << GVar->getAlignment();
1467 if (ETy->isSingleValueType()) {
1469 O << getPTXFundamentalTypeStr(ETy);
1471 O << *getSymbol(GVar);
1475 int64_t ElementSize = 0;
1477 // Although PTX has direct support for struct type and array type and LLVM IR
1478 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1479 // support these high level field accesses. Structs and arrays are lowered
1480 // into arrays of bytes.
1481 switch (ETy->getTypeID()) {
1482 case Type::StructTyID:
1483 case Type::ArrayTyID:
1484 case Type::VectorTyID:
1485 ElementSize = TD->getTypeStoreSize(ETy);
1486 O << " .b8 " << *getSymbol(GVar) << "[";
1488 O << itostr(ElementSize);
1493 llvm_unreachable("type not supported yet");
1498 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1499 if (Ty->isSingleValueType())
1500 return TD->getPrefTypeAlignment(Ty);
1502 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1504 return getOpenCLAlignment(TD, ATy->getElementType());
1506 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1508 Type *ETy = VTy->getElementType();
1509 unsigned int numE = VTy->getNumElements();
1510 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1514 return numE * alignE;
1517 const StructType *STy = dyn_cast<StructType>(Ty);
1519 unsigned int alignStruct = 1;
1520 // Go through each element of the struct and find the
1521 // largest alignment.
1522 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1523 Type *ETy = STy->getElementType(i);
1524 unsigned int align = getOpenCLAlignment(TD, ETy);
1525 if (align > alignStruct)
1526 alignStruct = align;
1531 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1533 return TD->getPointerPrefAlignment();
1534 return TD->getPrefTypeAlignment(Ty);
1537 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1538 int paramIndex, raw_ostream &O) {
1539 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1540 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1541 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1543 std::string argName = I->getName();
1544 const char *p = argName.c_str();
1555 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1556 Function::const_arg_iterator I, E;
1559 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1560 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1561 O << *CurrentFnSym << "_param_" << paramIndex;
1565 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1566 if (i == paramIndex) {
1567 printParamName(I, paramIndex, O);
1571 llvm_unreachable("paramIndex out of bound");
1574 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1575 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1576 const AttributeSet &PAL = F->getAttributes();
1577 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1578 Function::const_arg_iterator I, E;
1579 unsigned paramIndex = 0;
1581 bool isKernelFunc = llvm::isKernelFunction(*F);
1582 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1583 MVT thePointerTy = TLI->getPointerTy();
1587 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1588 Type *Ty = I->getType();
1595 // Handle image/sampler parameters
1596 if (isKernelFunction(*F)) {
1597 if (isSampler(*I) || isImage(*I)) {
1599 std::string sname = I->getName();
1600 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1601 if (nvptxSubtarget.hasImageHandles())
1602 O << "\t.param .u64 .ptr .surfref ";
1604 O << "\t.param .surfref ";
1605 O << *CurrentFnSym << "_param_" << paramIndex;
1607 else { // Default image is read_only
1608 if (nvptxSubtarget.hasImageHandles())
1609 O << "\t.param .u64 .ptr .texref ";
1611 O << "\t.param .texref ";
1612 O << *CurrentFnSym << "_param_" << paramIndex;
1615 if (nvptxSubtarget.hasImageHandles())
1616 O << "\t.param .u64 .ptr .samplerref ";
1618 O << "\t.param .samplerref ";
1619 O << *CurrentFnSym << "_param_" << paramIndex;
1625 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1626 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1627 // Just print .param .align <a> .b8 .param[size];
1628 // <a> = PAL.getparamalignment
1629 // size = typeallocsize of element type
1630 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1632 align = TD->getABITypeAlignment(Ty);
1634 unsigned sz = TD->getTypeAllocSize(Ty);
1635 O << "\t.param .align " << align << " .b8 ";
1636 printParamName(I, paramIndex, O);
1637 O << "[" << sz << "]";
1642 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1645 // Special handling for pointer arguments to kernel
1646 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1648 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1649 Type *ETy = PTy->getElementType();
1650 int addrSpace = PTy->getAddressSpace();
1651 switch (addrSpace) {
1655 case llvm::ADDRESS_SPACE_CONST:
1656 O << ".ptr .const ";
1658 case llvm::ADDRESS_SPACE_SHARED:
1659 O << ".ptr .shared ";
1661 case llvm::ADDRESS_SPACE_GLOBAL:
1662 O << ".ptr .global ";
1665 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1667 printParamName(I, paramIndex, O);
1671 // non-pointer scalar to kernel func
1673 // Special case: predicate operands become .u8 types
1674 if (Ty->isIntegerTy(1))
1677 O << getPTXFundamentalTypeStr(Ty);
1679 printParamName(I, paramIndex, O);
1682 // Non-kernel function, just print .param .b<size> for ABI
1683 // and .reg .b<size> for non-ABI
1685 if (isa<IntegerType>(Ty)) {
1686 sz = cast<IntegerType>(Ty)->getBitWidth();
1689 } else if (isa<PointerType>(Ty))
1690 sz = thePointerTy.getSizeInBits();
1692 sz = Ty->getPrimitiveSizeInBits();
1694 O << "\t.param .b" << sz << " ";
1696 O << "\t.reg .b" << sz << " ";
1697 printParamName(I, paramIndex, O);
1701 // param has byVal attribute. So should be a pointer
1702 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1703 assert(PTy && "Param with byval attribute should be a pointer type");
1704 Type *ETy = PTy->getElementType();
1706 if (isABI || isKernelFunc) {
1707 // Just print .param .align <a> .b8 .param[size];
1708 // <a> = PAL.getparamalignment
1709 // size = typeallocsize of element type
1710 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1712 align = TD->getABITypeAlignment(ETy);
1714 unsigned sz = TD->getTypeAllocSize(ETy);
1715 O << "\t.param .align " << align << " .b8 ";
1716 printParamName(I, paramIndex, O);
1717 O << "[" << sz << "]";
1720 // Split the ETy into constituent parts and
1721 // print .param .b<size> <name> for each part.
1722 // Further, if a part is vector, print the above for
1723 // each vector element.
1724 SmallVector<EVT, 16> vtparts;
1725 ComputeValueVTs(*TLI, ETy, vtparts);
1726 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1728 EVT elemtype = vtparts[i];
1729 if (vtparts[i].isVector()) {
1730 elems = vtparts[i].getVectorNumElements();
1731 elemtype = vtparts[i].getVectorElementType();
1734 for (unsigned j = 0, je = elems; j != je; ++j) {
1735 unsigned sz = elemtype.getSizeInBits();
1736 if (elemtype.isInteger() && (sz < 32))
1738 O << "\t.reg .b" << sz << " ";
1739 printParamName(I, paramIndex, O);
1755 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1757 const Function *F = MF.getFunction();
1758 emitFunctionParamList(F, O);
1761 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1762 const MachineFunction &MF) {
1763 SmallString<128> Str;
1764 raw_svector_ostream O(Str);
1766 // Map the global virtual register number to a register class specific
1767 // virtual register number starting from 1 with that class.
1768 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1769 //unsigned numRegClasses = TRI->getNumRegClasses();
1771 // Emit the Fake Stack Object
1772 const MachineFrameInfo *MFI = MF.getFrameInfo();
1773 int NumBytes = (int) MFI->getStackSize();
1775 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1776 << getFunctionNumber() << "[" << NumBytes << "];\n";
1777 if (nvptxSubtarget.is64Bit()) {
1778 O << "\t.reg .b64 \t%SP;\n";
1779 O << "\t.reg .b64 \t%SPL;\n";
1781 O << "\t.reg .b32 \t%SP;\n";
1782 O << "\t.reg .b32 \t%SPL;\n";
1786 // Go through all virtual registers to establish the mapping between the
1788 // register number and the per class virtual register number.
1789 // We use the per class virtual register number in the ptx output.
1790 unsigned int numVRs = MRI->getNumVirtRegs();
1791 for (unsigned i = 0; i < numVRs; i++) {
1792 unsigned int vr = TRI->index2VirtReg(i);
1793 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1794 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1795 int n = regmap.size();
1796 regmap.insert(std::make_pair(vr, n + 1));
1799 // Emit register declarations
1800 // @TODO: Extract out the real register usage
1801 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1802 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1803 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1804 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1805 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1806 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1807 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1809 // Emit declaration of the virtual registers or 'physical' registers for
1810 // each register class
1811 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1812 const TargetRegisterClass *RC = TRI->getRegClass(i);
1813 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1814 std::string rcname = getNVPTXRegClassName(RC);
1815 std::string rcStr = getNVPTXRegClassStr(RC);
1816 int n = regmap.size();
1818 // Only declare those registers that may be used.
1820 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1825 OutStreamer.EmitRawText(O.str());
1828 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1829 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1831 unsigned int numHex;
1834 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1837 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1838 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1841 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1843 llvm_unreachable("unsupported fp type");
1845 APInt API = APF.bitcastToAPInt();
1846 std::string hexstr(utohexstr(API.getZExtValue()));
1848 if (hexstr.length() < numHex)
1849 O << std::string(numHex - hexstr.length(), '0');
1850 O << utohexstr(API.getZExtValue());
1853 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1854 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1855 O << CI->getValue();
1858 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1859 printFPConstant(CFP, O);
1862 if (isa<ConstantPointerNull>(CPV)) {
1866 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1867 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1868 bool IsNonGenericPointer = false;
1869 if (PTy && PTy->getAddressSpace() != 0) {
1870 IsNonGenericPointer = true;
1872 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1874 O << *getSymbol(GVar);
1877 O << *getSymbol(GVar);
1881 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1882 const Value *v = Cexpr->stripPointerCasts();
1883 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1884 bool IsNonGenericPointer = false;
1885 if (PTy && PTy->getAddressSpace() != 0) {
1886 IsNonGenericPointer = true;
1888 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1889 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1891 O << *getSymbol(GVar);
1894 O << *getSymbol(GVar);
1898 O << *LowerConstant(CPV, *this);
1902 llvm_unreachable("Not scalar type found in printScalarConstant()");
1905 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1906 AggBuffer *aggBuffer) {
1908 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1910 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1911 int s = TD->getTypeAllocSize(CPV->getType());
1914 aggBuffer->addZeros(s);
1919 switch (CPV->getType()->getTypeID()) {
1921 case Type::IntegerTyID: {
1922 const Type *ETy = CPV->getType();
1923 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1925 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1927 aggBuffer->addBytes(ptr, 1, Bytes);
1928 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1929 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1930 ptr = (unsigned char *)&int16;
1931 aggBuffer->addBytes(ptr, 2, Bytes);
1932 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1933 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1934 int int32 = (int)(constInt->getZExtValue());
1935 ptr = (unsigned char *)&int32;
1936 aggBuffer->addBytes(ptr, 4, Bytes);
1938 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1939 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1940 ConstantFoldConstantExpression(Cexpr, TD))) {
1941 int int32 = (int)(constInt->getZExtValue());
1942 ptr = (unsigned char *)&int32;
1943 aggBuffer->addBytes(ptr, 4, Bytes);
1946 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1947 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1948 aggBuffer->addSymbol(v);
1949 aggBuffer->addZeros(4);
1953 llvm_unreachable("unsupported integer const type");
1954 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1955 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1956 long long int64 = (long long)(constInt->getZExtValue());
1957 ptr = (unsigned char *)&int64;
1958 aggBuffer->addBytes(ptr, 8, Bytes);
1960 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1961 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1962 ConstantFoldConstantExpression(Cexpr, TD))) {
1963 long long int64 = (long long)(constInt->getZExtValue());
1964 ptr = (unsigned char *)&int64;
1965 aggBuffer->addBytes(ptr, 8, Bytes);
1968 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1969 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1970 aggBuffer->addSymbol(v);
1971 aggBuffer->addZeros(8);
1975 llvm_unreachable("unsupported integer const type");
1977 llvm_unreachable("unsupported integer const type");
1980 case Type::FloatTyID:
1981 case Type::DoubleTyID: {
1982 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1983 const Type *Ty = CFP->getType();
1984 if (Ty == Type::getFloatTy(CPV->getContext())) {
1985 float float32 = (float) CFP->getValueAPF().convertToFloat();
1986 ptr = (unsigned char *)&float32;
1987 aggBuffer->addBytes(ptr, 4, Bytes);
1988 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1989 double float64 = CFP->getValueAPF().convertToDouble();
1990 ptr = (unsigned char *)&float64;
1991 aggBuffer->addBytes(ptr, 8, Bytes);
1993 llvm_unreachable("unsupported fp const type");
1997 case Type::PointerTyID: {
1998 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1999 aggBuffer->addSymbol(GVar);
2000 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2001 const Value *v = Cexpr->stripPointerCasts();
2002 aggBuffer->addSymbol(v);
2004 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2005 aggBuffer->addZeros(s);
2009 case Type::ArrayTyID:
2010 case Type::VectorTyID:
2011 case Type::StructTyID: {
2012 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2013 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
2014 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2015 bufferAggregateConstant(CPV, aggBuffer);
2016 if (Bytes > ElementSize)
2017 aggBuffer->addZeros(Bytes - ElementSize);
2018 } else if (isa<ConstantAggregateZero>(CPV))
2019 aggBuffer->addZeros(Bytes);
2021 llvm_unreachable("Unexpected Constant type");
2026 llvm_unreachable("unsupported type");
2030 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2031 AggBuffer *aggBuffer) {
2032 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
2036 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2037 if (CPV->getNumOperands())
2038 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2039 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2043 if (const ConstantDataSequential *CDS =
2044 dyn_cast<ConstantDataSequential>(CPV)) {
2045 if (CDS->getNumElements())
2046 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2047 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2052 if (isa<ConstantStruct>(CPV)) {
2053 if (CPV->getNumOperands()) {
2054 StructType *ST = cast<StructType>(CPV->getType());
2055 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2057 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2058 TD->getTypeAllocSize(ST) -
2059 TD->getStructLayout(ST)->getElementOffset(i);
2061 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2062 TD->getStructLayout(ST)->getElementOffset(i);
2063 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2068 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2071 // buildTypeNameMap - Run through symbol table looking for type names.
2074 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2076 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2078 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2079 !PI->second.compare("struct._image2d_t") ||
2080 !PI->second.compare("struct._image3d_t")))
2087 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2088 switch (MI.getOpcode()) {
2091 case NVPTX::CallArgBeginInst:
2092 case NVPTX::CallArgEndInst0:
2093 case NVPTX::CallArgEndInst1:
2094 case NVPTX::CallArgF32:
2095 case NVPTX::CallArgF64:
2096 case NVPTX::CallArgI16:
2097 case NVPTX::CallArgI32:
2098 case NVPTX::CallArgI32imm:
2099 case NVPTX::CallArgI64:
2100 case NVPTX::CallArgParam:
2101 case NVPTX::CallVoidInst:
2102 case NVPTX::CallVoidInstReg:
2103 case NVPTX::Callseq_End:
2104 case NVPTX::CallVoidInstReg64:
2105 case NVPTX::DeclareParamInst:
2106 case NVPTX::DeclareRetMemInst:
2107 case NVPTX::DeclareRetRegInst:
2108 case NVPTX::DeclareRetScalarInst:
2109 case NVPTX::DeclareScalarParamInst:
2110 case NVPTX::DeclareScalarRegInst:
2111 case NVPTX::StoreParamF32:
2112 case NVPTX::StoreParamF64:
2113 case NVPTX::StoreParamI16:
2114 case NVPTX::StoreParamI32:
2115 case NVPTX::StoreParamI64:
2116 case NVPTX::StoreParamI8:
2117 case NVPTX::StoreRetvalF32:
2118 case NVPTX::StoreRetvalF64:
2119 case NVPTX::StoreRetvalI16:
2120 case NVPTX::StoreRetvalI32:
2121 case NVPTX::StoreRetvalI64:
2122 case NVPTX::StoreRetvalI8:
2123 case NVPTX::LastCallArgF32:
2124 case NVPTX::LastCallArgF64:
2125 case NVPTX::LastCallArgI16:
2126 case NVPTX::LastCallArgI32:
2127 case NVPTX::LastCallArgI32imm:
2128 case NVPTX::LastCallArgI64:
2129 case NVPTX::LastCallArgParam:
2130 case NVPTX::LoadParamMemF32:
2131 case NVPTX::LoadParamMemF64:
2132 case NVPTX::LoadParamMemI16:
2133 case NVPTX::LoadParamMemI32:
2134 case NVPTX::LoadParamMemI64:
2135 case NVPTX::LoadParamMemI8:
2136 case NVPTX::PrototypeInst:
2137 case NVPTX::DBG_VALUE:
2143 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2145 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2146 unsigned AsmVariant,
2147 const char *ExtraCode, raw_ostream &O) {
2148 if (ExtraCode && ExtraCode[0]) {
2149 if (ExtraCode[1] != 0)
2150 return true; // Unknown modifier.
2152 switch (ExtraCode[0]) {
2154 // See if this is a generic print operand
2155 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2161 printOperand(MI, OpNo, O);
2166 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2167 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2168 const char *ExtraCode, raw_ostream &O) {
2169 if (ExtraCode && ExtraCode[0])
2170 return true; // Unknown modifier
2173 printMemOperand(MI, OpNo, O);
2179 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2180 raw_ostream &O, const char *Modifier) {
2181 const MachineOperand &MO = MI->getOperand(opNum);
2182 switch (MO.getType()) {
2183 case MachineOperand::MO_Register:
2184 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2185 if (MO.getReg() == NVPTX::VRDepot)
2186 O << DEPOTNAME << getFunctionNumber();
2188 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2190 emitVirtualRegister(MO.getReg(), O);
2194 case MachineOperand::MO_Immediate:
2197 else if (strstr(Modifier, "vec") == Modifier)
2198 printVecModifiedImmediate(MO, Modifier, O);
2201 "Don't know how to handle modifier on immediate operand");
2204 case MachineOperand::MO_FPImmediate:
2205 printFPConstant(MO.getFPImm(), O);
2208 case MachineOperand::MO_GlobalAddress:
2209 O << *getSymbol(MO.getGlobal());
2212 case MachineOperand::MO_MachineBasicBlock:
2213 O << *MO.getMBB()->getSymbol();
2217 llvm_unreachable("Operand type not supported.");
2221 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2222 raw_ostream &O, const char *Modifier) {
2223 printOperand(MI, opNum, O);
2225 if (Modifier && !strcmp(Modifier, "add")) {
2227 printOperand(MI, opNum + 1, O);
2229 if (MI->getOperand(opNum + 1).isImm() &&
2230 MI->getOperand(opNum + 1).getImm() == 0)
2231 return; // don't print ',0' or '+0'
2233 printOperand(MI, opNum + 1, O);
2238 // Force static initialization.
2239 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2240 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2241 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2244 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2245 std::stringstream temp;
2246 LineReader *reader = this->getReader(filename.str());
2248 temp << filename.str();
2252 temp << reader->readLine(line);
2254 this->OutStreamer.EmitRawText(Twine(temp.str()));
2257 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2259 reader = new LineReader(filename);
2262 if (reader->fileName() != filename) {
2264 reader = new LineReader(filename);
2270 std::string LineReader::readLine(unsigned lineNum) {
2271 if (lineNum < theCurLine) {
2273 fstr.seekg(0, std::ios::beg);
2275 while (theCurLine < lineNum) {
2276 fstr.getline(buff, 500);
2282 // Force static initialization.
2283 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2284 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2285 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);