LLVM 23.0.0git
NVPTXAsmPrinter.cpp
Go to the documentation of this file.
1//===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to NVPTX assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "NVPTXAsmPrinter.h"
19#include "NVPTX.h"
20#include "NVPTXDwarfDebug.h"
21#include "NVPTXMCExpr.h"
23#include "NVPTXRegisterInfo.h"
24#include "NVPTXSubtarget.h"
25#include "NVPTXTargetMachine.h"
26#include "NVPTXUtilities.h"
27#include "NVVMProperties.h"
29#include "cl_common_defines.h"
30#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/Twine.h"
54#include "llvm/IR/Argument.h"
55#include "llvm/IR/Attributes.h"
56#include "llvm/IR/BasicBlock.h"
57#include "llvm/IR/Constant.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/DebugInfo.h"
62#include "llvm/IR/DebugLoc.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/GlobalAlias.h"
66#include "llvm/IR/GlobalValue.h"
68#include "llvm/IR/Instruction.h"
69#include "llvm/IR/LLVMContext.h"
70#include "llvm/IR/Module.h"
71#include "llvm/IR/Operator.h"
72#include "llvm/IR/Type.h"
73#include "llvm/IR/User.h"
74#include "llvm/MC/MCExpr.h"
75#include "llvm/MC/MCInst.h"
76#include "llvm/MC/MCInstrDesc.h"
77#include "llvm/MC/MCStreamer.h"
78#include "llvm/MC/MCSymbol.h"
83#include "llvm/Support/Endian.h"
90#include <cassert>
91#include <cstdint>
92#include <cstring>
93#include <string>
94
95using namespace llvm;
96
97#define DEPOTNAME "__local_depot"
98
99static StringRef getTextureName(const Value &V) {
100 assert(V.hasName() && "Found texture variable with no name");
101 return V.getName();
102}
103
105 assert(V.hasName() && "Found surface variable with no name");
106 return V.getName();
107}
108
110 assert(V.hasName() && "Found sampler variable with no name");
111 return V.getName();
112}
113
114/// Emits initial debug location directive.
116 DwarfDebug *DD,
117 MCStreamer &OutStreamer) {
118 if (!DD)
119 return;
120
121 assert(OutStreamer.hasRawTextSupport() && "Expected assembly output mode.");
122 // This is NVPTX specific and it's unclear why.
123 // PR51079: If we have code without debug information we need to give up.
124 const DISubprogram *SP = MF.getFunction().getSubprogram();
125 if (!SP)
126 return;
127 assert(SP->getUnit());
128 // NoDebug and DebugDirectivesOnly do not require emitting the initial loc
129 // directive. NoDebug does not require any debug directives and the initial
130 // loc directive is not needed for DebugDirectivesOnly as it is redundant
131 // assuming this is a non-empty function.
132 if (SP->getUnit()->isDebugDirectivesOnly() || SP->getUnit()->isNoDebug())
133 return;
134
135 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
136}
137
138/// discoverDependentGlobals - Return a set of GlobalVariables on which \p V
139/// depends.
140static void
143 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
144 Globals.insert(GV);
145 return;
146 }
147
148 if (const User *U = dyn_cast<User>(V))
149 for (const auto &O : U->operands())
150 discoverDependentGlobals(O, Globals);
151}
152
153/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
154/// instances to be emitted, but only after any dependents have been added
155/// first.s
156static void
161 // Have we already visited this one?
162 if (Visited.count(GV))
163 return;
164
165 // Do we have a circular dependency?
166 if (!Visiting.insert(GV).second)
167 report_fatal_error("Circular dependency found in global variable set");
168
169 // Make sure we visit all dependents first
171 for (const auto &O : GV->operands())
172 discoverDependentGlobals(O, Others);
173
174 for (const GlobalVariable *GV : Others)
175 VisitGlobalVariableForEmission(GV, Order, Visited, Visiting);
176
177 // Now we can visit ourself
178 Order.push_back(GV);
179 Visited.insert(GV);
180 Visiting.erase(GV);
181}
182
183void NVPTXAsmPrinter::emitInstruction(const MachineInstr *MI) {
184 NVPTX_MC::verifyInstructionPredicates(MI->getOpcode(),
185 getSubtargetInfo().getFeatureBits());
186
187 MCInst Inst;
188 lowerToMCInst(MI, Inst);
190}
191
192void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
193 OutMI.setOpcode(MI->getOpcode());
194 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
195 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
196 const MachineOperand &MO = MI->getOperand(0);
197 OutMI.addOperand(GetSymbolRef(
198 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
199 return;
200 }
201
202 for (const auto MO : MI->operands())
203 OutMI.addOperand(lowerOperand(MO));
204}
205
206MCOperand NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO) {
207 switch (MO.getType()) {
208 default:
209 llvm_unreachable("unknown operand type");
211 return MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
213 return MCOperand::createImm(MO.getImm());
218 return GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
220 return GetSymbolRef(getSymbol(MO.getGlobal()));
222 const ConstantFP *Cnt = MO.getFPImm();
223 const APFloat &Val = Cnt->getValueAPF();
224
225 switch (Cnt->getType()->getTypeID()) {
226 default:
227 report_fatal_error("Unsupported FP type");
228 break;
229 case Type::HalfTyID:
232 case Type::BFloatTyID:
235 case Type::FloatTyID:
238 case Type::DoubleTyID:
241 }
242 break;
243 }
244 }
245}
246
247unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
249 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
250
251 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
252 unsigned RegNum = RegMap[Reg];
253
254 // Encode the register class in the upper 4 bits
255 // Must be kept in sync with NVPTXInstPrinter::printRegName
256 unsigned Ret = 0;
257 if (RC == &NVPTX::B1RegClass) {
258 Ret = (1 << 28);
259 } else if (RC == &NVPTX::B16RegClass) {
260 Ret = (2 << 28);
261 } else if (RC == &NVPTX::B32RegClass) {
262 Ret = (3 << 28);
263 } else if (RC == &NVPTX::B64RegClass) {
264 Ret = (4 << 28);
265 } else if (RC == &NVPTX::B128RegClass) {
266 Ret = (7 << 28);
267 } else {
268 report_fatal_error("Bad register class");
269 }
270
271 // Insert the vreg number
272 Ret |= (RegNum & 0x0FFFFFFF);
273 return Ret;
274 } else {
275 // Some special-use registers are actually physical registers.
276 // Encode this as the register class ID of 0 and the real register ID.
277 return Reg & 0x0FFFFFFF;
278 }
279}
280
281MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
282 const MCExpr *Expr;
283 Expr = MCSymbolRefExpr::create(Symbol, OutContext);
284 return MCOperand::createExpr(Expr);
285}
286
287void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
288 const DataLayout &DL = getDataLayout();
289 const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
290 const auto *TLI = cast<NVPTXTargetLowering>(STI.getTargetLowering());
291
292 Type *Ty = F->getReturnType();
293 if (Ty->getTypeID() == Type::VoidTyID)
294 return;
295 O << " (";
296
297 auto PrintScalarRetVal = [&](unsigned Size) {
298 O << ".param .b" << promoteScalarArgumentSize(Size) << " func_retval0";
299 };
300 if (shouldPassAsArray(Ty)) {
301 const unsigned TotalSize = DL.getTypeAllocSize(Ty);
302 const Align RetAlignment =
303 getPTXParamAlign(F, Ty, AttributeList::ReturnIndex, DL);
304 O << ".param .align " << RetAlignment.value() << " .b8 func_retval0["
305 << TotalSize << "]";
306 } else if (Ty->isFloatingPointTy()) {
307 PrintScalarRetVal(Ty->getPrimitiveSizeInBits());
308 } else if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
309 PrintScalarRetVal(ITy->getBitWidth());
310 } else if (isa<PointerType>(Ty)) {
311 PrintScalarRetVal(TLI->getPointerTy(DL).getSizeInBits());
312 } else
313 llvm_unreachable("Unknown return type");
314 O << ") ";
315}
316
317void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
318 raw_ostream &O) {
319 const Function &F = MF.getFunction();
320 printReturnValStr(&F, O);
321}
322
323// Return true if MBB is the header of a loop marked with
324// llvm.loop.unroll.disable or llvm.loop.unroll.count=1.
325bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
326 const MachineBasicBlock &MBB) const {
327 MachineLoopInfo &LI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
328 // We insert .pragma "nounroll" only to the loop header.
329 if (!LI.isLoopHeader(&MBB))
330 return false;
331
332 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
333 // we iterate through each back edge of the loop with header MBB, and check
334 // whether its metadata contains llvm.loop.unroll.disable.
335 for (const MachineBasicBlock *PMBB : MBB.predecessors()) {
336 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
337 // Edges from other loops to MBB are not back edges.
338 continue;
339 }
340 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
341 if (MDNode *LoopID =
342 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
343 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
344 return true;
345 if (MDNode *UnrollCountMD =
346 GetUnrollMetadata(LoopID, "llvm.loop.unroll.count")) {
347 if (mdconst::extract<ConstantInt>(UnrollCountMD->getOperand(1))
348 ->isOne())
349 return true;
350 }
351 }
352 }
353 }
354 return false;
355}
356
357void NVPTXAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
359 if (isLoopHeaderOfNoUnroll(MBB))
360 OutStreamer->emitRawText(StringRef("\t.pragma \"nounroll\";\n"));
361}
362
364 SmallString<128> Str;
365 raw_svector_ostream O(Str);
366
367 if (!GlobalsEmitted) {
368 emitGlobals(*MF->getFunction().getParent());
369 GlobalsEmitted = true;
370 }
371
372 // Set up
373 MRI = &MF->getRegInfo();
374 F = &MF->getFunction();
375 emitLinkageDirective(F, O);
376 if (isKernelFunction(*F))
377 O << ".entry ";
378 else {
379 O << ".func ";
380 printReturnValStr(*MF, O);
381 }
382
383 CurrentFnSym->print(O, MAI);
384
385 emitFunctionParamList(F, O);
386 O << "\n";
387
388 if (isKernelFunction(*F))
389 emitKernelFunctionDirectives(*F, O);
390
392 O << ".noreturn";
393
394 OutStreamer->emitRawText(O.str());
395
396 VRegMapping.clear();
397 // Emit open brace for function body.
398 OutStreamer->emitRawText(StringRef("{\n"));
399 setAndEmitFunctionVirtualRegisters(*MF);
400 encodeDebugInfoRegisterNumbers(*MF);
401 // Emit initial .loc debug directive for correct relocation symbol data.
403}
404
406 bool Result = AsmPrinter::runOnMachineFunction(F);
407 // Emit closing brace for the body of function F.
408 // The closing brace must be emitted here because we need to emit additional
409 // debug labels/data after the last basic block.
410 // We need to emit the closing brace here because we don't have function that
411 // finished emission of the function body.
412 OutStreamer->emitRawText(StringRef("}\n"));
413 return Result;
414}
415
418 raw_svector_ostream O(Str);
419 emitDemotedVars(&MF->getFunction(), O);
420 OutStreamer->emitRawText(O.str());
421}
422
424 VRegMapping.clear();
425}
426
430 return OutContext.getOrCreateSymbol(Str);
431}
432
433void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
434 Register RegNo = MI->getOperand(0).getReg();
435 if (RegNo.isVirtual()) {
436 OutStreamer->AddComment(Twine("implicit-def: ") +
438 } else {
439 const NVPTXSubtarget &STI = MI->getMF()->getSubtarget<NVPTXSubtarget>();
440 OutStreamer->AddComment(Twine("implicit-def: ") +
441 STI.getRegisterInfo()->getName(RegNo));
442 }
443 OutStreamer->addBlankLine();
444}
445
446void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
447 raw_ostream &O) const {
448 // If the NVVM IR has some of reqntid* specified, then output
449 // the reqntid directive, and set the unspecified ones to 1.
450 // If none of Reqntid* is specified, don't output reqntid directive.
451 const auto ReqNTID = getReqNTID(F);
452 if (!ReqNTID.empty())
453 O << formatv(".reqntid {0:$[, ]}\n",
455
456 const auto MaxNTID = getMaxNTID(F);
457 if (!MaxNTID.empty())
458 O << formatv(".maxntid {0:$[, ]}\n",
460
461 if (const auto Mincta = getMinCTASm(F))
462 O << ".minnctapersm " << *Mincta << "\n";
463
464 if (const auto Maxnreg = getMaxNReg(F))
465 O << ".maxnreg " << *Maxnreg << "\n";
466
467 // .maxclusterrank directive requires SM_90 or higher, make sure that we
468 // filter it out for lower SM versions, as it causes a hard ptxas crash.
469 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
470 const NVPTXSubtarget *STI = &NTM.getSubtarget<NVPTXSubtarget>(F);
471
472 if (STI->getSmVersion() >= 90) {
473 const auto ClusterDim = getClusterDim(F);
475
476 if (!ClusterDim.empty()) {
477
478 if (!BlocksAreClusters)
479 O << ".explicitcluster\n";
480
481 if (ClusterDim[0] != 0) {
482 assert(llvm::all_of(ClusterDim, not_equal_to(0)) &&
483 "cluster_dim_x != 0 implies cluster_dim_y and cluster_dim_z "
484 "should be non-zero as well");
485
486 O << formatv(".reqnctapercluster {0:$[, ]}\n",
488 } else {
489 assert(llvm::all_of(ClusterDim, equal_to(0)) &&
490 "cluster_dim_x == 0 implies cluster_dim_y and cluster_dim_z "
491 "should be 0 as well");
492 }
493 }
494
495 if (BlocksAreClusters) {
496 LLVMContext &Ctx = F.getContext();
497 if (ReqNTID.empty() || ClusterDim.empty())
498 Ctx.diagnose(DiagnosticInfoUnsupported(
499 F, "blocksareclusters requires reqntid and cluster_dim attributes",
500 F.getSubprogram()));
501 else if (STI->getPTXVersion() < 90)
502 Ctx.diagnose(DiagnosticInfoUnsupported(
503 F, "blocksareclusters requires PTX version >= 9.0",
504 F.getSubprogram()));
505 else
506 O << ".blocksareclusters\n";
507 }
508
509 if (const auto Maxclusterrank = getMaxClusterRank(F))
510 O << ".maxclusterrank " << *Maxclusterrank << "\n";
511 }
512}
513
514std::string NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
515 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
516
517 std::string Name;
518 raw_string_ostream NameStr(Name);
519
520 VRegRCMap::const_iterator I = VRegMapping.find(RC);
521 assert(I != VRegMapping.end() && "Bad register class");
522 const DenseMap<unsigned, unsigned> &RegMap = I->second;
523
524 VRegMap::const_iterator VI = RegMap.find(Reg);
525 assert(VI != RegMap.end() && "Bad virtual register");
526 unsigned MappedVR = VI->second;
527
528 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
529
530 return Name;
531}
532
533void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
534 raw_ostream &O) {
535 O << getVirtualRegisterName(vr);
536}
537
538void NVPTXAsmPrinter::emitAliasDeclaration(const GlobalAlias *GA,
539 raw_ostream &O) {
541 if (!F || isKernelFunction(*F) || F->isDeclaration())
543 "NVPTX aliasee must be a non-kernel function definition");
544
545 if (GA->hasLinkOnceLinkage() || GA->hasWeakLinkage() ||
547 report_fatal_error("NVPTX aliasee must not be '.weak'");
548
549 emitDeclarationWithName(F, getSymbol(GA), O);
550}
551
552void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
553 emitDeclarationWithName(F, getSymbol(F), O);
554}
555
556void NVPTXAsmPrinter::emitDeclarationWithName(const Function *F, MCSymbol *S,
557 raw_ostream &O) {
558 emitLinkageDirective(F, O);
559 if (isKernelFunction(*F))
560 O << ".entry ";
561 else
562 O << ".func ";
563 printReturnValStr(F, O);
564 S->print(O, MAI);
565 O << "\n";
566 emitFunctionParamList(F, O);
567 O << "\n";
569 O << ".noreturn";
570 O << ";\n";
571}
572
573static bool usedInGlobalVarDef(const Constant *C) {
574 if (!C)
575 return false;
576
578 return GV->getName() != "llvm.used";
579
580 for (const User *U : C->users())
581 if (const Constant *C = dyn_cast<Constant>(U))
583 return true;
584
585 return false;
586}
587
588static bool usedInOneFunc(const User *U, Function const *&OneFunc) {
589 if (const GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(U))
590 if (OtherGV->getName() == "llvm.used")
591 return true;
592
593 if (const Instruction *I = dyn_cast<Instruction>(U)) {
594 if (const Function *CurFunc = I->getFunction()) {
595 if (OneFunc && (CurFunc != OneFunc))
596 return false;
597 OneFunc = CurFunc;
598 return true;
599 }
600 return false;
601 }
602
603 for (const User *UU : U->users())
604 if (!usedInOneFunc(UU, OneFunc))
605 return false;
606
607 return true;
608}
609
610/* Find out if a global variable can be demoted to local scope.
611 * Currently, this is valid for CUDA shared variables, which have local
612 * scope and global lifetime. So the conditions to check are :
613 * 1. Is the global variable in shared address space?
614 * 2. Does it have local linkage?
615 * 3. Is the global variable referenced only in one function?
616 */
617static bool canDemoteGlobalVar(const GlobalVariable *GV, Function const *&f) {
618 if (!GV->hasLocalLinkage())
619 return false;
621 return false;
622
623 const Function *oneFunc = nullptr;
624
625 bool flag = usedInOneFunc(GV, oneFunc);
626 if (!flag)
627 return false;
628 if (!oneFunc)
629 return false;
630 f = oneFunc;
631 return true;
632}
633
634static bool useFuncSeen(const Constant *C,
635 const SmallPtrSetImpl<const Function *> &SeenSet) {
636 for (const User *U : C->users()) {
637 if (const Constant *cu = dyn_cast<Constant>(U)) {
638 if (useFuncSeen(cu, SeenSet))
639 return true;
640 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
641 if (const Function *Caller = I->getFunction())
642 if (SeenSet.contains(Caller))
643 return true;
644 }
645 }
646 return false;
647}
648
649void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
650 SmallPtrSet<const Function *, 32> SeenSet;
651 for (const Function &F : M) {
652 if (F.getAttributes().hasFnAttr("nvptx-libcall-callee")) {
653 emitDeclaration(&F, O);
654 continue;
655 }
656
657 if (F.isDeclaration()) {
658 if (F.use_empty())
659 continue;
660 if (F.getIntrinsicID())
661 continue;
662 // An unrecognized intrinsic would produce an invalid PTX declaration. Let
663 // the user know that, and skip it.
664 if (F.isIntrinsic()) {
665 LLVMContext &Ctx = F.getContext();
666 Ctx.diagnose(DiagnosticInfoUnsupported(
667 F, "unknown intrinsic '" + F.getName() +
668 "' cannot be lowered by the NVPTX backend"));
669 continue;
670 }
671 emitDeclaration(&F, O);
672 continue;
673 }
674 for (const User *U : F.users()) {
675 if (const Constant *C = dyn_cast<Constant>(U)) {
676 if (usedInGlobalVarDef(C)) {
677 // The use is in the initialization of a global variable
678 // that is a function pointer, so print a declaration
679 // for the original function
680 emitDeclaration(&F, O);
681 break;
682 }
683 // Emit a declaration of this function if the function that
684 // uses this constant expr has already been seen.
685 if (useFuncSeen(C, SeenSet)) {
686 emitDeclaration(&F, O);
687 break;
688 }
689 }
690
691 if (!isa<Instruction>(U))
692 continue;
693 const Function *Caller = cast<Instruction>(U)->getFunction();
694 if (!Caller)
695 continue;
696
697 // If a caller has already been seen, then the caller is
698 // appearing in the module before the callee. so print out
699 // a declaration for the callee.
700 if (SeenSet.contains(Caller)) {
701 emitDeclaration(&F, O);
702 break;
703 }
704 }
705 SeenSet.insert(&F);
706 }
707 for (const GlobalAlias &GA : M.aliases())
708 emitAliasDeclaration(&GA, O);
709}
710
711void NVPTXAsmPrinter::emitStartOfAsmFile(Module &M) {
712 // Construct a default subtarget off of the TargetMachine defaults. The
713 // rest of NVPTX isn't friendly to change subtargets per function and
714 // so the default TargetMachine will have all of the options.
715 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
716 const NVPTXSubtarget *STI = NTM.getSubtargetImpl();
717
718 // Emit header before any dwarf directives are emitted below.
719 emitHeader(M, *STI);
720}
721
722/// Create NVPTX-specific DwarfDebug handler.
726
728 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
729 const NVPTXSubtarget &STI = *NTM.getSubtargetImpl();
730 if (M.alias_size() && (STI.getPTXVersion() < 63 || STI.getSmVersion() < 30))
731 report_fatal_error(".alias requires PTX version >= 6.3 and sm_30");
732
733 // We need to call the parent's one explicitly.
734 bool Result = AsmPrinter::doInitialization(M);
735
736 GlobalsEmitted = false;
737
738 return Result;
739}
740
741void NVPTXAsmPrinter::emitGlobals(const Module &M) {
742 SmallString<128> Str2;
743 raw_svector_ostream OS2(Str2);
744
745 emitDeclarations(M, OS2);
746
747 // As ptxas does not support forward references of globals, we need to first
748 // sort the list of module-level globals in def-use order. We visit each
749 // global variable in order, and ensure that we emit it *after* its dependent
750 // globals. We use a little extra memory maintaining both a set and a list to
751 // have fast searches while maintaining a strict ordering.
755
756 // Visit each global variable, in order
757 for (const GlobalVariable &I : M.globals())
758 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
759
760 assert(GVVisited.size() == M.global_size() && "Missed a global variable");
761 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
762
763 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
764 const NVPTXSubtarget &STI = *NTM.getSubtargetImpl();
765
766 // Print out module-level global variables in proper order
767 for (const GlobalVariable *GV : Globals)
768 printModuleLevelGV(GV, OS2, /*ProcessDemoted=*/false, STI);
769
770 OS2 << '\n';
771
772 OutStreamer->emitRawText(OS2.str());
773}
774
775void NVPTXAsmPrinter::emitGlobalAlias(const Module &M, const GlobalAlias &GA) {
777 raw_svector_ostream OS(Str);
778
779 MCSymbol *Name = getSymbol(&GA);
780
781 OS << ".alias " << Name->getName() << ", " << GA.getAliaseeObject()->getName()
782 << ";\n";
783
784 OutStreamer->emitRawText(OS.str());
785}
786
787NVPTXTargetStreamer *NVPTXAsmPrinter::getTargetStreamer() const {
788 return static_cast<NVPTXTargetStreamer *>(OutStreamer->getTargetStreamer());
789}
790
791static bool hasFullDebugInfo(Module &M) {
792 for (DICompileUnit *CU : M.debug_compile_units()) {
793 switch(CU->getEmissionKind()) {
796 break;
799 return true;
800 }
801 }
802
803 return false;
804}
805
806void NVPTXAsmPrinter::emitHeader(Module &M, const NVPTXSubtarget &STI) {
807 auto *TS = getTargetStreamer();
808
809 TS->emitBanner();
810
811 const unsigned PTXVersion = STI.getPTXVersion();
812 TS->emitVersionDirective(PTXVersion);
813
814 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
815 bool TexModeIndependent = NTM.getDrvInterface() == NVPTX::NVCL;
816
817 TS->emitTargetDirective(STI.getTargetName(), TexModeIndependent,
819 TS->emitAddressSizeDirective(M.getDataLayout().getPointerSizeInBits());
820}
821
823 // If we did not emit any functions, then the global declarations have not
824 // yet been emitted.
825 if (!GlobalsEmitted) {
826 emitGlobals(M);
827 GlobalsEmitted = true;
828 }
829
830 // call doFinalization
831 bool ret = AsmPrinter::doFinalization(M);
832
834
835 auto *TS =
836 static_cast<NVPTXTargetStreamer *>(OutStreamer->getTargetStreamer());
837 // Close the last emitted section
838 if (hasDebugInfo()) {
839 TS->closeLastSection();
840 // Emit empty .debug_macinfo section for better support of the empty files.
841 OutStreamer->emitRawText("\t.section\t.debug_macinfo\t{\t}");
842 }
843
844 // Output last DWARF .file directives, if any.
846
847 return ret;
848}
849
850// This function emits appropriate linkage directives for
851// functions and global variables.
852//
853// extern function declaration -> .extern
854// extern function definition -> .visible
855// external global variable with init -> .visible
856// external without init -> .extern
857// appending -> not allowed, assert.
858// for any linkage other than
859// internal, private, linker_private,
860// linker_private_weak, linker_private_weak_def_auto,
861// we emit -> .weak.
862
863void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
864 raw_ostream &O) {
865 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
866 if (V->hasExternalLinkage()) {
867 if (const auto *GVar = dyn_cast<GlobalVariable>(V))
868 O << (GVar->hasInitializer() ? ".visible " : ".extern ");
869 else if (V->isDeclaration())
870 O << ".extern ";
871 else
872 O << ".visible ";
873 } else if (V->hasAppendingLinkage()) {
874 report_fatal_error("Symbol '" + (V->hasName() ? V->getName() : "") +
875 "' has unsupported appending linkage type");
876 } else if (!V->hasInternalLinkage() && !V->hasPrivateLinkage()) {
877 O << ".weak ";
878 }
879 }
880}
881
882void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
883 raw_ostream &O, bool ProcessDemoted,
884 const NVPTXSubtarget &STI) {
885 // Skip meta data
886 if (GVar->hasSection())
887 if (GVar->getSection() == "llvm.metadata")
888 return;
889
890 // Skip LLVM intrinsic global variables
891 if (GVar->getName().starts_with("llvm.") ||
892 GVar->getName().starts_with("nvvm."))
893 return;
894
895 const DataLayout &DL = getDataLayout();
896
897 // GlobalVariables are always constant pointers themselves.
898 Type *ETy = GVar->getValueType();
899
900 if (GVar->hasExternalLinkage()) {
901 if (GVar->hasInitializer())
902 O << ".visible ";
903 else
904 O << ".extern ";
905 } else if (STI.getPTXVersion() >= 50 && GVar->hasCommonLinkage() &&
907 O << ".common ";
908 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
910 GVar->hasCommonLinkage()) {
911 O << ".weak ";
912 }
913
914 const PTXOpaqueType OpaqueType = getPTXOpaqueType(*GVar);
915
916 if (OpaqueType == PTXOpaqueType::Texture) {
917 O << ".global .texref " << getTextureName(*GVar) << ";\n";
918 return;
919 }
920
921 if (OpaqueType == PTXOpaqueType::Surface) {
922 O << ".global .surfref " << getSurfaceName(*GVar) << ";\n";
923 return;
924 }
925
926 if (GVar->isDeclaration()) {
927 // (extern) declarations, no definition or initializer
928 // Currently the only known declaration is for an automatic __local
929 // (.shared) promoted to global.
930 emitPTXGlobalVariable(GVar, O, STI);
931 O << ";\n";
932 return;
933 }
934
935 if (OpaqueType == PTXOpaqueType::Sampler) {
936 O << ".global .samplerref " << getSamplerName(*GVar);
937
938 const Constant *Initializer = nullptr;
939 if (GVar->hasInitializer())
940 Initializer = GVar->getInitializer();
941 const ConstantInt *CI = nullptr;
942 if (Initializer)
943 CI = dyn_cast<ConstantInt>(Initializer);
944 if (CI) {
945 unsigned sample = CI->getZExtValue();
946
947 O << " = { ";
948
949 for (int i = 0,
950 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
951 i < 3; i++) {
952 O << "addr_mode_" << i << " = ";
953 switch (addr) {
954 case 0:
955 O << "wrap";
956 break;
957 case 1:
958 O << "clamp_to_border";
959 break;
960 case 2:
961 O << "clamp_to_edge";
962 break;
963 case 3:
964 O << "wrap";
965 break;
966 case 4:
967 O << "mirror";
968 break;
969 }
970 O << ", ";
971 }
972 O << "filter_mode = ";
973 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
974 case 0:
975 O << "nearest";
976 break;
977 case 1:
978 O << "linear";
979 break;
980 case 2:
981 llvm_unreachable("Anisotropic filtering is not supported");
982 default:
983 O << "nearest";
984 break;
985 }
986 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
987 O << ", force_unnormalized_coords = 1";
988 }
989 O << " }";
990 }
991
992 O << ";\n";
993 return;
994 }
995
996 if (GVar->hasPrivateLinkage()) {
997 if (GVar->getName().starts_with("unrollpragma"))
998 return;
999
1000 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1001 if (GVar->getName().starts_with("filename"))
1002 return;
1003 if (GVar->use_empty())
1004 return;
1005 }
1006
1007 const Function *DemotedFunc = nullptr;
1008 if (!ProcessDemoted && canDemoteGlobalVar(GVar, DemotedFunc)) {
1009 O << "// " << GVar->getName() << " has been demoted\n";
1010 localDecls[DemotedFunc].push_back(GVar);
1011 return;
1012 }
1013
1014 O << ".";
1015 emitPTXAddressSpace(GVar->getAddressSpace(), O);
1016
1017 if (isManaged(*GVar)) {
1018 if (STI.getPTXVersion() < 40 || STI.getSmVersion() < 30)
1020 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1021 O << " .attribute(.managed)";
1022 }
1023
1024 O << " .align "
1025 << GVar->getAlign().value_or(DL.getPrefTypeAlign(ETy)).value();
1026
1027 if (ETy->isPointerTy() || ((ETy->isIntegerTy() || ETy->isFloatingPointTy()) &&
1028 ETy->getScalarSizeInBits() <= 64)) {
1029 O << " .";
1030 // Special case: ABI requires that we use .u8 for predicates
1031 if (ETy->isIntegerTy(1))
1032 O << "u8";
1033 else
1034 O << getPTXFundamentalTypeStr(ETy, false);
1035 O << " ";
1036 getSymbol(GVar)->print(O, MAI);
1037
1038 // Ptx allows variable initilization only for constant and global state
1039 // spaces.
1040 if (GVar->hasInitializer()) {
1041 if ((GVar->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1042 (GVar->getAddressSpace() == ADDRESS_SPACE_CONST)) {
1043 const Constant *Initializer = GVar->getInitializer();
1044 // 'undef' is treated as there is no value specified.
1045 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1046 O << " = ";
1047 printScalarConstant(Initializer, O);
1048 }
1049 } else {
1050 // The frontend adds zero-initializer to device and constant variables
1051 // that don't have an initial value, and UndefValue to shared
1052 // variables, so skip warning for this case.
1053 if (!GVar->getInitializer()->isNullValue() &&
1054 !isa<UndefValue>(GVar->getInitializer())) {
1055 report_fatal_error("initial value of '" + GVar->getName() +
1056 "' is not allowed in addrspace(" +
1057 Twine(GVar->getAddressSpace()) + ")");
1058 }
1059 }
1060 }
1061 } else {
1062 // Although PTX has direct support for struct type and array type and
1063 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1064 // targets that support these high level field accesses. Structs, arrays
1065 // and vectors are lowered into arrays of bytes.
1066 switch (ETy->getTypeID()) {
1067 case Type::IntegerTyID: // Integers larger than 64 bits
1068 case Type::FP128TyID:
1069 case Type::StructTyID:
1070 case Type::ArrayTyID:
1071 case Type::FixedVectorTyID: {
1072 const uint64_t ElementSize = DL.getTypeStoreSize(ETy);
1073 // Ptx allows variable initilization only for constant and
1074 // global state spaces.
1075 if (((GVar->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1076 (GVar->getAddressSpace() == ADDRESS_SPACE_CONST)) &&
1077 GVar->hasInitializer()) {
1078 const Constant *Initializer = GVar->getInitializer();
1079 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1080 AggBuffer aggBuffer(ElementSize, *this);
1081 bufferAggregateConstant(Initializer, &aggBuffer);
1082 if (aggBuffer.numSymbols()) {
1083 const unsigned int ptrSize = MAI.getCodePointerSize();
1084 if (ElementSize % ptrSize ||
1085 !aggBuffer.allSymbolsAligned(ptrSize)) {
1086 // Print in bytes and use the mask() operator for pointers.
1087 if (!STI.hasMaskOperator())
1089 "initialized packed aggregate with pointers '" +
1090 GVar->getName() +
1091 "' requires at least PTX ISA version 7.1");
1092 O << " .u8 ";
1093 getSymbol(GVar)->print(O, MAI);
1094 O << "[" << ElementSize << "] = {";
1095 aggBuffer.printBytes(O);
1096 O << "}";
1097 } else {
1098 O << " .u" << ptrSize * 8 << " ";
1099 getSymbol(GVar)->print(O, MAI);
1100 O << "[" << ElementSize / ptrSize << "] = {";
1101 aggBuffer.printWords(O);
1102 O << "}";
1103 }
1104 } else {
1105 O << " .b8 ";
1106 getSymbol(GVar)->print(O, MAI);
1107 O << "[" << ElementSize << "] = {";
1108 aggBuffer.printBytes(O);
1109 O << "}";
1110 }
1111 } else {
1112 O << " .b8 ";
1113 getSymbol(GVar)->print(O, MAI);
1114 if (ElementSize)
1115 O << "[" << ElementSize << "]";
1116 }
1117 } else {
1118 O << " .b8 ";
1119 getSymbol(GVar)->print(O, MAI);
1120 if (ElementSize)
1121 O << "[" << ElementSize << "]";
1122 }
1123 break;
1124 }
1125 default:
1126 llvm_unreachable("type not supported yet");
1127 }
1128 }
1129 O << ";\n";
1130}
1131
1132void NVPTXAsmPrinter::AggBuffer::printSymbol(unsigned nSym, raw_ostream &os) {
1133 const Value *v = Symbols[nSym];
1134 const Value *v0 = SymbolsBeforeStripping[nSym];
1135 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1136 MCSymbol *Name = AP.getSymbol(GVar);
1138 // Is v0 a generic pointer?
1139 bool isGenericPointer = PTy && PTy->getAddressSpace() == 0;
1140 if (EmitGeneric && isGenericPointer && !isa<Function>(v)) {
1141 os << "generic(";
1142 Name->print(os, AP.MAI);
1143 os << ")";
1144 } else {
1145 Name->print(os, AP.MAI);
1146 }
1147 } else if (const ConstantExpr *CExpr = dyn_cast<ConstantExpr>(v0)) {
1148 const MCExpr *Expr = AP.lowerConstantForGV(CExpr, false);
1149 AP.printMCExpr(*Expr, os);
1150 } else
1151 llvm_unreachable("symbol type unknown");
1152}
1153
1154void NVPTXAsmPrinter::AggBuffer::printBytes(raw_ostream &os) {
1155 unsigned int ptrSize = AP.MAI.getCodePointerSize();
1156 // Do not emit trailing zero initializers. They will be zero-initialized by
1157 // ptxas. This saves on both space requirements for the generated PTX and on
1158 // memory use by ptxas. (See:
1159 // https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#global-state-space)
1160 unsigned int InitializerCount = Size;
1161 // TODO: symbols make this harder, but it would still be good to trim trailing
1162 // 0s for aggs with symbols as well.
1163 if (numSymbols() == 0)
1164 while (InitializerCount >= 1 && !buffer[InitializerCount - 1])
1165 InitializerCount--;
1166
1167 symbolPosInBuffer.push_back(InitializerCount);
1168 unsigned int nSym = 0;
1169 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1170 for (unsigned int pos = 0; pos < InitializerCount;) {
1171 if (pos)
1172 os << ", ";
1173 if (pos != nextSymbolPos) {
1174 os << (unsigned int)buffer[pos];
1175 ++pos;
1176 continue;
1177 }
1178 // Generate a per-byte mask() operator for the symbol, which looks like:
1179 // .global .u8 addr[] = {0xFF(foo), 0xFF00(foo), 0xFF0000(foo), ...};
1180 // See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#initializers
1181 std::string symText;
1182 llvm::raw_string_ostream oss(symText);
1183 printSymbol(nSym, oss);
1184 for (unsigned i = 0; i < ptrSize; ++i) {
1185 if (i)
1186 os << ", ";
1187 llvm::write_hex(os, 0xFFULL << i * 8, HexPrintStyle::PrefixUpper);
1188 os << "(" << symText << ")";
1189 }
1190 pos += ptrSize;
1191 nextSymbolPos = symbolPosInBuffer[++nSym];
1192 assert(nextSymbolPos >= pos);
1193 }
1194}
1195
1196void NVPTXAsmPrinter::AggBuffer::printWords(raw_ostream &os) {
1197 unsigned int ptrSize = AP.MAI.getCodePointerSize();
1198 symbolPosInBuffer.push_back(Size);
1199 unsigned int nSym = 0;
1200 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1201 assert(nextSymbolPos % ptrSize == 0);
1202 for (unsigned int pos = 0; pos < Size; pos += ptrSize) {
1203 if (pos)
1204 os << ", ";
1205 if (pos == nextSymbolPos) {
1206 printSymbol(nSym, os);
1207 nextSymbolPos = symbolPosInBuffer[++nSym];
1208 assert(nextSymbolPos % ptrSize == 0);
1209 assert(nextSymbolPos >= pos + ptrSize);
1210 } else if (ptrSize == 4)
1211 os << support::endian::read32le(&buffer[pos]);
1212 else
1213 os << support::endian::read64le(&buffer[pos]);
1214 }
1215}
1216
1217void NVPTXAsmPrinter::emitDemotedVars(const Function *F, raw_ostream &O) {
1218 auto It = localDecls.find(F);
1219 if (It == localDecls.end())
1220 return;
1221
1222 ArrayRef<const GlobalVariable *> GVars = It->second;
1223
1224 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
1225 const NVPTXSubtarget &STI = *NTM.getSubtargetImpl();
1226
1227 for (const GlobalVariable *GV : GVars) {
1228 O << "\t// demoted variable\n\t";
1229 printModuleLevelGV(GV, O, /*processDemoted=*/true, STI);
1230 }
1231}
1232
1233void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1234 raw_ostream &O) const {
1235 switch (AddressSpace) {
1237 O << "local";
1238 break;
1240 O << "global";
1241 break;
1243 O << "const";
1244 break;
1246 O << "shared";
1247 break;
1248 default:
1249 report_fatal_error("Bad address space found while emitting PTX: " +
1250 llvm::Twine(AddressSpace));
1251 break;
1252 }
1253}
1254
1255std::string
1256NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
1257 switch (Ty->getTypeID()) {
1258 case Type::IntegerTyID: {
1259 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1260 if (NumBits == 1)
1261 return "pred";
1262 if (NumBits <= 64) {
1263 std::string name = "u";
1264 return name + utostr(NumBits);
1265 }
1266 llvm_unreachable("Integer too large");
1267 break;
1268 }
1269 case Type::BFloatTyID:
1270 case Type::HalfTyID:
1271 // fp16 and bf16 are stored as .b16 for compatibility with pre-sm_53
1272 // PTX assembly.
1273 return "b16";
1274 case Type::FloatTyID:
1275 return "f32";
1276 case Type::DoubleTyID:
1277 return "f64";
1278 case Type::PointerTyID: {
1279 unsigned PtrSize = TM.getPointerSizeInBits(Ty->getPointerAddressSpace());
1280 assert((PtrSize == 64 || PtrSize == 32) && "Unexpected pointer size");
1281
1282 if (PtrSize == 64)
1283 if (useB4PTR)
1284 return "b64";
1285 else
1286 return "u64";
1287 else if (useB4PTR)
1288 return "b32";
1289 else
1290 return "u32";
1291 }
1292 default:
1293 break;
1294 }
1295 llvm_unreachable("unexpected type");
1296}
1297
1298void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1299 raw_ostream &O,
1300 const NVPTXSubtarget &STI) {
1301 const DataLayout &DL = getDataLayout();
1302
1303 // GlobalVariables are always constant pointers themselves.
1304 Type *ETy = GVar->getValueType();
1305
1306 O << ".";
1307 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
1308 if (isManaged(*GVar)) {
1309 if (STI.getPTXVersion() < 40 || STI.getSmVersion() < 30)
1311 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1312
1313 O << " .attribute(.managed)";
1314 }
1315 O << " .align "
1316 << GVar->getAlign().value_or(DL.getPrefTypeAlign(ETy)).value();
1317
1318 // Special case for i128/fp128
1319 if (ETy->getScalarSizeInBits() == 128) {
1320 O << " .b8 ";
1321 getSymbol(GVar)->print(O, MAI);
1322 O << "[16]";
1323 return;
1324 }
1325
1326 if (ETy->isFloatingPointTy() || ETy->isIntOrPtrTy()) {
1327 O << " ." << getPTXFundamentalTypeStr(ETy) << " ";
1328 getSymbol(GVar)->print(O, MAI);
1329 return;
1330 }
1331
1332 int64_t ElementSize = 0;
1333
1334 // Although PTX has direct support for struct type and array type and LLVM IR
1335 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1336 // support these high level field accesses. Structs and arrays are lowered
1337 // into arrays of bytes.
1338 switch (ETy->getTypeID()) {
1339 case Type::StructTyID:
1340 case Type::ArrayTyID:
1342 ElementSize = DL.getTypeStoreSize(ETy);
1343 O << " .b8 ";
1344 getSymbol(GVar)->print(O, MAI);
1345 O << "[";
1346 if (ElementSize) {
1347 O << ElementSize;
1348 }
1349 O << "]";
1350 break;
1351 default:
1352 llvm_unreachable("type not supported yet");
1353 }
1354}
1355
1356void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1357 const DataLayout &DL = getDataLayout();
1358 const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
1359 const auto *TLI = cast<NVPTXTargetLowering>(STI.getTargetLowering());
1360 const NVPTXMachineFunctionInfo *MFI =
1361 MF ? MF->getInfo<NVPTXMachineFunctionInfo>() : nullptr;
1362
1363 const bool IsKernelFunc = isKernelFunction(*F);
1364
1365 assert(!F->isVarArg() && "VarArg functions lowered in ExpandVariadics");
1366
1367 if (F->arg_empty()) {
1368 O << "()";
1369 return;
1370 }
1371
1372 O << "(\n";
1373
1374 auto EmitParam = [&](const Argument &Arg) {
1375 Type *Ty = Arg.getType();
1376 const std::string ParamSym = TLI->getParamName(F, Arg.getArgNo());
1377
1378 // Handle image/sampler parameters
1379 if (IsKernelFunc) {
1380 const PTXOpaqueType ArgOpaqueType = getPTXOpaqueType(Arg);
1381 if (ArgOpaqueType != PTXOpaqueType::None) {
1382 const bool EmitImgPtr = !MFI || !MFI->checkImageHandleSymbol(ParamSym);
1383 O << "\t.param ";
1384 if (EmitImgPtr)
1385 O << ".u64 .ptr ";
1386
1387 switch (ArgOpaqueType) {
1389 O << ".samplerref ";
1390 break;
1392 O << ".texref ";
1393 break;
1395 O << ".surfref ";
1396 break;
1398 llvm_unreachable("handled above");
1399 }
1400 O << ParamSym;
1401 return;
1402 }
1403 }
1404
1405 if (Arg.hasByValAttr()) {
1406 // param has byVal attribute.
1407 Type *ETy = Arg.getParamByValType();
1408 assert(ETy && "Param should have byval type");
1409
1410 // Print .param .align <a> .b8 .param[size];
1411 // <a> = optimal alignment for the element type; always multiple of
1412 // PAL.getParamAlignment
1413 // size = typeallocsize of element type
1414 const Align OptimalAlign =
1415 IsKernelFunc
1417 F, ETy, Arg.getArgNo() + AttributeList::FirstArgIndex, DL)
1418 : getDeviceByValParamAlign(F, ETy,
1419 Arg.getParamAlign().valueOrOne(), DL);
1420
1421 O << "\t.param .align " << OptimalAlign.value() << " .b8 " << ParamSym
1422 << "[" << DL.getTypeAllocSize(ETy) << "]";
1423 return;
1424 }
1425
1426 if (shouldPassAsArray(Ty)) {
1427 // Just print .param .align <a> .b8 .param[size];
1428 // <a> = optimal alignment for the element type; always multiple of
1429 // PAL.getParamAlignment
1430 // size = typeallocsize of element type
1431 Align OptimalAlign = getPTXParamAlign(
1432 F, Ty, Arg.getArgNo() + AttributeList::FirstArgIndex, DL);
1433
1434 O << "\t.param .align " << OptimalAlign.value() << " .b8 " << ParamSym
1435 << "[" << DL.getTypeAllocSize(Ty) << "]";
1436
1437 return;
1438 }
1439 // Just a scalar
1440 auto *PTy = dyn_cast<PointerType>(Ty);
1441 unsigned PTySizeInBits = 0;
1442 if (PTy) {
1443 PTySizeInBits =
1444 TLI->getPointerTy(DL, PTy->getAddressSpace()).getSizeInBits();
1445 assert(PTySizeInBits && "Invalid pointer size");
1446 }
1447
1448 if (IsKernelFunc) {
1449 if (PTy) {
1450 O << "\t.param .u" << PTySizeInBits << " .ptr";
1451
1452 switch (PTy->getAddressSpace()) {
1453 default:
1454 break;
1456 O << " .global";
1457 break;
1459 O << " .shared";
1460 break;
1462 O << " .const";
1463 break;
1465 O << " .local";
1466 break;
1467 }
1468
1469 O << " .align " << Arg.getParamAlign().valueOrOne().value() << " "
1470 << ParamSym;
1471 return;
1472 }
1473
1474 // non-pointer scalar to kernel func
1475 O << "\t.param .";
1476 // Special case: predicate operands become .u8 types
1477 if (Ty->isIntegerTy(1))
1478 O << "u8";
1479 else
1480 O << getPTXFundamentalTypeStr(Ty);
1481 O << " " << ParamSym;
1482 return;
1483 }
1484 // Non-kernel function, just print .param .b<size> for ABI
1485 // and .reg .b<size> for non-ABI
1486 unsigned Size;
1487 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
1488 Size = promoteScalarArgumentSize(ITy->getBitWidth());
1489 } else if (PTy) {
1490 assert(PTySizeInBits && "Invalid pointer size");
1491 Size = PTySizeInBits;
1492 } else
1494 O << "\t.param .b" << Size << " " << ParamSym;
1495 };
1496 interleave(F->args(), O, EmitParam, ",\n");
1497
1498 O << "\n)";
1499}
1500
1501void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1502 const MachineFunction &MF) {
1503 SmallString<128> Str;
1504 raw_svector_ostream O(Str);
1505
1506 // Map the global virtual register number to a register class specific
1507 // virtual register number starting from 1 with that class.
1508 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1509
1510 // Emit the Fake Stack Object
1511 const MachineFrameInfo &MFI = MF.getFrameInfo();
1512 int64_t NumBytes = MFI.getStackSize();
1513 if (NumBytes) {
1514 O << "\t.local .align " << MFI.getMaxAlign().value() << " .b8 \t"
1515 << DEPOTNAME << getFunctionNumber() << "[" << NumBytes << "];\n";
1516 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1517 O << "\t.reg .b64 \t%SP;\n"
1518 << "\t.reg .b64 \t%SPL;\n";
1519 } else {
1520 O << "\t.reg .b32 \t%SP;\n"
1521 << "\t.reg .b32 \t%SPL;\n";
1522 }
1523 }
1524
1525 // Go through all virtual registers to establish the mapping between the
1526 // global virtual
1527 // register number and the per class virtual register number.
1528 // We use the per class virtual register number in the ptx output.
1529 for (unsigned I : llvm::seq(MRI->getNumVirtRegs())) {
1531 if (MRI->use_empty(VR) && MRI->def_empty(VR))
1532 continue;
1533 auto &RCRegMap = VRegMapping[MRI->getRegClass(VR)];
1534 RCRegMap[VR] = RCRegMap.size() + 1;
1535 }
1536
1537 // Emit declaration of the virtual registers or 'physical' registers for
1538 // each register class
1539 for (const TargetRegisterClass *RC : TRI->regclasses()) {
1540 const unsigned N = VRegMapping[RC].size();
1541
1542 // Only declare those registers that may be used.
1543 if (N) {
1544 const StringRef RCName = getNVPTXRegClassName(RC);
1545 const StringRef RCStr = getNVPTXRegClassStr(RC);
1546 O << "\t.reg " << RCName << " \t" << RCStr << "<" << (N + 1) << ">;\n";
1547 }
1548 }
1549
1550 OutStreamer->emitRawText(O.str());
1551}
1552
1553/// Translate virtual register numbers in DebugInfo locations to their printed
1554/// encodings, as used by CUDA-GDB.
1555void NVPTXAsmPrinter::encodeDebugInfoRegisterNumbers(
1556 const MachineFunction &MF) {
1557 const NVPTXSubtarget &STI = MF.getSubtarget<NVPTXSubtarget>();
1558 const NVPTXRegisterInfo *registerInfo = STI.getRegisterInfo();
1559
1560 // Clear the old mapping, and add the new one. This mapping is used after the
1561 // printing of the current function is complete, but before the next function
1562 // is printed.
1563 registerInfo->clearDebugRegisterMap();
1564
1565 for (auto &classMap : VRegMapping) {
1566 for (auto &registerMapping : classMap.getSecond()) {
1567 auto reg = registerMapping.getFirst();
1568 registerInfo->addToDebugRegisterMap(reg, getVirtualRegisterName(reg));
1569 }
1570 }
1571}
1572
1573void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp,
1574 raw_ostream &O) const {
1575 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1576 bool ignored;
1577 unsigned int numHex;
1578 const char *lead;
1579
1580 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1581 numHex = 8;
1582 lead = "0f";
1584 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1585 numHex = 16;
1586 lead = "0d";
1588 } else
1589 llvm_unreachable("unsupported fp type");
1590
1591 APInt API = APF.bitcastToAPInt();
1592 O << lead << format_hex_no_prefix(API.getZExtValue(), numHex, /*Upper=*/true);
1593}
1594
1595void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1596 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1597 O << CI->getValue();
1598 return;
1599 }
1600 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1601 printFPConstant(CFP, O);
1602 return;
1603 }
1604 if (isa<ConstantPointerNull>(CPV)) {
1605 O << "0";
1606 return;
1607 }
1608 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1609 const bool IsNonGenericPointer = GVar->getAddressSpace() != 0;
1610 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1611 O << "generic(";
1612 getSymbol(GVar)->print(O, MAI);
1613 O << ")";
1614 } else {
1615 getSymbol(GVar)->print(O, MAI);
1616 }
1617 return;
1618 }
1619 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1620 const MCExpr *E = lowerConstantForGV(cast<Constant>(Cexpr), false);
1621 printMCExpr(*E, O);
1622 return;
1623 }
1624 llvm_unreachable("Not scalar type found in printScalarConstant()");
1625}
1626
1627void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1628 AggBuffer *AggBuffer) {
1629 const DataLayout &DL = getDataLayout();
1630 int AllocSize = DL.getTypeAllocSize(CPV->getType());
1631 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1632 // Non-zero Bytes indicates that we need to zero-fill everything. Otherwise,
1633 // only the space allocated by CPV.
1634 AggBuffer->addZeros(Bytes ? Bytes : AllocSize);
1635 return;
1636 }
1637
1638 // Helper for filling AggBuffer with APInts.
1639 auto AddIntToBuffer = [AggBuffer, Bytes](const APInt &Val) {
1640 size_t NumBytes = (Val.getBitWidth() + 7) / 8;
1641 SmallVector<unsigned char, 16> Buf(NumBytes);
1642 // `extractBitsAsZExtValue` does not allow the extraction of bits beyond the
1643 // input's bit width, and i1 arrays may not have a length that is a multuple
1644 // of 8. We handle the last byte separately, so we never request out of
1645 // bounds bits.
1646 for (unsigned I = 0; I < NumBytes - 1; ++I) {
1647 Buf[I] = Val.extractBitsAsZExtValue(8, I * 8);
1648 }
1649 size_t LastBytePosition = (NumBytes - 1) * 8;
1650 size_t LastByteBits = Val.getBitWidth() - LastBytePosition;
1651 Buf[NumBytes - 1] =
1652 Val.extractBitsAsZExtValue(LastByteBits, LastBytePosition);
1653 AggBuffer->addBytes(Buf.data(), NumBytes, Bytes);
1654 };
1655
1656 switch (CPV->getType()->getTypeID()) {
1657 case Type::IntegerTyID:
1658 if (const auto *CI = dyn_cast<ConstantInt>(CPV)) {
1659 AddIntToBuffer(CI->getValue());
1660 break;
1661 }
1662 if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1663 if (const auto *CI =
1665 AddIntToBuffer(CI->getValue());
1666 break;
1667 }
1668 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1669 Value *V = Cexpr->getOperand(0)->stripPointerCasts();
1670 AggBuffer->addSymbol(V, Cexpr->getOperand(0));
1671 AggBuffer->addZeros(AllocSize);
1672 break;
1673 }
1674 // A symbol-relative integer whose offset is applied outside the
1675 // ptrtoint, e.g. add(ptrtoint(@g), C). It can't fold to a ConstantInt
1676 // because it references a symbol; emit it through lowerConstantForGV, the
1677 // same path scalar symbol-relative integer globals use.
1678 AggBuffer->addSymbol(Cexpr, Cexpr);
1679 AggBuffer->addZeros(AllocSize);
1680 break;
1681 }
1682 llvm_unreachable("unsupported integer const type");
1683 break;
1684
1685 case Type::HalfTyID:
1686 case Type::BFloatTyID:
1687 case Type::FloatTyID:
1688 case Type::DoubleTyID:
1689 AddIntToBuffer(cast<ConstantFP>(CPV)->getValueAPF().bitcastToAPInt());
1690 break;
1691
1692 case Type::PointerTyID: {
1693 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1694 AggBuffer->addSymbol(GVar, GVar);
1695 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1696 const Value *v = Cexpr->stripPointerCasts();
1697 AggBuffer->addSymbol(v, Cexpr);
1698 }
1699 AggBuffer->addZeros(AllocSize);
1700 break;
1701 }
1702
1703 case Type::ArrayTyID:
1705 case Type::StructTyID: {
1707 // bufferAggregateConstant doesn't emit tail-padding, i.e. it writes
1708 // `store_size` bytes, not `alloc_size` bytes. Do it ourselves here.
1709 unsigned StartPos = AggBuffer->getCurpos();
1710 bufferAggregateConstant(CPV, AggBuffer);
1711 unsigned Written = AggBuffer->getCurpos() - StartPos;
1712 unsigned SlotSize = std::max<int>(Bytes, AllocSize);
1713 if (SlotSize > Written)
1714 AggBuffer->addZeros(SlotSize - Written);
1715 } else if (isa<ConstantAggregateZero>(CPV))
1716 AggBuffer->addZeros(Bytes);
1717 else
1718 llvm_unreachable("Unexpected Constant type");
1719 break;
1720 }
1721
1722 default:
1723 llvm_unreachable("unsupported type");
1724 }
1725}
1726
1727void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1728 AggBuffer *aggBuffer) {
1729 const DataLayout &DL = getDataLayout();
1730
1731 auto ExtendBuffer = [](APInt Val, AggBuffer *Buffer) {
1732 unsigned NumBytes = divideCeil(Val.getBitWidth(), 8);
1733 for (unsigned I : llvm::seq(NumBytes)) {
1734 unsigned NumBits = std::min(8u, Val.getBitWidth() - I * 8);
1735 Buffer->addByte(Val.extractBitsAsZExtValue(NumBits, I * 8));
1736 }
1737 };
1738
1739 // Integer or floating point vector splats.
1741 if (auto *VTy = dyn_cast<FixedVectorType>(CPV->getType())) {
1742 for (unsigned I : llvm::seq(VTy->getNumElements()))
1743 bufferLEByte(CPV->getAggregateElement(I), 0, aggBuffer);
1744 return;
1745 }
1746 }
1747
1748 // Integers of arbitrary width
1749 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1750 assert(CI->getType()->isIntegerTy() && "Expected integer constant!");
1751 ExtendBuffer(CI->getValue(), aggBuffer);
1752 return;
1753 }
1754
1755 // f128
1756 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1757 assert(CFP->getType()->isFloatingPointTy() && "Expected fp constant!");
1758 if (CFP->getType()->isFP128Ty()) {
1759 ExtendBuffer(CFP->getValueAPF().bitcastToAPInt(), aggBuffer);
1760 return;
1761 }
1762 }
1763
1764 // Buffer arrays one element at a time.
1765 if (isa<ConstantArray>(CPV)) {
1766 for (const auto &Op : CPV->operands())
1767 bufferLEByte(cast<Constant>(Op), 0, aggBuffer);
1768 return;
1769 }
1770
1771 // Constant vectors
1772 if (const auto *CVec = dyn_cast<ConstantVector>(CPV)) {
1773 bufferAggregateConstVec(CVec, aggBuffer);
1774 return;
1775 }
1776
1777 if (const auto *CDS = dyn_cast<ConstantDataSequential>(CPV)) {
1778 for (unsigned I : llvm::seq(CDS->getNumElements()))
1779 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(I)), 0, aggBuffer);
1780 return;
1781 }
1782
1783 if (isa<ConstantStruct>(CPV)) {
1784 if (CPV->getNumOperands()) {
1785 StructType *ST = cast<StructType>(CPV->getType());
1786 for (unsigned I : llvm::seq(CPV->getNumOperands())) {
1787 int EndOffset = (I + 1 == CPV->getNumOperands())
1788 ? DL.getStructLayout(ST)->getElementOffset(0) +
1789 DL.getTypeAllocSize(ST)
1790 : DL.getStructLayout(ST)->getElementOffset(I + 1);
1791 int Bytes = EndOffset - DL.getStructLayout(ST)->getElementOffset(I);
1792 bufferLEByte(cast<Constant>(CPV->getOperand(I)), Bytes, aggBuffer);
1793 }
1794 }
1795 return;
1796 }
1797 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1798}
1799
1800void NVPTXAsmPrinter::bufferAggregateConstVec(const ConstantVector *CV,
1801 AggBuffer *aggBuffer) {
1802 unsigned NumElems = CV->getType()->getNumElements();
1803 const unsigned BuffSize = aggBuffer->getBufferSize();
1804
1805 // Buffer one element at a time if we have allocated enough buffer space.
1806 if (BuffSize >= NumElems) {
1807 for (const auto &Op : CV->operands())
1808 bufferLEByte(cast<Constant>(Op), 0, aggBuffer);
1809 return;
1810 }
1811
1812 // Sub-byte datatypes will have more elements than bytes allocated for the
1813 // buffer. Merge consecutive elements to form a full byte. We expect that 8 %
1814 // sub-byte-elem-size should be 0 and current expected usage is for i4 (for
1815 // e2m1-fp4 types).
1816 Type *ElemTy = CV->getType()->getElementType();
1817 assert(ElemTy->isIntegerTy() && "Expected integer data type.");
1818 unsigned ElemTySize = ElemTy->getPrimitiveSizeInBits();
1819 assert(ElemTySize < 8 && "Expected sub-byte data type.");
1820 assert(8 % ElemTySize == 0 && "Element type size must evenly divide a byte.");
1821 // Number of elements to merge to form a full byte.
1822 unsigned NumElemsPerByte = 8 / ElemTySize;
1823 unsigned NumCompleteBytes = NumElems / NumElemsPerByte;
1824 unsigned NumTailElems = NumElems % NumElemsPerByte;
1825
1826 // Helper lambda to constant-fold sub-vector of sub-byte type elements into
1827 // i8. Start and end indices of the sub-vector is provided, along with number
1828 // of padding zeros if required.
1829 auto ConvertSubCVtoInt8 = [this, &ElemTy](const ConstantVector *CV,
1830 unsigned Start, unsigned End,
1831 unsigned NumPaddingZeros = 0) {
1832 // Collect elements to create sub-vector.
1833 SmallVector<Constant *, 8> SubCVElems;
1834 for (unsigned I : llvm::seq(Start, End))
1835 SubCVElems.push_back(CV->getAggregateElement(I));
1836
1837 // Optionally pad with zeros.
1838 if (NumPaddingZeros)
1839 SubCVElems.append(NumPaddingZeros, ConstantInt::getNullValue(ElemTy));
1840
1841 auto SubCV = ConstantVector::get(SubCVElems);
1842 Type *Int8Ty = IntegerType::get(SubCV->getContext(), 8);
1843
1844 // Merge elements of the sub-vector using ConstantFolding.
1845 ConstantInt *MergedElem =
1847 ConstantExpr::getBitCast(const_cast<Constant *>(SubCV), Int8Ty),
1848 getDataLayout()));
1849
1850 if (!MergedElem)
1852 "Cannot lower vector global with unusual element type");
1853
1854 return MergedElem;
1855 };
1856
1857 // Iterate through elements of vector one chunk at a time and buffer that
1858 // chunk.
1859 for (unsigned ByteIdx : llvm::seq(NumCompleteBytes))
1860 bufferLEByte(ConvertSubCVtoInt8(CV, ByteIdx * NumElemsPerByte,
1861 (ByteIdx + 1) * NumElemsPerByte),
1862 0, aggBuffer);
1863
1864 // For unevenly sized vectors add tail padding zeros.
1865 if (NumTailElems > 0)
1866 bufferLEByte(ConvertSubCVtoInt8(CV, NumElems - NumTailElems, NumElems,
1867 NumElemsPerByte - NumTailElems),
1868 0, aggBuffer);
1869}
1870
1871/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
1872/// a copy from AsmPrinter::lowerConstant, except customized to only handle
1873/// expressions that are representable in PTX and create
1874/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
1875const MCExpr *
1876NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV,
1877 bool ProcessingGeneric) const {
1878 MCContext &Ctx = OutContext;
1879
1880 if (CV->isNullValue() || isa<UndefValue>(CV))
1881 return MCConstantExpr::create(0, Ctx);
1882
1883 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1884 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1885
1886 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
1887 const MCSymbolRefExpr *Expr = MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1888 if (ProcessingGeneric)
1889 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
1890 return Expr;
1891 }
1892
1893 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1894 if (!CE) {
1895 llvm_unreachable("Unknown constant value to lower!");
1896 }
1897
1898 switch (CE->getOpcode()) {
1899 default:
1900 break; // Error
1901
1902 case Instruction::AddrSpaceCast: {
1903 // Strip the addrspacecast and pass along the operand
1904 PointerType *DstTy = cast<PointerType>(CE->getType());
1905 if (DstTy->getAddressSpace() == 0)
1906 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
1907
1908 break; // Error
1909 }
1910
1911 case Instruction::GetElementPtr: {
1912 const DataLayout &DL = getDataLayout();
1913
1914 // Generate a symbolic expression for the byte address
1915 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1916 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1917
1918 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
1919 ProcessingGeneric);
1920 if (!OffsetAI)
1921 return Base;
1922
1923 int64_t Offset = OffsetAI.getSExtValue();
1925 Ctx);
1926 }
1927
1928 case Instruction::Trunc:
1929 // We emit the value and depend on the assembler to truncate the generated
1930 // expression properly. This is important for differences between
1931 // blockaddress labels. Since the two labels are in the same function, it
1932 // is reasonable to treat their delta as a 32-bit value.
1933 [[fallthrough]];
1934 case Instruction::BitCast:
1935 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
1936
1937 case Instruction::IntToPtr: {
1938 const DataLayout &DL = getDataLayout();
1939
1940 // Handle casts to pointers by changing them into casts to the appropriate
1941 // integer type. This promotes constant folding and simplifies this code.
1942 Constant *Op = CE->getOperand(0);
1943 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1944 /*IsSigned*/ false, DL);
1945 if (Op)
1946 return lowerConstantForGV(Op, ProcessingGeneric);
1947
1948 break; // Error
1949 }
1950
1951 case Instruction::PtrToInt: {
1952 const DataLayout &DL = getDataLayout();
1953
1954 // Support only foldable casts to/from pointers that can be eliminated by
1955 // changing the pointer to the appropriately sized integer type.
1956 Constant *Op = CE->getOperand(0);
1957 Type *Ty = CE->getType();
1958
1959 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
1960
1961 // We can emit the pointer value into this slot if the slot is an
1962 // integer slot equal to the size of the pointer.
1963 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1964 return OpExpr;
1965
1966 // Otherwise the pointer is smaller than the resultant integer, mask off
1967 // the high bits so we are sure to get a proper truncation if the input is
1968 // a constant expr.
1969 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1970 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1971 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1972 }
1973
1974 // The MC library also has a right-shift operator, but it isn't consistently
1975 // signed or unsigned between different targets.
1976 case Instruction::Add: {
1977 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
1978 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
1979 switch (CE->getOpcode()) {
1980 default: llvm_unreachable("Unknown binary operator constant cast expr");
1981 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1982 }
1983 }
1984 }
1985
1986 // If the code isn't optimized, there may be outstanding folding
1987 // opportunities. Attempt to fold the expression using DataLayout as a
1988 // last resort before giving up.
1990 if (C != CE)
1991 return lowerConstantForGV(C, ProcessingGeneric);
1992
1993 // Otherwise report the problem to the user.
1994 std::string S;
1995 raw_string_ostream OS(S);
1996 OS << "Unsupported expression in static initializer: ";
1997 CE->printAsOperand(OS, /*PrintType=*/false,
1998 !MF ? nullptr : MF->getFunction().getParent());
1999 report_fatal_error(Twine(OS.str()));
2000}
2001
2002void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) const {
2003 OutContext.getAsmInfo().printExpr(OS, Expr);
2004}
2005
2006/// PrintAsmOperand - Print out an operand for an inline asm expression.
2007///
2008bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2009 const char *ExtraCode, raw_ostream &O) {
2010 if (ExtraCode && ExtraCode[0]) {
2011 if (ExtraCode[1] != 0)
2012 return true; // Unknown modifier.
2013
2014 switch (ExtraCode[0]) {
2015 default:
2016 // See if this is a generic print operand
2017 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
2018 case 'r':
2019 break;
2020 }
2021 }
2022
2023 printOperand(MI, OpNo, O);
2024
2025 return false;
2026}
2027
2028bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
2029 unsigned OpNo,
2030 const char *ExtraCode,
2031 raw_ostream &O) {
2032 if (ExtraCode && ExtraCode[0])
2033 return true; // Unknown modifier
2034
2035 O << '[';
2036 printMemOperand(MI, OpNo, O);
2037 O << ']';
2038
2039 return false;
2040}
2041
2042void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNum,
2043 raw_ostream &O) {
2044 const MachineOperand &MO = MI->getOperand(OpNum);
2045 switch (MO.getType()) {
2047 if (MO.getReg().isPhysical()) {
2048 if (MO.getReg() == NVPTX::VRDepot)
2050 else
2052 } else {
2053 emitVirtualRegister(MO.getReg(), O);
2054 }
2055 break;
2056
2058 O << MO.getImm();
2059 break;
2060
2062 printFPConstant(MO.getFPImm(), O);
2063 break;
2064
2066 PrintSymbolOperand(MO, O);
2067 break;
2068
2070 MO.getMBB()->getSymbol()->print(O, MAI);
2071 break;
2072
2073 default:
2074 llvm_unreachable("Operand type not supported.");
2075 }
2076}
2077
2078void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, unsigned OpNum,
2079 raw_ostream &O, const char *Modifier) {
2080 printOperand(MI, OpNum, O);
2081
2082 if (Modifier && strcmp(Modifier, "add") == 0) {
2083 O << ", ";
2084 printOperand(MI, OpNum + 1, O);
2085 } else {
2086 if (MI->getOperand(OpNum + 1).isImm() &&
2087 MI->getOperand(OpNum + 1).getImm() == 0)
2088 return; // don't print ',0' or '+0'
2089 O << "+";
2090 printOperand(MI, OpNum + 1, O);
2091 }
2092}
2093
2094/// Returns true if \p Line begins with an alphabetic character or underscore,
2095/// indicating it is a PTX instruction that should receive a .loc directive.
2096static bool isPTXInstruction(StringRef Line) {
2097 StringRef Trimmed = Line.ltrim();
2098 return !Trimmed.empty() &&
2099 (std::isalpha(static_cast<unsigned char>(Trimmed[0])) ||
2100 Trimmed[0] == '_');
2101}
2102
2103/// Returns the DILocation for an inline asm MachineInstr if debug line info
2104/// should be emitted, or nullptr otherwise.
2106 if (!MI || !MI->getDebugLoc())
2107 return nullptr;
2108 const DISubprogram *SP = MI->getMF()->getFunction().getSubprogram();
2109 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2110 return nullptr;
2111 const DILocation *DL = MI->getDebugLoc();
2112 if (!DL->getFile() || !DL->getLine())
2113 return nullptr;
2114 return DL;
2115}
2116
2117namespace {
2118struct InlineAsmInliningContext {
2119 MCSymbol *FuncNameSym = nullptr;
2120 unsigned FileIA = 0;
2121 unsigned LineIA = 0;
2122 unsigned ColIA = 0;
2123
2124 bool hasInlinedAt() const { return FuncNameSym != nullptr; }
2125};
2126} // namespace
2127
2128/// Resolves the enhanced-lineinfo inlining context for an inline asm debug
2129/// location. Returns a default (empty) context if inlining info is unavailable.
2130static InlineAsmInliningContext
2132 NVPTXDwarfDebug *NVDD, MCStreamer &Streamer,
2133 unsigned CUID) {
2134 InlineAsmInliningContext Ctx;
2135 const DILocation *InlinedAt = DL->getInlinedAt();
2136 if (!InlinedAt || !InlinedAt->getFile() || !NVDD ||
2137 !NVDD->isEnhancedLineinfo(MF))
2138 return Ctx;
2139 const auto *SubProg = getDISubprogram(DL->getScope());
2140 if (!SubProg)
2141 return Ctx;
2142 Ctx.FuncNameSym = NVDD->getOrCreateFuncNameSymbol(SubProg->getLinkageName());
2143 Ctx.FileIA = Streamer.emitDwarfFileDirective(
2144 0, InlinedAt->getFile()->getDirectory(),
2145 InlinedAt->getFile()->getFilename(), std::nullopt, std::nullopt, CUID);
2146 Ctx.LineIA = InlinedAt->getLine();
2147 Ctx.ColIA = InlinedAt->getColumn();
2148 return Ctx;
2149}
2150
2151void NVPTXAsmPrinter::emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
2152 const MCTargetOptions &MCOptions,
2153 const MDNode *LocMDNode,
2154 InlineAsm::AsmDialect Dialect,
2155 const MachineInstr *MI) {
2156 assert(!Str.empty() && "Can't emit empty inline asm block");
2157 if (Str.back() == 0)
2158 Str = Str.substr(0, Str.size() - 1);
2159
2160 auto emitAsmStr = [&](StringRef AsmStr) {
2162 OutStreamer->emitRawText(AsmStr);
2163 emitInlineAsmEnd(STI, nullptr, MI);
2164 };
2165
2166 const DILocation *DL = getInlineAsmDebugLoc(MI);
2167 if (!DL) {
2168 emitAsmStr(Str);
2169 return;
2170 }
2171
2172 const DIFile *File = DL->getFile();
2173 unsigned Line = DL->getLine();
2174 const unsigned Column = DL->getColumn();
2175 const unsigned CUID = OutStreamer->getContext().getDwarfCompileUnitID();
2176 const unsigned FileNumber = OutStreamer->emitDwarfFileDirective(
2177 0, File->getDirectory(), File->getFilename(), std::nullopt, std::nullopt,
2178 CUID);
2179
2180 auto *NVDD = static_cast<NVPTXDwarfDebug *>(getDwarfDebug());
2181 InlineAsmInliningContext InlineCtx =
2182 getInlineAsmInliningContext(DL, *MI->getMF(), NVDD, *OutStreamer, CUID);
2183
2184 SmallVector<StringRef, 16> Lines;
2185 Str.split(Lines, '\n');
2187 for (const StringRef &L : Lines) {
2188 StringRef RTrimmed = L.rtrim('\r');
2189 if (isPTXInstruction(L)) {
2190 if (InlineCtx.hasInlinedAt()) {
2191 OutStreamer->emitDwarfLocDirectiveWithInlinedAt(
2192 FileNumber, Line, Column, InlineCtx.FileIA, InlineCtx.LineIA,
2193 InlineCtx.ColIA, InlineCtx.FuncNameSym, DWARF2_FLAG_IS_STMT, 0, 0,
2194 File->getFilename());
2195 } else {
2196 OutStreamer->emitDwarfLocDirective(FileNumber, Line, Column,
2197 DWARF2_FLAG_IS_STMT, 0, 0,
2198 File->getFilename());
2199 }
2200 }
2201 OutStreamer->emitRawText(RTrimmed);
2202 ++Line;
2203 }
2204 emitInlineAsmEnd(STI, nullptr, MI);
2205}
2206
2207char NVPTXAsmPrinter::ID = 0;
2208
2209INITIALIZE_PASS(NVPTXAsmPrinter, "nvptx-asm-printer", "NVPTX Assembly Printer",
2210 false, false)
2211
2212// Force static initialization.
2213extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
2214LLVMInitializeNVPTXAsmPrinter() {
2217}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define DWARF2_FLAG_IS_STMT
Definition MCDwarf.h:119
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static StringRef getTextureName(const Value &V)
static const DILocation * getInlineAsmDebugLoc(const MachineInstr *MI)
Returns the DILocation for an inline asm MachineInstr if debug line info should be emitted,...
#define DEPOTNAME
static void discoverDependentGlobals(const Value *V, DenseSet< const GlobalVariable * > &Globals)
discoverDependentGlobals - Return a set of GlobalVariables on which V depends.
static bool hasFullDebugInfo(Module &M)
static StringRef getSurfaceName(const Value &V)
static bool canDemoteGlobalVar(const GlobalVariable *GV, Function const *&f)
static StringRef getSamplerName(const Value &V)
static bool useFuncSeen(const Constant *C, const SmallPtrSetImpl< const Function * > &SeenSet)
static void VisitGlobalVariableForEmission(const GlobalVariable *GV, SmallVectorImpl< const GlobalVariable * > &Order, DenseSet< const GlobalVariable * > &Visited, DenseSet< const GlobalVariable * > &Visiting)
VisitGlobalVariableForEmission - Add GV to the list of GlobalVariable instances to be emitted,...
static bool usedInGlobalVarDef(const Constant *C)
static InlineAsmInliningContext getInlineAsmInliningContext(const DILocation *DL, const MachineFunction &MF, NVPTXDwarfDebug *NVDD, MCStreamer &Streamer, unsigned CUID)
Resolves the enhanced-lineinfo inlining context for an inline asm debug location.
static bool isPTXInstruction(StringRef Line)
Returns true if Line begins with an alphabetic character or underscore, indicating it is a PTX instru...
static bool usedInOneFunc(const User *U, Function const *&OneFunc)
static void emitInitialRawDwarfLocDirective(const MachineFunction &MF, DwarfDebug *DD, MCStreamer &OutStreamer)
Emits initial debug location directive.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static const char * name
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
@ __CLK_ADDRESS_BASE
@ __CLK_FILTER_BASE
@ __CLK_NORMALIZED_BASE
@ __CLK_NORMALIZED_MASK
@ __CLK_ADDRESS_MASK
@ __CLK_FILTER_MASK
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5912
APInt bitcastToAPInt() const
Definition APFloat.h:1430
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1563
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:521
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
MCSymbol * getSymbol(const GlobalValue *GV) const
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
DwarfDebug * getDwarfDebug()
Definition AsmPrinter.h:290
virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, const MCSubtargetInfo *EndInfo, const MachineInstr *MI)
Let the target do anything it needs to do after emitting inlineasm.
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:94
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:109
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition AsmPrinter.h:515
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition AsmPrinter.h:622
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
unsigned getFunctionNumber() const
Return a unique ID for the current function.
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition AsmPrinter.h:128
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:101
bool doFinalization(Module &M) override
Shut down the asmprinter.
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition AsmPrinter.h:453
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:106
const MCAsmInfo & MAI
Target Asm Printer information.
Definition AsmPrinter.h:97
virtual void emitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition AsmPrinter.h:626
const DataLayout & getDataLayout() const
Return information about data layout.
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
MCSymbol * GetExternalSymbolSymbol(const Twine &Sym) const
Return the MCSymbol for the specified ExternalSymbol.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
virtual void emitInlineAsmStart() const
Let the target do anything it needs to do before emitting inlineasm.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
const APFloat & getValueAPF() const
Definition Constants.h:463
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition Constants.h:691
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Subprogram description. Uses SubclassData1.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:225
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:136
iterator end()
Definition DenseMap.h:143
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
const MachineInstr * emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
unsigned getNumElements() const
DISubprogram * getSubprogram() const
Get the attached subprogram.
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:659
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasSection() const
Check if this global has a custom object file section.
bool hasLinkOnceLinkage() const
bool hasExternalLinkage() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:337
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
unsigned getAddressSpace() const
PointerType * getType() const
Global values are always pointers.
bool hasWeakLinkage() const
bool hasCommonLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:350
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:343
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:348
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:166
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual bool hasRawTextSupport() const
Return true if this asm streamer supports emitting unformatted text to the .s file with EmitRawText.
Definition MCStreamer.h:385
unsigned emitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, std::optional< MD5::MD5Result > Checksum=std::nullopt, std::optional< StringRef > Source=std::nullopt, unsigned CUID=0)
Associate a filename with a specified logical file number.
Definition MCStreamer.h:889
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition MCSymbol.cpp:59
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
iterator_range< pred_iterator > predecessors()
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
MachineBasicBlock * getMBB() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_FPImmediate
Floating-point immediate operand.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
bool runOnMachineFunction(MachineFunction &F) override
Emit the specified function out to the OutStreamer.
DwarfDebug * createDwarfDebug() override
Create NVPTX-specific DwarfDebug handler.
std::string getVirtualRegisterName(unsigned) const
bool doFinalization(Module &M) override
Shut down the asmprinter.
const MCSymbol * getFunctionFrameSymbol() const override
Return symbol for the function pseudo stack if the stack frame is not a register based.
NVPTX-specific DwarfDebug implementation.
bool isEnhancedLineinfo(const MachineFunction &MF) const
Returns true if the enhanced lineinfo mode (with inlined_at) is active for the given MachineFunction.
MCSymbol * getOrCreateFuncNameSymbol(StringRef LinkageName)
Get or create an MCSymbol in .debug_str for a function's linkage name.
static const NVPTXFloatMCExpr * createConstantBFPHalf(const APFloat &Flt, MCContext &Ctx)
Definition NVPTXMCExpr.h:44
static const NVPTXFloatMCExpr * createConstantFPHalf(const APFloat &Flt, MCContext &Ctx)
Definition NVPTXMCExpr.h:49
static const NVPTXFloatMCExpr * createConstantFPSingle(const APFloat &Flt, MCContext &Ctx)
Definition NVPTXMCExpr.h:54
static const NVPTXFloatMCExpr * createConstantFPDouble(const APFloat &Flt, MCContext &Ctx)
Definition NVPTXMCExpr.h:59
static const NVPTXGenericMCSymbolRefExpr * create(const MCSymbolRefExpr *SymExpr, MCContext &Ctx)
static const char * getRegisterName(MCRegister Reg)
bool checkImageHandleSymbol(StringRef Symbol) const
Check if the symbol has a mapping.
const char * getName(unsigned RegNo) const
std::string getTargetName() const
bool hasMaskOperator() const
const NVPTXTargetLowering * getTargetLowering() const override
unsigned getPTXVersion() const
const NVPTXRegisterInfo * getRegisterInfo() const override
unsigned int getSmVersion() const
NVPTX::DrvInterface getDrvInterface() const
const NVPTXSubtarget * getSubtargetImpl(const Function &) const override
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Implments NVPTX-specific streamer.
void outputDwarfFileDirectives()
Outputs the list of the DWARF '.file' directives to the streamer.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
Definition StringRef.h:820
iterator end() const
Definition StringRef.h:116
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:76
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ VoidTyID
type with no size
Definition Type.h:64
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ StructTyID
Structures.
Definition Type.h:75
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ PointerTyID
Pointers.
Definition Type.h:74
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
TypeID getTypeID() const
Return the type id for the type.
Definition Type.h:138
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
size_type size() const
Definition DenseSet.h:87
bool erase(const ValueT &V)
Definition DenseSet.h:100
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:190
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
constexpr StringLiteral MaxNTID("nvvm.maxntid")
constexpr StringLiteral ReqNTID("nvvm.reqntid")
constexpr StringLiteral ClusterDim("nvvm.cluster_dim")
constexpr StringLiteral BlocksAreClusters("nvvm.blocksareclusters")
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:50
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
uint64_t read64le(const void *P)
Definition Endian.h:435
uint32_t read32le(const void *P)
Definition Endian.h:432
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2179
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool isManaged(const Value &V)
StringRef getNVPTXRegClassStr(TargetRegisterClass const *RC)
bool shouldEmitPTXNoReturn(const Value *V, const TargetMachine &TM)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
std::optional< unsigned > getMaxNReg(const Function &F)
void interleave(ForwardIterator begin, ForwardIterator end, UnaryFunctor each_fn, NullaryFunctor between_fn)
An STL-style algorithm similar to std::for_each that applies a second functor between every pair of e...
Definition STLExtras.h:2274
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::string utostr(uint64_t X, bool isNeg=false)
std::optional< unsigned > getMinCTASm(const Function &F)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2172
SmallVector< unsigned, 3 > getReqNTID(const Function &F)
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
unsigned promoteScalarArgumentSize(unsigned size)
void clearAnnotationCache(const Module *Mod)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool shouldPassAsArray(Type *Ty)
StringRef getNVPTXRegClassName(TargetRegisterClass const *RC)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition Format.h:204
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
std::optional< unsigned > getMaxClusterRank(const Function &F)
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
SmallVector< unsigned, 3 > getMaxNTID(const Function &F)
LLVM_ABI void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
DWARFExpression::Operation Op
Align getPTXParamAlign(const Function *F, Type *Ty, unsigned AttrIdx, const DataLayout &DL)
Get the alignment for a function parameter or return value.
ArrayRef(const T &OneElt) -> ArrayRef< T >
Align getDeviceByValParamAlign(const Function *F, Type *ArgTy, Align InitialAlign, const DataLayout &DL)
Target & getTheNVPTXTarget64()
bool isKernelFunction(const Function &F)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
bool hasBlocksAreClusters(const Function &F)
SmallVector< unsigned, 3 > getClusterDim(const Function &F)
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
PTXOpaqueType getPTXOpaqueType(const GlobalVariable &GV)
LLVM_ABI MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
LLVM_ABI DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Target & getTheNVPTXTarget32()
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...