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 "InstPrinter/NVPTXInstPrinter.h"
16 #include "MCTargetDesc/NVPTXBaseInfo.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXAsmPrinter.h"
20 #include "NVPTXMCExpr.h"
21 #include "NVPTXMachineFunctionInfo.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXSubtarget.h"
24 #include "NVPTXTargetMachine.h"
25 #include "NVPTXUtilities.h"
26 #include "cl_common_defines.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/Triple.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/ConstantFolding.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/MachineValueType.h"
48 #include "llvm/CodeGen/ValueTypes.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/Constant.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DebugInfo.h"
55 #include "llvm/IR/DebugInfoMetadata.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/GlobalValue.h"
60 #include "llvm/IR/GlobalVariable.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/Operator.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/User.h"
67 #include "llvm/MC/MCExpr.h"
68 #include "llvm/MC/MCInst.h"
69 #include "llvm/MC/MCInstrDesc.h"
70 #include "llvm/MC/MCStreamer.h"
71 #include "llvm/MC/MCSymbol.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/Path.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/Support/TargetRegistry.h"
78 #include "llvm/Target/TargetLowering.h"
79 #include "llvm/Target/TargetLoweringObjectFile.h"
80 #include "llvm/Target/TargetMachine.h"
81 #include "llvm/Target/TargetRegisterInfo.h"
82 #include "llvm/Transforms/Utils/UnrollLoop.h"
94 #define DEPOTNAME "__local_depot"
97 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
98 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
102 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
103 cl::desc("NVPTX Specific: Emit source line in ptx file"),
106 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
109 DiscoverDependentGlobals(const Value *V,
110 DenseSet<const GlobalVariable *> &Globals) {
111 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
114 if (const User *U = dyn_cast<User>(V)) {
115 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
116 DiscoverDependentGlobals(U->getOperand(i), Globals);
122 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
123 /// instances to be emitted, but only after any dependents have been added
126 VisitGlobalVariableForEmission(const GlobalVariable *GV,
127 SmallVectorImpl<const GlobalVariable *> &Order,
128 DenseSet<const GlobalVariable *> &Visited,
129 DenseSet<const GlobalVariable *> &Visiting) {
130 // Have we already visited this one?
131 if (Visited.count(GV))
134 // Do we have a circular dependency?
135 if (!Visiting.insert(GV).second)
136 report_fatal_error("Circular dependency found in global variable set");
138 // Make sure we visit all dependents first
139 DenseSet<const GlobalVariable *> Others;
140 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
141 DiscoverDependentGlobals(GV->getOperand(i), Others);
143 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
146 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
148 // Now we can visit ourself
154 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
155 if (!EmitLineNumbers)
160 const DebugLoc &curLoc = MI.getDebugLoc();
162 if (!prevDebugLoc && !curLoc)
165 if (prevDebugLoc == curLoc)
168 prevDebugLoc = curLoc;
173 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
177 StringRef fileName(Scope->getFilename());
178 StringRef dirName(Scope->getDirectory());
179 SmallString<128> FullPathName = dirName;
180 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
181 sys::path::append(FullPathName, fileName);
182 fileName = FullPathName;
185 if (filenameMap.find(fileName) == filenameMap.end())
188 // Emit the line from the source file.
190 this->emitSrcInText(fileName, curLoc.getLine());
192 std::stringstream temp;
193 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
194 << " " << curLoc.getCol();
195 OutStreamer->EmitRawText(temp.str());
198 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
199 SmallString<128> Str;
200 raw_svector_ostream OS(Str);
201 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
202 emitLineNumberAsDotLoc(*MI);
205 lowerToMCInst(MI, Inst);
206 EmitToStreamer(*OutStreamer, Inst);
209 // Handle symbol backtracking for targets that do not support image handles
210 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
211 unsigned OpNo, MCOperand &MCOp) {
212 const MachineOperand &MO = MI->getOperand(OpNo);
213 const MCInstrDesc &MCID = MI->getDesc();
215 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
216 // This is a texture fetch, so operand 4 is a texref and operand 5 is
218 if (OpNo == 4 && MO.isImm()) {
219 lowerImageHandleSymbol(MO.getImm(), MCOp);
222 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
223 lowerImageHandleSymbol(MO.getImm(), MCOp);
228 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
230 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
232 // For a surface load of vector size N, the Nth operand will be the surfref
233 if (OpNo == VecSize && MO.isImm()) {
234 lowerImageHandleSymbol(MO.getImm(), MCOp);
239 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
240 // This is a surface store, so operand 0 is a surfref
241 if (OpNo == 0 && MO.isImm()) {
242 lowerImageHandleSymbol(MO.getImm(), MCOp);
247 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
248 // This is a query, so operand 1 is a surfref/texref
249 if (OpNo == 1 && MO.isImm()) {
250 lowerImageHandleSymbol(MO.getImm(), MCOp);
260 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
262 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
263 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
264 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
265 const char *Sym = MFI->getImageHandleSymbol(Index);
266 std::string *SymNamePtr =
267 nvTM.getManagedStrPool()->getManagedString(Sym);
268 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(StringRef(*SymNamePtr)));
271 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
272 OutMI.setOpcode(MI->getOpcode());
273 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
274 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
275 const MachineOperand &MO = MI->getOperand(0);
276 OutMI.addOperand(GetSymbolRef(
277 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
281 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282 const MachineOperand &MO = MI->getOperand(i);
285 if (!nvptxSubtarget->hasImageHandles()) {
286 if (lowerImageHandleOperand(MI, i, MCOp)) {
287 OutMI.addOperand(MCOp);
292 if (lowerOperand(MO, MCOp))
293 OutMI.addOperand(MCOp);
297 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
299 switch (MO.getType()) {
300 default: llvm_unreachable("unknown operand type");
301 case MachineOperand::MO_Register:
302 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
304 case MachineOperand::MO_Immediate:
305 MCOp = MCOperand::createImm(MO.getImm());
307 case MachineOperand::MO_MachineBasicBlock:
308 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
309 MO.getMBB()->getSymbol(), OutContext));
311 case MachineOperand::MO_ExternalSymbol:
312 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
314 case MachineOperand::MO_GlobalAddress:
315 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
317 case MachineOperand::MO_FPImmediate: {
318 const ConstantFP *Cnt = MO.getFPImm();
319 const APFloat &Val = Cnt->getValueAPF();
321 switch (Cnt->getType()->getTypeID()) {
322 default: report_fatal_error("Unsupported FP type"); break;
324 MCOp = MCOperand::createExpr(
325 NVPTXFloatMCExpr::createConstantFPHalf(Val, OutContext));
327 case Type::FloatTyID:
328 MCOp = MCOperand::createExpr(
329 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
331 case Type::DoubleTyID:
332 MCOp = MCOperand::createExpr(
333 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
342 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
343 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
344 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
346 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
347 unsigned RegNum = RegMap[Reg];
349 // Encode the register class in the upper 4 bits
350 // Must be kept in sync with NVPTXInstPrinter::printRegName
352 if (RC == &NVPTX::Int1RegsRegClass) {
354 } else if (RC == &NVPTX::Int16RegsRegClass) {
356 } else if (RC == &NVPTX::Int32RegsRegClass) {
358 } else if (RC == &NVPTX::Int64RegsRegClass) {
360 } else if (RC == &NVPTX::Float32RegsRegClass) {
362 } else if (RC == &NVPTX::Float64RegsRegClass) {
364 } else if (RC == &NVPTX::Float16RegsRegClass) {
366 } else if (RC == &NVPTX::Float16x2RegsRegClass) {
369 report_fatal_error("Bad register class");
372 // Insert the vreg number
373 Ret |= (RegNum & 0x0FFFFFFF);
376 // Some special-use registers are actually physical registers.
377 // Encode this as the register class ID of 0 and the real register ID.
378 return Reg & 0x0FFFFFFF;
382 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
384 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
386 return MCOperand::createExpr(Expr);
389 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
390 const DataLayout &DL = getDataLayout();
391 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
393 Type *Ty = F->getReturnType();
395 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
397 if (Ty->getTypeID() == Type::VoidTyID)
403 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
405 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
406 size = ITy->getBitWidth();
408 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
409 size = Ty->getPrimitiveSizeInBits();
411 // PTX ABI requires all scalar return values to be at least 32
412 // bits in size. fp16 normally uses .b16 as its storage type in
413 // PTX, so its size must be adjusted here, too.
417 O << ".param .b" << size << " func_retval0";
418 } else if (isa<PointerType>(Ty)) {
419 O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
421 } else if (Ty->isAggregateType() || Ty->isVectorTy()) {
422 unsigned totalsz = DL.getTypeAllocSize(Ty);
423 unsigned retAlignment = 0;
424 if (!getAlign(*F, 0, retAlignment))
425 retAlignment = DL.getABITypeAlignment(Ty);
426 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
429 llvm_unreachable("Unknown return type");
431 SmallVector<EVT, 16> vtparts;
432 ComputeValueVTs(*TLI, DL, Ty, vtparts);
434 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
436 EVT elemtype = vtparts[i];
437 if (vtparts[i].isVector()) {
438 elems = vtparts[i].getVectorNumElements();
439 elemtype = vtparts[i].getVectorElementType();
442 for (unsigned j = 0, je = elems; j != je; ++j) {
443 unsigned sz = elemtype.getSizeInBits();
444 if (elemtype.isInteger() && (sz < 32))
446 O << ".reg .b" << sz << " func_retval" << idx;
458 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
460 const Function *F = MF.getFunction();
461 printReturnValStr(F, O);
464 // Return true if MBB is the header of a loop marked with
465 // llvm.loop.unroll.disable.
466 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
467 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
468 const MachineBasicBlock &MBB) const {
469 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
470 // We insert .pragma "nounroll" only to the loop header.
471 if (!LI.isLoopHeader(&MBB))
474 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
475 // we iterate through each back edge of the loop with header MBB, and check
476 // whether its metadata contains llvm.loop.unroll.disable.
477 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
478 const MachineBasicBlock *PMBB = *I;
479 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
480 // Edges from other loops to MBB are not back edges.
483 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
485 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
486 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
494 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
495 AsmPrinter::EmitBasicBlockStart(MBB);
496 if (isLoopHeaderOfNoUnroll(MBB))
497 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
500 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
501 SmallString<128> Str;
502 raw_svector_ostream O(Str);
504 if (!GlobalsEmitted) {
505 emitGlobals(*MF->getFunction()->getParent());
506 GlobalsEmitted = true;
510 MRI = &MF->getRegInfo();
511 F = MF->getFunction();
512 emitLinkageDirective(F, O);
513 if (isKernelFunction(*F))
517 printReturnValStr(*MF, O);
520 CurrentFnSym->print(O, MAI);
522 emitFunctionParamList(*MF, O);
524 if (isKernelFunction(*F))
525 emitKernelFunctionDirectives(*F, O);
527 OutStreamer->EmitRawText(O.str());
529 prevDebugLoc = DebugLoc();
532 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
534 OutStreamer->EmitRawText(StringRef("{\n"));
535 setAndEmitFunctionVirtualRegisters(*MF);
537 SmallString<128> Str;
538 raw_svector_ostream O(Str);
539 emitDemotedVars(MF->getFunction(), O);
540 OutStreamer->EmitRawText(O.str());
543 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
544 OutStreamer->EmitRawText(StringRef("}\n"));
548 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
549 unsigned RegNo = MI->getOperand(0).getReg();
550 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
551 OutStreamer->AddComment(Twine("implicit-def: ") +
552 getVirtualRegisterName(RegNo));
554 OutStreamer->AddComment(Twine("implicit-def: ") +
555 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
557 OutStreamer->AddBlankLine();
560 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
561 raw_ostream &O) const {
562 // If the NVVM IR has some of reqntid* specified, then output
563 // the reqntid directive, and set the unspecified ones to 1.
564 // If none of reqntid* is specified, don't output reqntid directive.
565 unsigned reqntidx, reqntidy, reqntidz;
566 bool specified = false;
567 if (!getReqNTIDx(F, reqntidx))
571 if (!getReqNTIDy(F, reqntidy))
575 if (!getReqNTIDz(F, reqntidz))
581 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
584 // If the NVVM IR has some of maxntid* specified, then output
585 // the maxntid directive, and set the unspecified ones to 1.
586 // If none of maxntid* is specified, don't output maxntid directive.
587 unsigned maxntidx, maxntidy, maxntidz;
589 if (!getMaxNTIDx(F, maxntidx))
593 if (!getMaxNTIDy(F, maxntidy))
597 if (!getMaxNTIDz(F, maxntidz))
603 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
607 if (getMinCTASm(F, mincta))
608 O << ".minnctapersm " << mincta << "\n";
611 if (getMaxNReg(F, maxnreg))
612 O << ".maxnreg " << maxnreg << "\n";
616 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
617 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
620 raw_string_ostream NameStr(Name);
622 VRegRCMap::const_iterator I = VRegMapping.find(RC);
623 assert(I != VRegMapping.end() && "Bad register class");
624 const DenseMap<unsigned, unsigned> &RegMap = I->second;
626 VRegMap::const_iterator VI = RegMap.find(Reg);
627 assert(VI != RegMap.end() && "Bad virtual register");
628 unsigned MappedVR = VI->second;
630 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
636 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
638 O << getVirtualRegisterName(vr);
641 void NVPTXAsmPrinter::printVecModifiedImmediate(
642 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
643 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
644 int Imm = (int) MO.getImm();
645 if (0 == strcmp(Modifier, "vecelem"))
646 O << "_" << vecelem[Imm];
647 else if (0 == strcmp(Modifier, "vecv4comm1")) {
648 if ((Imm < 0) || (Imm > 3))
650 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
651 if ((Imm < 4) || (Imm > 7))
653 } else if (0 == strcmp(Modifier, "vecv4pos")) {
656 O << "_" << vecelem[Imm % 4];
657 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
658 if ((Imm < 0) || (Imm > 1))
660 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
661 if ((Imm < 2) || (Imm > 3))
663 } else if (0 == strcmp(Modifier, "vecv2pos")) {
666 O << "_" << vecelem[Imm % 2];
668 llvm_unreachable("Unknown Modifier on immediate operand");
671 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
672 emitLinkageDirective(F, O);
673 if (isKernelFunction(*F))
677 printReturnValStr(F, O);
678 getSymbol(F)->print(O, MAI);
680 emitFunctionParamList(F, O);
684 static bool usedInGlobalVarDef(const Constant *C) {
688 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
689 return GV->getName() != "llvm.used";
692 for (const User *U : C->users())
693 if (const Constant *C = dyn_cast<Constant>(U))
694 if (usedInGlobalVarDef(C))
700 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
701 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
702 if (othergv->getName() == "llvm.used")
706 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
707 if (instr->getParent() && instr->getParent()->getParent()) {
708 const Function *curFunc = instr->getParent()->getParent();
709 if (oneFunc && (curFunc != oneFunc))
717 for (const User *UU : U->users())
718 if (!usedInOneFunc(UU, oneFunc))
724 /* Find out if a global variable can be demoted to local scope.
725 * Currently, this is valid for CUDA shared variables, which have local
726 * scope and global lifetime. So the conditions to check are :
727 * 1. Is the global variable in shared address space?
728 * 2. Does it have internal linkage?
729 * 3. Is the global variable referenced only in one function?
731 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
732 if (!gv->hasInternalLinkage())
734 PointerType *Pty = gv->getType();
735 if (Pty->getAddressSpace() != ADDRESS_SPACE_SHARED)
738 const Function *oneFunc = nullptr;
740 bool flag = usedInOneFunc(gv, oneFunc);
749 static bool useFuncSeen(const Constant *C,
750 DenseMap<const Function *, bool> &seenMap) {
751 for (const User *U : C->users()) {
752 if (const Constant *cu = dyn_cast<Constant>(U)) {
753 if (useFuncSeen(cu, seenMap))
755 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
756 const BasicBlock *bb = I->getParent();
759 const Function *caller = bb->getParent();
762 if (seenMap.find(caller) != seenMap.end())
769 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
770 DenseMap<const Function *, bool> seenMap;
771 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
772 const Function *F = &*FI;
774 if (F->isDeclaration()) {
777 if (F->getIntrinsicID())
779 emitDeclaration(F, O);
782 for (const User *U : F->users()) {
783 if (const Constant *C = dyn_cast<Constant>(U)) {
784 if (usedInGlobalVarDef(C)) {
785 // The use is in the initialization of a global variable
786 // that is a function pointer, so print a declaration
787 // for the original function
788 emitDeclaration(F, O);
791 // Emit a declaration of this function if the function that
792 // uses this constant expr has already been seen.
793 if (useFuncSeen(C, seenMap)) {
794 emitDeclaration(F, O);
799 if (!isa<Instruction>(U))
801 const Instruction *instr = cast<Instruction>(U);
802 const BasicBlock *bb = instr->getParent();
805 const Function *caller = bb->getParent();
809 // If a caller has already been seen, then the caller is
810 // appearing in the module before the callee. so print out
811 // a declaration for the callee.
812 if (seenMap.find(caller) != seenMap.end()) {
813 emitDeclaration(F, O);
821 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
822 DebugInfoFinder DbgFinder;
823 DbgFinder.processModule(M);
826 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
827 StringRef Filename = DIUnit->getFilename();
828 StringRef Dirname = DIUnit->getDirectory();
829 SmallString<128> FullPathName = Dirname;
830 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
831 sys::path::append(FullPathName, Filename);
832 Filename = FullPathName;
834 if (filenameMap.find(Filename) != filenameMap.end())
836 filenameMap[Filename] = i;
837 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
841 for (DISubprogram *SP : DbgFinder.subprograms()) {
842 StringRef Filename = SP->getFilename();
843 StringRef Dirname = SP->getDirectory();
844 SmallString<128> FullPathName = Dirname;
845 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
846 sys::path::append(FullPathName, Filename);
847 Filename = FullPathName;
849 if (filenameMap.find(Filename) != filenameMap.end())
851 filenameMap[Filename] = i;
852 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
857 static bool isEmptyXXStructor(GlobalVariable *GV) {
858 if (!GV) return true;
859 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
860 if (!InitList) return true; // Not an array; we don't know how to parse.
861 return InitList->getNumOperands() == 0;
864 bool NVPTXAsmPrinter::doInitialization(Module &M) {
865 // Construct a default subtarget off of the TargetMachine defaults. The
866 // rest of NVPTX isn't friendly to change subtargets per function and
867 // so the default TargetMachine will have all of the options.
868 const Triple &TT = TM.getTargetTriple();
869 StringRef CPU = TM.getTargetCPU();
870 StringRef FS = TM.getTargetFeatureString();
871 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
872 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
874 if (M.alias_size()) {
875 report_fatal_error("Module has aliases, which NVPTX does not support.");
876 return true; // error
878 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
880 "Module has a nontrivial global ctor, which NVPTX does not support.");
881 return true; // error
883 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
885 "Module has a nontrivial global dtor, which NVPTX does not support.");
886 return true; // error
889 SmallString<128> Str1;
890 raw_svector_ostream OS1(Str1);
892 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
894 // We need to call the parent's one explicitly.
895 //bool Result = AsmPrinter::doInitialization(M);
897 // Initialize TargetLoweringObjectFile since we didn't do in
898 // AsmPrinter::doInitialization either right above or where it's commented out
900 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
901 .Initialize(OutContext, TM);
903 // Emit header before any dwarf directives are emitted below.
904 emitHeader(M, OS1, STI);
905 OutStreamer->EmitRawText(OS1.str());
907 // Already commented out
908 //bool Result = AsmPrinter::doInitialization(M);
910 // Emit module-level inline asm if it exists.
911 if (!M.getModuleInlineAsm().empty()) {
912 OutStreamer->AddComment("Start of file scope inline assembly");
913 OutStreamer->AddBlankLine();
914 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
915 OutStreamer->AddBlankLine();
916 OutStreamer->AddComment("End of file scope inline assembly");
917 OutStreamer->AddBlankLine();
920 // If we're not NVCL we're CUDA, go ahead and emit filenames.
921 if (TM.getTargetTriple().getOS() != Triple::NVCL)
922 recordAndEmitFilenames(M);
924 GlobalsEmitted = false;
926 return false; // success
929 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
930 SmallString<128> Str2;
931 raw_svector_ostream OS2(Str2);
933 emitDeclarations(M, OS2);
935 // As ptxas does not support forward references of globals, we need to first
936 // sort the list of module-level globals in def-use order. We visit each
937 // global variable in order, and ensure that we emit it *after* its dependent
938 // globals. We use a little extra memory maintaining both a set and a list to
939 // have fast searches while maintaining a strict ordering.
940 SmallVector<const GlobalVariable *, 8> Globals;
941 DenseSet<const GlobalVariable *> GVVisited;
942 DenseSet<const GlobalVariable *> GVVisiting;
944 // Visit each global variable, in order
945 for (const GlobalVariable &I : M.globals())
946 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
948 assert(GVVisited.size() == M.getGlobalList().size() &&
949 "Missed a global variable");
950 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
952 // Print out module-level global variables in proper order
953 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
954 printModuleLevelGV(Globals[i], OS2);
958 OutStreamer->EmitRawText(OS2.str());
961 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
962 const NVPTXSubtarget &STI) {
964 O << "// Generated by LLVM NVPTX Back-End\n";
968 unsigned PTXVersion = STI.getPTXVersion();
969 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
972 O << STI.getTargetName();
974 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
975 if (NTM.getDrvInterface() == NVPTX::NVCL)
976 O << ", texmode_independent";
978 if (!STI.hasDouble())
979 O << ", map_f64_to_f32";
982 if (MAI->doesSupportDebugInformation())
987 O << ".address_size ";
997 bool NVPTXAsmPrinter::doFinalization(Module &M) {
998 // If we did not emit any functions, then the global declarations have not
1000 if (!GlobalsEmitted) {
1002 GlobalsEmitted = true;
1005 // XXX Temproarily remove global variables so that doFinalization() will not
1006 // emit them again (global variables are emitted at beginning).
1008 Module::GlobalListType &global_list = M.getGlobalList();
1009 int i, n = global_list.size();
1010 GlobalVariable **gv_array = new GlobalVariable *[n];
1012 // first, back-up GlobalVariable in gv_array
1014 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1016 gv_array[i++] = &*I;
1018 // second, empty global_list
1019 while (!global_list.empty())
1020 global_list.remove(global_list.begin());
1022 // call doFinalization
1023 bool ret = AsmPrinter::doFinalization(M);
1025 // now we restore global variables
1026 for (i = 0; i < n; i++)
1027 global_list.insert(global_list.end(), gv_array[i]);
1029 clearAnnotationCache(&M);
1034 //bool Result = AsmPrinter::doFinalization(M);
1035 // Instead of calling the parents doFinalization, we may
1036 // clone parents doFinalization and customize here.
1037 // Currently, we if NVISA out the EmitGlobals() in
1038 // parent's doFinalization, which is too intrusive.
1040 // Same for the doInitialization.
1044 // This function emits appropriate linkage directives for
1045 // functions and global variables.
1047 // extern function declaration -> .extern
1048 // extern function definition -> .visible
1049 // external global variable with init -> .visible
1050 // external without init -> .extern
1051 // appending -> not allowed, assert.
1052 // for any linkage other than
1053 // internal, private, linker_private,
1054 // linker_private_weak, linker_private_weak_def_auto,
1055 // we emit -> .weak.
1057 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1059 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
1060 if (V->hasExternalLinkage()) {
1061 if (isa<GlobalVariable>(V)) {
1062 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1064 if (GVar->hasInitializer())
1069 } else if (V->isDeclaration())
1073 } else if (V->hasAppendingLinkage()) {
1075 msg.append("Error: ");
1076 msg.append("Symbol ");
1078 msg.append(V->getName());
1079 msg.append("has unsupported appending linkage type");
1080 llvm_unreachable(msg.c_str());
1081 } else if (!V->hasInternalLinkage() &&
1082 !V->hasPrivateLinkage()) {
1088 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1090 bool processDemoted) {
1092 if (GVar->hasSection()) {
1093 if (GVar->getSection() == "llvm.metadata")
1097 // Skip LLVM intrinsic global variables
1098 if (GVar->getName().startswith("llvm.") ||
1099 GVar->getName().startswith("nvvm."))
1102 const DataLayout &DL = getDataLayout();
1104 // GlobalVariables are always constant pointers themselves.
1105 PointerType *PTy = GVar->getType();
1106 Type *ETy = GVar->getValueType();
1108 if (GVar->hasExternalLinkage()) {
1109 if (GVar->hasInitializer())
1113 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1114 GVar->hasAvailableExternallyLinkage() ||
1115 GVar->hasCommonLinkage()) {
1119 if (isTexture(*GVar)) {
1120 O << ".global .texref " << getTextureName(*GVar) << ";\n";
1124 if (isSurface(*GVar)) {
1125 O << ".global .surfref " << getSurfaceName(*GVar) << ";\n";
1129 if (GVar->isDeclaration()) {
1130 // (extern) declarations, no definition or initializer
1131 // Currently the only known declaration is for an automatic __local
1132 // (.shared) promoted to global.
1133 emitPTXGlobalVariable(GVar, O);
1138 if (isSampler(*GVar)) {
1139 O << ".global .samplerref " << getSamplerName(*GVar);
1141 const Constant *Initializer = nullptr;
1142 if (GVar->hasInitializer())
1143 Initializer = GVar->getInitializer();
1144 const ConstantInt *CI = nullptr;
1146 CI = dyn_cast<ConstantInt>(Initializer);
1148 unsigned sample = CI->getZExtValue();
1153 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1155 O << "addr_mode_" << i << " = ";
1161 O << "clamp_to_border";
1164 O << "clamp_to_edge";
1175 O << "filter_mode = ";
1176 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1184 llvm_unreachable("Anisotropic filtering is not supported");
1189 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1190 O << ", force_unnormalized_coords = 1";
1199 if (GVar->hasPrivateLinkage()) {
1200 if (strncmp(GVar->getName().data(), "unrollpragma", 12) == 0)
1203 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1204 if (strncmp(GVar->getName().data(), "filename", 8) == 0)
1206 if (GVar->use_empty())
1210 const Function *demotedFunc = nullptr;
1211 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1212 O << "// " << GVar->getName() << " has been demoted\n";
1213 if (localDecls.find(demotedFunc) != localDecls.end())
1214 localDecls[demotedFunc].push_back(GVar);
1216 std::vector<const GlobalVariable *> temp;
1217 temp.push_back(GVar);
1218 localDecls[demotedFunc] = temp;
1224 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1226 if (isManaged(*GVar)) {
1227 O << " .attribute(.managed)";
1230 if (GVar->getAlignment() == 0)
1231 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1233 O << " .align " << GVar->getAlignment();
1235 if (ETy->isFloatingPointTy() || ETy->isPointerTy() ||
1236 (ETy->isIntegerTy() && ETy->getScalarSizeInBits() <= 64)) {
1238 // Special case: ABI requires that we use .u8 for predicates
1239 if (ETy->isIntegerTy(1))
1242 O << getPTXFundamentalTypeStr(ETy, false);
1244 getSymbol(GVar)->print(O, MAI);
1246 // Ptx allows variable initilization only for constant and global state
1248 if (GVar->hasInitializer()) {
1249 if ((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1250 (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) {
1251 const Constant *Initializer = GVar->getInitializer();
1252 // 'undef' is treated as there is no value specified.
1253 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1255 printScalarConstant(Initializer, O);
1258 // The frontend adds zero-initializer to device and constant variables
1259 // that don't have an initial value, and UndefValue to shared
1260 // variables, so skip warning for this case.
1261 if (!GVar->getInitializer()->isNullValue() &&
1262 !isa<UndefValue>(GVar->getInitializer())) {
1263 report_fatal_error("initial value of '" + GVar->getName() +
1264 "' is not allowed in addrspace(" +
1265 Twine(PTy->getAddressSpace()) + ")");
1270 unsigned int ElementSize = 0;
1272 // Although PTX has direct support for struct type and array type and
1273 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1274 // targets that support these high level field accesses. Structs, arrays
1275 // and vectors are lowered into arrays of bytes.
1276 switch (ETy->getTypeID()) {
1277 case Type::IntegerTyID: // Integers larger than 64 bits
1278 case Type::StructTyID:
1279 case Type::ArrayTyID:
1280 case Type::VectorTyID:
1281 ElementSize = DL.getTypeStoreSize(ETy);
1282 // Ptx allows variable initilization only for constant and
1283 // global state spaces.
1284 if (((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1285 (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) &&
1286 GVar->hasInitializer()) {
1287 const Constant *Initializer = GVar->getInitializer();
1288 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1289 AggBuffer aggBuffer(ElementSize, O, *this);
1290 bufferAggregateConstant(Initializer, &aggBuffer);
1291 if (aggBuffer.numSymbols) {
1292 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1294 getSymbol(GVar)->print(O, MAI);
1296 O << ElementSize / 8;
1299 getSymbol(GVar)->print(O, MAI);
1301 O << ElementSize / 4;
1306 getSymbol(GVar)->print(O, MAI);
1316 getSymbol(GVar)->print(O, MAI);
1325 getSymbol(GVar)->print(O, MAI);
1334 llvm_unreachable("type not supported yet");
1340 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1341 if (localDecls.find(f) == localDecls.end())
1344 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1346 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1347 O << "\t// demoted variable\n\t";
1348 printModuleLevelGV(gvars[i], O, true);
1352 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1353 raw_ostream &O) const {
1354 switch (AddressSpace) {
1355 case ADDRESS_SPACE_LOCAL:
1358 case ADDRESS_SPACE_GLOBAL:
1361 case ADDRESS_SPACE_CONST:
1364 case ADDRESS_SPACE_SHARED:
1368 report_fatal_error("Bad address space found while emitting PTX");
1374 NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
1375 switch (Ty->getTypeID()) {
1377 llvm_unreachable("unexpected type");
1379 case Type::IntegerTyID: {
1380 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1383 else if (NumBits <= 64) {
1384 std::string name = "u";
1385 return name + utostr(NumBits);
1387 llvm_unreachable("Integer too large");
1392 case Type::HalfTyID:
1393 // fp16 is stored as .b16 for compatibility with pre-sm_53 PTX assembly.
1395 case Type::FloatTyID:
1397 case Type::DoubleTyID:
1399 case Type::PointerTyID:
1400 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1410 llvm_unreachable("unexpected type");
1414 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1416 const DataLayout &DL = getDataLayout();
1418 // GlobalVariables are always constant pointers themselves.
1419 Type *ETy = GVar->getValueType();
1422 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
1423 if (GVar->getAlignment() == 0)
1424 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1426 O << " .align " << GVar->getAlignment();
1428 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1430 O << getPTXFundamentalTypeStr(ETy);
1432 getSymbol(GVar)->print(O, MAI);
1436 int64_t ElementSize = 0;
1438 // Although PTX has direct support for struct type and array type and LLVM IR
1439 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1440 // support these high level field accesses. Structs and arrays are lowered
1441 // into arrays of bytes.
1442 switch (ETy->getTypeID()) {
1443 case Type::StructTyID:
1444 case Type::ArrayTyID:
1445 case Type::VectorTyID:
1446 ElementSize = DL.getTypeStoreSize(ETy);
1448 getSymbol(GVar)->print(O, MAI);
1456 llvm_unreachable("type not supported yet");
1460 static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
1461 if (Ty->isSingleValueType())
1462 return DL.getPrefTypeAlignment(Ty);
1464 auto *ATy = dyn_cast<ArrayType>(Ty);
1466 return getOpenCLAlignment(DL, ATy->getElementType());
1468 auto *STy = dyn_cast<StructType>(Ty);
1470 unsigned int alignStruct = 1;
1471 // Go through each element of the struct and find the
1472 // largest alignment.
1473 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1474 Type *ETy = STy->getElementType(i);
1475 unsigned int align = getOpenCLAlignment(DL, ETy);
1476 if (align > alignStruct)
1477 alignStruct = align;
1482 auto *FTy = dyn_cast<FunctionType>(Ty);
1484 return DL.getPointerPrefAlignment();
1485 return DL.getPrefTypeAlignment(Ty);
1488 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1489 int paramIndex, raw_ostream &O) {
1490 getSymbol(I->getParent())->print(O, MAI);
1491 O << "_param_" << paramIndex;
1494 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1495 const DataLayout &DL = getDataLayout();
1496 const AttributeList &PAL = F->getAttributes();
1497 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1498 Function::const_arg_iterator I, E;
1499 unsigned paramIndex = 0;
1501 bool isKernelFunc = isKernelFunction(*F);
1502 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1503 MVT thePointerTy = TLI->getPointerTy(DL);
1505 if (F->arg_empty()) {
1512 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1513 Type *Ty = I->getType();
1520 // Handle image/sampler parameters
1521 if (isKernelFunction(*F)) {
1522 if (isSampler(*I) || isImage(*I)) {
1524 std::string sname = I->getName();
1525 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1526 if (nvptxSubtarget->hasImageHandles())
1527 O << "\t.param .u64 .ptr .surfref ";
1529 O << "\t.param .surfref ";
1530 CurrentFnSym->print(O, MAI);
1531 O << "_param_" << paramIndex;
1533 else { // Default image is read_only
1534 if (nvptxSubtarget->hasImageHandles())
1535 O << "\t.param .u64 .ptr .texref ";
1537 O << "\t.param .texref ";
1538 CurrentFnSym->print(O, MAI);
1539 O << "_param_" << paramIndex;
1542 if (nvptxSubtarget->hasImageHandles())
1543 O << "\t.param .u64 .ptr .samplerref ";
1545 O << "\t.param .samplerref ";
1546 CurrentFnSym->print(O, MAI);
1547 O << "_param_" << paramIndex;
1553 if (!PAL.hasParamAttribute(paramIndex, Attribute::ByVal)) {
1554 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1555 // Just print .param .align <a> .b8 .param[size];
1556 // <a> = PAL.getparamalignment
1557 // size = typeallocsize of element type
1558 unsigned align = PAL.getParamAlignment(paramIndex);
1560 align = DL.getABITypeAlignment(Ty);
1562 unsigned sz = DL.getTypeAllocSize(Ty);
1563 O << "\t.param .align " << align << " .b8 ";
1564 printParamName(I, paramIndex, O);
1565 O << "[" << sz << "]";
1570 auto *PTy = dyn_cast<PointerType>(Ty);
1573 // Special handling for pointer arguments to kernel
1574 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1576 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1578 Type *ETy = PTy->getElementType();
1579 int addrSpace = PTy->getAddressSpace();
1580 switch (addrSpace) {
1584 case ADDRESS_SPACE_CONST:
1585 O << ".ptr .const ";
1587 case ADDRESS_SPACE_SHARED:
1588 O << ".ptr .shared ";
1590 case ADDRESS_SPACE_GLOBAL:
1591 O << ".ptr .global ";
1594 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
1596 printParamName(I, paramIndex, O);
1600 // non-pointer scalar to kernel func
1602 // Special case: predicate operands become .u8 types
1603 if (Ty->isIntegerTy(1))
1606 O << getPTXFundamentalTypeStr(Ty);
1608 printParamName(I, paramIndex, O);
1611 // Non-kernel function, just print .param .b<size> for ABI
1612 // and .reg .b<size> for non-ABI
1614 if (isa<IntegerType>(Ty)) {
1615 sz = cast<IntegerType>(Ty)->getBitWidth();
1618 } else if (isa<PointerType>(Ty))
1619 sz = thePointerTy.getSizeInBits();
1620 else if (Ty->isHalfTy())
1621 // PTX ABI requires all scalar parameters to be at least 32
1622 // bits in size. fp16 normally uses .b16 as its storage type
1623 // in PTX, so its size must be adjusted here, too.
1626 sz = Ty->getPrimitiveSizeInBits();
1628 O << "\t.param .b" << sz << " ";
1630 O << "\t.reg .b" << sz << " ";
1631 printParamName(I, paramIndex, O);
1635 // param has byVal attribute. So should be a pointer
1636 auto *PTy = dyn_cast<PointerType>(Ty);
1637 assert(PTy && "Param with byval attribute should be a pointer type");
1638 Type *ETy = PTy->getElementType();
1640 if (isABI || isKernelFunc) {
1641 // Just print .param .align <a> .b8 .param[size];
1642 // <a> = PAL.getparamalignment
1643 // size = typeallocsize of element type
1644 unsigned align = PAL.getParamAlignment(paramIndex);
1646 align = DL.getABITypeAlignment(ETy);
1647 // Work around a bug in ptxas. When PTX code takes address of
1648 // byval parameter with alignment < 4, ptxas generates code to
1649 // spill argument into memory. Alas on sm_50+ ptxas generates
1650 // SASS code that fails with misaligned access. To work around
1651 // the problem, make sure that we align byval parameters by at
1652 // least 4. Matching change must be made in LowerCall() where we
1653 // prepare parameters for the call.
1655 // TODO: this will need to be undone when we get to support multi-TU
1656 // device-side compilation as it breaks ABI compatibility with nvcc.
1657 // Hopefully ptxas bug is fixed by then.
1658 if (!isKernelFunc && align < 4)
1660 unsigned sz = DL.getTypeAllocSize(ETy);
1661 O << "\t.param .align " << align << " .b8 ";
1662 printParamName(I, paramIndex, O);
1663 O << "[" << sz << "]";
1666 // Split the ETy into constituent parts and
1667 // print .param .b<size> <name> for each part.
1668 // Further, if a part is vector, print the above for
1669 // each vector element.
1670 SmallVector<EVT, 16> vtparts;
1671 ComputeValueVTs(*TLI, DL, ETy, vtparts);
1672 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1674 EVT elemtype = vtparts[i];
1675 if (vtparts[i].isVector()) {
1676 elems = vtparts[i].getVectorNumElements();
1677 elemtype = vtparts[i].getVectorElementType();
1680 for (unsigned j = 0, je = elems; j != je; ++j) {
1681 unsigned sz = elemtype.getSizeInBits();
1682 if (elemtype.isInteger() && (sz < 32))
1684 O << "\t.reg .b" << sz << " ";
1685 printParamName(I, paramIndex, O);
1701 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1703 const Function *F = MF.getFunction();
1704 emitFunctionParamList(F, O);
1707 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1708 const MachineFunction &MF) {
1709 SmallString<128> Str;
1710 raw_svector_ostream O(Str);
1712 // Map the global virtual register number to a register class specific
1713 // virtual register number starting from 1 with that class.
1714 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1715 //unsigned numRegClasses = TRI->getNumRegClasses();
1717 // Emit the Fake Stack Object
1718 const MachineFrameInfo &MFI = MF.getFrameInfo();
1719 int NumBytes = (int) MFI.getStackSize();
1721 O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
1722 << getFunctionNumber() << "[" << NumBytes << "];\n";
1723 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1724 O << "\t.reg .b64 \t%SP;\n";
1725 O << "\t.reg .b64 \t%SPL;\n";
1727 O << "\t.reg .b32 \t%SP;\n";
1728 O << "\t.reg .b32 \t%SPL;\n";
1732 // Go through all virtual registers to establish the mapping between the
1734 // register number and the per class virtual register number.
1735 // We use the per class virtual register number in the ptx output.
1736 unsigned int numVRs = MRI->getNumVirtRegs();
1737 for (unsigned i = 0; i < numVRs; i++) {
1738 unsigned int vr = TRI->index2VirtReg(i);
1739 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1740 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1741 int n = regmap.size();
1742 regmap.insert(std::make_pair(vr, n + 1));
1745 // Emit register declarations
1746 // @TODO: Extract out the real register usage
1747 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1748 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1749 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1750 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1751 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1752 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1753 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1755 // Emit declaration of the virtual registers or 'physical' registers for
1756 // each register class
1757 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1758 const TargetRegisterClass *RC = TRI->getRegClass(i);
1759 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1760 std::string rcname = getNVPTXRegClassName(RC);
1761 std::string rcStr = getNVPTXRegClassStr(RC);
1762 int n = regmap.size();
1764 // Only declare those registers that may be used.
1766 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1771 OutStreamer->EmitRawText(O.str());
1774 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1775 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1777 unsigned int numHex;
1780 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1783 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &ignored);
1784 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1787 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &ignored);
1789 llvm_unreachable("unsupported fp type");
1791 APInt API = APF.bitcastToAPInt();
1792 std::string hexstr(utohexstr(API.getZExtValue()));
1794 if (hexstr.length() < numHex)
1795 O << std::string(numHex - hexstr.length(), '0');
1796 O << utohexstr(API.getZExtValue());
1799 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1800 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1801 O << CI->getValue();
1804 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1805 printFPConstant(CFP, O);
1808 if (isa<ConstantPointerNull>(CPV)) {
1812 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1813 bool IsNonGenericPointer = false;
1814 if (GVar->getType()->getAddressSpace() != 0) {
1815 IsNonGenericPointer = true;
1817 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1819 getSymbol(GVar)->print(O, MAI);
1822 getSymbol(GVar)->print(O, MAI);
1826 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1827 const Value *v = Cexpr->stripPointerCasts();
1828 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1829 bool IsNonGenericPointer = false;
1830 if (PTy && PTy->getAddressSpace() != 0) {
1831 IsNonGenericPointer = true;
1833 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1834 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1836 getSymbol(GVar)->print(O, MAI);
1839 getSymbol(GVar)->print(O, MAI);
1843 lowerConstant(CPV)->print(O, MAI);
1847 llvm_unreachable("Not scalar type found in printScalarConstant()");
1850 // These utility functions assure we get the right sequence of bytes for a given
1851 // type even for big-endian machines
1852 template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1853 int64_t vp = (int64_t)val;
1854 for (unsigned i = 0; i < sizeof(T); ++i) {
1855 p[i] = (unsigned char)vp;
1859 static void ConvertFloatToBytes(unsigned char *p, float val) {
1860 int32_t *vp = (int32_t *)&val;
1861 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1862 p[i] = (unsigned char)*vp;
1866 static void ConvertDoubleToBytes(unsigned char *p, double val) {
1867 int64_t *vp = (int64_t *)&val;
1868 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1869 p[i] = (unsigned char)*vp;
1874 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1875 AggBuffer *aggBuffer) {
1876 const DataLayout &DL = getDataLayout();
1878 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1879 int s = DL.getTypeAllocSize(CPV->getType());
1882 aggBuffer->addZeros(s);
1886 unsigned char ptr[8];
1887 switch (CPV->getType()->getTypeID()) {
1889 case Type::IntegerTyID: {
1890 Type *ETy = CPV->getType();
1891 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1892 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1893 ConvertIntToBytes<>(ptr, c);
1894 aggBuffer->addBytes(ptr, 1, Bytes);
1895 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1896 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1897 ConvertIntToBytes<>(ptr, int16);
1898 aggBuffer->addBytes(ptr, 2, Bytes);
1899 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1900 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1901 int int32 = (int)(constInt->getZExtValue());
1902 ConvertIntToBytes<>(ptr, int32);
1903 aggBuffer->addBytes(ptr, 4, Bytes);
1905 } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1906 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1907 ConstantFoldConstant(Cexpr, DL))) {
1908 int int32 = (int)(constInt->getZExtValue());
1909 ConvertIntToBytes<>(ptr, int32);
1910 aggBuffer->addBytes(ptr, 4, Bytes);
1913 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1914 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1915 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1916 aggBuffer->addZeros(4);
1920 llvm_unreachable("unsupported integer const type");
1921 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1922 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1923 long long int64 = (long long)(constInt->getZExtValue());
1924 ConvertIntToBytes<>(ptr, int64);
1925 aggBuffer->addBytes(ptr, 8, Bytes);
1927 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1928 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1929 ConstantFoldConstant(Cexpr, DL))) {
1930 long long int64 = (long long)(constInt->getZExtValue());
1931 ConvertIntToBytes<>(ptr, int64);
1932 aggBuffer->addBytes(ptr, 8, Bytes);
1935 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1936 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1937 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1938 aggBuffer->addZeros(8);
1942 llvm_unreachable("unsupported integer const type");
1944 llvm_unreachable("unsupported integer const type");
1947 case Type::FloatTyID:
1948 case Type::DoubleTyID: {
1949 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1950 Type *Ty = CFP->getType();
1951 if (Ty == Type::getFloatTy(CPV->getContext())) {
1952 float float32 = (float) CFP->getValueAPF().convertToFloat();
1953 ConvertFloatToBytes(ptr, float32);
1954 aggBuffer->addBytes(ptr, 4, Bytes);
1955 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1956 double float64 = CFP->getValueAPF().convertToDouble();
1957 ConvertDoubleToBytes(ptr, float64);
1958 aggBuffer->addBytes(ptr, 8, Bytes);
1960 llvm_unreachable("unsupported fp const type");
1964 case Type::PointerTyID: {
1965 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1966 aggBuffer->addSymbol(GVar, GVar);
1967 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1968 const Value *v = Cexpr->stripPointerCasts();
1969 aggBuffer->addSymbol(v, Cexpr);
1971 unsigned int s = DL.getTypeAllocSize(CPV->getType());
1972 aggBuffer->addZeros(s);
1976 case Type::ArrayTyID:
1977 case Type::VectorTyID:
1978 case Type::StructTyID: {
1979 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
1980 int ElementSize = DL.getTypeAllocSize(CPV->getType());
1981 bufferAggregateConstant(CPV, aggBuffer);
1982 if (Bytes > ElementSize)
1983 aggBuffer->addZeros(Bytes - ElementSize);
1984 } else if (isa<ConstantAggregateZero>(CPV))
1985 aggBuffer->addZeros(Bytes);
1987 llvm_unreachable("Unexpected Constant type");
1992 llvm_unreachable("unsupported type");
1996 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1997 AggBuffer *aggBuffer) {
1998 const DataLayout &DL = getDataLayout();
2001 // Integers of arbitrary width
2002 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
2003 APInt Val = CI->getValue();
2004 for (unsigned I = 0, E = DL.getTypeAllocSize(CPV->getType()); I < E; ++I) {
2005 uint8_t Byte = Val.getLoBits(8).getZExtValue();
2006 aggBuffer->addBytes(&Byte, 1, 1);
2013 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2014 if (CPV->getNumOperands())
2015 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2016 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2020 if (const ConstantDataSequential *CDS =
2021 dyn_cast<ConstantDataSequential>(CPV)) {
2022 if (CDS->getNumElements())
2023 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2024 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2029 if (isa<ConstantStruct>(CPV)) {
2030 if (CPV->getNumOperands()) {
2031 StructType *ST = cast<StructType>(CPV->getType());
2032 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2034 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
2035 DL.getTypeAllocSize(ST) -
2036 DL.getStructLayout(ST)->getElementOffset(i);
2038 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
2039 DL.getStructLayout(ST)->getElementOffset(i);
2040 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2045 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2048 // buildTypeNameMap - Run through symbol table looking for type names.
2051 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2052 switch (MI.getOpcode()) {
2055 case NVPTX::CallArgBeginInst:
2056 case NVPTX::CallArgEndInst0:
2057 case NVPTX::CallArgEndInst1:
2058 case NVPTX::CallArgF32:
2059 case NVPTX::CallArgF64:
2060 case NVPTX::CallArgI16:
2061 case NVPTX::CallArgI32:
2062 case NVPTX::CallArgI32imm:
2063 case NVPTX::CallArgI64:
2064 case NVPTX::CallArgParam:
2065 case NVPTX::CallVoidInst:
2066 case NVPTX::CallVoidInstReg:
2067 case NVPTX::Callseq_End:
2068 case NVPTX::CallVoidInstReg64:
2069 case NVPTX::DeclareParamInst:
2070 case NVPTX::DeclareRetMemInst:
2071 case NVPTX::DeclareRetRegInst:
2072 case NVPTX::DeclareRetScalarInst:
2073 case NVPTX::DeclareScalarParamInst:
2074 case NVPTX::DeclareScalarRegInst:
2075 case NVPTX::StoreParamF32:
2076 case NVPTX::StoreParamF64:
2077 case NVPTX::StoreParamI16:
2078 case NVPTX::StoreParamI32:
2079 case NVPTX::StoreParamI64:
2080 case NVPTX::StoreParamI8:
2081 case NVPTX::StoreRetvalF32:
2082 case NVPTX::StoreRetvalF64:
2083 case NVPTX::StoreRetvalI16:
2084 case NVPTX::StoreRetvalI32:
2085 case NVPTX::StoreRetvalI64:
2086 case NVPTX::StoreRetvalI8:
2087 case NVPTX::LastCallArgF32:
2088 case NVPTX::LastCallArgF64:
2089 case NVPTX::LastCallArgI16:
2090 case NVPTX::LastCallArgI32:
2091 case NVPTX::LastCallArgI32imm:
2092 case NVPTX::LastCallArgI64:
2093 case NVPTX::LastCallArgParam:
2094 case NVPTX::LoadParamMemF32:
2095 case NVPTX::LoadParamMemF64:
2096 case NVPTX::LoadParamMemI16:
2097 case NVPTX::LoadParamMemI32:
2098 case NVPTX::LoadParamMemI64:
2099 case NVPTX::LoadParamMemI8:
2100 case NVPTX::PrototypeInst:
2101 case NVPTX::DBG_VALUE:
2107 /// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2108 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
2109 /// expressions that are representable in PTX and create
2110 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2112 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2113 MCContext &Ctx = OutContext;
2115 if (CV->isNullValue() || isa<UndefValue>(CV))
2116 return MCConstantExpr::create(0, Ctx);
2118 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2119 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2121 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2122 const MCSymbolRefExpr *Expr =
2123 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2124 if (ProcessingGeneric) {
2125 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2131 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2133 llvm_unreachable("Unknown constant value to lower!");
2136 switch (CE->getOpcode()) {
2138 // If the code isn't optimized, there may be outstanding folding
2139 // opportunities. Attempt to fold the expression using DataLayout as a
2140 // last resort before giving up.
2141 if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2143 return lowerConstantForGV(C, ProcessingGeneric);
2145 // Otherwise report the problem to the user.
2148 raw_string_ostream OS(S);
2149 OS << "Unsupported expression in static initializer: ";
2150 CE->printAsOperand(OS, /*PrintType=*/false,
2151 !MF ? nullptr : MF->getFunction()->getParent());
2152 report_fatal_error(OS.str());
2155 case Instruction::AddrSpaceCast: {
2156 // Strip the addrspacecast and pass along the operand
2157 PointerType *DstTy = cast<PointerType>(CE->getType());
2158 if (DstTy->getAddressSpace() == 0) {
2159 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2162 raw_string_ostream OS(S);
2163 OS << "Unsupported expression in static initializer: ";
2164 CE->printAsOperand(OS, /*PrintType=*/ false,
2165 !MF ? nullptr : MF->getFunction()->getParent());
2166 report_fatal_error(OS.str());
2169 case Instruction::GetElementPtr: {
2170 const DataLayout &DL = getDataLayout();
2172 // Generate a symbolic expression for the byte address
2173 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2174 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2176 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2181 int64_t Offset = OffsetAI.getSExtValue();
2182 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2186 case Instruction::Trunc:
2187 // We emit the value and depend on the assembler to truncate the generated
2188 // expression properly. This is important for differences between
2189 // blockaddress labels. Since the two labels are in the same function, it
2190 // is reasonable to treat their delta as a 32-bit value.
2192 case Instruction::BitCast:
2193 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2195 case Instruction::IntToPtr: {
2196 const DataLayout &DL = getDataLayout();
2198 // Handle casts to pointers by changing them into casts to the appropriate
2199 // integer type. This promotes constant folding and simplifies this code.
2200 Constant *Op = CE->getOperand(0);
2201 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2203 return lowerConstantForGV(Op, ProcessingGeneric);
2206 case Instruction::PtrToInt: {
2207 const DataLayout &DL = getDataLayout();
2209 // Support only foldable casts to/from pointers that can be eliminated by
2210 // changing the pointer to the appropriately sized integer type.
2211 Constant *Op = CE->getOperand(0);
2212 Type *Ty = CE->getType();
2214 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2216 // We can emit the pointer value into this slot if the slot is an
2217 // integer slot equal to the size of the pointer.
2218 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2221 // Otherwise the pointer is smaller than the resultant integer, mask off
2222 // the high bits so we are sure to get a proper truncation if the input is
2224 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2225 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2226 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2229 // The MC library also has a right-shift operator, but it isn't consistently
2230 // signed or unsigned between different targets.
2231 case Instruction::Add: {
2232 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2233 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2234 switch (CE->getOpcode()) {
2235 default: llvm_unreachable("Unknown binary operator constant cast expr");
2236 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2242 // Copy of MCExpr::print customized for NVPTX
2243 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2244 switch (Expr.getKind()) {
2245 case MCExpr::Target:
2246 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
2247 case MCExpr::Constant:
2248 OS << cast<MCConstantExpr>(Expr).getValue();
2251 case MCExpr::SymbolRef: {
2252 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2253 const MCSymbol &Sym = SRE.getSymbol();
2258 case MCExpr::Unary: {
2259 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2260 switch (UE.getOpcode()) {
2261 case MCUnaryExpr::LNot: OS << '!'; break;
2262 case MCUnaryExpr::Minus: OS << '-'; break;
2263 case MCUnaryExpr::Not: OS << '~'; break;
2264 case MCUnaryExpr::Plus: OS << '+'; break;
2266 printMCExpr(*UE.getSubExpr(), OS);
2270 case MCExpr::Binary: {
2271 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2273 // Only print parens around the LHS if it is non-trivial.
2274 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2275 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2276 printMCExpr(*BE.getLHS(), OS);
2279 printMCExpr(*BE.getLHS(), OS);
2283 switch (BE.getOpcode()) {
2284 case MCBinaryExpr::Add:
2285 // Print "X-42" instead of "X+-42".
2286 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2287 if (RHSC->getValue() < 0) {
2288 OS << RHSC->getValue();
2295 default: llvm_unreachable("Unhandled binary operator");
2298 // Only print parens around the LHS if it is non-trivial.
2299 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2300 printMCExpr(*BE.getRHS(), OS);
2303 printMCExpr(*BE.getRHS(), OS);
2310 llvm_unreachable("Invalid expression kind!");
2313 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2315 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2316 unsigned AsmVariant,
2317 const char *ExtraCode, raw_ostream &O) {
2318 if (ExtraCode && ExtraCode[0]) {
2319 if (ExtraCode[1] != 0)
2320 return true; // Unknown modifier.
2322 switch (ExtraCode[0]) {
2324 // See if this is a generic print operand
2325 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2331 printOperand(MI, OpNo, O);
2336 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2337 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2338 const char *ExtraCode, raw_ostream &O) {
2339 if (ExtraCode && ExtraCode[0])
2340 return true; // Unknown modifier
2343 printMemOperand(MI, OpNo, O);
2349 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2350 raw_ostream &O, const char *Modifier) {
2351 const MachineOperand &MO = MI->getOperand(opNum);
2352 switch (MO.getType()) {
2353 case MachineOperand::MO_Register:
2354 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2355 if (MO.getReg() == NVPTX::VRDepot)
2356 O << DEPOTNAME << getFunctionNumber();
2358 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2360 emitVirtualRegister(MO.getReg(), O);
2364 case MachineOperand::MO_Immediate:
2367 else if (strstr(Modifier, "vec") == Modifier)
2368 printVecModifiedImmediate(MO, Modifier, O);
2371 "Don't know how to handle modifier on immediate operand");
2374 case MachineOperand::MO_FPImmediate:
2375 printFPConstant(MO.getFPImm(), O);
2378 case MachineOperand::MO_GlobalAddress:
2379 getSymbol(MO.getGlobal())->print(O, MAI);
2382 case MachineOperand::MO_MachineBasicBlock:
2383 MO.getMBB()->getSymbol()->print(O, MAI);
2387 llvm_unreachable("Operand type not supported.");
2391 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2392 raw_ostream &O, const char *Modifier) {
2393 printOperand(MI, opNum, O);
2395 if (Modifier && strcmp(Modifier, "add") == 0) {
2397 printOperand(MI, opNum + 1, O);
2399 if (MI->getOperand(opNum + 1).isImm() &&
2400 MI->getOperand(opNum + 1).getImm() == 0)
2401 return; // don't print ',0' or '+0'
2403 printOperand(MI, opNum + 1, O);
2407 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2408 std::stringstream temp;
2409 LineReader *reader = this->getReader(filename);
2411 temp << filename.str();
2415 temp << reader->readLine(line);
2417 this->OutStreamer->EmitRawText(temp.str());
2420 LineReader *NVPTXAsmPrinter::getReader(const std::string &filename) {
2422 reader = new LineReader(filename);
2425 if (reader->fileName() != filename) {
2427 reader = new LineReader(filename);
2433 std::string LineReader::readLine(unsigned lineNum) {
2434 if (lineNum < theCurLine) {
2436 fstr.seekg(0, std::ios::beg);
2438 while (theCurLine < lineNum) {
2439 fstr.getline(buff, 500);
2445 // Force static initialization.
2446 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2447 RegisterAsmPrinter<NVPTXAsmPrinter> X(getTheNVPTXTarget32());
2448 RegisterAsmPrinter<NVPTXAsmPrinter> Y(getTheNVPTXTarget64());