64#include "llvm/Config/config.h"
118#include "llvm/Support/VCSRevision.h"
137#define DEBUG_TYPE "asm-printer"
155 "Function Entry Count"),
157 "Basic Block Frequency"),
161 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
162 "extracted from PGO related analysis."));
165 "basic-block-address-map-skip-bb-entries",
166 cl::desc(
"Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP "
167 "section. It's used to save binary size when BB entries are "
168 "unnecessary for some PGOAnalysisMap features."),
172 "emit-jump-table-sizes-section",
173 cl::desc(
"Emit a section containing jump table addresses and sizes"),
183STATISTIC(EmittedInsts,
"Number of machine instrs printed");
185char AsmPrinter::ID = 0;
188class AddrLabelMapCallbackPtr final :
CallbackVH {
192 AddrLabelMapCallbackPtr() =
default;
208 struct AddrLabelSymEntry {
220 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
226 DeletedAddrLabelsNeedingEmission;
233 "Some labels for deleted blocks never got emitted");
239 std::vector<MCSymbol *> &Result);
247 "Shouldn't get label for block without address taken");
248 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
251 if (!Entry.Symbols.empty()) {
253 return Entry.Symbols;
258 BBCallbacks.emplace_back(BB);
259 BBCallbacks.back().setMap(
this);
260 Entry.Index = BBCallbacks.size() - 1;
264 Entry.Symbols.push_back(
Sym);
265 return Entry.Symbols;
270 Function *
F, std::vector<MCSymbol *> &Result) {
272 DeletedAddrLabelsNeedingEmission.find(
F);
275 if (
I == DeletedAddrLabelsNeedingEmission.end())
280 DeletedAddrLabelsNeedingEmission.erase(
I);
288 if (!AddrLabelSymbols)
289 AddrLabelSymbols = std::make_unique<AddrLabelMap>(
OutContext);
290 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
295 const Function *
F, std::vector<MCSymbol *> &Result) {
297 if (!AddrLabelSymbols)
299 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
307 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
308 AddrLabelSymbols.erase(BB);
309 assert(!Entry.Symbols.empty() &&
"Didn't have a symbol, why a callback?");
310 BBCallbacks[Entry.Index] =
nullptr;
312#if !LLVM_MEMORY_SANITIZER_BUILD
315 "Block/parent mismatch");
319 if (
Sym->isDefined())
326 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(
Sym);
332 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
333 AddrLabelSymbols.erase(Old);
334 assert(!OldEntry.Symbols.empty() &&
"Didn't have a symbol, why a callback?");
336 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
339 if (NewEntry.Symbols.empty()) {
340 BBCallbacks[OldEntry.Index].setPtr(New);
341 NewEntry = std::move(OldEntry);
345 BBCallbacks[OldEntry.Index] =
nullptr;
351void AddrLabelMapCallbackPtr::deleted() {
352 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
355void AddrLabelMapCallbackPtr::allUsesReplacedWith(
Value *V2) {
356 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
365 Alignment =
DL.getPreferredAlign(GVar);
368 if (InAlign > Alignment)
376 assert(GVAlign &&
"GVAlign must be set");
381 Alignment = *GVAlign;
387 OutContext(Streamer->getContext()), OutStreamer(
std::
move(Streamer)),
390 DwarfUsesRelocationsAcrossSections =
396 "Debug/EH info didn't get finalized");
413 assert(
MMI &&
"MMI could not be nullptr!");
424 assert(
MF &&
"getSubtargetInfo requires a valid MachineFunction!");
435 "Expected assembly output mode.");
460 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
461 MMI = MMIWP ? &MMIWP->getMMI() :
nullptr;
462 HasSplitStack =
false;
463 HasNoSplitStack =
false;
464 DbgInfoAvailable = !M.debug_compile_units().empty();
466 AddrLabelSymbols =
nullptr;
473 .getModuleMetadata(M);
491 if (
Target.isOSBinFormatMachO() &&
Target.isOSDarwin()) {
492 Triple TVT(M.getDarwinTargetVariantTriple());
494 Target, M.getSDKVersion(),
495 M.getDarwinTargetVariantTriple().empty() ?
nullptr : &TVT,
496 M.getDarwinTargetVariantSDKVersion());
511 FileName = M.getSourceFileName();
513 const char VerStr[] =
517 PACKAGE_NAME
" version " PACKAGE_VERSION
519 " (" LLVM_REVISION
")"
523 OutStreamer->emitFileDirective(FileName, VerStr,
"",
"");
532 emitModuleCommandLines(M);
541 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
549 assert(
MI &&
"AsmPrinter didn't require GCModuleInfo?");
550 for (
const auto &
I : *
MI)
552 MP->beginAssembly(M, *
MI, *
this);
555 if (!M.getModuleInlineAsm().empty()) {
556 OutStreamer->AddComment(
"Start of file scope inline assembly");
562 OutStreamer->AddComment(
"End of file scope inline assembly");
567 bool EmitCodeView = M.getCodeViewFlag();
569 DebugHandlers.push_back(std::make_unique<CodeViewDebug>(
this));
570 if (!EmitCodeView || M.getDwarfVersion()) {
579 PP = std::make_unique<PseudoProbeHandler>(
this);
588 for (
auto &
F : M.getFunctionList()) {
636 Handlers.push_back(std::unique_ptr<EHStreamer>(ES));
639 if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag(
"cfguard")))
640 Handlers.push_back(std::make_unique<WinCFGuard>(
this));
643 Handler->beginModule(&M);
645 Handler->beginModule(&M);
727 "No emulated TLS variables in the common section");
766 "tagged symbols (-fsanitize=memtag-globals) are "
767 "only supported on AArch64 Android");
777 "' is already defined");
793 Handler->setSymbolSize(GVSym,
Size);
885 unsigned PtrSize =
DL.getPointerTypeSize(GV->
getType());
904 if (LocalAlias != EmittedInitSym)
925void AsmPrinter::emitFunctionHeaderComment() {}
930 for (
auto &
C : Prefix)
940 for (
auto &
C : Prefix) {
950void AsmPrinter::emitFunctionHeader() {
955 <<
"-- Begin function "
983 if (
F.hasFnAttribute(Attribute::Cold))
987 if (
F.hasPrefixData())
988 emitFunctionPrefix({
F.getPrefixData()});
995 unsigned PatchableFunctionPrefix = 0;
996 unsigned PatchableFunctionEntry = 0;
997 (void)
F.getFnAttribute(
"patchable-function-prefix")
999 .getAsInteger(10, PatchableFunctionPrefix);
1000 (void)
F.getFnAttribute(
"patchable-function-entry")
1002 .getAsInteger(10, PatchableFunctionEntry);
1003 if (PatchableFunctionPrefix) {
1008 }
else if (PatchableFunctionEntry) {
1015 if (
const MDNode *MD =
F.getMetadata(LLVMContext::MD_func_sanitize)) {
1016 assert(MD->getNumOperands() == 2);
1018 auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
1019 auto *TypeHash = mdconst::extract<Constant>(MD->getOperand(1));
1020 emitFunctionPrefix({PrologueSig, TypeHash});
1025 false,
F.getParent());
1026 emitFunctionHeaderComment();
1044 std::vector<MCSymbol*> DeadBlockSyms;
1046 for (
MCSymbol *DeadBlockSym : DeadBlockSyms) {
1047 OutStreamer->AddComment(
"Address taken block that was later removed");
1064 Handler->beginFunction(
MF);
1065 Handler->beginBasicBlockSection(
MF->
front());
1068 Handler->beginFunction(
MF);
1070 Handler->beginBasicBlockSection(
MF->
front());
1073 if (
F.hasPrologueData())
1086 "' is a protected alias");
1112 std::optional<LocationSize>
Size;
1114 CommentOS <<
Size->getValue() <<
"-byte Reload\n";
1115 }
else if ((
Size =
MI.getFoldedRestoreSize(
TII))) {
1116 if (!
Size->hasValue())
1117 CommentOS <<
"Unknown-size Folded Reload\n";
1118 else if (
Size->getValue())
1119 CommentOS <<
Size->getValue() <<
"-byte Folded Reload\n";
1120 }
else if ((
Size =
MI.getSpillSize(
TII))) {
1121 CommentOS <<
Size->getValue() <<
"-byte Spill\n";
1122 }
else if ((
Size =
MI.getFoldedSpillSize(
TII))) {
1123 if (!
Size->hasValue())
1124 CommentOS <<
"Unknown-size Folded Spill\n";
1125 else if (
Size->getValue())
1126 CommentOS <<
Size->getValue() <<
"-byte Folded Spill\n";
1131 CommentOS <<
" Reload Reuse\n";
1141 CommentOS <<
" Latency: " <<
Latency <<
"\n";
1152 OS <<
"implicit-def: "
1164 assert(
Op.isReg() &&
"KILL instruction must have only register operands");
1165 OS <<
' ' << (
Op.isDef() ?
"def " :
"killed ")
1192 if (
MI->isNonListDebugValue() &&
MI->getNumOperands() != 4)
1197 OS <<
"DEBUG_VALUE: ";
1200 if (
auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
1212 Expr = *NonVariadicExpr;
1219 for (
unsigned I = 0;
I <
Op.getNumArgs(); ++
I)
1220 OS <<
' ' <<
Op.getArg(
I);
1227 if (&
Op !=
MI->debug_operands().begin())
1229 switch (
Op.getType()) {
1232 Type *ImmTy =
Op.getFPImm()->getType();
1251 Op.getCImm()->getValue().
print(
OS,
false );
1255 OS <<
"!target-index(" <<
Op.getIndex() <<
"," <<
Op.getOffset() <<
")";
1261 std::optional<StackOffset>
Offset;
1275 if (
MI->isIndirectDebugValue())
1281 OS <<
'+' <<
Offset->getFixed() <<
']';
1298 if (
MI->getNumOperands() != 1)
1303 OS <<
"DEBUG_LABEL: ";
1306 if (
auto *SP = dyn_cast<DISubprogram>(
1307 V->getScope()->getNonLexicalBlockFileScope())) {
1322 if (
F.isDeclarationForLinker())
1326 F.needsUnwindTableEntry())
1363 auto *
MBB =
MI.getParent();
1364 auto I = std::next(
MI.getIterator());
1365 while (
I !=
MBB->
end() &&
I->isTransient())
1372 unsigned CFIIndex =
MI.getOperand(0).getCFIIndex();
1379 MCSymbol *FrameAllocSym =
MI.getOperand(0).getMCSymbol();
1380 int FrameOffset =
MI.getOperand(1).getImm();
1407 "-pgo-anaylsis-map can accept only all or none with no additional "
1413 bool FuncEntryCountEnabled =
1415 PGOMapFeaturesEnum::FuncEntryCount));
1416 bool BBFreqEnabled =
1419 bool BrProbEnabled =
1425 "BB entries info is required for BBFreq and BrProb "
1428 return {FuncEntryCountEnabled, BBFreqEnabled, BrProbEnabled,
1436 assert(BBAddrMapSection &&
".llvm_bb_addr_map section is not initialized.");
1449 if (Features.MultiBBRange) {
1450 OutStreamer->AddComment(
"number of basic block ranges");
1455 const MCSymbol *PrevMBBEndSymbol =
nullptr;
1456 if (!Features.MultiBBRange) {
1459 OutStreamer->AddComment(
"number of basic blocks");
1461 PrevMBBEndSymbol = FunctionSymbol;
1463 unsigned BBCount = 0;
1478 bool IsBeginSection =
1480 if (IsBeginSection) {
1483 OutStreamer->AddComment(
"number of basic blocks");
1485 PrevMBBEndSymbol = MBBSymbol;
1488 if (!Features.OmitBBEntries) {
1490 if (BBAddrMapVersion > 1) {
1512 if (Features.hasPGOAnalysis()) {
1513 assert(BBAddrMapVersion >= 2 &&
1514 "PGOAnalysisMap only supports version 2 or later");
1516 if (Features.FuncEntryCount) {
1520 MaybeEntryCount ? MaybeEntryCount->getCount() : 0);
1524 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
1528 ? &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI()
1531 if (Features.BBFreq || Features.BrProb) {
1533 if (Features.BBFreq) {
1538 if (Features.BrProb) {
1540 OutStreamer->AddComment(
"basic block successor count");
1544 OutStreamer->emitULEB128IntValue(SuccMBB->getBBID()->BaseID);
1545 OutStreamer->AddComment(
"successor branch probability");
1569 OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
1576 if (
const MDNode *MD =
F.getMetadata(LLVMContext::MD_kcfi_type))
1578 mdconst::extract<ConstantInt>(MD->getOperand(0)));
1583 auto GUID =
MI.getOperand(0).getImm();
1584 auto Index =
MI.getOperand(1).getImm();
1585 auto Type =
MI.getOperand(2).getImm();
1586 auto Attr =
MI.getOperand(3).getImm();
1588 PP->emitPseudoProbe(GUID, Index,
Type, Attr,
DebugLoc);
1598 if (!StackSizeSection)
1629 if (StackUsageStream ==
nullptr) {
1634 errs() <<
"Could not open file: " << EC.message();
1640 *StackUsageStream << DSP->getFilename() <<
':' << DSP->getLine();
1644 *StackUsageStream <<
':' <<
MF.
getName() <<
'\t' << StackSize <<
'\t';
1646 *StackUsageStream <<
"dynamic\n";
1648 *StackUsageStream <<
"static\n";
1655 PCSectionsSymbols[&MD].emplace_back(S);
1660 if (PCSectionsSymbols.empty() && !
F.hasMetadata(LLVMContext::MD_pcsections))
1664 const unsigned RelativeRelocSize =
1674 assert(S &&
"PC section is not initialized");
1685 bool ConstULEB128 =
false;
1687 if (
auto *S = dyn_cast<MDString>(MDO)) {
1691 const StringRef SecWithOpt = S->getString();
1692 const size_t OptStart = SecWithOpt.
find(
'!');
1698 assert((O ==
'!' || O ==
'C') &&
"Invalid !pcsections options");
1701 const MCSymbol *Prev = Syms.front();
1703 if (
Sym == Prev || !Deltas) {
1722 assert(isa<MDNode>(MDO) &&
"expecting either string or tuple");
1723 const auto *AuxMDs = cast<MDNode>(MDO);
1724 for (
const MDOperand &AuxMDO : AuxMDs->operands()) {
1725 assert(isa<ConstantAsMetadata>(AuxMDO) &&
"expecting a constant");
1726 const Constant *
C = cast<ConstantAsMetadata>(AuxMDO)->getValue();
1730 if (
auto *CI = dyn_cast<ConstantInt>(
C);
1731 CI && ConstULEB128 &&
Size > 1 &&
Size <= 8) {
1743 if (
const MDNode *MD =
F.getMetadata(LLVMContext::MD_pcsections))
1746 for (
const auto &MS : PCSectionsSymbols)
1747 EmitForMD(*MS.first, MS.second,
false);
1749 PCSectionsSymbols.clear();
1771 MI.getParent()->getParent()->getSubtarget().getInstrInfo();
1777 assert(!
Name.empty() &&
"Missing mnemonic and name for opcode");
1784 emitFunctionHeader();
1791 auto MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
1792 MDT = MDTWrapper ? &MDTWrapper->getDomTree() :
nullptr;
1794 OwnedMDT = std::make_unique<MachineDominatorTree>();
1795 OwnedMDT->recalculate(*
MF);
1796 MDT = OwnedMDT.get();
1800 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
1801 MLI = MLIWrapper ? &MLIWrapper->getLI() :
nullptr;
1803 OwnedMLI = std::make_unique<MachineLoopInfo>();
1804 OwnedMLI->analyze(*
MDT);
1805 MLI = OwnedMLI.get();
1810 bool HasAnyRealCode =
false;
1811 int NumInstsInFunction = 0;
1827 for (
auto &
MBB : *
MF) {
1831 for (
auto &
MI :
MBB) {
1833 if (!
MI.isPosition() && !
MI.isImplicitDef() && !
MI.isKill() &&
1834 !
MI.isDebugInstr()) {
1835 HasAnyRealCode =
true;
1842 if (
MDNode *MD =
MI.getPCSections())
1846 Handler->beginInstruction(&
MI);
1851 switch (
MI.getOpcode()) {
1852 case TargetOpcode::CFI_INSTRUCTION:
1855 case TargetOpcode::LOCAL_ESCAPE:
1858 case TargetOpcode::ANNOTATION_LABEL:
1859 case TargetOpcode::GC_LABEL:
1862 case TargetOpcode::EH_LABEL:
1872 auto MI2 = std::next(
MI.getIterator());
1873 if (IsEHa && MI2 !=
MBB.
end() &&
1874 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
1878 case TargetOpcode::INLINEASM:
1879 case TargetOpcode::INLINEASM_BR:
1882 case TargetOpcode::DBG_VALUE:
1883 case TargetOpcode::DBG_VALUE_LIST:
1889 case TargetOpcode::DBG_INSTR_REF:
1894 case TargetOpcode::DBG_PHI:
1898 case TargetOpcode::DBG_LABEL:
1904 case TargetOpcode::IMPLICIT_DEF:
1907 case TargetOpcode::KILL:
1910 case TargetOpcode::FAKE_USE:
1914 case TargetOpcode::PSEUDO_PROBE:
1917 case TargetOpcode::ARITH_FENCE:
1921 case TargetOpcode::MEMBARRIER:
1924 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
1928 case TargetOpcode::INIT_UNDEF:
1937 if (
MI.isMetaInstruction())
1939 ++NumInstsInFunction;
1940 if (CanDoExtraAnalysis) {
1942 ++MnemonicCounts[
Name];
1945 if (!
MI.isBundle()) {
1946 CountInstruction(
MI);
1950 for (
auto It = std::next(
MI.getIterator());
1951 It !=
MBB.
end() && It->isInsideBundle(); ++It) {
1952 CountInstruction(*It);
1962 Handler->endInstruction();
1982 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1985 "Overwrite section range");
1992 if (CanDoExtraAnalysis) {
2003 for (
auto &KV : MnemonicCounts)
2006 sort(MnemonicVec, [](
const std::pair<StringRef, unsigned> &
A,
2007 const std::pair<StringRef, unsigned> &
B) {
2008 if (
A.second >
B.second)
2010 if (
A.second ==
B.second)
2015 for (
auto &KV : MnemonicVec) {
2016 auto Name = (
Twine(
"INST_") + getToken(KV.first.trim()).first).str();
2017 R << KV.first <<
": " <<
ore::NV(
Name, KV.second) <<
"\n";
2023 EmittedInsts += NumInstsInFunction;
2027 R <<
ore::NV(
"NumInstructions", NumInstsInFunction)
2028 <<
" instructions in function";
2041 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2047 OutStreamer->AddComment(
"avoids zero-length function");
2056 for (
const auto &BB :
F) {
2057 if (!BB.hasAddressTaken())
2060 if (
Sym->isDefined())
2062 OutStreamer->AddComment(
"Address of block that was removed by CodeGen");
2084 if (EmitFunctionSize) {
2099 Handler->endBasicBlockSection(
MF->
back());
2101 Handler->endBasicBlockSection(
MF->
back());
2104 Handler->markFunctionEnd();
2113 Handler->endFunction(
MF);
2115 Handler->endFunction(
MF);
2119 if (HasAnyRealCode) {
2124 SMLoc(),
"pgo-analysis-map is enabled for function " +
MF->
getName() +
2125 " but it does not have labels");
2140 OutStreamer->getCommentOS() <<
"-- End function\n";
2150 if (isa<GlobalVariable>(
C))
2153 unsigned NumUses = 0;
2154 for (
const auto *
CU :
C->users())
2166 unsigned &NumGOTEquivUsers) {
2177 for (
const auto *U : GV->
users())
2180 return NumGOTEquivUsers > 0;
2194 for (
const auto &
G : M.globals()) {
2195 unsigned NumGOTEquivUsers = 0;
2214 unsigned Cnt =
I.second.second;
2220 for (
const auto *GV : FailedCandidates)
2238 "Visibility should be handled with emitLinkage() on AIX.");
2279 if (
MAI->
isMachO() && isa<MCBinaryExpr>(Expr))
2285 if (LocalAlias !=
Name)
2304 "IFunc is not supported on AIX.");
2325 if (LocalAlias !=
Name)
2388 std::optional<SmallString<128>> Filename;
2389 if (std::optional<StringRef> FilenameRef = RS.
getFilename()) {
2390 Filename = *FilenameRef;
2392 assert(!Filename->empty() &&
"The filename can't be empty.");
2397 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2400 MetaSerializer->emit();
2411 Constant *Initializer =
G->getInitializer();
2413 M.getDataLayout().getTypeAllocSize(Initializer->
getType());
2416 if (SizeInBytes != NewSize) {
2422 M, Initializer->
getType(),
G->isConstant(),
G->getLinkage(),
2423 Initializer,
"",
G,
G->getThreadLocalMode(),
G->getAddressSpace());
2424 NewGV->copyAttributesFrom(
G);
2425 NewGV->setComdat(
G->getComdat());
2426 NewGV->copyMetadata(
G, 0);
2429 G->replaceAllUsesWith(NewGV);
2430 G->eraseFromParent();
2434 if (
G->getAlign().valueOrOne() < 16)
2435 G->setAlignment(
Align(16));
2448 std::vector<GlobalVariable *> GlobalsToTag;
2450 if (
G.isDeclaration() || !
G.isTagged())
2464 for (
const auto &
G : M.globals())
2474 if (!
F.isDeclarationForLinker())
2489 if (
F.isIntrinsic())
2501 if (
F.hasAddressTaken())
2518 if (!Stubs.empty()) {
2523 for (
const auto &Stub : Stubs) {
2525 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2526 DL.getPointerSize());
2537 if (!Stubs.empty()) {
2540 for (
const auto &Stub : Stubs) {
2551 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2552 DL.getPointerSize());
2560 TS->emitConstantPools();
2574 for (
const auto &Alias : M.aliases()) {
2575 if (Alias.hasAvailableExternallyLinkage())
2578 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
2579 if (!AliasVisited.
insert(Cur).second)
2591 for (
const auto &IFunc : M.ifuncs())
2592 emitGlobalIFunc(M, IFunc);
2596 Handler->endModule();
2598 Handler->endModule();
2616 for (
const auto &GO : M.global_objects()) {
2617 if (!GO.hasExternalWeakLinkage())
2622 auto SymbolName =
"swift_async_extendedFramePointerFlags";
2623 auto Global = M.getGlobalVariable(SymbolName);
2635 assert(
MI &&
"AsmPrinter didn't require GCModuleInfo?");
2638 MP->finishAssembly(M, *
MI, *
this);
2641 emitModuleIdents(M);
2646 emitModuleCommandLines(M);
2653 if (HasNoSplitStack)
2660 Function *InitTrampolineIntrinsic = M.getFunction(
"llvm.init.trampoline");
2661 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->
use_empty())
2669 if (!GV.use_empty() && !GV.isThreadLocal() &&
2670 !GV.hasDLLImportStorageClass() &&
2671 !GV.getName().starts_with(
"llvm.") &&
2672 !GV.hasAtLeastLocalUnnamedAddr())
2679 unsigned UniqueID = 0;
2681 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
2687 "",
false, ++UniqueID,
nullptr));
2701 AddrLabelSymbols =
nullptr;
2715 return Res.first->second;
2725 HasSplitStack =
true;
2728 HasNoSplitStack =
true;
2730 HasNoSplitStack =
true;
2737 "Only AIX uses the function descriptor hooks.");
2742 " initalized first.");
2751 CurrentSectionBeginSym =
nullptr;
2753 MBBSectionExceptionSyms.clear();
2755 if (
F.hasFnAttribute(
"patchable-function-entry") ||
2756 F.hasFnAttribute(
"function-instrument") ||
2757 F.hasFnAttribute(
"xray-instruction-threshold") ||
2762 if (NeedsLocalForSize)
2766 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2788 const std::vector<MachineConstantPoolEntry> &CP = MCP->
getConstants();
2789 if (CP.empty())
return;
2794 for (
unsigned i = 0, e = CP.size(); i != e; ++i) {
2810 unsigned SecIdx = CPSections.
size();
2811 while (SecIdx != 0) {
2812 if (CPSections[--SecIdx].S == S) {
2818 SecIdx = CPSections.
size();
2819 CPSections.
push_back(SectionCPs(S, Alignment));
2822 if (Alignment > CPSections[SecIdx].Alignment)
2823 CPSections[SecIdx].Alignment = Alignment;
2830 for (
unsigned i = 0, e = CPSections.
size(); i != e; ++i) {
2831 for (
unsigned j = 0, ee = CPSections[i].CPEs.
size(); j != ee; ++j) {
2832 unsigned CPI = CPSections[i].CPEs[j];
2834 if (!
Sym->isUndefined())
2837 if (CurSection != CPSections[i].S) {
2840 CurSection = CPSections[i].S;
2868 const std::vector<MachineJumpTableEntry> &JT = MJTI->
getJumpTables();
2869 if (JT.empty())
return;
2879 if (JTInDiffSection) {
2889 if (!JTInDiffSection)
2892 for (
unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2893 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2896 if (JTBBs.empty())
continue;
2922 if (JTInDiffSection &&
DL.hasLinkerPrivateGlobalPrefix())
2934 emitJumpTableEntry(MJTI,
MBB, JTI);
2938 emitJumpTableSizesSection(MJTI,
F);
2940 if (!JTInDiffSection)
2946 const std::vector<MachineJumpTableEntry> &JT = MJTI->
getJumpTables();
2951 StringRef GroupName =
F.hasComdat() ?
F.getComdat()->getName() :
"";
2952 MCSection *JumpTableSizesSection =
nullptr;
2953 StringRef sectionName =
".llvm_jump_table_sizes";
2958 if (!isCoff && !isElf)
2968 }
else if (isCoff) {
2969 if (
F.hasComdat()) {
2983 OutStreamer->switchSection(JumpTableSizesSection);
2985 for (
unsigned JTI = 0, E =
JT.size(); JTI != E; ++JTI) {
2986 const std::vector<MachineBasicBlock *> &JTBBs =
JT[JTI].MBBs;
2996 unsigned UID)
const {
3062 if (GV->
getName() ==
"llvm.used") {
3073 if (GV->
getName() ==
"llvm.arm64ec.symbolmap") {
3080 for (
auto &U : Arr->operands()) {
3081 auto *
C = cast<Constant>(U);
3082 auto *Src = cast<GlobalValue>(
C->getOperand(0)->stripPointerCasts());
3083 auto *Dst = cast<GlobalValue>(
C->getOperand(1)->stripPointerCasts());
3084 int Kind = cast<ConstantInt>(
C->getOperand(2))->getZExtValue();
3086 if (Src->hasDLLImportStorageClass()) {
3110 if (GV->
getName() ==
"llvm.global_ctors") {
3117 if (GV->
getName() ==
"llvm.global_dtors") {
3129void AsmPrinter::emitLLVMUsedList(
const ConstantArray *InitList) {
3131 for (
unsigned i = 0, e = InitList->
getNumOperands(); i != e; ++i) {
3144 if (!isa<ConstantArray>(
List))
3148 for (
Value *O : cast<ConstantArray>(
List)->operands()) {
3149 auto *CS = cast<ConstantStruct>(O);
3150 if (CS->getOperand(1)->isNullValue())
3152 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3159 if (!CS->getOperand(2)->isNullValue()) {
3162 "associated data of XXStructor list is not yet supported on AIX");
3164 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3170 return L.Priority < R.Priority;
3180 if (Structors.
empty())
3186 std::reverse(Structors.
begin(), Structors.
end());
3214void AsmPrinter::emitModuleIdents(
Module &M) {
3218 if (
const NamedMDNode *NMD = M.getNamedMetadata(
"llvm.ident")) {
3219 for (
const MDNode *
N : NMD->operands()) {
3220 assert(
N->getNumOperands() == 1 &&
3221 "llvm.ident metadata entry can have only one operand");
3222 const MDString *S = cast<MDString>(
N->getOperand(0));
3228void AsmPrinter::emitModuleCommandLines(
Module &M) {
3233 const NamedMDNode *NMD =
M.getNamedMetadata(
"llvm.commandline");
3241 assert(
N->getNumOperands() == 1 &&
3242 "llvm.commandline metadata entry can have only one operand");
3243 const MDString *S = cast<MDString>(
N->getOperand(0));
3273 unsigned PadTo)
const {
3289 unsigned Size)
const {
3304 bool IsSectionRelative)
const {
3328 unsigned MaxBytesToEmit)
const {
3332 if (Alignment ==
Align(1))
3341 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3343 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3356 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
3362 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
3365 if (
const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
3368 if (
const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
3382 switch (CE->getOpcode()) {
3385 case Instruction::AddrSpaceCast: {
3387 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3388 unsigned SrcAS =
Op->getType()->getPointerAddressSpace();
3394 case Instruction::GetElementPtr: {
3397 cast<GEPOperator>(CE)->accumulateConstantOffset(
getDataLayout(), OffsetAI);
3408 case Instruction::Trunc:
3414 case Instruction::BitCast:
3417 case Instruction::IntToPtr: {
3431 case Instruction::PtrToInt: {
3437 Type *Ty = CE->getType();
3446 if (
DL.getTypeAllocSize(Ty).getFixedValue() <=
3447 DL.getTypeAllocSize(
Op->getType()).getFixedValue())
3453 case Instruction::Sub: {
3463 const MCExpr *RelocExpr =
3475 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3489 case Instruction::Add: {
3506 OS <<
"Unsupported expression in static initializer: ";
3507 CE->printAsOperand(
OS,
false,
3526 assert(!
Data.empty() &&
"Empty aggregates should be CAZ node");
3528 for (
unsigned i = 1, e =
Data.size(); i != e; ++i)
3529 if (
Data[i] !=
C)
return -1;
3537 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3543 if (!
Value.isSplat(8))
3546 return Value.zextOrTrunc(8).getZExtValue();
3551 assert(CA->getNumOperands() != 0 &&
"Should be a CAZ");
3558 for (
unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
3559 if (CA->getOperand(i) != Op0)
3574 if (AliasIt != AliasList->
end()) {
3618 unsigned EmittedSize =
3620 assert(EmittedSize <=
Size &&
"Size cannot be less than EmittedSize!");
3621 if (
unsigned Padding =
Size - EmittedSize)
3650 auto *VTy = cast<FixedVectorType>(CV->
getType());
3651 Type *ElementType = VTy->getElementType();
3652 uint64_t ElementSizeInBits =
DL.getTypeSizeInBits(ElementType);
3653 uint64_t ElementAllocSizeInBits =
DL.getTypeAllocSizeInBits(ElementType);
3655 if (ElementSizeInBits != ElementAllocSizeInBits) {
3667 "Cannot lower vector global with unusual element type");
3671 EmittedSize =
DL.getTypeStoreSize(CV->
getType());
3673 for (
unsigned I = 0, E = VTy->getNumElements();
I != E; ++
I) {
3677 EmittedSize =
DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
3681 if (
unsigned Padding =
Size - EmittedSize)
3705 SizeSoFar += FieldSize + PadSize;
3713 "Layout of constant struct may be incorrect!");
3717 assert(ET &&
"Unknown float type");
3726 AP.
OutStreamer->getCommentOS() <<
' ' << StrVal <<
'\n';
3733 unsigned TrailingBytes = NumBytes %
sizeof(
uint64_t);
3742 AP.
OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
3744 for (; Chunk >= 0; --Chunk)
3748 for (Chunk = 0; Chunk < NumBytes /
sizeof(
uint64_t); ++Chunk)
3752 AP.
OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
3757 AP.
OutStreamer->emitZeros(
DL.getTypeAllocSize(ET) -
DL.getTypeStoreSize(ET));
3772 unsigned ExtraBitsSize =
BitWidth & 63;
3774 if (ExtraBitsSize) {
3782 if (
DL.isBigEndian()) {
3791 ExtraBitsSize =
alignTo(ExtraBitsSize, 8);
3793 (((
uint64_t)-1) >> (64 - ExtraBitsSize));
3804 for (
unsigned i = 0, e =
BitWidth / 64; i != e; ++i) {
3805 uint64_t Val =
DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
3809 if (ExtraBitsSize) {
3816 (ExtraBits & (((
uint64_t)-1) >> (64 - ExtraBitsSize)))
3817 == ExtraBits &&
"Directive too small for extra bits.");
3849 if (!(*ME)->evaluateAsRelocatable(MV,
nullptr,
nullptr) || MV.
isAbsolute())
3860 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
3868 if (!SymB || BaseSym != &SymB->
getSymbol())
3896 int NumUses = (int)Result.second;
3913 "AliasList only expected for XCOFF");
3921 BaseCV = dyn_cast<Constant>(CV->
user_back());
3923 if (isa<ConstantAggregateZero>(CV)) {
3925 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->
getType()))) {
3929 for (
unsigned int i = 0, n = structType->
getNumElements(); i < n - 1;
3933 SizeSoFar += GapToNext;
3943 if (isa<UndefValue>(CV))
3946 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3947 if (isa<VectorType>(CV->
getType()))
3951 if (StoreSize <= 8) {
3954 <<
format(
"0x%" PRIx64
"\n", CI->getZExtValue());
3955 AP.
OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3961 if (
Size != StoreSize)
3967 if (
const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
3968 if (isa<VectorType>(CV->
getType()))
3974 if (isa<ConstantPointerNull>(CV)) {
3988 if (
const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3991 if (CE->getOpcode() == Instruction::BitCast)
4004 if (isa<ConstantVector>(CV))
4035 for (
auto &AliasPair : *AliasList) {
4094 if (
Sym->isUndefined())
4136 unsigned FunctionNumber) {
4140 <<
"Parent Loop BB" << FunctionNumber <<
"_"
4148 unsigned FunctionNumber) {
4152 <<
"Child Loop BB" << FunctionNumber <<
"_"
4153 << CL->getHeader()->getNumber() <<
" Depth " << CL->getLoopDepth()
4168 assert(Header &&
"No header for loop");
4172 if (Header != &
MBB) {
4173 AP.
OutStreamer->AddComment(
" in Loop: Header=BB" +
4204 Handler->endFunclet();
4205 Handler->beginFunclet(
MBB);
4220 Handler->beginCodeAlignment(
MBB);
4224 if (Alignment !=
Align(1))
4246 if (BB->hasName()) {
4248 false, BB->getModule());
4253 assert(
MLI !=
nullptr &&
"MachineLoopInfo should has been computed");
4258 if (shouldEmitLabelForBasicBlock(
MBB)) {
4260 OutStreamer->AddComment(
"Label of block must be emitted");
4280 Handler->beginBasicBlockSection(
MBB);
4282 Handler->beginBasicBlockSection(
MBB);
4291 Handler->endBasicBlockSection(
MBB);
4293 Handler->endBasicBlockSection(
MBB);
4298 bool IsDefinition)
const {
4301 switch (Visibility) {
4318bool AsmPrinter::shouldEmitLabelForBasicBlock(
4360 if (!
MI.isBranch() ||
MI.isIndirectBranch())
4369 if (
OP->isMBB() &&
OP->getMBB() ==
MBB)
4381 auto [GCPI, Inserted] = GCMetadataPrinters.insert({&S,
nullptr});
4383 return GCPI->second.get();
4389 if (
Name == GCMetaPrinter.getName()) {
4390 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4392 GCPI->second = std::move(GMP);
4393 return GCPI->second.get();
4401 assert(
MI &&
"AsmPrinter didn't require GCModuleInfo?");
4402 bool NeedsDefault =
false;
4403 if (
MI->begin() ==
MI->end())
4405 NeedsDefault =
true;
4407 for (
const auto &
I : *
MI) {
4409 if (MP->emitStackMaps(
SM, *
this))
4413 NeedsDefault =
true;
4421 std::unique_ptr<AsmPrinterHandler> Handler) {
4440 auto Kind8 =
static_cast<uint8_t>(