107#include <type_traits>
112#define DEPOTNAME "__local_depot"
146 unsigned numSymbols()
const {
return Symbols.size(); }
148 bool allSymbolsAligned(
unsigned ptrSize)
const {
150 [=](
unsigned pos) {
return pos % ptrSize == 0; });
155 std::vector<unsigned char> buffer;
167 const NVPTXAsmPrinter &AP;
168 const bool EmitGeneric;
171 AggBuffer(
unsigned Size,
const NVPTXAsmPrinter &AP)
173 EmitGeneric(AP.EmitGeneric) {}
175 unsigned getBufferSize()
const {
return Size; }
178 unsigned getCurpos()
const {
return curpos; }
182 void addBytes(
const unsigned char *Ptr,
unsigned Num,
unsigned Bytes) {
186 addZeros(Bytes - Num);
191 buffer[curpos] = Byte;
195 void addZeros(
unsigned Num) {
196 for ([[maybe_unused]]
unsigned _ :
llvm::seq(Num)) {
203 Symbols.push_back(GVar);
204 SymbolsBeforeStripping.
push_back(GVarBeforeStripping);
214 friend class AggBuffer;
219 StringRef getPassName()
const override {
return "NVPTX Assembly Printer"; }
226 void emitStartOfAsmFile(
Module &M)
override;
228 void emitFunctionEntryLabel()
override;
229 void emitFunctionBodyStart()
override;
230 void emitFunctionBodyEnd()
override;
241 unsigned getVirtualRegisterNumber(
Register Reg)
const;
244 const char *Modifier =
nullptr);
247 void emitGlobals(
const Module &M);
256 void emitCallPrototype(
const CallBase &CB,
unsigned UniqueCallSite,
262 template <
typename T>
bool shouldEmitPTXNoReturn(
const T &V)
const {
263 static_assert(std::is_same_v<Function, T> || std::is_base_of_v<CallBase, T>,
264 "expected a function or a call site");
267 if (!NTM.getSubtargetImpl()->hasNoReturn())
270 if (!V.doesNotReturn() || !V.getFunctionType()->getReturnType()->isVoidTy())
273 if constexpr (std::is_same_v<Function, T>)
286 bool ProcessingGeneric)
const;
295 bool doInitialization(
Module &M)
override;
296 bool doFinalization(
Module &M)
override;
311 VRegRCMap VRegMapping;
314 std::map<const Function *, std::vector<const GlobalVariable *>> localDecls;
321 bool EmitInitializer);
323 std::string getPTXFundamentalTypeStr(
Type *Ty,
bool =
true)
const;
326 void bufferLEByte(
const Constant *CPV,
int Bytes, AggBuffer *aggBuffer);
327 void bufferAggregateConstant(
const Constant *CV, AggBuffer *aggBuffer);
328 void bufferAggregateConstVec(
const ConstantVector *CV, AggBuffer *aggBuffer);
350 const bool EmitGeneric;
365 std::string getVirtualRegisterName(
Register Reg)
const;
367 const MCSymbol *getFunctionFrameSymbol()
const override;
378 assert(V.hasName() &&
"Found texture variable with no name");
383 assert(V.hasName() &&
"Found surface variable with no name");
388 assert(V.hasName() &&
"Found sampler variable with no name");
410 if (SP->getUnit()->isDebugDirectivesOnly() || SP->getUnit()->isNoDebug())
420discoverDependentGlobals(
const Value *V,
421 SmallVectorImpl<const GlobalVariable *> &Globals,
422 SmallPtrSetImpl<const GlobalVariable *> &Seen) {
424 if (Seen.
insert(GV).second)
437 discoverDependentGlobals(
GEP->getPointerOperand(), Globals, Seen);
442 for (
const auto &O :
U->operands())
443 discoverDependentGlobals(O, Globals, Seen);
446struct GlobalVariableDependencyNode {
447 const GlobalVariable *GV =
nullptr;
448 unsigned ModuleOrder = 0;
452class GlobalVariableDependencyGraph {
455 GlobalVariableDependencyNode SyntheticRoot;
458 std::map<const GlobalVariable *, GlobalVariableDependencyNode> Nodes;
461 explicit GlobalVariableDependencyGraph(
const Module &M) {
462 unsigned ModuleOrder = 0;
463 for (
const GlobalVariable &GV :
M.globals()) {
464 GlobalVariableDependencyNode &
Node = Nodes.try_emplace(&GV).first->second;
466 Node.ModuleOrder = ModuleOrder++;
467 SyntheticRoot.Dependencies.push_back(&Node);
470 for (
auto &[GV, Node] : Nodes) {
472 SmallPtrSet<const GlobalVariable *, 4> Seen;
473 for (
const Use &Operand : GV->operands())
474 discoverDependentGlobals(Operand, Dependencies, Seen);
476 for (
const GlobalVariable *Dependency : Dependencies) {
477 auto It = Nodes.find(Dependency);
478 if (It != Nodes.end())
479 Node.Dependencies.push_back(&It->second);
484 const GlobalVariableDependencyNode *getEntryNode()
const {
485 return &SyntheticRoot;
489struct GlobalVariableDependencyGraphTraits {
490 using NodeRef =
const GlobalVariableDependencyNode *;
491 using ChildIteratorType =
494 static NodeRef getEntryNode(NodeRef Node) {
return Node; }
495 static ChildIteratorType child_begin(NodeRef Node) {
496 return Node->Dependencies.begin();
498 static ChildIteratorType child_end(NodeRef Node) {
499 return Node->Dependencies.end();
503using GlobalVariableSCCIterator =
504 scc_iterator<
const GlobalVariableDependencyNode *,
505 GlobalVariableDependencyGraphTraits>;
507static bool shouldSkipModuleLevelGlobal(
const GlobalVariable &GV) {
513static bool isForwardDeclarableGlobal(
const GlobalVariable *GVar) {
514 if (shouldSkipModuleLevelGlobal(*GVar) || GVar->
isDeclaration() ||
535 const DenseSet<const GlobalVariableDependencyNode *> &ForwardDeclared) {
536 using Node = GlobalVariableDependencyNode;
538 DenseSet<const Node *> SCCSet;
541 DenseMap<const Node *, unsigned> DependencyCount;
542 DenseMap<const Node *, SmallVector<const Node *, 4>> Dependents;
543 std::set<std::pair<unsigned, const Node *>>
Ready;
547 for (
const Node *
N : SCC) {
548 unsigned &
Count = DependencyCount[
N];
549 for (
const Node *Dependency :
N->Dependencies) {
550 if (!SCCSet.
count(Dependency) || ForwardDeclared.
count(Dependency))
553 Dependents[Dependency].push_back(
N);
556 Ready.emplace(
N->ModuleOrder,
N);
560 while (!
Ready.empty()) {
565 auto It = Dependents.
find(
N);
566 if (It == Dependents.
end())
568 for (
const Node *Dependent : It->second) {
569 assert(DependencyCount[Dependent] &&
"Dependency already satisfied");
570 if (--DependencyCount[Dependent] == 0)
571 Ready.emplace(Dependent->ModuleOrder, Dependent);
575 if (Order.
size() !=
SCC.size())
583 NVPTX_MC::verifyInstructionPredicates(
MI->getOpcode(),
584 getSubtargetInfo().getFeatureBits());
587 lowerToMCInst(
MI, Inst);
588 EmitToStreamer(*OutStreamer, Inst);
591void NVPTXAsmPrinter::lowerToMCInst(
const MachineInstr *
MI, MCInst &OutMI) {
593 for (
const auto MO :
MI->operands())
597MCOperand NVPTXAsmPrinter::lowerOperand(
const MachineOperand &MO) {
629 case Type::BFloatTyID:
632 case Type::FloatTyID:
635 case Type::DoubleTyID:
644static NVPTX::VirtualRegisterKind
646 if (RC == &NVPTX::B1RegClass)
648 if (RC == &NVPTX::B16RegClass)
650 if (RC == &NVPTX::B32RegClass)
652 if (RC == &NVPTX::B64RegClass)
654 if (RC == &NVPTX::B128RegClass)
659unsigned NVPTXAsmPrinter::getVirtualRegisterNumber(
Register Reg)
const {
661 assert(It != VRegMapping.
end() &&
"Bad register class");
663 const unsigned Num = It->second.lookup(
Reg);
664 assert(Num &&
"Bad virtual register");
668MCRegister NVPTXAsmPrinter::encodeVirtualRegister(
Register Reg) {
673 const unsigned Num = getVirtualRegisterNumber(
Reg);
674 assert(Num <= NVPTX::VirtualRegisterNumMask &&
675 "Too many virtual registers");
676 return (
static_cast<unsigned>(Kind) << NVPTX::VirtualRegisterKindShift) |
682 assert(
Reg.
id() <= NVPTX::VirtualRegisterNumMask &&
683 "Physical register would decode as a virtual register");
687MCOperand NVPTXAsmPrinter::GetSymbolRef(
const MCSymbol *Symbol) {
693void NVPTXAsmPrinter::printReturnValStr(
const Function *
F, raw_ostream &O) {
694 const DataLayout &
DL = getDataLayout();
695 const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
698 Type *Ty =
F->getReturnType();
705 auto PrintScalarRetVal = [&](
unsigned Size) {
709 const unsigned TotalSize =
DL.getTypeAllocSize(Ty);
710 const Align RetAlignment =
712 O <<
".param .align " << RetAlignment.
value() <<
" .b8 func_retval0["
717 PrintScalarRetVal(ITy->getBitWidth());
719 PrintScalarRetVal(TLI->getPointerTy(
DL).getSizeInBits());
728 printReturnValStr(&
F, O);
731void NVPTXAsmPrinter::emitCallPrototype(
const CallBase &CB,
732 unsigned UniqueCallSite,
733 raw_ostream &O)
const {
734 const DataLayout &
DL = getDataLayout();
735 const NVPTXSubtarget &STI = MF->
getSubtarget<NVPTXSubtarget>();
737 const auto PtrVT = TLI->getPointerTy(
DL);
740 O <<
"prototype_" << UniqueCallSite <<
" : .callprototype ";
747 const Align RetAlign =
749 O <<
".param .align " << RetAlign.
value() <<
" .b8 _["
750 <<
DL.getTypeAllocSize(RetTy) <<
"]";
754 size = ITy->getBitWidth();
757 "Floating point type expected here");
765 O <<
".param .b" <<
size <<
" _";
767 O <<
".param .b" << PtrVT.getSizeInBits() <<
" _";
775 auto MakeArg = [&](
const unsigned I) {
781 &CB, ETy,
I + AttributeList::FirstArgIndex,
DL);
783 O <<
".param .align " << ParamByValAlign.
value() <<
" .b8 _["
784 <<
DL.getTypeAllocSize(ETy) <<
"]";
791 O <<
".param .align " << ParamAlign.
value() <<
" .b8 _["
792 <<
DL.getTypeAllocSize(Ty) <<
"]";
800 sz = PtrVT.getSizeInBits();
804 O <<
".param .b" << sz <<
" _";
808 const unsigned NumArgs = FTy->getNumParams();
818 if (FTy->isVarArg() && CB.
arg_size() > NumArgs)
819 O << (NonEmptyArgs.empty() ?
"" :
",") <<
" .param .align "
823 if (shouldEmitPTXNoReturn(CB))
828void NVPTXAsmPrinter::emitJumpTable(
const MachineJumpTableEntry &MJT,
829 unsigned MJTI)
const {
830 OutStreamer->emitLabel(GetJTISymbol(MJTI));
832 if (MJT.
MBBs.empty())
837 return MBB->getSymbol();
839 getTargetStreamer()->emitBranchTargetsDirective(Targets);
844bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
845 const MachineBasicBlock &
MBB)
const {
846 const MachineLoopInfo *LI = GetMLI(*MF);
847 assert(LI &&
"NVPTXAsmPrinter requires MachineLoopInfo");
860 if (
const BasicBlock *PBB = PMBB->getBasicBlock()) {
862 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
865 if (MDNode *UnrollCountMD =
877void NVPTXAsmPrinter::emitBasicBlockStart(
const MachineBasicBlock &
MBB) {
879 if (isLoopHeaderOfNoUnroll(
MBB))
880 getTargetStreamer()->emitPragmaDirective(
"nounroll");
883void NVPTXAsmPrinter::emitFunctionEntryLabel() {
884 SmallString<128> Str;
885 raw_svector_ostream
O(Str);
887 if (!GlobalsEmitted) {
889 GlobalsEmitted =
true;
895 emitLinkageDirective(
F, O);
900 printReturnValStr(*MF, O);
903 CurrentFnSym->print(O, MAI);
905 emitFunctionParamList(
F, O);
909 emitKernelFunctionDirectives(*
F, O);
911 if (shouldEmitPTXNoReturn(*
F))
914 OutStreamer->emitRawText(
O.str());
918 OutStreamer->emitRawText(StringRef(
"{\n"));
919 setAndEmitFunctionVirtualRegisters(*MF);
920 encodeDebugInfoRegisterNumbers(*MF);
932 OutStreamer->emitRawText(StringRef(
"}\n"));
936void NVPTXAsmPrinter::emitFunctionBodyStart() {
937 SmallString<128> Str;
938 raw_svector_ostream
O(Str);
941 const auto *MFI = MF->
getInfo<NVPTXMachineFunctionInfo>();
942 for (
const auto &[Id, CB] : MFI->getCallPrototypes())
943 emitCallPrototype(*CB, Id, O);
945 OutStreamer->emitRawText(
O.str());
948 for (
const auto &[Idx, JT] :
enumerate(MJTI->getJumpTables()))
949 emitJumpTable(JT, Idx);
952void NVPTXAsmPrinter::emitFunctionBodyEnd() {
956const MCSymbol *NVPTXAsmPrinter::getFunctionFrameSymbol()
const {
957 return OutContext.getOrCreateSymbol(
DEPOTNAME + Twine(getFunctionNumber()));
960void NVPTXAsmPrinter::emitImplicitDef(
const MachineInstr *
MI)
const {
963 OutStreamer->AddComment(Twine(
"implicit-def: ") +
964 getVirtualRegisterName(RegNo));
966 OutStreamer->AddComment(Twine(
"implicit-def: ") +
968 OutStreamer->addBlankLine();
971void NVPTXAsmPrinter::emitKernelFunctionDirectives(
const Function &
F,
972 raw_ostream &O)
const {
978 O <<
formatv(
".reqntid {0:$[, ]}\n",
983 O <<
formatv(
".maxntid {0:$[, ]}\n",
987 O <<
".minnctapersm " << *Mincta <<
"\n";
990 O <<
".maxnreg " << *Maxnreg <<
"\n";
994 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
995 const NVPTXSubtarget *STI = &NTM.
getSubtarget<NVPTXSubtarget>(
F);
997 if (STI->hasFeature(NVPTX::SM90)) {
1003 if (!BlocksAreClusters)
1004 O <<
".explicitcluster\n";
1006 if (ClusterDim[0] != 0) {
1008 "cluster_dim_x != 0 implies cluster_dim_y and cluster_dim_z "
1009 "should be non-zero as well");
1011 O <<
formatv(
".reqnctapercluster {0:$[, ]}\n",
1015 "cluster_dim_x == 0 implies cluster_dim_y and cluster_dim_z "
1016 "should be 0 as well");
1020 if (BlocksAreClusters) {
1021 LLVMContext &Ctx =
F.getContext();
1023 Ctx.
diagnose(DiagnosticInfoUnsupported(
1024 F,
"blocksareclusters requires reqntid and cluster_dim attributes",
1025 F.getSubprogram()));
1026 else if (!STI->hasFeature(NVPTX::PTX90))
1027 Ctx.
diagnose(DiagnosticInfoUnsupported(
1028 F,
"blocksareclusters requires PTX version >= 9.0",
1029 F.getSubprogram()));
1031 O <<
".blocksareclusters\n";
1035 O <<
".maxclusterrank " << *Maxclusterrank <<
"\n";
1039std::string NVPTXAsmPrinter::getVirtualRegisterName(
Register Reg)
const {
1043 raw_string_ostream(Name) << NVPTX::getVirtualRegisterPrefix(Kind)
1044 << getVirtualRegisterNumber(
Reg);
1048void NVPTXAsmPrinter::emitAliasDeclaration(
const GlobalAlias *GA,
1053 "NVPTX aliasee must be a non-kernel function definition");
1059 emitDeclarationWithName(
F, getSymbol(GA), O);
1062void NVPTXAsmPrinter::emitDeclaration(
const Function *
F, raw_ostream &O) {
1063 emitDeclarationWithName(
F, getSymbol(
F), O);
1066void NVPTXAsmPrinter::emitDeclarationWithName(
const Function *
F, MCSymbol *S,
1068 emitLinkageDirective(
F, O);
1073 printReturnValStr(
F, O);
1076 emitFunctionParamList(
F, O);
1078 if (shouldEmitPTXNoReturn(*
F))
1088 return GV->
getName() !=
"llvm.used";
1090 for (
const User *U :
C->users())
1100 if (OtherGV->getName() ==
"llvm.used")
1104 if (
const Function *CurFunc =
I->getFunction()) {
1105 if (OneFunc && (CurFunc != OneFunc))
1146 for (
const User *U :
C->users()) {
1151 if (
const Function *Caller =
I->getFunction())
1159void NVPTXAsmPrinter::emitDeclarations(
const Module &M, raw_ostream &O) {
1160 SmallPtrSet<const Function *, 32> SeenSet;
1162 if (
F.getAttributes().hasFnAttr(
"nvptx-libcall-callee")) {
1163 emitDeclaration(&
F, O);
1167 if (
F.isDeclaration()) {
1170 if (
F.getIntrinsicID())
1174 if (
F.isIntrinsic()) {
1175 LLVMContext &Ctx =
F.getContext();
1176 Ctx.
diagnose(DiagnosticInfoUnsupported(
1177 F,
"unknown intrinsic '" +
F.getName() +
1178 "' cannot be lowered by the NVPTX backend"));
1181 emitDeclaration(&
F, O);
1184 for (
const User *U :
F.users()) {
1190 emitDeclaration(&
F, O);
1196 emitDeclaration(&
F, O);
1211 emitDeclaration(&
F, O);
1217 for (
const GlobalAlias &GA :
M.aliases())
1218 emitAliasDeclaration(&GA, O);
1221void NVPTXAsmPrinter::emitStartOfAsmFile(
Module &M) {
1225 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1229 emitHeader(M, *STI);
1233DwarfDebug *NVPTXAsmPrinter::createDwarfDebug() {
1234 return new NVPTXDwarfDebug(
this);
1237bool NVPTXAsmPrinter::doInitialization(
Module &M) {
1238 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1240 if (
M.alias_size() &&
1241 (!STI.hasFeature(NVPTX::PTX63) || !STI.hasFeature(NVPTX::SM30)))
1247 GlobalsEmitted =
false;
1252void NVPTXAsmPrinter::emitGlobals(
const Module &M) {
1253 SmallString<128> Str2;
1254 raw_svector_ostream OS2(Str2);
1256 emitDeclarations(M, OS2);
1258 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1266 GlobalVariableDependencyGraph DependencyGraph(M);
1267 for (GlobalVariableSCCIterator
I =
1268 GlobalVariableSCCIterator::begin(DependencyGraph.getEntryNode());
1269 !
I.isAtEnd(); ++
I) {
1274 if (!
SCC.front()->GV) {
1275 assert(
SCC.size() == 1 &&
"Synthetic root must be in its own SCC");
1280 return LHS->ModuleOrder <
RHS->ModuleOrder;
1283 const bool IsCyclic =
I.hasCycle();
1284 DenseSet<const GlobalVariableDependencyNode *> ForwardDeclared;
1286 for (
const auto *Node : SCC)
1287 if (isForwardDeclarableGlobal(
Node->GV))
1288 ForwardDeclared.
insert(Node);
1292 IsCyclic ? orderDefinitionsInSCC(SCC, ForwardDeclared)
1295 for (
const auto *Node : SCC) {
1296 if (!ForwardDeclared.
count(Node))
1299 emitPTXGlobalVariableDefinition(
Node->GV, OS2, STI,
1304 for (
const GlobalVariable *GV : OrderedGlobals)
1305 printModuleLevelGV(GV, OS2,
false, STI);
1310 OutStreamer->emitRawText(OS2.str());
1313void NVPTXAsmPrinter::emitGlobalAlias(
const Module &M,
const GlobalAlias &GA) {
1314 getTargetStreamer()->emitAliasDirective(getSymbol(&GA),
1318NVPTXTargetStreamer *NVPTXAsmPrinter::getTargetStreamer()
const {
1319 return static_cast<NVPTXTargetStreamer *
>(OutStreamer->getTargetStreamer());
1324 switch(
CU->getEmissionKind()) {
1337void NVPTXAsmPrinter::emitHeader(
Module &M,
const NVPTXSubtarget &STI) {
1338 auto *TS = getTargetStreamer();
1343 TS->emitVersionDirective(PTXVersion);
1345 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1348 TS->emitTargetDirective(STI.
getTargetName(), TexModeIndependent,
1350 TS->emitAddressSizeDirective(
M.getDataLayout().getPointerSizeInBits());
1353bool NVPTXAsmPrinter::doFinalization(
Module &M) {
1356 if (!GlobalsEmitted) {
1358 GlobalsEmitted =
true;
1367 static_cast<NVPTXTargetStreamer *
>(OutStreamer->getTargetStreamer());
1370 TS->closeLastSection();
1372 TS->emitEmptySectionDirective(
".debug_macinfo");
1376 TS->outputDwarfFileDirectives();
1394void NVPTXAsmPrinter::emitLinkageDirective(
const GlobalValue *V,
1396 if (
static_cast<NVPTXTargetMachine &
>(TM).getDrvInterface() == NVPTX::CUDA) {
1397 if (
V->hasExternalLinkage()) {
1400 else if (
V->isDeclaration())
1404 }
else if (
V->hasAppendingLinkage()) {
1406 "' has unsupported appending linkage type");
1407 }
else if (!
V->hasInternalLinkage() && !
V->hasPrivateLinkage()) {
1413void NVPTXAsmPrinter::printModuleLevelGV(
const GlobalVariable *GVar,
1414 raw_ostream &O,
bool ProcessDemoted,
1415 const NVPTXSubtarget &STI) {
1417 if (shouldSkipModuleLevelGlobal(*GVar))
1436 if (OpaqueType == PTXOpaqueType::Texture) {
1441 if (OpaqueType == PTXOpaqueType::Surface) {
1450 emitPTXGlobalVariable(GVar, O, STI);
1455 if (OpaqueType == PTXOpaqueType::Sampler) {
1458 const Constant *Initializer =
nullptr;
1461 const ConstantInt *CI =
nullptr;
1472 O <<
"addr_mode_" << i <<
" = ";
1478 O <<
"clamp_to_border";
1481 O <<
"clamp_to_edge";
1492 O <<
"filter_mode = ";
1507 O <<
", force_unnormalized_coords = 1";
1527 const Function *DemotedFunc =
nullptr;
1529 O <<
"// " << GVar->
getName() <<
" has been demoted\n";
1530 localDecls[DemotedFunc].push_back(GVar);
1534 emitPTXGlobalVariableDefinition(GVar, O, STI,
true);
1538void NVPTXAsmPrinter::emitPTXGlobalVariableDefinition(
1539 const GlobalVariable *GVar, raw_ostream &O,
const NVPTXSubtarget &STI,
1540 bool EmitInitializer) {
1541 const DataLayout &
DL = getDataLayout();
1549 if (!STI.hasFeature(NVPTX::PTX40) || !STI.hasFeature(NVPTX::SM30))
1551 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1552 O <<
" .attribute(.managed)";
1556 << GVar->
getAlign().value_or(
DL.getPrefTypeAlign(ETy)).value();
1565 O << getPTXFundamentalTypeStr(ETy,
false);
1567 getSymbol(GVar)->print(O, MAI);
1578 printScalarConstant(Initializer, O);
1587 "' is not allowed in addrspace(" +
1598 case Type::IntegerTyID:
1599 case Type::FP128TyID:
1600 case Type::StructTyID:
1601 case Type::ArrayTyID:
1602 case Type::FixedVectorTyID: {
1603 const uint64_t ElementSize =
DL.getTypeStoreSize(ETy);
1611 AggBuffer aggBuffer(ElementSize, *
this);
1612 bufferAggregateConstant(Initializer, &aggBuffer);
1613 if (aggBuffer.numSymbols()) {
1614 const unsigned int ptrSize = MAI.getCodePointerSize();
1615 if (ElementSize % ptrSize ||
1616 !aggBuffer.allSymbolsAligned(ptrSize)) {
1620 "initialized packed aggregate with pointers '" +
1622 "' requires at least PTX ISA version 7.1");
1624 getSymbol(GVar)->print(O, MAI);
1625 O <<
"[" << ElementSize <<
"]";
1626 if (EmitInitializer) {
1628 aggBuffer.printBytes(O);
1632 O <<
" .u" << ptrSize * 8 <<
" ";
1633 getSymbol(GVar)->print(O, MAI);
1634 O <<
"[" << ElementSize / ptrSize <<
"]";
1635 if (EmitInitializer) {
1637 aggBuffer.printWords(O);
1643 getSymbol(GVar)->print(O, MAI);
1644 O <<
"[" << ElementSize <<
"]";
1645 if (EmitInitializer) {
1647 aggBuffer.printBytes(O);
1653 getSymbol(GVar)->print(O, MAI);
1655 O <<
"[" << ElementSize <<
"]";
1659 getSymbol(GVar)->print(O, MAI);
1661 O <<
"[" << ElementSize <<
"]";
1671void NVPTXAsmPrinter::AggBuffer::printSymbol(
unsigned nSym, raw_ostream &os) {
1672 const Value *
v = Symbols[nSym];
1673 const Value *v0 = SymbolsBeforeStripping[nSym];
1678 bool isGenericPointer = PTy && PTy->getAddressSpace() == 0;
1681 Name->print(os, AP.MAI);
1684 Name->print(os, AP.MAI);
1687 const MCExpr *Expr = AP.lowerConstantForGV(CExpr,
false);
1688 AP.printMCExpr(*Expr, os);
1693void NVPTXAsmPrinter::AggBuffer::printBytes(raw_ostream &os) {
1694 unsigned int ptrSize = AP.MAI.getCodePointerSize();
1699 unsigned int InitializerCount =
Size;
1702 if (numSymbols() == 0)
1703 while (InitializerCount >= 1 && !buffer[InitializerCount - 1])
1706 symbolPosInBuffer.push_back(InitializerCount);
1707 unsigned int nSym = 0;
1708 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1709 for (
unsigned int pos = 0; pos < InitializerCount;) {
1712 if (pos != nextSymbolPos) {
1713 os << (
unsigned int)buffer[pos];
1720 std::string symText;
1721 llvm::raw_string_ostream oss(symText);
1722 printSymbol(nSym, oss);
1723 for (
unsigned i = 0; i < ptrSize; ++i) {
1727 os <<
"(" << symText <<
")";
1730 nextSymbolPos = symbolPosInBuffer[++nSym];
1731 assert(nextSymbolPos >= pos);
1735void NVPTXAsmPrinter::AggBuffer::printWords(raw_ostream &os) {
1736 unsigned int ptrSize = AP.MAI.getCodePointerSize();
1737 symbolPosInBuffer.push_back(
Size);
1738 unsigned int nSym = 0;
1739 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1740 assert(nextSymbolPos % ptrSize == 0);
1741 for (
unsigned int pos = 0; pos <
Size; pos += ptrSize) {
1744 if (pos == nextSymbolPos) {
1745 printSymbol(nSym, os);
1746 nextSymbolPos = symbolPosInBuffer[++nSym];
1747 assert(nextSymbolPos % ptrSize == 0);
1748 assert(nextSymbolPos >= pos + ptrSize);
1749 }
else if (ptrSize == 4)
1756void NVPTXAsmPrinter::emitDemotedVars(
const Function *
F, raw_ostream &O) {
1757 auto It = localDecls.find(
F);
1758 if (It == localDecls.end())
1763 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1766 for (
const GlobalVariable *GV : GVars) {
1767 O <<
"\t// demoted variable\n\t";
1768 printModuleLevelGV(GV, O,
true, STI);
1772void NVPTXAsmPrinter::emitPTXAddressSpace(
unsigned int AddressSpace,
1773 raw_ostream &O)
const {
1795NVPTXAsmPrinter::getPTXFundamentalTypeStr(
Type *Ty,
bool useB4PTR)
const {
1797 case Type::IntegerTyID: {
1801 if (NumBits <= 64) {
1802 std::string
name =
"u";
1808 case Type::BFloatTyID:
1809 case Type::HalfTyID:
1813 case Type::FloatTyID:
1815 case Type::DoubleTyID:
1817 case Type::PointerTyID: {
1819 assert((PtrSize == 64 || PtrSize == 32) &&
"Unexpected pointer size");
1837void NVPTXAsmPrinter::emitPTXGlobalVariable(
const GlobalVariable *GVar,
1839 const NVPTXSubtarget &STI) {
1840 const DataLayout &
DL = getDataLayout();
1848 if (!STI.hasFeature(NVPTX::PTX40) || !STI.hasFeature(NVPTX::SM30))
1850 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1852 O <<
" .attribute(.managed)";
1855 << GVar->
getAlign().value_or(
DL.getPrefTypeAlign(ETy)).value();
1860 getSymbol(GVar)->print(O, MAI);
1866 O <<
" ." << getPTXFundamentalTypeStr(ETy) <<
" ";
1867 getSymbol(GVar)->print(O, MAI);
1871 int64_t ElementSize = 0;
1878 case Type::StructTyID:
1879 case Type::ArrayTyID:
1880 case Type::FixedVectorTyID:
1881 ElementSize =
DL.getTypeStoreSize(ETy);
1883 getSymbol(GVar)->print(O, MAI);
1895void NVPTXAsmPrinter::emitFunctionParamList(
const Function *
F, raw_ostream &O) {
1896 const DataLayout &
DL = getDataLayout();
1897 const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
1899 const NVPTXMachineFunctionInfo *MFI =
1900 MF ? MF->
getInfo<NVPTXMachineFunctionInfo>() : nullptr;
1902 bool IsFirst =
true;
1909 const auto NonEmptyArgs =
1911 return !Arg.getType()->isEmptyTy();
1914 if (NonEmptyArgs.empty() && !
F->isVarArg()) {
1921 for (
const auto &[ParamIndex, Arg] :
enumerate(NonEmptyArgs)) {
1922 Type *Ty = Arg.getType();
1923 MCSymbol *
const ParamSym = TLI->getParamSymbol(OutContext,
F, ParamIndex);
1933 if (ArgOpaqueType != PTXOpaqueType::None) {
1939 switch (ArgOpaqueType) {
1940 case PTXOpaqueType::Sampler:
1941 O <<
".samplerref ";
1943 case PTXOpaqueType::Texture:
1946 case PTXOpaqueType::Surface:
1949 case PTXOpaqueType::None:
1957 if (Arg.hasByValAttr()) {
1959 Type *ETy = Arg.getParamByValType();
1960 assert(ETy &&
"Param should have byval type");
1966 const unsigned ParamIdx = Arg.getArgNo() + AttributeList::FirstArgIndex;
1967 const Align OptimalAlign =
1971 O <<
"\t.param .align " << OptimalAlign.
value() <<
" .b8 " << *ParamSym
1972 <<
"[" <<
DL.getTypeAllocSize(ETy) <<
"]";
1982 F, Ty, Arg.getArgNo() + AttributeList::FirstArgIndex,
DL);
1984 O <<
"\t.param .align " << OptimalAlign.
value() <<
" .b8 " << *ParamSym
1985 <<
"[" <<
DL.getTypeAllocSize(Ty) <<
"]";
1991 unsigned PTySizeInBits = 0;
1994 TLI->getPointerTy(
DL, PTy->getAddressSpace()).getSizeInBits();
1995 assert(PTySizeInBits &&
"Invalid pointer size");
2000 O <<
"\t.param .u" << PTySizeInBits <<
" .ptr";
2002 switch (PTy->getAddressSpace()) {
2019 O <<
" .align " << Arg.getParamAlign().valueOrOne().value() <<
" "
2030 O << getPTXFundamentalTypeStr(Ty);
2031 O <<
" " << *ParamSym;
2040 assert(PTySizeInBits &&
"Invalid pointer size");
2041 Size = PTySizeInBits;
2044 O <<
"\t.param .b" <<
Size <<
" " << *ParamSym;
2047 if (
F->isVarArg()) {
2051 << *TLI->getParamSymbol(OutContext,
F, -1) <<
"[]";
2057void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
2059 auto *TS = getTargetStreamer();
2064 TS->emitLocalDirective(MFI.
getMaxAlign(), getFunctionFrameSymbol(),
2068 const NVPTXRegisterInfo *NRI =
2072 TS->emitRegDirective(
2073 NRI->getRegSizeInBits(FrameReg, *MRI).getFixedValue(),
2082 Register VR = Register::index2VirtReg(
I);
2085 auto &RCRegMap = VRegMapping[MRI->
getRegClass(VR)];
2086 RCRegMap[VR] = RCRegMap.
size() + 1;
2094 const auto It = VRegMapping.
find(&RC);
2095 if (It == VRegMapping.
end() || It->second.empty())
2098 TS->emitRegDirective(
2099 TRI->getRegSizeInBits(RC).getFixedValue(),
2101 It->second.size() + 1);
2107void NVPTXAsmPrinter::encodeDebugInfoRegisterNumbers(
2109 const NVPTXSubtarget &STI = MF.
getSubtarget<NVPTXSubtarget>();
2119 NRI->addToDebugRegisterMap(
Reg, getVirtualRegisterName(
Reg));
2122void NVPTXAsmPrinter::printFPConstant(
const ConstantFP *Fp,
2123 raw_ostream &O)
const {
2126 unsigned int numHex;
2132 APF.
convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &ignored);
2136 APF.
convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &ignored);
2144void NVPTXAsmPrinter::printScalarConstant(
const Constant *CPV, raw_ostream &O) {
2150 printFPConstant(CFP, O);
2159 if (EmitGeneric && !
isa<Function>(CPV) && !IsNonGenericPointer) {
2161 getSymbol(GVar)->print(O, MAI);
2164 getSymbol(GVar)->print(O, MAI);
2176void NVPTXAsmPrinter::bufferLEByte(
const Constant *CPV,
int Bytes,
2177 AggBuffer *AggBuffer) {
2178 const DataLayout &
DL = getDataLayout();
2179 int AllocSize =
DL.getTypeAllocSize(CPV->
getType());
2183 AggBuffer->addZeros(Bytes ? Bytes : AllocSize);
2188 auto AddIntToBuffer = [AggBuffer, Bytes](
const APInt &Val) {
2189 size_t NumBytes = (Val.getBitWidth() + 7) / 8;
2195 for (
unsigned I = 0;
I < NumBytes - 1; ++
I) {
2196 Buf[
I] = Val.extractBitsAsZExtValue(8,
I * 8);
2198 size_t LastBytePosition = (NumBytes - 1) * 8;
2199 size_t LastByteBits = Val.getBitWidth() - LastBytePosition;
2201 Val.extractBitsAsZExtValue(LastByteBits, LastBytePosition);
2202 AggBuffer->addBytes(Buf.data(), NumBytes, Bytes);
2206 case Type::IntegerTyID:
2212 if (
const auto *CI =
2217 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2218 Value *
V = Cexpr->getOperand(0)->stripPointerCasts();
2219 AggBuffer->addSymbol(V, Cexpr->getOperand(0));
2220 AggBuffer->addZeros(AllocSize);
2227 AggBuffer->addSymbol(Cexpr, Cexpr);
2228 AggBuffer->addZeros(AllocSize);
2234 case Type::HalfTyID:
2235 case Type::BFloatTyID:
2236 case Type::FloatTyID:
2237 case Type::DoubleTyID:
2238 case Type::FP128TyID:
2242 case Type::PointerTyID: {
2244 AggBuffer->addSymbol(GVar, GVar);
2246 const Value *
v = Cexpr->stripPointerCasts();
2247 AggBuffer->addSymbol(v, Cexpr);
2249 AggBuffer->addZeros(AllocSize);
2253 case Type::ArrayTyID:
2254 case Type::FixedVectorTyID:
2255 case Type::StructTyID: {
2259 unsigned StartPos = AggBuffer->getCurpos();
2260 bufferAggregateConstant(CPV, AggBuffer);
2261 unsigned Written = AggBuffer->getCurpos() - StartPos;
2262 unsigned SlotSize = std::max<int>(Bytes, AllocSize);
2263 if (SlotSize > Written)
2264 AggBuffer->addZeros(SlotSize - Written);
2266 AggBuffer->addZeros(Bytes);
2277void NVPTXAsmPrinter::bufferAggregateConstant(
const Constant *CPV,
2278 AggBuffer *aggBuffer) {
2279 const DataLayout &
DL = getDataLayout();
2281 auto ExtendBuffer = [](APInt Val, AggBuffer *Buffer) {
2284 unsigned NumBits = std::min(8u, Val.
getBitWidth() -
I * 8);
2292 for (
unsigned I :
llvm::seq(VTy->getNumElements()))
2301 ExtendBuffer(CI->
getValue(), aggBuffer);
2307 assert(CFP->getType()->isFloatingPointTy() &&
"Expected fp constant!");
2308 if (CFP->getType()->isFP128Ty()) {
2309 ExtendBuffer(CFP->getValueAPF().bitcastToAPInt(), aggBuffer);
2323 bufferAggregateConstVec(CVec, aggBuffer);
2328 for (
unsigned I :
llvm::seq(CDS->getNumElements()))
2329 bufferLEByte(
cast<Constant>(CDS->getElementAsConstant(
I)), 0, aggBuffer);
2338 ?
DL.getStructLayout(ST)->getElementOffset(0) +
2339 DL.getTypeAllocSize(ST)
2340 :
DL.getStructLayout(ST)->getElementOffset(
I + 1);
2341 int Bytes = EndOffset -
DL.getStructLayout(ST)->getElementOffset(
I);
2350void NVPTXAsmPrinter::bufferAggregateConstVec(
const ConstantVector *CV,
2351 AggBuffer *aggBuffer) {
2353 const unsigned BuffSize = aggBuffer->getBufferSize();
2356 if (BuffSize >= NumElems) {
2369 assert(ElemTySize < 8 &&
"Expected sub-byte data type.");
2370 assert(8 % ElemTySize == 0 &&
"Element type size must evenly divide a byte.");
2372 unsigned NumElemsPerByte = 8 / ElemTySize;
2373 unsigned NumCompleteBytes = NumElems / NumElemsPerByte;
2374 unsigned NumTailElems = NumElems % NumElemsPerByte;
2379 auto ConvertSubCVtoInt8 = [
this, &ElemTy](
const ConstantVector *CV,
2380 unsigned Start,
unsigned End,
2381 unsigned NumPaddingZeros = 0) {
2388 if (NumPaddingZeros)
2389 SubCVElems.
append(NumPaddingZeros, ConstantInt::getNullValue(ElemTy));
2395 ConstantInt *MergedElem =
2402 "Cannot lower vector global with unusual element type");
2409 for (
unsigned ByteIdx :
llvm::seq(NumCompleteBytes))
2410 bufferLEByte(ConvertSubCVtoInt8(CV, ByteIdx * NumElemsPerByte,
2411 (ByteIdx + 1) * NumElemsPerByte),
2415 if (NumTailElems > 0)
2416 bufferLEByte(ConvertSubCVtoInt8(CV, NumElems - NumTailElems, NumElems,
2417 NumElemsPerByte - NumTailElems),
2426NVPTXAsmPrinter::lowerConstantForGV(
const Constant *CV,
2427 bool ProcessingGeneric)
const {
2428 MCContext &Ctx = OutContext;
2438 if (ProcessingGeneric)
2448 switch (
CE->getOpcode()) {
2452 case Instruction::AddrSpaceCast: {
2455 if (DstTy->getAddressSpace() == 0)
2461 case Instruction::GetElementPtr: {
2462 const DataLayout &
DL = getDataLayout();
2465 APInt OffsetAI(
DL.getPointerTypeSizeInBits(
CE->getType()), 0);
2468 const MCExpr *
Base = lowerConstantForGV(
CE->getOperand(0),
2473 int64_t
Offset = OffsetAI.getSExtValue();
2478 case Instruction::Trunc:
2484 case Instruction::BitCast:
2485 return lowerConstantForGV(
CE->getOperand(0), ProcessingGeneric);
2487 case Instruction::IntToPtr: {
2488 const DataLayout &
DL = getDataLayout();
2496 return lowerConstantForGV(
Op, ProcessingGeneric);
2501 case Instruction::PtrToInt: {
2502 const DataLayout &
DL = getDataLayout();
2507 Type *Ty =
CE->getType();
2509 const MCExpr *OpExpr = lowerConstantForGV(
Op, ProcessingGeneric);
2513 if (
DL.getTypeAllocSize(Ty) ==
DL.getTypeAllocSize(
Op->getType()))
2519 unsigned InBits =
DL.getTypeAllocSizeInBits(
Op->getType());
2526 case Instruction::Add: {
2527 const MCExpr *
LHS = lowerConstantForGV(
CE->getOperand(0), ProcessingGeneric);
2528 const MCExpr *
RHS = lowerConstantForGV(
CE->getOperand(1), ProcessingGeneric);
2529 switch (
CE->getOpcode()) {
2541 return lowerConstantForGV(
C, ProcessingGeneric);
2545 raw_string_ostream OS(S);
2546 OS <<
"Unsupported expression in static initializer: ";
2547 CE->printAsOperand(OS,
false,
2552void NVPTXAsmPrinter::printMCExpr(
const MCExpr &Expr, raw_ostream &OS)
const {
2553 OutContext.getAsmInfo().printExpr(OS, Expr);
2558bool NVPTXAsmPrinter::PrintAsmOperand(
const MachineInstr *
MI,
unsigned OpNo,
2559 const char *ExtraCode, raw_ostream &O) {
2560 if (ExtraCode && ExtraCode[0]) {
2561 if (ExtraCode[1] != 0)
2564 switch (ExtraCode[0]) {
2578bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
const MachineInstr *
MI,
2580 const char *ExtraCode,
2582 if (ExtraCode && ExtraCode[0])
2592void NVPTXAsmPrinter::printOperand(
const MachineInstr *
MI,
unsigned OpNum,
2594 const MachineOperand &MO =
MI->getOperand(OpNum);
2598 if (MO.
getReg() == NVPTX::VRDepot)
2599 getFunctionFrameSymbol()->print(O, MAI);
2603 O << getVirtualRegisterName(MO.
getReg());
2616 PrintSymbolOperand(MO, O);
2632void NVPTXAsmPrinter::printMemOperand(
const MachineInstr *
MI,
unsigned OpNum,
2633 raw_ostream &O,
const char *Modifier) {
2636 if (Modifier && strcmp(Modifier,
"add") == 0) {
2640 if (
MI->getOperand(OpNum + 1).isImm() &&
2641 MI->getOperand(OpNum + 1).getImm() == 0)
2652 return !Trimmed.
empty() &&
2653 (std::isalpha(
static_cast<unsigned char>(Trimmed[0])) ||
2660 if (!
MI || !
MI->getDebugLoc())
2662 const DISubprogram *SP =
MI->getMF()->getFunction().getSubprogram();
2666 if (!
DL->getFile() || !
DL->getLine())
2672struct InlineAsmInliningContext {
2674 unsigned FileIA = 0;
2675 unsigned LineIA = 0;
2678 bool hasInlinedAt()
const {
return FuncNameSym !=
nullptr; }
2684static InlineAsmInliningContext
2688 InlineAsmInliningContext Ctx;
2690 if (!InlinedAt || !InlinedAt->getFile() || !NVDD ||
2697 Ctx.FileIA =
Streamer.emitDwarfFileDirective(
2698 0, InlinedAt->getFile()->getDirectory(),
2699 InlinedAt->getFile()->getFilename(), std::nullopt, std::nullopt, CUID);
2700 Ctx.LineIA = InlinedAt->getLine();
2701 Ctx.ColIA = InlinedAt->getColumn();
2705void NVPTXAsmPrinter::emitInlineAsm(StringRef Str,
const MCSubtargetInfo &STI,
2706 const MCTargetOptions &MCOptions,
2707 const MDNode *LocMDNode,
2709 const MachineInstr *
MI) {
2710 assert(!Str.empty() &&
"Can't emit empty inline asm block");
2711 if (Str.back() == 0)
2712 Str = Str.substr(0, Str.size() - 1);
2714 auto emitAsmStr = [&](StringRef AsmStr) {
2715 emitInlineAsmStart();
2716 OutStreamer->emitRawText(AsmStr);
2717 emitInlineAsmEnd(STI,
nullptr,
MI);
2726 const DIFile *
File =
DL->getFile();
2727 unsigned Line =
DL->getLine();
2728 const unsigned Column =
DL->getColumn();
2729 const unsigned CUID = OutStreamer->getContext().getDwarfCompileUnitID();
2730 const unsigned FileNumber = OutStreamer->emitDwarfFileDirective(
2731 0,
File->getDirectory(),
File->getFilename(), std::nullopt, std::nullopt,
2734 auto *NVDD =
static_cast<NVPTXDwarfDebug *
>(getDwarfDebug());
2735 InlineAsmInliningContext InlineCtx =
2738 SmallVector<StringRef, 16>
Lines;
2739 Str.split(Lines,
'\n');
2740 emitInlineAsmStart();
2741 for (
const StringRef &L : Lines) {
2742 StringRef RTrimmed =
L.rtrim(
'\r');
2744 if (InlineCtx.hasInlinedAt()) {
2745 OutStreamer->emitDwarfLocDirectiveWithInlinedAt(
2746 FileNumber, Line, Column, InlineCtx.FileIA, InlineCtx.LineIA,
2748 File->getFilename());
2750 OutStreamer->emitDwarfLocDirective(FileNumber, Line, Column,
2752 File->getFilename());
2755 OutStreamer->emitRawText(RTrimmed);
2758 emitInlineAsmEnd(STI,
nullptr,
MI);
2761char NVPTXAsmPrinter::ID = 0;
2768LLVMInitializeNVPTXAsmPrinter() {
2789 Printer.runOnMachineFunction(MF);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu next use AMDGPU Next Use Analysis Printer
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 MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_EXTERNAL_VISIBILITY
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool hasDebugInfo(const MachineFunction *MF)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
static MCOperand GetSymbolRef(const MachineOperand &MO, const MCSymbol *Symbol, HexagonAsmPrinter &Printer, bool MustExtend)
Module.h This file contains the declarations for the Module class.
#define DWARF2_FLAG_IS_STMT
Machine Check Debug Module
Register const TargetRegisterInfo * TRI
Promote Memory to Register
static void emitInlineAsm(LLVMContext &C, BasicBlock *BB, StringRef AsmText)
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,...
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 NVPTX::VirtualRegisterKind getVirtualRegisterKind(const TargetRegisterClass *RC)
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.
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
static void printMemOperand(raw_ostream &OS, const MachineMemOperand &MMO, const MachineFunction *MF, const Module *M, const MachineFrameInfo *MFI, const TargetInstrInfo *TII, LLVMContext &Ctx)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
std::unique_ptr< MCStreamer > && Streamer
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
APInt bitcastToAPInt() const
uint64_t getZExtValue() const
Get zero extended value.
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
unsigned getBitWidth() const
Return the number of bits in the APInt.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
This class is intended to be used as a driving class for all asm writers.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
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.
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.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
const APFloat & getValueAPF() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
Constant Vector Declarations.
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
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)
Collects and handles dwarf debug information.
const MachineInstr * emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
unsigned getNumElements() const
Type * getReturnType() const
DISubprogram * getSubprogram() const
Get the attached subprogram.
LLVM_ABI const GlobalObject * getAliaseeObject() const
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...
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
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.
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())
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Base class for the full range of assembler expressions which are needed for parsing.
Instances of this class represent a single low-level machine instruction.
void addOperand(const MCOperand Op)
void setOpcode(unsigned Op)
Instances of this class represent operands of the MCInst class.
static MCOperand createExpr(const MCExpr *Val)
static MCOperand createReg(MCRegister Reg)
static MCOperand createImm(int64_t Val)
Wrapper class representing physical registers. Should be passed by value.
Streaming machine code generation interface.
virtual bool hasRawTextSupport() const
Return true if this asm streamer supports emitting unformatted text to the .s file with EmitRawText.
Generic base class for all target subtargets.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
LLVM_ABI void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
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 alignment of this function's frame.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() 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
MCSymbol * getMCSymbol() const
@ MO_Immediate
Immediate operand.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_FPImmediate
Floating-point immediate operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
A Module instance is used to store all the information related to an LLVM module.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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)
static const NVPTXFloatMCExpr * createConstantFPHalf(const APFloat &Flt, MCContext &Ctx)
static const NVPTXFloatMCExpr * createConstantFPSingle(const APFloat &Flt, MCContext &Ctx)
static const NVPTXFloatMCExpr * createConstantFPDouble(const APFloat &Flt, MCContext &Ctx)
static const NVPTXGenericMCSymbolRefExpr * create(const MCSymbolRefExpr *SymExpr, MCContext &Ctx)
static const char * getRegisterName(MCRegister Reg)
bool checkImageHandleSymbol(const MCSymbol *Symbol) const
Check whether Symbol's handle was replaced with an image reference.
void clearDebugRegisterMap() const
Register getFrameLocalRegister(const MachineFunction &MF) const
Register getFrameRegister(const MachineFunction &MF) const override
unsigned getMaxRequiredAlignment() const
StringRef getTargetName() const
bool hasMaskOperator() const
const NVPTXTargetLowering * getTargetLowering() const override
unsigned getPTXVersion() const
const NVPTXRegisterInfo * getRegisterInfo() const override
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.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr unsigned id() const
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
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
typename SuperClass::const_iterator const_iterator
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.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
Primary interface to the complete machine description for the target machine.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeID getTypeID() const
Return the type id for the type.
bool isVoidTy() const
Return true if this is 'void'.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
iterator_range< user_iterator > users()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
This class implements an extremely fast bulk output stream that can only output to a stream.
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.
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)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
std::pair< NodeId, LaneBitmask > NodeRef
NodeAddr< NodeBase * > Node
uint64_t read64le(const void *P)
uint32_t read32le(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
bool isManaged(const Value &)
SmallVector< unsigned, 3 > getReqNTID(const Function &)
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...
Align getDeviceByValParamAlign(const Function *F, Type *ArgTy, unsigned AttrIdx, const DataLayout &DL)
The .param-space alignment for a byval parameter or call argument: the (possibly promoted) parameter ...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
bool hasBlocksAreClusters(const Function &)
SmallVector< unsigned, 3 > getClusterDim(const Function &)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
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...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::optional< unsigned > getMaxNReg(const Function &)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
PTXOpaqueType getPTXOpaqueType(const GlobalVariable &)
std::string utostr(uint64_t X, bool isNeg=false)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
std::optional< unsigned > getMinCTASm(const Function &)
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)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
void sort(IteratorTy Start, IteratorTy End)
unsigned promoteScalarArgumentSize(unsigned size)
SmallVector< unsigned, 3 > getMaxNTID(const Function &)
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
bool shouldPassAsArray(Type *Ty)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
std::optional< unsigned > getMaxClusterRank(const Function &)
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.
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...
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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)
Alignment for a function parameter or return value at AttributeList index AttrIdx (FirstArgIndex + ar...
ArrayRef(const T &OneElt) -> ArrayRef< T >
Target & getTheNVPTXTarget64()
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
bool isKernelFunction(const Function &F)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
void clearAnnotationCache(const Module *)
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...
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.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Target & getTheNVPTXTarget32()
MCRegisterClass TargetRegisterClass
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
MachineJumpTableEntry - One jump table in the jump table info.
std::vector< MachineBasicBlock * > MBBs
MBBs - The vector of basic blocks from which to create the jump table.
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...