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 "NVPTXMCExpr.h"
21 #include "NVPTXMachineFunctionInfo.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/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Mangler.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TimeValue.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Transforms/Utils/UnrollLoop.h"
53 #define DEPOTNAME "__local_depot"
56 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
61 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
62 cl::desc("NVPTX Specific: Emit source line in ptx file"),
66 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
68 void DiscoverDependentGlobals(const Value *V,
69 DenseSet<const GlobalVariable *> &Globals) {
70 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
73 if (const User *U = dyn_cast<User>(V)) {
74 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
75 DiscoverDependentGlobals(U->getOperand(i), Globals);
81 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
82 /// instances to be emitted, but only after any dependents have been added
84 void VisitGlobalVariableForEmission(
85 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
86 DenseSet<const GlobalVariable *> &Visited,
87 DenseSet<const GlobalVariable *> &Visiting) {
88 // Have we already visited this one?
89 if (Visited.count(GV))
92 // Do we have a circular dependency?
93 if (!Visiting.insert(GV).second)
94 report_fatal_error("Circular dependency found in global variable set");
96 // Make sure we visit all dependents first
97 DenseSet<const GlobalVariable *> Others;
98 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99 DiscoverDependentGlobals(GV->getOperand(i), Others);
101 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
104 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
106 // Now we can visit ourself
113 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
114 if (!EmitLineNumbers)
119 DebugLoc curLoc = MI.getDebugLoc();
121 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
124 if (prevDebugLoc == curLoc)
127 prevDebugLoc = curLoc;
129 if (curLoc.isUnknown())
132 const MachineFunction *MF = MI.getParent()->getParent();
133 //const TargetMachine &TM = MF->getTarget();
135 const LLVMContext &ctx = MF->getFunction()->getContext();
136 DIScope Scope(curLoc.getScope(ctx));
138 assert((!Scope || Scope.isScope()) &&
139 "Scope of a DebugLoc should be null or a DIScope.");
143 StringRef fileName(Scope.getFilename());
144 StringRef dirName(Scope.getDirectory());
145 SmallString<128> FullPathName = dirName;
146 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
147 sys::path::append(FullPathName, fileName);
148 fileName = FullPathName.str();
151 if (filenameMap.find(fileName.str()) == filenameMap.end())
154 // Emit the line from the source file.
156 this->emitSrcInText(fileName.str(), curLoc.getLine());
158 std::stringstream temp;
159 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
160 << " " << curLoc.getCol();
161 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
164 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
165 SmallString<128> Str;
166 raw_svector_ostream OS(Str);
167 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
168 emitLineNumberAsDotLoc(*MI);
171 lowerToMCInst(MI, Inst);
172 EmitToStreamer(OutStreamer, Inst);
175 // Handle symbol backtracking for targets that do not support image handles
176 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
177 unsigned OpNo, MCOperand &MCOp) {
178 const MachineOperand &MO = MI->getOperand(OpNo);
179 const MCInstrDesc &MCID = MI->getDesc();
181 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
182 // This is a texture fetch, so operand 4 is a texref and operand 5 is
184 if (OpNo == 4 && MO.isImm()) {
185 lowerImageHandleSymbol(MO.getImm(), MCOp);
188 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
189 lowerImageHandleSymbol(MO.getImm(), MCOp);
194 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
196 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
198 // For a surface load of vector size N, the Nth operand will be the surfref
199 if (OpNo == VecSize && MO.isImm()) {
200 lowerImageHandleSymbol(MO.getImm(), MCOp);
205 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
206 // This is a surface store, so operand 0 is a surfref
207 if (OpNo == 0 && MO.isImm()) {
208 lowerImageHandleSymbol(MO.getImm(), MCOp);
213 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
214 // This is a query, so operand 1 is a surfref/texref
215 if (OpNo == 1 && MO.isImm()) {
216 lowerImageHandleSymbol(MO.getImm(), MCOp);
226 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
228 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
229 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
230 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
231 const char *Sym = MFI->getImageHandleSymbol(Index);
232 std::string *SymNamePtr =
233 nvTM.getManagedStrPool()->getManagedString(Sym);
234 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
235 StringRef(SymNamePtr->c_str())));
238 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
239 OutMI.setOpcode(MI->getOpcode());
240 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
241 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
242 const MachineOperand &MO = MI->getOperand(0);
243 OutMI.addOperand(GetSymbolRef(
244 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
248 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
249 const MachineOperand &MO = MI->getOperand(i);
252 if (!nvptxSubtarget->hasImageHandles()) {
253 if (lowerImageHandleOperand(MI, i, MCOp)) {
254 OutMI.addOperand(MCOp);
259 if (lowerOperand(MO, MCOp))
260 OutMI.addOperand(MCOp);
264 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
266 switch (MO.getType()) {
267 default: llvm_unreachable("unknown operand type");
268 case MachineOperand::MO_Register:
269 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
271 case MachineOperand::MO_Immediate:
272 MCOp = MCOperand::CreateImm(MO.getImm());
274 case MachineOperand::MO_MachineBasicBlock:
275 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
276 MO.getMBB()->getSymbol(), OutContext));
278 case MachineOperand::MO_ExternalSymbol:
279 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
281 case MachineOperand::MO_GlobalAddress:
282 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
284 case MachineOperand::MO_FPImmediate: {
285 const ConstantFP *Cnt = MO.getFPImm();
286 APFloat Val = Cnt->getValueAPF();
288 switch (Cnt->getType()->getTypeID()) {
289 default: report_fatal_error("Unsupported FP type"); break;
290 case Type::FloatTyID:
291 MCOp = MCOperand::CreateExpr(
292 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
294 case Type::DoubleTyID:
295 MCOp = MCOperand::CreateExpr(
296 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
305 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
306 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
307 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
309 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
310 unsigned RegNum = RegMap[Reg];
312 // Encode the register class in the upper 4 bits
313 // Must be kept in sync with NVPTXInstPrinter::printRegName
315 if (RC == &NVPTX::Int1RegsRegClass) {
317 } else if (RC == &NVPTX::Int16RegsRegClass) {
319 } else if (RC == &NVPTX::Int32RegsRegClass) {
321 } else if (RC == &NVPTX::Int64RegsRegClass) {
323 } else if (RC == &NVPTX::Float32RegsRegClass) {
325 } else if (RC == &NVPTX::Float64RegsRegClass) {
328 report_fatal_error("Bad register class");
331 // Insert the vreg number
332 Ret |= (RegNum & 0x0FFFFFFF);
335 // Some special-use registers are actually physical registers.
336 // Encode this as the register class ID of 0 and the real register ID.
337 return Reg & 0x0FFFFFFF;
341 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
343 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
345 return MCOperand::CreateExpr(Expr);
348 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
349 const DataLayout *TD = TM.getDataLayout();
350 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
352 Type *Ty = F->getReturnType();
354 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
356 if (Ty->getTypeID() == Type::VoidTyID)
362 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
364 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
365 size = ITy->getBitWidth();
369 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
370 size = Ty->getPrimitiveSizeInBits();
373 O << ".param .b" << size << " func_retval0";
374 } else if (isa<PointerType>(Ty)) {
375 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
377 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
378 unsigned totalsz = TD->getTypeAllocSize(Ty);
379 unsigned retAlignment = 0;
380 if (!llvm::getAlign(*F, 0, retAlignment))
381 retAlignment = TD->getABITypeAlignment(Ty);
382 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
385 llvm_unreachable("Unknown return type");
387 SmallVector<EVT, 16> vtparts;
388 ComputeValueVTs(*TLI, Ty, vtparts);
390 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
392 EVT elemtype = vtparts[i];
393 if (vtparts[i].isVector()) {
394 elems = vtparts[i].getVectorNumElements();
395 elemtype = vtparts[i].getVectorElementType();
398 for (unsigned j = 0, je = elems; j != je; ++j) {
399 unsigned sz = elemtype.getSizeInBits();
400 if (elemtype.isInteger() && (sz < 32))
402 O << ".reg .b" << sz << " func_retval" << idx;
415 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
417 const Function *F = MF.getFunction();
418 printReturnValStr(F, O);
421 // Return true if MBB is the header of a loop marked with
422 // llvm.loop.unroll.disable.
423 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
424 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
425 const MachineBasicBlock &MBB) const {
426 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
427 // TODO: isLoopHeader() should take "const MachineBasicBlock *".
428 // We insert .pragma "nounroll" only to the loop header.
429 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
432 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
433 // we iterate through each back edge of the loop with header MBB, and check
434 // whether its metadata contains llvm.loop.unroll.disable.
435 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
436 const MachineBasicBlock *PMBB = *I;
437 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
438 // Edges from other loops to MBB are not back edges.
441 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
442 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
443 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
451 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
452 AsmPrinter::EmitBasicBlockStart(MBB);
453 if (isLoopHeaderOfNoUnroll(MBB))
454 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
457 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
458 SmallString<128> Str;
459 raw_svector_ostream O(Str);
461 if (!GlobalsEmitted) {
462 emitGlobals(*MF->getFunction()->getParent());
463 GlobalsEmitted = true;
467 MRI = &MF->getRegInfo();
468 F = MF->getFunction();
469 emitLinkageDirective(F, O);
470 if (llvm::isKernelFunction(*F))
474 printReturnValStr(*MF, O);
479 emitFunctionParamList(*MF, O);
481 if (llvm::isKernelFunction(*F))
482 emitKernelFunctionDirectives(*F, O);
484 OutStreamer.EmitRawText(O.str());
486 prevDebugLoc = DebugLoc();
489 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
491 OutStreamer.EmitRawText(StringRef("{\n"));
492 setAndEmitFunctionVirtualRegisters(*MF);
494 SmallString<128> Str;
495 raw_svector_ostream O(Str);
496 emitDemotedVars(MF->getFunction(), O);
497 OutStreamer.EmitRawText(O.str());
500 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
501 OutStreamer.EmitRawText(StringRef("}\n"));
505 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
506 unsigned RegNo = MI->getOperand(0).getReg();
507 const TargetRegisterInfo *TRI = nvptxSubtarget->getRegisterInfo();
508 if (TRI->isVirtualRegister(RegNo)) {
509 OutStreamer.AddComment(Twine("implicit-def: ") +
510 getVirtualRegisterName(RegNo));
512 OutStreamer.AddComment(Twine("implicit-def: ") +
513 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
515 OutStreamer.AddBlankLine();
518 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
519 raw_ostream &O) const {
520 // If the NVVM IR has some of reqntid* specified, then output
521 // the reqntid directive, and set the unspecified ones to 1.
522 // If none of reqntid* is specified, don't output reqntid directive.
523 unsigned reqntidx, reqntidy, reqntidz;
524 bool specified = false;
525 if (llvm::getReqNTIDx(F, reqntidx) == false)
529 if (llvm::getReqNTIDy(F, reqntidy) == false)
533 if (llvm::getReqNTIDz(F, reqntidz) == false)
539 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
542 // If the NVVM IR has some of maxntid* specified, then output
543 // the maxntid directive, and set the unspecified ones to 1.
544 // If none of maxntid* is specified, don't output maxntid directive.
545 unsigned maxntidx, maxntidy, maxntidz;
547 if (llvm::getMaxNTIDx(F, maxntidx) == false)
551 if (llvm::getMaxNTIDy(F, maxntidy) == false)
555 if (llvm::getMaxNTIDz(F, maxntidz) == false)
561 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
565 if (llvm::getMinCTASm(F, mincta))
566 O << ".minnctapersm " << mincta << "\n";
570 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
571 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
574 raw_string_ostream NameStr(Name);
576 VRegRCMap::const_iterator I = VRegMapping.find(RC);
577 assert(I != VRegMapping.end() && "Bad register class");
578 const DenseMap<unsigned, unsigned> &RegMap = I->second;
580 VRegMap::const_iterator VI = RegMap.find(Reg);
581 assert(VI != RegMap.end() && "Bad virtual register");
582 unsigned MappedVR = VI->second;
584 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
590 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
592 O << getVirtualRegisterName(vr);
595 void NVPTXAsmPrinter::printVecModifiedImmediate(
596 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
597 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
598 int Imm = (int) MO.getImm();
599 if (0 == strcmp(Modifier, "vecelem"))
600 O << "_" << vecelem[Imm];
601 else if (0 == strcmp(Modifier, "vecv4comm1")) {
602 if ((Imm < 0) || (Imm > 3))
604 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
605 if ((Imm < 4) || (Imm > 7))
607 } else if (0 == strcmp(Modifier, "vecv4pos")) {
610 O << "_" << vecelem[Imm % 4];
611 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
612 if ((Imm < 0) || (Imm > 1))
614 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
615 if ((Imm < 2) || (Imm > 3))
617 } else if (0 == strcmp(Modifier, "vecv2pos")) {
620 O << "_" << vecelem[Imm % 2];
622 llvm_unreachable("Unknown Modifier on immediate operand");
627 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
629 emitLinkageDirective(F, O);
630 if (llvm::isKernelFunction(*F))
634 printReturnValStr(F, O);
635 O << *getSymbol(F) << "\n";
636 emitFunctionParamList(F, O);
640 static bool usedInGlobalVarDef(const Constant *C) {
644 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
645 if (GV->getName().str() == "llvm.used")
650 for (const User *U : C->users())
651 if (const Constant *C = dyn_cast<Constant>(U))
652 if (usedInGlobalVarDef(C))
658 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
659 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
660 if (othergv->getName().str() == "llvm.used")
664 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
665 if (instr->getParent() && instr->getParent()->getParent()) {
666 const Function *curFunc = instr->getParent()->getParent();
667 if (oneFunc && (curFunc != oneFunc))
675 for (const User *UU : U->users())
676 if (usedInOneFunc(UU, oneFunc) == false)
682 /* Find out if a global variable can be demoted to local scope.
683 * Currently, this is valid for CUDA shared variables, which have local
684 * scope and global lifetime. So the conditions to check are :
685 * 1. Is the global variable in shared address space?
686 * 2. Does it have internal linkage?
687 * 3. Is the global variable referenced only in one function?
689 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
690 if (gv->hasInternalLinkage() == false)
692 const PointerType *Pty = gv->getType();
693 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
696 const Function *oneFunc = nullptr;
698 bool flag = usedInOneFunc(gv, oneFunc);
707 static bool useFuncSeen(const Constant *C,
708 llvm::DenseMap<const Function *, bool> &seenMap) {
709 for (const User *U : C->users()) {
710 if (const Constant *cu = dyn_cast<Constant>(U)) {
711 if (useFuncSeen(cu, seenMap))
713 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
714 const BasicBlock *bb = I->getParent();
717 const Function *caller = bb->getParent();
720 if (seenMap.find(caller) != seenMap.end())
727 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
728 llvm::DenseMap<const Function *, bool> seenMap;
729 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
730 const Function *F = FI;
732 if (F->isDeclaration()) {
735 if (F->getIntrinsicID())
737 emitDeclaration(F, O);
740 for (const User *U : F->users()) {
741 if (const Constant *C = dyn_cast<Constant>(U)) {
742 if (usedInGlobalVarDef(C)) {
743 // The use is in the initialization of a global variable
744 // that is a function pointer, so print a declaration
745 // for the original function
746 emitDeclaration(F, O);
749 // Emit a declaration of this function if the function that
750 // uses this constant expr has already been seen.
751 if (useFuncSeen(C, seenMap)) {
752 emitDeclaration(F, O);
757 if (!isa<Instruction>(U))
759 const Instruction *instr = cast<Instruction>(U);
760 const BasicBlock *bb = instr->getParent();
763 const Function *caller = bb->getParent();
767 // If a caller has already been seen, then the caller is
768 // appearing in the module before the callee. so print out
769 // a declaration for the callee.
770 if (seenMap.find(caller) != seenMap.end()) {
771 emitDeclaration(F, O);
779 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
780 DebugInfoFinder DbgFinder;
781 DbgFinder.processModule(M);
784 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
785 StringRef Filename(DIUnit.getFilename());
786 StringRef Dirname(DIUnit.getDirectory());
787 SmallString<128> FullPathName = Dirname;
788 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
789 sys::path::append(FullPathName, Filename);
790 Filename = FullPathName.str();
792 if (filenameMap.find(Filename.str()) != filenameMap.end())
794 filenameMap[Filename.str()] = i;
795 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
799 for (DISubprogram SP : DbgFinder.subprograms()) {
800 StringRef Filename(SP.getFilename());
801 StringRef Dirname(SP.getDirectory());
802 SmallString<128> FullPathName = Dirname;
803 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
804 sys::path::append(FullPathName, Filename);
805 Filename = FullPathName.str();
807 if (filenameMap.find(Filename.str()) != filenameMap.end())
809 filenameMap[Filename.str()] = i;
814 bool NVPTXAsmPrinter::doInitialization(Module &M) {
815 // Construct a default subtarget off of the TargetMachine defaults. The
816 // rest of NVPTX isn't friendly to change subtargets per function and
817 // so the default TargetMachine will have all of the options.
818 StringRef TT = TM.getTargetTriple();
819 StringRef CPU = TM.getTargetCPU();
820 StringRef FS = TM.getTargetFeatureString();
821 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
822 const NVPTXSubtarget STI(TT, CPU, FS, NTM, NTM.is64Bit());
824 SmallString<128> Str1;
825 raw_svector_ostream OS1(Str1);
827 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
828 MMI->AnalyzeModule(M);
830 // We need to call the parent's one explicitly.
831 //bool Result = AsmPrinter::doInitialization(M);
833 // Initialize TargetLoweringObjectFile.
834 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
835 .Initialize(OutContext, TM);
837 Mang = new Mangler(TM.getDataLayout());
839 // Emit header before any dwarf directives are emitted below.
840 emitHeader(M, OS1, STI);
841 OutStreamer.EmitRawText(OS1.str());
843 // Already commented out
844 //bool Result = AsmPrinter::doInitialization(M);
846 // Emit module-level inline asm if it exists.
847 if (!M.getModuleInlineAsm().empty()) {
848 OutStreamer.AddComment("Start of file scope inline assembly");
849 OutStreamer.AddBlankLine();
850 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
851 OutStreamer.AddBlankLine();
852 OutStreamer.AddComment("End of file scope inline assembly");
853 OutStreamer.AddBlankLine();
856 // If we're not NVCL we're CUDA, go ahead and emit filenames.
857 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
858 recordAndEmitFilenames(M);
860 GlobalsEmitted = false;
862 return false; // success
865 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
866 SmallString<128> Str2;
867 raw_svector_ostream OS2(Str2);
869 emitDeclarations(M, OS2);
871 // As ptxas does not support forward references of globals, we need to first
872 // sort the list of module-level globals in def-use order. We visit each
873 // global variable in order, and ensure that we emit it *after* its dependent
874 // globals. We use a little extra memory maintaining both a set and a list to
875 // have fast searches while maintaining a strict ordering.
876 SmallVector<const GlobalVariable *, 8> Globals;
877 DenseSet<const GlobalVariable *> GVVisited;
878 DenseSet<const GlobalVariable *> GVVisiting;
880 // Visit each global variable, in order
881 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
883 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
885 assert(GVVisited.size() == M.getGlobalList().size() &&
886 "Missed a global variable");
887 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
889 // Print out module-level global variables in proper order
890 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
891 printModuleLevelGV(Globals[i], OS2);
895 OutStreamer.EmitRawText(OS2.str());
898 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
899 const NVPTXSubtarget &STI) {
901 O << "// Generated by LLVM NVPTX Back-End\n";
905 unsigned PTXVersion = STI.getPTXVersion();
906 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
909 O << STI.getTargetName();
911 const NVPTXTargetMachine &TM = static_cast<const NVPTXTargetMachine &>(TM);
912 if (TM.getDrvInterface() == NVPTX::NVCL)
913 O << ", texmode_independent";
915 if (!STI.hasDouble())
916 O << ", map_f64_to_f32";
919 if (MAI->doesSupportDebugInformation())
924 O << ".address_size ";
934 bool NVPTXAsmPrinter::doFinalization(Module &M) {
935 // If we did not emit any functions, then the global declarations have not
937 if (!GlobalsEmitted) {
939 GlobalsEmitted = true;
942 // XXX Temproarily remove global variables so that doFinalization() will not
943 // emit them again (global variables are emitted at beginning).
945 Module::GlobalListType &global_list = M.getGlobalList();
946 int i, n = global_list.size();
947 GlobalVariable **gv_array = new GlobalVariable *[n];
949 // first, back-up GlobalVariable in gv_array
951 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
955 // second, empty global_list
956 while (!global_list.empty())
957 global_list.remove(global_list.begin());
959 // call doFinalization
960 bool ret = AsmPrinter::doFinalization(M);
962 // now we restore global variables
963 for (i = 0; i < n; i++)
964 global_list.insert(global_list.end(), gv_array[i]);
966 clearAnnotationCache(&M);
971 //bool Result = AsmPrinter::doFinalization(M);
972 // Instead of calling the parents doFinalization, we may
973 // clone parents doFinalization and customize here.
974 // Currently, we if NVISA out the EmitGlobals() in
975 // parent's doFinalization, which is too intrusive.
977 // Same for the doInitialization.
981 // This function emits appropriate linkage directives for
982 // functions and global variables.
984 // extern function declaration -> .extern
985 // extern function definition -> .visible
986 // external global variable with init -> .visible
987 // external without init -> .extern
988 // appending -> not allowed, assert.
989 // for any linkage other than
990 // internal, private, linker_private,
991 // linker_private_weak, linker_private_weak_def_auto,
994 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
996 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
997 if (V->hasExternalLinkage()) {
998 if (isa<GlobalVariable>(V)) {
999 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1001 if (GVar->hasInitializer())
1006 } else if (V->isDeclaration())
1010 } else if (V->hasAppendingLinkage()) {
1012 msg.append("Error: ");
1013 msg.append("Symbol ");
1015 msg.append(V->getName().str());
1016 msg.append("has unsupported appending linkage type");
1017 llvm_unreachable(msg.c_str());
1018 } else if (!V->hasInternalLinkage() &&
1019 !V->hasPrivateLinkage()) {
1025 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1027 bool processDemoted) {
1030 if (GVar->hasSection()) {
1031 if (GVar->getSection() == StringRef("llvm.metadata"))
1035 // Skip LLVM intrinsic global variables
1036 if (GVar->getName().startswith("llvm.") ||
1037 GVar->getName().startswith("nvvm."))
1040 const DataLayout *TD = TM.getDataLayout();
1042 // GlobalVariables are always constant pointers themselves.
1043 const PointerType *PTy = GVar->getType();
1044 Type *ETy = PTy->getElementType();
1046 if (GVar->hasExternalLinkage()) {
1047 if (GVar->hasInitializer())
1051 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1052 GVar->hasAvailableExternallyLinkage() ||
1053 GVar->hasCommonLinkage()) {
1057 if (llvm::isTexture(*GVar)) {
1058 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1062 if (llvm::isSurface(*GVar)) {
1063 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1067 if (GVar->isDeclaration()) {
1068 // (extern) declarations, no definition or initializer
1069 // Currently the only known declaration is for an automatic __local
1070 // (.shared) promoted to global.
1071 emitPTXGlobalVariable(GVar, O);
1076 if (llvm::isSampler(*GVar)) {
1077 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1079 const Constant *Initializer = nullptr;
1080 if (GVar->hasInitializer())
1081 Initializer = GVar->getInitializer();
1082 const ConstantInt *CI = nullptr;
1084 CI = dyn_cast<ConstantInt>(Initializer);
1086 unsigned sample = CI->getZExtValue();
1091 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1093 O << "addr_mode_" << i << " = ";
1099 O << "clamp_to_border";
1102 O << "clamp_to_edge";
1113 O << "filter_mode = ";
1114 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1122 llvm_unreachable("Anisotropic filtering is not supported");
1127 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1128 O << ", force_unnormalized_coords = 1";
1137 if (GVar->hasPrivateLinkage()) {
1139 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1142 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1143 if (!strncmp(GVar->getName().data(), "filename", 8))
1145 if (GVar->use_empty())
1149 const Function *demotedFunc = nullptr;
1150 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1151 O << "// " << GVar->getName().str() << " has been demoted\n";
1152 if (localDecls.find(demotedFunc) != localDecls.end())
1153 localDecls[demotedFunc].push_back(GVar);
1155 std::vector<const GlobalVariable *> temp;
1156 temp.push_back(GVar);
1157 localDecls[demotedFunc] = temp;
1163 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1165 if (isManaged(*GVar)) {
1166 O << " .attribute(.managed)";
1169 if (GVar->getAlignment() == 0)
1170 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1172 O << " .align " << GVar->getAlignment();
1174 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1176 // Special case: ABI requires that we use .u8 for predicates
1177 if (ETy->isIntegerTy(1))
1180 O << getPTXFundamentalTypeStr(ETy, false);
1182 O << *getSymbol(GVar);
1184 // Ptx allows variable initilization only for constant and global state
1186 if (GVar->hasInitializer()) {
1187 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1188 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1189 const Constant *Initializer = GVar->getInitializer();
1190 // 'undef' is treated as there is no value spefied.
1191 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1193 printScalarConstant(Initializer, O);
1196 // The frontend adds zero-initializer to variables that don't have an
1197 // initial value, so skip warning for this case.
1198 if (!GVar->getInitializer()->isNullValue()) {
1199 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1200 "' is not allowed in addrspace(" +
1201 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1202 report_fatal_error(warnMsg.c_str());
1207 unsigned int ElementSize = 0;
1209 // Although PTX has direct support for struct type and array type and
1210 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1211 // targets that support these high level field accesses. Structs, arrays
1212 // and vectors are lowered into arrays of bytes.
1213 switch (ETy->getTypeID()) {
1214 case Type::StructTyID:
1215 case Type::ArrayTyID:
1216 case Type::VectorTyID:
1217 ElementSize = TD->getTypeStoreSize(ETy);
1218 // Ptx allows variable initilization only for constant and
1219 // global state spaces.
1220 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1221 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1222 GVar->hasInitializer()) {
1223 const Constant *Initializer = GVar->getInitializer();
1224 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1225 AggBuffer aggBuffer(ElementSize, O, *this);
1226 bufferAggregateConstant(Initializer, &aggBuffer);
1227 if (aggBuffer.numSymbols) {
1228 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1229 O << " .u64 " << *getSymbol(GVar) << "[";
1230 O << ElementSize / 8;
1232 O << " .u32 " << *getSymbol(GVar) << "[";
1233 O << ElementSize / 4;
1237 O << " .b8 " << *getSymbol(GVar) << "[";
1245 O << " .b8 " << *getSymbol(GVar);
1253 O << " .b8 " << *getSymbol(GVar);
1262 llvm_unreachable("type not supported yet");
1269 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1270 if (localDecls.find(f) == localDecls.end())
1273 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1275 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1276 O << "\t// demoted variable\n\t";
1277 printModuleLevelGV(gvars[i], O, true);
1281 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1282 raw_ostream &O) const {
1283 switch (AddressSpace) {
1284 case llvm::ADDRESS_SPACE_LOCAL:
1287 case llvm::ADDRESS_SPACE_GLOBAL:
1290 case llvm::ADDRESS_SPACE_CONST:
1293 case llvm::ADDRESS_SPACE_SHARED:
1297 report_fatal_error("Bad address space found while emitting PTX");
1303 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1304 switch (Ty->getTypeID()) {
1306 llvm_unreachable("unexpected type");
1308 case Type::IntegerTyID: {
1309 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1312 else if (NumBits <= 64) {
1313 std::string name = "u";
1314 return name + utostr(NumBits);
1316 llvm_unreachable("Integer too large");
1321 case Type::FloatTyID:
1323 case Type::DoubleTyID:
1325 case Type::PointerTyID:
1326 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1336 llvm_unreachable("unexpected type");
1340 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1343 const DataLayout *TD = TM.getDataLayout();
1345 // GlobalVariables are always constant pointers themselves.
1346 const PointerType *PTy = GVar->getType();
1347 Type *ETy = PTy->getElementType();
1350 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1351 if (GVar->getAlignment() == 0)
1352 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1354 O << " .align " << GVar->getAlignment();
1356 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1358 O << getPTXFundamentalTypeStr(ETy);
1360 O << *getSymbol(GVar);
1364 int64_t ElementSize = 0;
1366 // Although PTX has direct support for struct type and array type and LLVM IR
1367 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1368 // support these high level field accesses. Structs and arrays are lowered
1369 // into arrays of bytes.
1370 switch (ETy->getTypeID()) {
1371 case Type::StructTyID:
1372 case Type::ArrayTyID:
1373 case Type::VectorTyID:
1374 ElementSize = TD->getTypeStoreSize(ETy);
1375 O << " .b8 " << *getSymbol(GVar) << "[";
1377 O << itostr(ElementSize);
1382 llvm_unreachable("type not supported yet");
1387 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1388 if (Ty->isSingleValueType())
1389 return TD->getPrefTypeAlignment(Ty);
1391 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1393 return getOpenCLAlignment(TD, ATy->getElementType());
1395 const StructType *STy = dyn_cast<StructType>(Ty);
1397 unsigned int alignStruct = 1;
1398 // Go through each element of the struct and find the
1399 // largest alignment.
1400 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1401 Type *ETy = STy->getElementType(i);
1402 unsigned int align = getOpenCLAlignment(TD, ETy);
1403 if (align > alignStruct)
1404 alignStruct = align;
1409 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1411 return TD->getPointerPrefAlignment();
1412 return TD->getPrefTypeAlignment(Ty);
1415 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1416 int paramIndex, raw_ostream &O) {
1417 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1420 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1421 O << *CurrentFnSym << "_param_" << paramIndex;
1424 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1425 const DataLayout *TD = TM.getDataLayout();
1426 const AttributeSet &PAL = F->getAttributes();
1427 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1428 Function::const_arg_iterator I, E;
1429 unsigned paramIndex = 0;
1431 bool isKernelFunc = llvm::isKernelFunction(*F);
1432 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1433 MVT thePointerTy = TLI->getPointerTy();
1437 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1438 Type *Ty = I->getType();
1445 // Handle image/sampler parameters
1446 if (isKernelFunction(*F)) {
1447 if (isSampler(*I) || isImage(*I)) {
1449 std::string sname = I->getName();
1450 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1451 if (nvptxSubtarget->hasImageHandles())
1452 O << "\t.param .u64 .ptr .surfref ";
1454 O << "\t.param .surfref ";
1455 O << *CurrentFnSym << "_param_" << paramIndex;
1457 else { // Default image is read_only
1458 if (nvptxSubtarget->hasImageHandles())
1459 O << "\t.param .u64 .ptr .texref ";
1461 O << "\t.param .texref ";
1462 O << *CurrentFnSym << "_param_" << paramIndex;
1465 if (nvptxSubtarget->hasImageHandles())
1466 O << "\t.param .u64 .ptr .samplerref ";
1468 O << "\t.param .samplerref ";
1469 O << *CurrentFnSym << "_param_" << paramIndex;
1475 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1476 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1477 // Just print .param .align <a> .b8 .param[size];
1478 // <a> = PAL.getparamalignment
1479 // size = typeallocsize of element type
1480 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1482 align = TD->getABITypeAlignment(Ty);
1484 unsigned sz = TD->getTypeAllocSize(Ty);
1485 O << "\t.param .align " << align << " .b8 ";
1486 printParamName(I, paramIndex, O);
1487 O << "[" << sz << "]";
1492 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1495 // Special handling for pointer arguments to kernel
1496 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1498 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1500 Type *ETy = PTy->getElementType();
1501 int addrSpace = PTy->getAddressSpace();
1502 switch (addrSpace) {
1506 case llvm::ADDRESS_SPACE_CONST:
1507 O << ".ptr .const ";
1509 case llvm::ADDRESS_SPACE_SHARED:
1510 O << ".ptr .shared ";
1512 case llvm::ADDRESS_SPACE_GLOBAL:
1513 O << ".ptr .global ";
1516 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1518 printParamName(I, paramIndex, O);
1522 // non-pointer scalar to kernel func
1524 // Special case: predicate operands become .u8 types
1525 if (Ty->isIntegerTy(1))
1528 O << getPTXFundamentalTypeStr(Ty);
1530 printParamName(I, paramIndex, O);
1533 // Non-kernel function, just print .param .b<size> for ABI
1534 // and .reg .b<size> for non-ABI
1536 if (isa<IntegerType>(Ty)) {
1537 sz = cast<IntegerType>(Ty)->getBitWidth();
1540 } else if (isa<PointerType>(Ty))
1541 sz = thePointerTy.getSizeInBits();
1543 sz = Ty->getPrimitiveSizeInBits();
1545 O << "\t.param .b" << sz << " ";
1547 O << "\t.reg .b" << sz << " ";
1548 printParamName(I, paramIndex, O);
1552 // param has byVal attribute. So should be a pointer
1553 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1554 assert(PTy && "Param with byval attribute should be a pointer type");
1555 Type *ETy = PTy->getElementType();
1557 if (isABI || isKernelFunc) {
1558 // Just print .param .align <a> .b8 .param[size];
1559 // <a> = PAL.getparamalignment
1560 // size = typeallocsize of element type
1561 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1563 align = TD->getABITypeAlignment(ETy);
1565 unsigned sz = TD->getTypeAllocSize(ETy);
1566 O << "\t.param .align " << align << " .b8 ";
1567 printParamName(I, paramIndex, O);
1568 O << "[" << sz << "]";
1571 // Split the ETy into constituent parts and
1572 // print .param .b<size> <name> for each part.
1573 // Further, if a part is vector, print the above for
1574 // each vector element.
1575 SmallVector<EVT, 16> vtparts;
1576 ComputeValueVTs(*TLI, ETy, vtparts);
1577 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1579 EVT elemtype = vtparts[i];
1580 if (vtparts[i].isVector()) {
1581 elems = vtparts[i].getVectorNumElements();
1582 elemtype = vtparts[i].getVectorElementType();
1585 for (unsigned j = 0, je = elems; j != je; ++j) {
1586 unsigned sz = elemtype.getSizeInBits();
1587 if (elemtype.isInteger() && (sz < 32))
1589 O << "\t.reg .b" << sz << " ";
1590 printParamName(I, paramIndex, O);
1606 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1608 const Function *F = MF.getFunction();
1609 emitFunctionParamList(F, O);
1612 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1613 const MachineFunction &MF) {
1614 SmallString<128> Str;
1615 raw_svector_ostream O(Str);
1617 // Map the global virtual register number to a register class specific
1618 // virtual register number starting from 1 with that class.
1619 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1620 //unsigned numRegClasses = TRI->getNumRegClasses();
1622 // Emit the Fake Stack Object
1623 const MachineFrameInfo *MFI = MF.getFrameInfo();
1624 int NumBytes = (int) MFI->getStackSize();
1626 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1627 << getFunctionNumber() << "[" << NumBytes << "];\n";
1628 if (nvptxSubtarget->is64Bit()) {
1629 O << "\t.reg .b64 \t%SP;\n";
1630 O << "\t.reg .b64 \t%SPL;\n";
1632 O << "\t.reg .b32 \t%SP;\n";
1633 O << "\t.reg .b32 \t%SPL;\n";
1637 // Go through all virtual registers to establish the mapping between the
1639 // register number and the per class virtual register number.
1640 // We use the per class virtual register number in the ptx output.
1641 unsigned int numVRs = MRI->getNumVirtRegs();
1642 for (unsigned i = 0; i < numVRs; i++) {
1643 unsigned int vr = TRI->index2VirtReg(i);
1644 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1645 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1646 int n = regmap.size();
1647 regmap.insert(std::make_pair(vr, n + 1));
1650 // Emit register declarations
1651 // @TODO: Extract out the real register usage
1652 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1653 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1654 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1655 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1656 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1657 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1658 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1660 // Emit declaration of the virtual registers or 'physical' registers for
1661 // each register class
1662 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1663 const TargetRegisterClass *RC = TRI->getRegClass(i);
1664 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1665 std::string rcname = getNVPTXRegClassName(RC);
1666 std::string rcStr = getNVPTXRegClassStr(RC);
1667 int n = regmap.size();
1669 // Only declare those registers that may be used.
1671 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1676 OutStreamer.EmitRawText(O.str());
1679 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1680 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1682 unsigned int numHex;
1685 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1688 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1689 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1692 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1694 llvm_unreachable("unsupported fp type");
1696 APInt API = APF.bitcastToAPInt();
1697 std::string hexstr(utohexstr(API.getZExtValue()));
1699 if (hexstr.length() < numHex)
1700 O << std::string(numHex - hexstr.length(), '0');
1701 O << utohexstr(API.getZExtValue());
1704 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1705 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1706 O << CI->getValue();
1709 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1710 printFPConstant(CFP, O);
1713 if (isa<ConstantPointerNull>(CPV)) {
1717 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1718 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1719 bool IsNonGenericPointer = false;
1720 if (PTy && PTy->getAddressSpace() != 0) {
1721 IsNonGenericPointer = true;
1723 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1725 O << *getSymbol(GVar);
1728 O << *getSymbol(GVar);
1732 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1733 const Value *v = Cexpr->stripPointerCasts();
1734 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1735 bool IsNonGenericPointer = false;
1736 if (PTy && PTy->getAddressSpace() != 0) {
1737 IsNonGenericPointer = true;
1739 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1740 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1742 O << *getSymbol(GVar);
1745 O << *getSymbol(GVar);
1749 O << *lowerConstant(CPV);
1753 llvm_unreachable("Not scalar type found in printScalarConstant()");
1756 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1757 AggBuffer *aggBuffer) {
1759 const DataLayout *TD = TM.getDataLayout();
1761 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1762 int s = TD->getTypeAllocSize(CPV->getType());
1765 aggBuffer->addZeros(s);
1770 switch (CPV->getType()->getTypeID()) {
1772 case Type::IntegerTyID: {
1773 const Type *ETy = CPV->getType();
1774 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1776 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1778 aggBuffer->addBytes(ptr, 1, Bytes);
1779 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1780 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1781 ptr = (unsigned char *)&int16;
1782 aggBuffer->addBytes(ptr, 2, Bytes);
1783 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1784 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1785 int int32 = (int)(constInt->getZExtValue());
1786 ptr = (unsigned char *)&int32;
1787 aggBuffer->addBytes(ptr, 4, Bytes);
1789 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1790 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1791 ConstantFoldConstantExpression(Cexpr, TD))) {
1792 int int32 = (int)(constInt->getZExtValue());
1793 ptr = (unsigned char *)&int32;
1794 aggBuffer->addBytes(ptr, 4, Bytes);
1797 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1798 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1799 aggBuffer->addSymbol(v);
1800 aggBuffer->addZeros(4);
1804 llvm_unreachable("unsupported integer const type");
1805 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1806 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1807 long long int64 = (long long)(constInt->getZExtValue());
1808 ptr = (unsigned char *)&int64;
1809 aggBuffer->addBytes(ptr, 8, Bytes);
1811 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1812 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1813 ConstantFoldConstantExpression(Cexpr, TD))) {
1814 long long int64 = (long long)(constInt->getZExtValue());
1815 ptr = (unsigned char *)&int64;
1816 aggBuffer->addBytes(ptr, 8, Bytes);
1819 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1820 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1821 aggBuffer->addSymbol(v);
1822 aggBuffer->addZeros(8);
1826 llvm_unreachable("unsupported integer const type");
1828 llvm_unreachable("unsupported integer const type");
1831 case Type::FloatTyID:
1832 case Type::DoubleTyID: {
1833 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1834 const Type *Ty = CFP->getType();
1835 if (Ty == Type::getFloatTy(CPV->getContext())) {
1836 float float32 = (float) CFP->getValueAPF().convertToFloat();
1837 ptr = (unsigned char *)&float32;
1838 aggBuffer->addBytes(ptr, 4, Bytes);
1839 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1840 double float64 = CFP->getValueAPF().convertToDouble();
1841 ptr = (unsigned char *)&float64;
1842 aggBuffer->addBytes(ptr, 8, Bytes);
1844 llvm_unreachable("unsupported fp const type");
1848 case Type::PointerTyID: {
1849 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1850 aggBuffer->addSymbol(GVar);
1851 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1852 const Value *v = Cexpr->stripPointerCasts();
1853 aggBuffer->addSymbol(v);
1855 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1856 aggBuffer->addZeros(s);
1860 case Type::ArrayTyID:
1861 case Type::VectorTyID:
1862 case Type::StructTyID: {
1863 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1864 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1865 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1866 bufferAggregateConstant(CPV, aggBuffer);
1867 if (Bytes > ElementSize)
1868 aggBuffer->addZeros(Bytes - ElementSize);
1869 } else if (isa<ConstantAggregateZero>(CPV))
1870 aggBuffer->addZeros(Bytes);
1872 llvm_unreachable("Unexpected Constant type");
1877 llvm_unreachable("unsupported type");
1881 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1882 AggBuffer *aggBuffer) {
1883 const DataLayout *TD = TM.getDataLayout();
1887 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1888 if (CPV->getNumOperands())
1889 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1890 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1894 if (const ConstantDataSequential *CDS =
1895 dyn_cast<ConstantDataSequential>(CPV)) {
1896 if (CDS->getNumElements())
1897 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1898 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1903 if (isa<ConstantStruct>(CPV)) {
1904 if (CPV->getNumOperands()) {
1905 StructType *ST = cast<StructType>(CPV->getType());
1906 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1908 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1909 TD->getTypeAllocSize(ST) -
1910 TD->getStructLayout(ST)->getElementOffset(i);
1912 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1913 TD->getStructLayout(ST)->getElementOffset(i);
1914 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1919 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1922 // buildTypeNameMap - Run through symbol table looking for type names.
1925 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1927 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1929 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1930 !PI->second.compare("struct._image2d_t") ||
1931 !PI->second.compare("struct._image3d_t")))
1938 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1939 switch (MI.getOpcode()) {
1942 case NVPTX::CallArgBeginInst:
1943 case NVPTX::CallArgEndInst0:
1944 case NVPTX::CallArgEndInst1:
1945 case NVPTX::CallArgF32:
1946 case NVPTX::CallArgF64:
1947 case NVPTX::CallArgI16:
1948 case NVPTX::CallArgI32:
1949 case NVPTX::CallArgI32imm:
1950 case NVPTX::CallArgI64:
1951 case NVPTX::CallArgParam:
1952 case NVPTX::CallVoidInst:
1953 case NVPTX::CallVoidInstReg:
1954 case NVPTX::Callseq_End:
1955 case NVPTX::CallVoidInstReg64:
1956 case NVPTX::DeclareParamInst:
1957 case NVPTX::DeclareRetMemInst:
1958 case NVPTX::DeclareRetRegInst:
1959 case NVPTX::DeclareRetScalarInst:
1960 case NVPTX::DeclareScalarParamInst:
1961 case NVPTX::DeclareScalarRegInst:
1962 case NVPTX::StoreParamF32:
1963 case NVPTX::StoreParamF64:
1964 case NVPTX::StoreParamI16:
1965 case NVPTX::StoreParamI32:
1966 case NVPTX::StoreParamI64:
1967 case NVPTX::StoreParamI8:
1968 case NVPTX::StoreRetvalF32:
1969 case NVPTX::StoreRetvalF64:
1970 case NVPTX::StoreRetvalI16:
1971 case NVPTX::StoreRetvalI32:
1972 case NVPTX::StoreRetvalI64:
1973 case NVPTX::StoreRetvalI8:
1974 case NVPTX::LastCallArgF32:
1975 case NVPTX::LastCallArgF64:
1976 case NVPTX::LastCallArgI16:
1977 case NVPTX::LastCallArgI32:
1978 case NVPTX::LastCallArgI32imm:
1979 case NVPTX::LastCallArgI64:
1980 case NVPTX::LastCallArgParam:
1981 case NVPTX::LoadParamMemF32:
1982 case NVPTX::LoadParamMemF64:
1983 case NVPTX::LoadParamMemI16:
1984 case NVPTX::LoadParamMemI32:
1985 case NVPTX::LoadParamMemI64:
1986 case NVPTX::LoadParamMemI8:
1987 case NVPTX::PrototypeInst:
1988 case NVPTX::DBG_VALUE:
1994 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1996 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1997 unsigned AsmVariant,
1998 const char *ExtraCode, raw_ostream &O) {
1999 if (ExtraCode && ExtraCode[0]) {
2000 if (ExtraCode[1] != 0)
2001 return true; // Unknown modifier.
2003 switch (ExtraCode[0]) {
2005 // See if this is a generic print operand
2006 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2012 printOperand(MI, OpNo, O);
2017 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2018 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2019 const char *ExtraCode, raw_ostream &O) {
2020 if (ExtraCode && ExtraCode[0])
2021 return true; // Unknown modifier
2024 printMemOperand(MI, OpNo, O);
2030 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2031 raw_ostream &O, const char *Modifier) {
2032 const MachineOperand &MO = MI->getOperand(opNum);
2033 switch (MO.getType()) {
2034 case MachineOperand::MO_Register:
2035 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2036 if (MO.getReg() == NVPTX::VRDepot)
2037 O << DEPOTNAME << getFunctionNumber();
2039 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2041 emitVirtualRegister(MO.getReg(), O);
2045 case MachineOperand::MO_Immediate:
2048 else if (strstr(Modifier, "vec") == Modifier)
2049 printVecModifiedImmediate(MO, Modifier, O);
2052 "Don't know how to handle modifier on immediate operand");
2055 case MachineOperand::MO_FPImmediate:
2056 printFPConstant(MO.getFPImm(), O);
2059 case MachineOperand::MO_GlobalAddress:
2060 O << *getSymbol(MO.getGlobal());
2063 case MachineOperand::MO_MachineBasicBlock:
2064 O << *MO.getMBB()->getSymbol();
2068 llvm_unreachable("Operand type not supported.");
2072 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2073 raw_ostream &O, const char *Modifier) {
2074 printOperand(MI, opNum, O);
2076 if (Modifier && !strcmp(Modifier, "add")) {
2078 printOperand(MI, opNum + 1, O);
2080 if (MI->getOperand(opNum + 1).isImm() &&
2081 MI->getOperand(opNum + 1).getImm() == 0)
2082 return; // don't print ',0' or '+0'
2084 printOperand(MI, opNum + 1, O);
2089 // Force static initialization.
2090 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2091 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2092 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2095 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2096 std::stringstream temp;
2097 LineReader *reader = this->getReader(filename.str());
2099 temp << filename.str();
2103 temp << reader->readLine(line);
2105 this->OutStreamer.EmitRawText(Twine(temp.str()));
2108 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2110 reader = new LineReader(filename);
2113 if (reader->fileName() != filename) {
2115 reader = new LineReader(filename);
2121 std::string LineReader::readLine(unsigned lineNum) {
2122 if (lineNum < theCurLine) {
2124 fstr.seekg(0, std::ios::beg);
2126 while (theCurLine < lineNum) {
2127 fstr.getline(buff, 500);
2133 // Force static initialization.
2134 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2135 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2136 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);