111#define DEPOTNAME "__local_depot"
145 unsigned numSymbols()
const {
return Symbols.size(); }
147 bool allSymbolsAligned(
unsigned ptrSize)
const {
149 [=](
unsigned pos) {
return pos % ptrSize == 0; });
154 std::vector<unsigned char> buffer;
166 const NVPTXAsmPrinter &AP;
167 const bool EmitGeneric;
170 AggBuffer(
unsigned Size,
const NVPTXAsmPrinter &AP)
172 EmitGeneric(AP.EmitGeneric) {}
175 unsigned getCurpos()
const {
return curpos; }
179 void addBytes(
const unsigned char *Ptr,
unsigned Num,
unsigned Bytes) {
183 addZeros(Bytes - Num);
188 buffer[curpos] = Byte;
192 void addZeros(
unsigned Num) {
193 for ([[maybe_unused]]
unsigned _ :
llvm::seq(Num)) {
200 Symbols.push_back(GVar);
201 SymbolsBeforeStripping.
push_back(GVarBeforeStripping);
211 friend class AggBuffer;
216 StringRef getPassName()
const override {
return "NVPTX Assembly Printer"; }
223 void emitStartOfAsmFile(
Module &M)
override;
225 void emitFunctionEntryLabel()
override;
226 void emitFunctionBodyStart()
override;
227 void emitFunctionBodyEnd()
override;
238 unsigned getVirtualRegisterNumber(
Register Reg)
const;
241 const char *Modifier =
nullptr);
246 template <
typename T>
247 void printFunctionDirectives(
const T &
V,
raw_ostream &O)
const;
249 void emitGlobals(
const Module &M);
256 void emitCallPrototype(
const CallBase &CB,
MCSymbol *PrototypeSymbol)
const;
266 bool ProcessingGeneric)
const;
275 bool doInitialization(
Module &M)
override;
276 bool doFinalization(
Module &M)
override;
291 VRegRCMap VRegMapping;
294 std::map<const Function *, std::vector<const GlobalVariable *>> localDecls;
303 bool EmitInitializer);
305 std::string getPTXFundamentalTypeStr(
Type *Ty)
const;
308 void bufferLEByte(
const Constant *CPV,
int Bytes, AggBuffer *aggBuffer);
309 void bufferAggregateConstant(
const Constant *CV, AggBuffer *aggBuffer);
331 const bool EmitGeneric;
346 std::string getVirtualRegisterName(
Register Reg)
const;
348 const MCSymbol *getFunctionFrameSymbol()
const override;
376 if (SP->getUnit()->isDebugDirectivesOnly() || SP->getUnit()->isNoDebug())
386discoverDependentGlobals(
const Value *
V,
387 SmallVectorImpl<const GlobalVariable *> &Globals,
388 SmallPtrSetImpl<const GlobalVariable *> &Seen) {
390 if (Seen.
insert(GV).second)
403 discoverDependentGlobals(
GEP->getPointerOperand(), Globals, Seen);
408 for (
const auto &O :
U->operands())
409 discoverDependentGlobals(O, Globals, Seen);
412struct GlobalVariableDependencyNode {
413 const GlobalVariable *GV =
nullptr;
414 unsigned ModuleOrder = 0;
418class GlobalVariableDependencyGraph {
421 GlobalVariableDependencyNode SyntheticRoot;
424 std::map<const GlobalVariable *, GlobalVariableDependencyNode> Nodes;
427 explicit GlobalVariableDependencyGraph(
const Module &M) {
428 unsigned ModuleOrder = 0;
429 for (
const GlobalVariable &GV :
M.globals()) {
430 GlobalVariableDependencyNode &
Node = Nodes.try_emplace(&GV).first->second;
432 Node.ModuleOrder = ModuleOrder++;
433 SyntheticRoot.Dependencies.push_back(&Node);
436 for (
auto &[GV, Node] : Nodes) {
438 SmallPtrSet<const GlobalVariable *, 4> Seen;
439 for (
const Use &Operand : GV->operands())
440 discoverDependentGlobals(Operand, Dependencies, Seen);
442 for (
const GlobalVariable *Dependency : Dependencies) {
443 auto It = Nodes.find(Dependency);
444 if (It != Nodes.end())
445 Node.Dependencies.push_back(&It->second);
450 const GlobalVariableDependencyNode *getEntryNode()
const {
451 return &SyntheticRoot;
455struct GlobalVariableDependencyGraphTraits {
456 using NodeRef =
const GlobalVariableDependencyNode *;
457 using ChildIteratorType =
460 static NodeRef getEntryNode(NodeRef Node) {
return Node; }
461 static ChildIteratorType child_begin(NodeRef Node) {
462 return Node->Dependencies.begin();
464 static ChildIteratorType child_end(NodeRef Node) {
465 return Node->Dependencies.end();
469using GlobalVariableSCCIterator =
470 scc_iterator<
const GlobalVariableDependencyNode *,
471 GlobalVariableDependencyGraphTraits>;
473static bool shouldSkipModuleLevelGlobal(
const GlobalVariable &GV) {
479static bool isForwardDeclarableGlobal(
const GlobalVariable *GVar) {
480 if (shouldSkipModuleLevelGlobal(*GVar) || GVar->
isDeclaration() ||
501 const DenseSet<const GlobalVariableDependencyNode *> &ForwardDeclared) {
502 using Node = GlobalVariableDependencyNode;
504 DenseSet<const Node *> SCCSet;
507 DenseMap<const Node *, unsigned> DependencyCount;
508 DenseMap<const Node *, SmallVector<const Node *, 4>> Dependents;
509 std::set<std::pair<unsigned, const Node *>>
Ready;
513 for (
const Node *
N : SCC) {
514 unsigned &
Count = DependencyCount[
N];
515 for (
const Node *Dependency :
N->Dependencies) {
516 if (!SCCSet.
count(Dependency) || ForwardDeclared.
count(Dependency))
519 Dependents[Dependency].push_back(
N);
522 Ready.emplace(
N->ModuleOrder,
N);
526 while (!
Ready.empty()) {
531 auto It = Dependents.
find(
N);
532 if (It == Dependents.
end())
534 for (
const Node *Dependent : It->second) {
535 assert(DependencyCount[Dependent] &&
"Dependency already satisfied");
536 if (--DependencyCount[Dependent] == 0)
537 Ready.emplace(Dependent->ModuleOrder, Dependent);
541 if (Order.
size() !=
SCC.size())
549 NVPTX_MC::verifyInstructionPredicates(
MI->getOpcode(),
550 getSubtargetInfo().getFeatureBits());
553 lowerToMCInst(
MI, Inst);
554 EmitToStreamer(*OutStreamer, Inst);
557void NVPTXAsmPrinter::lowerToMCInst(
const MachineInstr *
MI, MCInst &OutMI) {
559 for (
const auto MO :
MI->operands())
563MCOperand NVPTXAsmPrinter::lowerOperand(
const MachineOperand &MO) {
595 case Type::BFloatTyID:
598 case Type::FloatTyID:
601 case Type::DoubleTyID:
610static NVPTX::VirtualRegisterKind
612 if (RC == &NVPTX::B1RegClass)
614 if (RC == &NVPTX::B16RegClass)
616 if (RC == &NVPTX::B32RegClass)
618 if (RC == &NVPTX::B64RegClass)
620 if (RC == &NVPTX::B128RegClass)
625unsigned NVPTXAsmPrinter::getVirtualRegisterNumber(
Register Reg)
const {
627 assert(It != VRegMapping.
end() &&
"Bad register class");
629 const unsigned Num = It->second.lookup(
Reg);
630 assert(Num &&
"Bad virtual register");
634MCRegister NVPTXAsmPrinter::encodeVirtualRegister(
Register Reg) {
639 const unsigned Num = getVirtualRegisterNumber(
Reg);
640 assert(Num <= NVPTX::VirtualRegisterNumMask &&
641 "Too many virtual registers");
642 return (
static_cast<unsigned>(Kind) << NVPTX::VirtualRegisterKindShift) |
648 assert(
Reg.
id() <= NVPTX::VirtualRegisterNumMask &&
649 "Physical register would decode as a virtual register");
653MCOperand NVPTXAsmPrinter::GetSymbolRef(
const MCSymbol *Symbol) {
659template <
typename OwnerT>
661 bool IsByVal,
bool IsKernel,
StringRef Name,
666 const Align ParamAlign =
669 O <<
".align " << ParamAlign.
value() <<
" .b8 " << Name <<
"["
670 <<
DL.getTypeAllocSize(Ty) <<
"]";
674 assert((Ty->isFloatingPointTy() || Ty->isIntOrPtrTy()) &&
675 "Unknown parameter type");
676 const unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
683template <
typename OwnerT>
686 Type *RetTy =
Owner->getFunctionType()->getReturnType();
700void NVPTXAsmPrinter::emitCallPrototype(
const CallBase &CB,
701 MCSymbol *PrototypeSymbol)
const {
702 const DataLayout &
DL = getDataLayout();
703 const NVPTXSubtarget &STI = MF->getSubtarget<NVPTXSubtarget>();
705 OutStreamer->emitLabel(PrototypeSymbol);
707 SmallString<128> Str;
708 raw_svector_ostream
O(Str);
710 O <<
".callprototype ";
714 auto MakeArg = [&](
const unsigned I) {
719 printParam(&CB, Ty,
I + AttributeList::FirstArgIndex, IsByVal,
724 const unsigned NumArgs = FTy->getNumParams();
734 if (FTy->isVarArg() && CB.
arg_size() > NumArgs)
735 O << (NonEmptyArgs.empty() ?
"" :
",") <<
" .param .align "
739 printFunctionDirectives(CB, O);
742 OutStreamer->emitRawText(
O.str());
745void NVPTXAsmPrinter::emitJumpTable(
const MachineJumpTableEntry &MJT,
746 unsigned MJTI)
const {
747 OutStreamer->emitLabel(GetJTISymbol(MJTI));
749 if (MJT.
MBBs.empty())
754 return MBB->getSymbol();
756 getTargetStreamer()->emitBranchTargetsDirective(Targets);
761bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
762 const MachineBasicBlock &
MBB)
const {
763 const MachineLoopInfo *LI = GetMLI(*MF);
764 assert(LI &&
"NVPTXAsmPrinter requires MachineLoopInfo");
777 if (
const BasicBlock *PBB = PMBB->getBasicBlock()) {
779 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
782 if (MDNode *UnrollCountMD =
794void NVPTXAsmPrinter::emitBasicBlockStart(
const MachineBasicBlock &
MBB) {
796 if (isLoopHeaderOfNoUnroll(
MBB))
797 getTargetStreamer()->emitPragmaDirective(
"nounroll");
800void NVPTXAsmPrinter::emitFunctionEntryLabel() {
801 SmallString<128> Str;
802 raw_svector_ostream
O(Str);
804 if (!GlobalsEmitted) {
805 emitGlobals(*MF->getFunction().getParent());
806 GlobalsEmitted =
true;
810 MRI = &MF->getRegInfo();
811 F = &MF->getFunction();
812 emitLinkageDirective(
F, O);
820 CurrentFnSym->print(O, MAI);
822 emitFunctionParamList(
F, O);
826 emitKernelFunctionDirectives(*
F, O);
828 printFunctionDirectives(*
F, O);
830 OutStreamer->emitRawText(
O.str());
834 OutStreamer->emitRawText(StringRef(
"{\n"));
835 setAndEmitFunctionVirtualRegisters(*MF);
836 encodeDebugInfoRegisterNumbers(*MF);
848 OutStreamer->emitRawText(StringRef(
"}\n"));
852void NVPTXAsmPrinter::emitFunctionBodyStart() {
853 SmallString<128> Str;
854 raw_svector_ostream
O(Str);
855 emitDemotedVars(&MF->getFunction(), O);
856 OutStreamer->emitRawText(
O.str());
858 const auto *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
859 for (
const auto &[CB, Symbol] : MFI->getCallPrototypes())
860 emitCallPrototype(*CB, Symbol);
862 if (
const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo())
863 for (
const auto &[Idx, JT] :
enumerate(MJTI->getJumpTables()))
864 emitJumpTable(JT, Idx);
867void NVPTXAsmPrinter::emitFunctionBodyEnd() {
871const MCSymbol *NVPTXAsmPrinter::getFunctionFrameSymbol()
const {
872 return OutContext.getOrCreateSymbol(
DEPOTNAME + Twine(getFunctionNumber()));
875void NVPTXAsmPrinter::emitImplicitDef(
const MachineInstr *
MI)
const {
878 OutStreamer->AddComment(Twine(
"implicit-def: ") +
879 getVirtualRegisterName(RegNo));
881 OutStreamer->AddComment(Twine(
"implicit-def: ") +
883 OutStreamer->addBlankLine();
886void NVPTXAsmPrinter::emitKernelFunctionDirectives(
const Function &
F,
887 raw_ostream &O)
const {
893 O <<
formatv(
".reqntid {0:$[, ]}\n",
898 O <<
formatv(
".maxntid {0:$[, ]}\n",
902 O <<
".minnctapersm " << *Mincta <<
"\n";
905 O <<
".maxnreg " << *Maxnreg <<
"\n";
909 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
910 const NVPTXSubtarget *STI = &NTM.
getSubtarget<NVPTXSubtarget>(
F);
912 if (STI->hasFeature(NVPTX::SM90)) {
918 if (!BlocksAreClusters)
919 O <<
".explicitcluster\n";
921 if (ClusterDim[0] != 0) {
923 "cluster_dim_x != 0 implies cluster_dim_y and cluster_dim_z "
924 "should be non-zero as well");
926 O <<
formatv(
".reqnctapercluster {0:$[, ]}\n",
930 "cluster_dim_x == 0 implies cluster_dim_y and cluster_dim_z "
931 "should be 0 as well");
935 if (BlocksAreClusters) {
936 LLVMContext &Ctx =
F.getContext();
938 Ctx.
diagnose(DiagnosticInfoUnsupported(
939 F,
"blocksareclusters requires reqntid and cluster_dim attributes",
941 else if (!STI->hasFeature(NVPTX::PTX90))
942 Ctx.
diagnose(DiagnosticInfoUnsupported(
943 F,
"blocksareclusters requires PTX version >= 9.0",
946 O <<
".blocksareclusters\n";
950 O <<
".maxclusterrank " << *Maxclusterrank <<
"\n";
954std::string NVPTXAsmPrinter::getVirtualRegisterName(
Register Reg)
const {
958 raw_string_ostream(Name) << NVPTX::getVirtualRegisterPrefix(Kind)
959 << getVirtualRegisterNumber(
Reg);
963void NVPTXAsmPrinter::emitAliasDeclaration(
const GlobalAlias *GA,
968 "NVPTX aliasee must be a non-kernel function definition");
974 emitDeclarationWithName(
F, getSymbol(GA), O);
977void NVPTXAsmPrinter::emitDeclaration(
const Function *
F, raw_ostream &O) {
978 emitDeclarationWithName(
F, getSymbol(
F), O);
981void NVPTXAsmPrinter::emitDeclarationWithName(
const Function *
F, MCSymbol *S,
983 emitLinkageDirective(
F, O);
992 emitFunctionParamList(
F, O);
995 printFunctionDirectives(*
F, O);
1004 return GV->
getName() !=
"llvm.used";
1006 for (
const User *U :
C->users())
1016 if (OtherGV->getName() ==
"llvm.used")
1020 if (
const Function *CurFunc =
I->getFunction()) {
1021 if (OneFunc && (CurFunc != OneFunc))
1062 for (
const User *U :
C->users()) {
1067 if (
const Function *Caller =
I->getFunction())
1075void NVPTXAsmPrinter::emitDeclarations(
const Module &M, raw_ostream &O) {
1076 SmallPtrSet<const Function *, 32> SeenSet;
1078 if (
F.getAttributes().hasFnAttr(
"nvptx-libcall-callee")) {
1079 emitDeclaration(&
F, O);
1083 if (
F.isDeclaration()) {
1086 if (
F.getIntrinsicID())
1090 if (
F.isIntrinsic()) {
1091 LLVMContext &Ctx =
F.getContext();
1092 Ctx.
diagnose(DiagnosticInfoUnsupported(
1093 F,
"unknown intrinsic '" +
F.getName() +
1094 "' cannot be lowered by the NVPTX backend"));
1097 emitDeclaration(&
F, O);
1100 for (
const User *U :
F.users()) {
1106 emitDeclaration(&
F, O);
1112 emitDeclaration(&
F, O);
1127 emitDeclaration(&
F, O);
1133 for (
const GlobalAlias &GA :
M.aliases())
1134 emitAliasDeclaration(&GA, O);
1137void NVPTXAsmPrinter::emitStartOfAsmFile(
Module &M) {
1141 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1145 emitHeader(M, *STI);
1149DwarfDebug *NVPTXAsmPrinter::createDwarfDebug() {
1150 return new NVPTXDwarfDebug(
this);
1153bool NVPTXAsmPrinter::doInitialization(
Module &M) {
1154 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1156 if (
M.alias_size() &&
1157 (!STI.hasFeature(NVPTX::PTX63) || !STI.hasFeature(NVPTX::SM30)))
1163 GlobalsEmitted =
false;
1167 for (
const GlobalValue &GV :
M.global_values())
1173void NVPTXAsmPrinter::emitGlobals(
const Module &M) {
1174 SmallString<128> Str2;
1175 raw_svector_ostream OS2(Str2);
1177 emitDeclarations(M, OS2);
1179 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1187 GlobalVariableDependencyGraph DependencyGraph(M);
1188 for (GlobalVariableSCCIterator
I =
1189 GlobalVariableSCCIterator::begin(DependencyGraph.getEntryNode());
1190 !
I.isAtEnd(); ++
I) {
1195 if (!
SCC.front()->GV) {
1196 assert(
SCC.size() == 1 &&
"Synthetic root must be in its own SCC");
1201 return LHS->ModuleOrder <
RHS->ModuleOrder;
1204 const bool IsCyclic =
I.hasCycle();
1205 DenseSet<const GlobalVariableDependencyNode *> ForwardDeclared;
1207 for (
const auto *Node : SCC)
1208 if (isForwardDeclarableGlobal(
Node->GV))
1209 ForwardDeclared.
insert(Node);
1213 IsCyclic ? orderDefinitionsInSCC(SCC, ForwardDeclared)
1216 for (
const auto *Node : SCC) {
1217 if (!ForwardDeclared.
count(Node))
1220 emitPTXGlobalVariableDefinition(
Node->GV, OS2, STI,
1225 for (
const GlobalVariable *GV : OrderedGlobals)
1226 printModuleLevelGV(GV, OS2,
false, STI);
1231 OutStreamer->emitRawText(OS2.str());
1234void NVPTXAsmPrinter::emitGlobalAlias(
const Module &M,
const GlobalAlias &GA) {
1235 getTargetStreamer()->emitAliasDirective(getSymbol(&GA),
1239NVPTXTargetStreamer *NVPTXAsmPrinter::getTargetStreamer()
const {
1240 return static_cast<NVPTXTargetStreamer *
>(OutStreamer->getTargetStreamer());
1245 switch(
CU->getEmissionKind()) {
1258void NVPTXAsmPrinter::emitHeader(
Module &M,
const NVPTXSubtarget &STI) {
1259 auto *TS = getTargetStreamer();
1264 TS->emitVersionDirective(PTXVersion);
1266 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1269 TS->emitTargetDirective(STI.
getTargetName(), TexModeIndependent,
1271 TS->emitAddressSizeDirective(
M.getDataLayout().getPointerSizeInBits());
1274bool NVPTXAsmPrinter::doFinalization(
Module &M) {
1277 if (!GlobalsEmitted) {
1279 GlobalsEmitted =
true;
1288 static_cast<NVPTXTargetStreamer *
>(OutStreamer->getTargetStreamer());
1291 TS->closeLastSection();
1293 TS->emitEmptySectionDirective(
".debug_macinfo");
1297 TS->outputDwarfFileDirectives();
1315void NVPTXAsmPrinter::emitLinkageDirective(
const GlobalValue *
V,
1317 if (
static_cast<NVPTXTargetMachine &
>(TM).getDrvInterface() == NVPTX::CUDA) {
1318 if (
V->hasExternalLinkage()) {
1321 else if (
V->isDeclaration())
1325 }
else if (
V->hasAppendingLinkage()) {
1327 "' has unsupported appending linkage type");
1328 }
else if (!
V->hasInternalLinkage() && !
V->hasPrivateLinkage()) {
1334void NVPTXAsmPrinter::printModuleLevelGV(
const GlobalVariable *GVar,
1335 raw_ostream &O,
bool ProcessDemoted,
1336 const NVPTXSubtarget &STI) {
1338 if (shouldSkipModuleLevelGlobal(*GVar))
1357 if (OpaqueType == PTXOpaqueType::Texture) {
1358 O <<
".global .texref ";
1359 getSymbol(GVar)->print(O, MAI);
1364 if (OpaqueType == PTXOpaqueType::Surface) {
1365 O <<
".global .surfref ";
1366 getSymbol(GVar)->print(O, MAI);
1375 emitPTXGlobalVariableDefinition(GVar, O, STI,
false);
1380 if (OpaqueType == PTXOpaqueType::Sampler) {
1381 O <<
".global .samplerref ";
1382 getSymbol(GVar)->print(O, MAI);
1384 const Constant *Initializer =
nullptr;
1387 const ConstantInt *CI =
nullptr;
1398 O <<
"addr_mode_" << i <<
" = ";
1404 O <<
"clamp_to_border";
1407 O <<
"clamp_to_edge";
1418 O <<
"filter_mode = ";
1433 O <<
", force_unnormalized_coords = 1";
1453 const Function *DemotedFunc =
nullptr;
1455 O <<
"// " << GVar->
getName() <<
" has been demoted\n";
1456 localDecls[DemotedFunc].push_back(GVar);
1460 emitPTXGlobalVariableDefinition(GVar, O, STI,
true);
1464template <
typename T>
1465void NVPTXAsmPrinter::printFunctionDirectives(
const T &
V,
1466 raw_ostream &O)
const {
1467 const NVPTXSubtarget &STI =
1468 *
static_cast<const NVPTXTargetMachine &
>(TM).getSubtargetImpl();
1471 V.getFunctionType()->getReturnType()->isVoidTy())
1481 O <<
".abi_preserve " << *
ABI.Preserve <<
"\n";
1482 if (
ABI.PreserveControl)
1483 O <<
".abi_preserve_control " << *
ABI.PreserveControl <<
"\n";
1486void NVPTXAsmPrinter::emitPTXGlobalVariableDefinition(
1487 const GlobalVariable *GVar, raw_ostream &O,
const NVPTXSubtarget &STI,
1488 bool EmitInitializer) {
1489 const DataLayout &
DL = getDataLayout();
1496 if (!STI.hasFeature(NVPTX::PTX40) || !STI.hasFeature(NVPTX::SM30))
1498 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1499 O <<
" .attribute(.managed)";
1503 << GVar->
getAlign().value_or(
DL.getPrefTypeAlign(ETy)).value();
1505 const Constant *Initializer =
nullptr;
1512 "' is not allowed in addrspace(" +
1520 O <<
" ." << getPTXFundamentalTypeStr(ETy) <<
" ";
1521 getSymbol(GVar)->print(O, MAI);
1523 if (EmitInitializer && Initializer) {
1525 printScalarConstant(Initializer, O);
1536 "type not supported yet");
1538 const uint64_t ElementSize =
DL.getTypeStoreSize(ETy);
1542 getSymbol(GVar)->print(O, MAI);
1544 O <<
"[" << ElementSize <<
"]";
1545 else if (!EmitInitializer)
1550 AggBuffer aggBuffer(ElementSize, *
this);
1551 bufferAggregateConstant(Initializer, &aggBuffer);
1552 if (aggBuffer.numSymbols()) {
1553 const unsigned int ptrSize = MAI.getCodePointerSize();
1554 if (ElementSize % ptrSize || !aggBuffer.allSymbolsAligned(ptrSize)) {
1559 "' requires at least PTX ISA version 7.1");
1561 getSymbol(GVar)->print(O, MAI);
1562 O <<
"[" << ElementSize <<
"]";
1563 if (EmitInitializer) {
1565 aggBuffer.printBytes(O);
1569 O <<
" .u" << ptrSize * 8 <<
" ";
1570 getSymbol(GVar)->print(O, MAI);
1571 O <<
"[" << ElementSize / ptrSize <<
"]";
1572 if (EmitInitializer) {
1574 aggBuffer.printWords(O);
1580 getSymbol(GVar)->print(O, MAI);
1581 O <<
"[" << ElementSize <<
"]";
1582 if (EmitInitializer) {
1584 aggBuffer.printBytes(O);
1590void NVPTXAsmPrinter::AggBuffer::printSymbol(
unsigned nSym, raw_ostream &os) {
1591 const Value *
v = Symbols[nSym];
1592 const Value *v0 = SymbolsBeforeStripping[nSym];
1597 bool isGenericPointer = PTy && PTy->getAddressSpace() == 0;
1600 Name->print(os, AP.MAI);
1603 Name->print(os, AP.MAI);
1606 const MCExpr *Expr = AP.lowerConstantForGV(CExpr,
false);
1607 AP.printMCExpr(*Expr, os);
1612void NVPTXAsmPrinter::AggBuffer::printBytes(raw_ostream &os) {
1613 unsigned int ptrSize = AP.MAI.getCodePointerSize();
1618 unsigned int InitializerCount =
Size;
1621 if (numSymbols() == 0)
1622 while (InitializerCount >= 1 && !buffer[InitializerCount - 1])
1625 symbolPosInBuffer.push_back(InitializerCount);
1626 unsigned int nSym = 0;
1627 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1628 for (
unsigned int pos = 0; pos < InitializerCount;) {
1631 if (pos != nextSymbolPos) {
1632 os << (
unsigned int)buffer[pos];
1639 std::string symText;
1640 llvm::raw_string_ostream oss(symText);
1641 printSymbol(nSym, oss);
1642 for (
unsigned i = 0; i < ptrSize; ++i) {
1646 os <<
"(" << symText <<
")";
1649 nextSymbolPos = symbolPosInBuffer[++nSym];
1650 assert(nextSymbolPos >= pos);
1654void NVPTXAsmPrinter::AggBuffer::printWords(raw_ostream &os) {
1655 unsigned int ptrSize = AP.MAI.getCodePointerSize();
1656 symbolPosInBuffer.push_back(
Size);
1657 unsigned int nSym = 0;
1658 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1659 assert(nextSymbolPos % ptrSize == 0);
1660 for (
unsigned int pos = 0; pos <
Size; pos += ptrSize) {
1663 if (pos == nextSymbolPos) {
1664 printSymbol(nSym, os);
1665 nextSymbolPos = symbolPosInBuffer[++nSym];
1666 assert(nextSymbolPos % ptrSize == 0);
1667 assert(nextSymbolPos >= pos + ptrSize);
1668 }
else if (ptrSize == 4)
1675void NVPTXAsmPrinter::emitDemotedVars(
const Function *
F, raw_ostream &O) {
1676 auto It = localDecls.find(
F);
1677 if (It == localDecls.end())
1682 const NVPTXTargetMachine &NTM =
static_cast<const NVPTXTargetMachine &
>(TM);
1685 for (
const GlobalVariable *GV : GVars) {
1686 O <<
"\t// demoted variable\n\t";
1687 printModuleLevelGV(GV, O,
true, STI);
1711 switch (OpaqueType) {
1713 return ".samplerref";
1724void NVPTXAsmPrinter::emitPTXAddressSpace(
unsigned int AddressSpace,
1725 raw_ostream &O)
const {
1733std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(
Type *Ty)
const {
1735 case Type::IntegerTyID:
1736 case Type::PointerTyID: {
1737 const uint64_t NumBits = getDataLayout().getTypeStoreSizeInBits(Ty);
1738 assert(NumBits <= 64 &&
"type too large");
1741 case Type::BFloatTyID:
1742 case Type::HalfTyID:
1743 case Type::FloatTyID:
1744 case Type::DoubleTyID:
1752void NVPTXAsmPrinter::emitFunctionParamList(
const Function *
F, raw_ostream &O) {
1753 const DataLayout &
DL = getDataLayout();
1754 const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
1756 const NVPTXMachineFunctionInfo *MFI =
1757 MF ? MF->getInfo<NVPTXMachineFunctionInfo>() : nullptr;
1765 const auto NonEmptyArgs =
1767 return !Arg.getType()->isEmptyTy();
1770 if (NonEmptyArgs.empty() && !
F->isVarArg()) {
1777 auto MakeParam = [&](
const auto &IndexedArg) {
1778 const auto &[ParamIndex, Arg] = IndexedArg;
1779 Type *Ty = Arg.getType();
1780 MCSymbol *
const ParamSym =
TLI->getParamSymbol(OutContext,
F, ParamIndex);
1786 const bool IsByVal = Arg.hasByValAttr();
1792 if (IsKernelFunc && !AsArray) {
1794 if (!OpaqueType.
empty()) {
1799 O << OpaqueType <<
" " << *ParamSym;
1804 const unsigned AS = PTy->getAddressSpace();
1805 O <<
".param .u" <<
DL.getPointerSizeInBits(AS) <<
" .ptr";
1811 O <<
" .align " << Arg.getParamAlign().valueOrOne().value() <<
" "
1817 printParam(
F, IsByVal ? Arg.getParamByValType() : Ty,
1818 Arg.getArgNo() + AttributeList::FirstArgIndex, IsByVal,
1819 IsKernelFunc, ParamSym->
getName(),
DL, O);
1825 O << (NonEmptyArgs.empty() ?
"" :
",\n") <<
"\t.param .align "
1827 << *
TLI->getParamSymbol(OutContext,
F, -1) <<
"[]";
1832void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1834 auto *TS = getTargetStreamer();
1839 TS->emitLocalDirective(MFI.
getMaxAlign(), getFunctionFrameSymbol(),
1843 const NVPTXRegisterInfo *NRI =
1847 TS->emitRegDirective(
1848 NRI->getRegSizeInBits(FrameReg, *
MRI).getFixedValue(),
1857 Register VR = Register::index2VirtReg(
I);
1861 RCRegMap[VR] = RCRegMap.
size() + 1;
1869 const auto It = VRegMapping.
find(&RC);
1870 if (It == VRegMapping.
end() || It->second.empty())
1873 TS->emitRegDirective(
1874 TRI->getRegSizeInBits(RC).getFixedValue(),
1876 It->second.size() + 1);
1882void NVPTXAsmPrinter::encodeDebugInfoRegisterNumbers(
1884 const NVPTXSubtarget &STI = MF.
getSubtarget<NVPTXSubtarget>();
1894 NRI->addToDebugRegisterMap(
Reg, getVirtualRegisterName(
Reg));
1897void NVPTXAsmPrinter::printFPConstant(
const ConstantFP *Fp,
1898 raw_ostream &O)
const {
1911void NVPTXAsmPrinter::printScalarConstant(
const Constant *CPV, raw_ostream &O) {
1917 const APInt API = CFP->getValueAPF().bitcastToAPInt();
1929 if (EmitGeneric && !
isa<Function>(CPV) && !IsNonGenericPointer) {
1931 getSymbol(GVar)->print(O, MAI);
1934 getSymbol(GVar)->print(O, MAI);
1946void NVPTXAsmPrinter::bufferLEByte(
const Constant *CPV,
int Bytes,
1947 AggBuffer *AggBuffer) {
1948 const DataLayout &
DL = getDataLayout();
1949 int AllocSize =
DL.getTypeAllocSize(CPV->
getType());
1953 AggBuffer->addZeros(Bytes ? Bytes : AllocSize);
1958 auto AddIntToBuffer = [AggBuffer, Bytes](
const APInt &Val) {
1959 size_t NumBytes = (Val.getBitWidth() + 7) / 8;
1965 for (
unsigned I = 0;
I < NumBytes - 1; ++
I) {
1966 Buf[
I] = Val.extractBitsAsZExtValue(8,
I * 8);
1968 size_t LastBytePosition = (NumBytes - 1) * 8;
1969 size_t LastByteBits = Val.getBitWidth() - LastBytePosition;
1971 Val.extractBitsAsZExtValue(LastByteBits, LastBytePosition);
1972 AggBuffer->addBytes(Buf.data(), NumBytes, Bytes);
1976 case Type::IntegerTyID:
1982 if (
const auto *CI =
1987 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1988 Value *
V = Cexpr->getOperand(0)->stripPointerCasts();
1989 AggBuffer->addSymbol(
V, Cexpr->getOperand(0));
1990 AggBuffer->addZeros(AllocSize);
1997 AggBuffer->addSymbol(Cexpr, Cexpr);
1998 AggBuffer->addZeros(AllocSize);
2004 case Type::HalfTyID:
2005 case Type::BFloatTyID:
2006 case Type::FloatTyID:
2007 case Type::DoubleTyID:
2008 case Type::FP128TyID:
2012 case Type::PointerTyID: {
2014 AggBuffer->addSymbol(GVar, GVar);
2016 const Value *
v = Cexpr->stripPointerCasts();
2017 AggBuffer->addSymbol(v, Cexpr);
2019 AggBuffer->addZeros(AllocSize);
2023 case Type::ArrayTyID:
2024 case Type::FixedVectorTyID:
2025 case Type::StructTyID: {
2030 unsigned StartPos = AggBuffer->getCurpos();
2031 bufferAggregateConstant(CPV, AggBuffer);
2032 unsigned Written = AggBuffer->getCurpos() - StartPos;
2033 unsigned SlotSize = std::max<int>(Bytes, AllocSize);
2034 assert(Written <= SlotSize &&
"Constant overflows its slot");
2035 if (SlotSize > Written)
2036 AggBuffer->addZeros(SlotSize - Written);
2038 AggBuffer->addZeros(Bytes);
2049void NVPTXAsmPrinter::bufferAggregateConstant(
const Constant *CPV,
2050 AggBuffer *aggBuffer) {
2051 const DataLayout &
DL = getDataLayout();
2053 auto ExtendBuffer = [](APInt Val, AggBuffer *Buffer) {
2056 unsigned NumBits = std::min(8u, Val.
getBitWidth() -
I * 8);
2064 if (!
DL.typeSizeEqualsStoreSize(VTy->getElementType())) {
2071 "Cannot lower vector global with unusual element type");
2072 ExtendBuffer(
Packed->getValue(), aggBuffer);
2079 for (
unsigned I = 0,
E = VTy->getNumElements();
I !=
E; ++
I)
2080 bufferLEByte(
Splat, 0, aggBuffer);
2088 ExtendBuffer(CI->
getValue(), aggBuffer);
2094 assert(CFP->getType()->isFloatingPointTy() &&
"Expected fp constant!");
2095 if (CFP->getType()->isFP128Ty()) {
2096 ExtendBuffer(CFP->getValueAPF().bitcastToAPInt(), aggBuffer);
2109 for (
unsigned I :
llvm::seq(CDS->getNumElements()))
2110 bufferLEByte(
cast<Constant>(CDS->getElementAsConstant(
I)), 0, aggBuffer);
2119 ?
DL.getStructLayout(ST)->getElementOffset(0) +
2120 DL.getTypeAllocSize(ST)
2121 :
DL.getStructLayout(ST)->getElementOffset(
I + 1);
2122 int Bytes = EndOffset -
DL.getStructLayout(ST)->getElementOffset(
I);
2136NVPTXAsmPrinter::lowerConstantForGV(
const Constant *CV,
2137 bool ProcessingGeneric)
const {
2138 MCContext &Ctx = OutContext;
2148 if (ProcessingGeneric)
2158 switch (
CE->getOpcode()) {
2162 case Instruction::AddrSpaceCast: {
2165 if (DstTy->getAddressSpace() == 0)
2171 case Instruction::GetElementPtr: {
2172 const DataLayout &
DL = getDataLayout();
2175 APInt OffsetAI(
DL.getPointerTypeSizeInBits(
CE->getType()), 0);
2178 const MCExpr *
Base = lowerConstantForGV(
CE->getOperand(0),
2183 int64_t
Offset = OffsetAI.getSExtValue();
2188 case Instruction::Trunc:
2194 case Instruction::BitCast:
2195 return lowerConstantForGV(
CE->getOperand(0), ProcessingGeneric);
2197 case Instruction::IntToPtr: {
2198 const DataLayout &
DL = getDataLayout();
2206 return lowerConstantForGV(
Op, ProcessingGeneric);
2211 case Instruction::PtrToInt: {
2212 const DataLayout &
DL = getDataLayout();
2217 Type *Ty =
CE->getType();
2219 const MCExpr *OpExpr = lowerConstantForGV(
Op, ProcessingGeneric);
2223 if (
DL.getTypeAllocSize(Ty) ==
DL.getTypeAllocSize(
Op->getType()))
2229 unsigned InBits =
DL.getTypeAllocSizeInBits(
Op->getType());
2236 case Instruction::Add: {
2237 const MCExpr *
LHS = lowerConstantForGV(
CE->getOperand(0), ProcessingGeneric);
2238 const MCExpr *
RHS = lowerConstantForGV(
CE->getOperand(1), ProcessingGeneric);
2239 switch (
CE->getOpcode()) {
2251 return lowerConstantForGV(
C, ProcessingGeneric);
2255 raw_string_ostream OS(S);
2256 OS <<
"Unsupported expression in static initializer: ";
2257 CE->printAsOperand(OS,
false,
2262void NVPTXAsmPrinter::printMCExpr(
const MCExpr &Expr, raw_ostream &OS)
const {
2263 OutContext.getAsmInfo().printExpr(OS, Expr);
2268bool NVPTXAsmPrinter::PrintAsmOperand(
const MachineInstr *
MI,
unsigned OpNo,
2269 const char *ExtraCode, raw_ostream &O) {
2270 if (ExtraCode && ExtraCode[0]) {
2271 if (ExtraCode[1] != 0)
2274 switch (ExtraCode[0]) {
2288bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
const MachineInstr *
MI,
2290 const char *ExtraCode,
2292 if (ExtraCode && ExtraCode[0])
2302void NVPTXAsmPrinter::printOperand(
const MachineInstr *
MI,
unsigned OpNum,
2304 const MachineOperand &MO =
MI->getOperand(OpNum);
2308 if (MO.
getReg() == NVPTX::VRDepot)
2309 getFunctionFrameSymbol()->print(O, MAI);
2313 O << getVirtualRegisterName(MO.
getReg());
2326 PrintSymbolOperand(MO, O);
2342void NVPTXAsmPrinter::printMemOperand(
const MachineInstr *
MI,
unsigned OpNum,
2343 raw_ostream &O,
const char *Modifier) {
2346 if (Modifier && strcmp(Modifier,
"add") == 0) {
2350 if (
MI->getOperand(OpNum + 1).isImm() &&
2351 MI->getOperand(OpNum + 1).getImm() == 0)
2362 return !Trimmed.
empty() &&
2363 (std::isalpha(
static_cast<unsigned char>(Trimmed[0])) ||
2370 if (!
MI || !
MI->getDebugLoc())
2372 const DISubprogram *SP =
MI->getMF()->getFunction().getSubprogram();
2376 if (!
DL->getFile() || !
DL->getLine() ||
DL->isImplicitCode())
2382struct InlineAsmInliningContext {
2384 unsigned FileIA = 0;
2385 unsigned LineIA = 0;
2388 bool hasInlinedAt()
const {
return FuncNameSym !=
nullptr; }
2394static InlineAsmInliningContext
2398 InlineAsmInliningContext Ctx;
2400 if (!InlinedAt || !InlinedAt->getFile() || !NVDD ||
2407 Ctx.FileIA =
Streamer.emitDwarfFileDirective(
2408 0, InlinedAt->getFile()->getDirectory(),
2409 InlinedAt->getFile()->getFilename(), std::nullopt, std::nullopt, CUID);
2410 Ctx.LineIA = InlinedAt->getLine();
2411 Ctx.ColIA = InlinedAt->getColumn();
2415void NVPTXAsmPrinter::emitInlineAsm(StringRef Str,
const MCSubtargetInfo &STI,
2416 const MCTargetOptions &MCOptions,
2417 const MDNode *LocMDNode,
2419 const MachineInstr *
MI) {
2420 assert(!Str.empty() &&
"Can't emit empty inline asm block");
2421 if (Str.back() == 0)
2422 Str = Str.substr(0, Str.size() - 1);
2424 auto emitAsmStr = [&](StringRef AsmStr) {
2425 emitInlineAsmStart();
2426 OutStreamer->emitRawText(AsmStr);
2427 emitInlineAsmEnd(STI,
nullptr,
MI);
2436 const DIFile *
File =
DL->getFile();
2437 unsigned Line =
DL->getLine();
2438 const unsigned Column =
DL->getColumn();
2439 const unsigned CUID = OutStreamer->getContext().getDwarfCompileUnitID();
2440 const unsigned FileNumber = OutStreamer->emitDwarfFileDirective(
2441 0,
File->getDirectory(),
File->getFilename(), std::nullopt, std::nullopt,
2444 auto *NVDD =
static_cast<NVPTXDwarfDebug *
>(getDwarfDebug());
2445 InlineAsmInliningContext InlineCtx =
2448 SmallVector<StringRef, 16>
Lines;
2449 Str.split(Lines,
'\n');
2450 emitInlineAsmStart();
2451 for (
const StringRef &L : Lines) {
2452 StringRef RTrimmed =
L.rtrim(
'\r');
2454 if (InlineCtx.hasInlinedAt()) {
2455 OutStreamer->emitDwarfLocDirectiveWithInlinedAt(
2456 FileNumber, Line, Column, InlineCtx.FileIA, InlineCtx.LineIA,
2458 File->getFilename());
2460 OutStreamer->emitDwarfLocDirective(FileNumber, Line, Column,
2462 File->getFilename());
2465 OutStreamer->emitRawText(RTrimmed);
2468 emitInlineAsmEnd(STI,
nullptr,
MI);
2471char NVPTXAsmPrinter::ID = 0;
2478LLVMInitializeNVPTXAsmPrinter() {
2499 Printer.runOnMachineFunction(MF);
const TargetLowering & TLI
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 ManagedStatic< DebugCounterOwner > Owner
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 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 bool canDemoteGlobalVar(const GlobalVariable *GV, Function const *&f)
static void printReturnValClause(const OwnerT *Owner, StringRef Name, const DataLayout &DL, raw_ostream &O)
static StringRef getPTXAddressSpaceName(unsigned AddressSpace)
The PTX state space directive for AddressSpace, or an empty string if it does not name one,...
static StringRef getPTXOpaqueTypeName(PTXOpaqueType OpaqueType)
The PTX opaque type directive for an image or sampler handle, or an empty string for PTXOpaqueType::N...
static bool useFuncSeen(const Constant *C, const SmallPtrSetImpl< const Function * > &SeenSet)
static NVPTX::VirtualRegisterKind getVirtualRegisterKind(const TargetRegisterClass *RC)
static void printParam(const OwnerT *Owner, Type *Ty, unsigned AttrIdx, bool IsByVal, bool IsKernel, StringRef Name, const DataLayout &DL, raw_ostream &O)
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)
MachineRegisterInfo & MRI
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")
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...
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
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.
This is an important base class in LLVM.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Subprogram description. Uses SubclassData1.
A parsed version of the target data layout string in and methods for querying it.
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.
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...
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.
StringRef getName() const
getName - Get the symbol name.
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.
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
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
bool hasABIPreserve() 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.
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 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.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isFP128Ty() const
Return true if this is 'fp128'.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
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.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
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 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.
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 &)
unsigned promoteScalarKernelArgumentSize(unsigned Size)
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)
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...
unsigned promoteScalarArgumentSize(unsigned Size)
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 *)
ABIPreserveInfo getABIPreserve(AttributeList Attrs)
On a function, the attributes are looked up on the function definition or declaration.
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
This struct is a compact representation of a valid (non-zero power of two) alignment.
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,...