64#include "llvm/Config/config.h"
116#include "llvm/Support/VCSRevision.h"
135#define DEBUG_TYPE "asm-printer"
149 "func-entry-count",
"Function Entry Count"),
151 "Basic Block Frequency"),
153 "Branch Probability")),
155 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
156 "extracted from PGO related analysis."));
158STATISTIC(EmittedInsts,
"Number of machine instrs printed");
160char AsmPrinter::ID = 0;
163class AddrLabelMapCallbackPtr final :
CallbackVH {
167 AddrLabelMapCallbackPtr() =
default;
183 struct AddrLabelSymEntry {
195 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
201 DeletedAddrLabelsNeedingEmission;
208 "Some labels for deleted blocks never got emitted");
214 std::vector<MCSymbol *> &Result);
222 "Shouldn't get label for block without address taken");
223 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
226 if (!Entry.Symbols.empty()) {
228 return Entry.Symbols;
233 BBCallbacks.emplace_back(BB);
234 BBCallbacks.back().setMap(
this);
235 Entry.Index = BBCallbacks.size() - 1;
239 Entry.Symbols.push_back(
Sym);
240 return Entry.Symbols;
245 Function *
F, std::vector<MCSymbol *> &Result) {
247 DeletedAddrLabelsNeedingEmission.find(
F);
250 if (
I == DeletedAddrLabelsNeedingEmission.end())
255 DeletedAddrLabelsNeedingEmission.erase(
I);
263 if (!AddrLabelSymbols)
264 AddrLabelSymbols = std::make_unique<AddrLabelMap>(
OutContext);
265 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
270 const Function *
F, std::vector<MCSymbol *> &Result) {
272 if (!AddrLabelSymbols)
274 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
282 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
283 AddrLabelSymbols.erase(BB);
284 assert(!Entry.Symbols.empty() &&
"Didn't have a symbol, why a callback?");
285 BBCallbacks[Entry.Index] =
nullptr;
287#if !LLVM_MEMORY_SANITIZER_BUILD
290 "Block/parent mismatch");
294 if (
Sym->isDefined())
301 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(
Sym);
307 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
308 AddrLabelSymbols.erase(Old);
309 assert(!OldEntry.Symbols.empty() &&
"Didn't have a symbol, why a callback?");
311 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
314 if (NewEntry.Symbols.empty()) {
315 BBCallbacks[OldEntry.Index].setPtr(New);
316 NewEntry = std::move(OldEntry);
320 BBCallbacks[OldEntry.Index] =
nullptr;
326void AddrLabelMapCallbackPtr::deleted() {
327 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
330void AddrLabelMapCallbackPtr::allUsesReplacedWith(
Value *V2) {
331 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
340 Alignment =
DL.getPreferredAlign(GVar);
343 if (InAlign > Alignment)
351 assert(GVAlign &&
"GVAlign must be set");
356 Alignment = *GVAlign;
362 OutContext(Streamer->getContext()), OutStreamer(
std::
move(Streamer)),
365 DwarfUsesRelocationsAcrossSections =
371 "Debug/EH info didn't get finalized");
388 assert(
MMI &&
"MMI could not be nullptr!");
399 assert(
MF &&
"getSubtargetInfo requires a valid MachineFunction!");
410 "Expected assembly output mode.");
435 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
436 MMI = MMIWP ? &MMIWP->getMMI() :
nullptr;
437 HasSplitStack =
false;
438 HasNoSplitStack =
false;
439 DbgInfoAvailable = !M.debug_compile_units().empty();
441 AddrLabelSymbols =
nullptr;
448 .getModuleMetadata(M);
466 if (
Target.isOSBinFormatMachO() &&
Target.isOSDarwin()) {
467 Triple TVT(M.getDarwinTargetVariantTriple());
469 Target, M.getSDKVersion(),
470 M.getDarwinTargetVariantTriple().empty() ?
nullptr : &TVT,
471 M.getDarwinTargetVariantSDKVersion());
486 FileName = M.getSourceFileName();
488 const char VerStr[] =
492 PACKAGE_NAME
" version " PACKAGE_VERSION
494 " (" LLVM_REVISION
")"
498 OutStreamer->emitFileDirective(FileName, VerStr,
"",
"");
507 emitModuleCommandLines(M);
515 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
523 assert(
MI &&
"AsmPrinter didn't require GCModuleInfo?");
524 for (
const auto &
I : *
MI)
526 MP->beginAssembly(M, *
MI, *
this);
529 if (!M.getModuleInlineAsm().empty()) {
530 OutStreamer->AddComment(
"Start of file scope inline assembly");
536 OutStreamer->AddComment(
"End of file scope inline assembly");
541 bool EmitCodeView = M.getCodeViewFlag();
543 DebugHandlers.push_back(std::make_unique<CodeViewDebug>(
this));
544 if (!EmitCodeView || M.getDwarfVersion()) {
553 PP = std::make_unique<PseudoProbeHandler>(
this);
562 for (
auto &
F : M.getFunctionList()) {
610 Handlers.push_back(std::unique_ptr<EHStreamer>(ES));
613 if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag(
"cfguard")))
614 Handlers.push_back(std::make_unique<WinCFGuard>(
this));
617 Handler->beginModule(&M);
619 Handler->beginModule(&M);
701 "No emulated TLS variables in the common section");
740 "tagged symbols (-fsanitize=memtag-globals) are "
741 "only supported on AArch64 Android");
751 "' is already defined");
767 Handler->setSymbolSize(GVSym,
Size);
860 unsigned PtrSize =
DL.getPointerTypeSize(GV->
getType());
879 if (LocalAlias != EmittedInitSym)
900void AsmPrinter::emitFunctionHeaderComment() {}
905 for (
auto &
C : Prefix)
915 for (
auto &
C : Prefix) {
925void AsmPrinter::emitFunctionHeader() {
930 <<
"-- Begin function "
958 if (
F.hasFnAttribute(Attribute::Cold))
962 if (
F.hasPrefixData())
963 emitFunctionPrefix({
F.getPrefixData()});
970 unsigned PatchableFunctionPrefix = 0;
971 unsigned PatchableFunctionEntry = 0;
972 (void)
F.getFnAttribute(
"patchable-function-prefix")
974 .getAsInteger(10, PatchableFunctionPrefix);
975 (void)
F.getFnAttribute(
"patchable-function-entry")
977 .getAsInteger(10, PatchableFunctionEntry);
978 if (PatchableFunctionPrefix) {
983 }
else if (PatchableFunctionEntry) {
990 if (
const MDNode *MD =
F.getMetadata(LLVMContext::MD_func_sanitize)) {
991 assert(MD->getNumOperands() == 2);
993 auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
994 auto *TypeHash = mdconst::extract<Constant>(MD->getOperand(1));
995 emitFunctionPrefix({PrologueSig, TypeHash});
1000 false,
F.getParent());
1001 emitFunctionHeaderComment();
1019 std::vector<MCSymbol*> DeadBlockSyms;
1021 for (
MCSymbol *DeadBlockSym : DeadBlockSyms) {
1022 OutStreamer->AddComment(
"Address taken block that was later removed");
1039 Handler->beginFunction(
MF);
1040 Handler->beginBasicBlockSection(
MF->
front());
1043 Handler->beginFunction(
MF);
1045 Handler->beginBasicBlockSection(
MF->
front());
1048 if (
F.hasPrologueData())
1061 "' is a protected alias");
1086 std::optional<LocationSize>
Size;
1088 CommentOS <<
Size->getValue() <<
"-byte Reload\n";
1089 }
else if ((
Size =
MI.getFoldedRestoreSize(
TII))) {
1090 if (!
Size->hasValue())
1091 CommentOS <<
"Unknown-size Folded Reload\n";
1092 else if (
Size->getValue())
1093 CommentOS <<
Size->getValue() <<
"-byte Folded Reload\n";
1094 }
else if ((
Size =
MI.getSpillSize(
TII))) {
1095 CommentOS <<
Size->getValue() <<
"-byte Spill\n";
1096 }
else if ((
Size =
MI.getFoldedSpillSize(
TII))) {
1097 if (!
Size->hasValue())
1098 CommentOS <<
"Unknown-size Folded Spill\n";
1099 else if (
Size->getValue())
1100 CommentOS <<
Size->getValue() <<
"-byte Folded Spill\n";
1105 CommentOS <<
" Reload Reuse\n";
1115 OS <<
"implicit-def: "
1127 assert(
Op.isReg() &&
"KILL instruction must have only register operands");
1128 OS <<
' ' << (
Op.isDef() ?
"def " :
"killed ")
1140 if (
MI->isNonListDebugValue() &&
MI->getNumOperands() != 4)
1145 OS <<
"DEBUG_VALUE: ";
1148 if (
auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
1160 Expr = *NonVariadicExpr;
1167 for (
unsigned I = 0;
I <
Op.getNumArgs(); ++
I)
1168 OS <<
' ' <<
Op.getArg(
I);
1175 if (&
Op !=
MI->debug_operands().begin())
1177 switch (
Op.getType()) {
1180 Type *ImmTy =
Op.getFPImm()->getType();
1199 Op.getCImm()->getValue().
print(
OS,
false );
1203 OS <<
"!target-index(" <<
Op.getIndex() <<
"," <<
Op.getOffset() <<
")";
1209 std::optional<StackOffset>
Offset;
1223 if (
MI->isIndirectDebugValue())
1229 OS <<
'+' <<
Offset->getFixed() <<
']';
1246 if (
MI->getNumOperands() != 1)
1251 OS <<
"DEBUG_LABEL: ";
1254 if (
auto *SP = dyn_cast<DISubprogram>(
1255 V->getScope()->getNonLexicalBlockFileScope())) {
1270 if (
F.isDeclarationForLinker())
1274 F.needsUnwindTableEntry())
1311 auto *
MBB =
MI.getParent();
1312 auto I = std::next(
MI.getIterator());
1313 while (
I !=
MBB->
end() &&
I->isTransient())
1320 unsigned CFIIndex =
MI.getOperand(0).getCFIIndex();
1327 MCSymbol *FrameAllocSym =
MI.getOperand(0).getMCSymbol();
1328 int FrameOffset =
MI.getOperand(1).getImm();
1358 assert(BBAddrMapSection &&
".llvm_bb_addr_map section is not initialized.");
1365 uint8_t BBAddrMapVersion =
OutStreamer->getContext().getBBAddrMapVersion();
1371 if (Features.MultiBBRange) {
1372 OutStreamer->AddComment(
"number of basic block ranges");
1377 const MCSymbol *PrevMBBEndSymbol =
nullptr;
1378 if (!Features.MultiBBRange) {
1381 OutStreamer->AddComment(
"number of basic blocks");
1383 PrevMBBEndSymbol = FunctionSymbol;
1385 unsigned BBCount = 0;
1400 bool IsBeginSection =
1402 if (IsBeginSection) {
1405 OutStreamer->AddComment(
"number of basic blocks");
1407 PrevMBBEndSymbol = MBBSymbol;
1410 if (BBAddrMapVersion > 1) {
1430 if (Features.hasPGOAnalysis()) {
1431 assert(BBAddrMapVersion >= 2 &&
1432 "PGOAnalysisMap only supports version 2 or later");
1434 if (Features.FuncEntryCount) {
1438 MaybeEntryCount ? MaybeEntryCount->getCount() : 0);
1442 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
1446 ? &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI()
1449 if (Features.BBFreq || Features.BrProb) {
1451 if (Features.BBFreq) {
1456 if (Features.BrProb) {
1458 OutStreamer->AddComment(
"basic block successor count");
1462 OutStreamer->emitULEB128IntValue(SuccMBB->getBBID()->BaseID);
1463 OutStreamer->AddComment(
"successor branch probability");
1487 OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
1494 if (
const MDNode *MD =
F.getMetadata(LLVMContext::MD_kcfi_type))
1496 mdconst::extract<ConstantInt>(MD->getOperand(0)));
1501 auto GUID =
MI.getOperand(0).getImm();
1502 auto Index =
MI.getOperand(1).getImm();
1503 auto Type =
MI.getOperand(2).getImm();
1504 auto Attr =
MI.getOperand(3).getImm();
1516 if (!StackSizeSection)
1547 if (StackUsageStream ==
nullptr) {
1552 errs() <<
"Could not open file: " << EC.message();
1558 *StackUsageStream << DSP->getFilename() <<
':' << DSP->getLine();
1562 *StackUsageStream <<
':' <<
MF.
getName() <<
'\t' << StackSize <<
'\t';
1564 *StackUsageStream <<
"dynamic\n";
1566 *StackUsageStream <<
"static\n";
1573 PCSectionsSymbols[&MD].emplace_back(S);
1578 if (PCSectionsSymbols.empty() && !
F.hasMetadata(LLVMContext::MD_pcsections))
1582 const unsigned RelativeRelocSize =
1592 assert(S &&
"PC section is not initialized");
1603 bool ConstULEB128 =
false;
1605 if (
auto *S = dyn_cast<MDString>(MDO)) {
1609 const StringRef SecWithOpt = S->getString();
1610 const size_t OptStart = SecWithOpt.
find(
'!');
1616 assert((O ==
'!' || O ==
'C') &&
"Invalid !pcsections options");
1619 const MCSymbol *Prev = Syms.front();
1621 if (
Sym == Prev || !Deltas) {
1640 assert(isa<MDNode>(MDO) &&
"expecting either string or tuple");
1641 const auto *AuxMDs = cast<MDNode>(MDO);
1642 for (
const MDOperand &AuxMDO : AuxMDs->operands()) {
1643 assert(isa<ConstantAsMetadata>(AuxMDO) &&
"expecting a constant");
1644 const Constant *
C = cast<ConstantAsMetadata>(AuxMDO)->getValue();
1648 if (
auto *CI = dyn_cast<ConstantInt>(
C);
1649 CI && ConstULEB128 &&
Size > 1 &&
Size <= 8) {
1661 if (
const MDNode *MD =
F.getMetadata(LLVMContext::MD_pcsections))
1664 for (
const auto &MS : PCSectionsSymbols)
1665 EmitForMD(*MS.first, MS.second,
false);
1667 PCSectionsSymbols.clear();
1688 emitFunctionHeader();
1695 auto MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
1696 MDT = MDTWrapper ? &MDTWrapper->getDomTree() :
nullptr;
1698 OwnedMDT = std::make_unique<MachineDominatorTree>();
1699 OwnedMDT->getBase().recalculate(*
MF);
1700 MDT = OwnedMDT.get();
1704 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
1705 MLI = MLIWrapper ? &MLIWrapper->getLI() :
nullptr;
1707 OwnedMLI = std::make_unique<MachineLoopInfo>();
1709 MLI = OwnedMLI.get();
1714 bool HasAnyRealCode =
false;
1715 int NumInstsInFunction = 0;
1719 for (
auto &
MBB : *
MF) {
1723 for (
auto &
MI :
MBB) {
1725 if (!
MI.isPosition() && !
MI.isImplicitDef() && !
MI.isKill() &&
1726 !
MI.isDebugInstr()) {
1727 HasAnyRealCode =
true;
1728 ++NumInstsInFunction;
1735 if (
MDNode *MD =
MI.getPCSections())
1739 Handler->beginInstruction(&
MI);
1744 switch (
MI.getOpcode()) {
1745 case TargetOpcode::CFI_INSTRUCTION:
1748 case TargetOpcode::LOCAL_ESCAPE:
1751 case TargetOpcode::ANNOTATION_LABEL:
1752 case TargetOpcode::GC_LABEL:
1755 case TargetOpcode::EH_LABEL:
1765 auto MI2 = std::next(
MI.getIterator());
1766 if (IsEHa && MI2 !=
MBB.
end() &&
1767 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
1771 case TargetOpcode::INLINEASM:
1772 case TargetOpcode::INLINEASM_BR:
1775 case TargetOpcode::DBG_VALUE:
1776 case TargetOpcode::DBG_VALUE_LIST:
1782 case TargetOpcode::DBG_INSTR_REF:
1787 case TargetOpcode::DBG_PHI:
1791 case TargetOpcode::DBG_LABEL:
1797 case TargetOpcode::IMPLICIT_DEF:
1800 case TargetOpcode::KILL:
1803 case TargetOpcode::PSEUDO_PROBE:
1806 case TargetOpcode::ARITH_FENCE:
1810 case TargetOpcode::MEMBARRIER:
1813 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
1819 if (CanDoExtraAnalysis) {
1834 Handler->endInstruction();
1854 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1857 "Overwrite section range");
1864 if (CanDoExtraAnalysis) {
1875 for (
auto &KV : MnemonicCounts)
1878 sort(MnemonicVec, [](
const std::pair<StringRef, unsigned> &
A,
1879 const std::pair<StringRef, unsigned> &
B) {
1880 if (
A.second >
B.second)
1882 if (
A.second ==
B.second)
1887 for (
auto &KV : MnemonicVec) {
1888 auto Name = (
Twine(
"INST_") + getToken(KV.first.trim()).first).str();
1889 R << KV.first <<
": " <<
ore::NV(
Name, KV.second) <<
"\n";
1895 EmittedInsts += NumInstsInFunction;
1899 R <<
ore::NV(
"NumInstructions", NumInstsInFunction)
1900 <<
" instructions in function";
1913 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1919 OutStreamer->AddComment(
"avoids zero-length function");
1928 for (
const auto &BB :
F) {
1929 if (!BB.hasAddressTaken())
1932 if (
Sym->isDefined())
1934 OutStreamer->AddComment(
"Address of block that was removed by CodeGen");
1953 if (EmitFunctionSize) {
1968 Handler->endBasicBlockSection(
MF->
back());
1970 Handler->endBasicBlockSection(
MF->
back());
1973 Handler->markFunctionEnd();
1976 "Overwrite section range");
1985 Handler->endFunction(
MF);
1987 Handler->endFunction(
MF);
1991 if (HasAnyRealCode) {
1996 SMLoc(),
"pgo-analysis-map is enabled for function " +
MF->
getName() +
1997 " but it does not have labels");
2012 OutStreamer->getCommentOS() <<
"-- End function\n";
2022 if (isa<GlobalVariable>(
C))
2025 unsigned NumUses = 0;
2026 for (
const auto *
CU :
C->users())
2038 unsigned &NumGOTEquivUsers) {
2049 for (
const auto *U : GV->
users())
2052 return NumGOTEquivUsers > 0;
2066 for (
const auto &
G : M.globals()) {
2067 unsigned NumGOTEquivUsers = 0;
2086 unsigned Cnt =
I.second.second;
2092 for (
const auto *GV : FailedCandidates)
2110 "Visibility should be handled with emitLinkage() on AIX.");
2157 if (LocalAlias !=
Name)
2176 "IFunc is not supported on AIX.");
2197 if (LocalAlias !=
Name)
2260 std::optional<SmallString<128>> Filename;
2261 if (std::optional<StringRef> FilenameRef = RS.
getFilename()) {
2262 Filename = *FilenameRef;
2264 assert(!Filename->empty() &&
"The filename can't be empty.");
2269 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2272 MetaSerializer->emit();
2295 for (
const auto &
G : M.globals())
2305 if (!
F.isDeclarationForLinker())
2320 if (
F.isIntrinsic())
2332 if (
F.hasAddressTaken())
2349 if (!Stubs.empty()) {
2354 for (
const auto &Stub : Stubs) {
2356 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2357 DL.getPointerSize());
2368 if (!Stubs.empty()) {
2371 for (
const auto &Stub : Stubs) {
2382 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2383 DL.getPointerSize());
2391 TS->emitConstantPools();
2405 for (
const auto &Alias : M.aliases()) {
2406 if (Alias.hasAvailableExternallyLinkage())
2409 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
2410 if (!AliasVisited.
insert(Cur).second)
2422 for (
const auto &IFunc : M.ifuncs())
2423 emitGlobalIFunc(M, IFunc);
2427 Handler->endModule();
2429 Handler->endModule();
2447 for (
const auto &GO : M.global_objects()) {
2448 if (!GO.hasExternalWeakLinkage())
2453 auto SymbolName =
"swift_async_extendedFramePointerFlags";
2454 auto Global = M.getGlobalVariable(SymbolName);
2466 assert(
MI &&
"AsmPrinter didn't require GCModuleInfo?");
2469 MP->finishAssembly(M, *
MI, *
this);
2472 emitModuleIdents(M);
2477 emitModuleCommandLines(M);
2484 if (HasNoSplitStack)
2491 Function *InitTrampolineIntrinsic = M.getFunction(
"llvm.init.trampoline");
2492 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->
use_empty())
2500 if (!GV.use_empty() && !GV.isThreadLocal() &&
2501 !GV.hasDLLImportStorageClass() &&
2502 !GV.getName().starts_with(
"llvm.") &&
2503 !GV.hasAtLeastLocalUnnamedAddr())
2510 unsigned UniqueID = 0;
2512 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
2518 "",
false, ++UniqueID,
nullptr));
2532 AddrLabelSymbols =
nullptr;
2546 return Res.first->second;
2556 HasSplitStack =
true;
2559 HasNoSplitStack =
true;
2561 HasNoSplitStack =
true;
2568 "Only AIX uses the function descriptor hooks.");
2573 " initalized first.");
2582 CurrentSectionBeginSym =
nullptr;
2584 MBBSectionExceptionSyms.clear();
2586 if (
F.hasFnAttribute(
"patchable-function-entry") ||
2587 F.hasFnAttribute(
"function-instrument") ||
2588 F.hasFnAttribute(
"xray-instruction-threshold") ||
2593 if (NeedsLocalForSize)
2597 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2619 const std::vector<MachineConstantPoolEntry> &CP = MCP->
getConstants();
2620 if (CP.empty())
return;
2625 for (
unsigned i = 0, e = CP.size(); i != e; ++i) {
2641 unsigned SecIdx = CPSections.
size();
2642 while (SecIdx != 0) {
2643 if (CPSections[--SecIdx].S == S) {
2649 SecIdx = CPSections.
size();
2650 CPSections.
push_back(SectionCPs(S, Alignment));
2653 if (Alignment > CPSections[SecIdx].Alignment)
2654 CPSections[SecIdx].Alignment = Alignment;
2661 for (
unsigned i = 0, e = CPSections.
size(); i != e; ++i) {
2662 for (
unsigned j = 0, ee = CPSections[i].CPEs.
size(); j != ee; ++j) {
2663 unsigned CPI = CPSections[i].CPEs[j];
2665 if (!
Sym->isUndefined())
2668 if (CurSection != CPSections[i].S) {
2671 CurSection = CPSections[i].S;
2699 const std::vector<MachineJumpTableEntry> &JT = MJTI->
getJumpTables();
2700 if (JT.empty())
return;
2710 if (JTInDiffSection) {
2720 if (!JTInDiffSection)
2723 for (
unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2724 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2727 if (JTBBs.empty())
continue;
2753 if (JTInDiffSection &&
DL.hasLinkerPrivateGlobalPrefix())
2765 emitJumpTableEntry(MJTI,
MBB, JTI);
2767 if (!JTInDiffSection)
2775 unsigned UID)
const {
2841 if (GV->
getName() ==
"llvm.used") {
2852 if (GV->
getName() ==
"llvm.arm64ec.symbolmap") {
2859 for (
auto &U : Arr->operands()) {
2860 auto *
C = cast<Constant>(U);
2861 auto *Src = cast<GlobalValue>(
C->getOperand(0)->stripPointerCasts());
2862 auto *Dst = cast<GlobalValue>(
C->getOperand(1)->stripPointerCasts());
2863 int Kind = cast<ConstantInt>(
C->getOperand(2))->getZExtValue();
2865 if (Src->hasDLLImportStorageClass()) {
2889 if (GV->
getName() ==
"llvm.global_ctors") {
2896 if (GV->
getName() ==
"llvm.global_dtors") {
2908void AsmPrinter::emitLLVMUsedList(
const ConstantArray *InitList) {
2910 for (
unsigned i = 0, e = InitList->
getNumOperands(); i != e; ++i) {
2923 if (!isa<ConstantArray>(
List))
2927 for (
Value *O : cast<ConstantArray>(
List)->operands()) {
2928 auto *CS = cast<ConstantStruct>(O);
2929 if (CS->getOperand(1)->isNullValue())
2931 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2938 if (!CS->getOperand(2)->isNullValue()) {
2941 "associated data of XXStructor list is not yet supported on AIX");
2943 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2949 return L.Priority < R.Priority;
2959 if (Structors.
empty())
2965 std::reverse(Structors.
begin(), Structors.
end());
2993void AsmPrinter::emitModuleIdents(
Module &M) {
2997 if (
const NamedMDNode *NMD = M.getNamedMetadata(
"llvm.ident")) {
2998 for (
const MDNode *
N : NMD->operands()) {
2999 assert(
N->getNumOperands() == 1 &&
3000 "llvm.ident metadata entry can have only one operand");
3001 const MDString *S = cast<MDString>(
N->getOperand(0));
3007void AsmPrinter::emitModuleCommandLines(
Module &M) {
3012 const NamedMDNode *NMD =
M.getNamedMetadata(
"llvm.commandline");
3020 assert(
N->getNumOperands() == 1 &&
3021 "llvm.commandline metadata entry can have only one operand");
3022 const MDString *S = cast<MDString>(
N->getOperand(0));
3052 unsigned PadTo)
const {
3068 unsigned Size)
const {
3083 bool IsSectionRelative)
const {
3107 unsigned MaxBytesToEmit)
const {
3111 if (Alignment ==
Align(1))
3120 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3122 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3135 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
3141 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
3144 if (
const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
3147 if (
const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
3161 switch (CE->getOpcode()) {
3164 case Instruction::AddrSpaceCast: {
3166 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3167 unsigned SrcAS =
Op->getType()->getPointerAddressSpace();
3173 case Instruction::GetElementPtr: {
3176 cast<GEPOperator>(CE)->accumulateConstantOffset(
getDataLayout(), OffsetAI);
3187 case Instruction::Trunc:
3193 case Instruction::BitCast:
3196 case Instruction::IntToPtr: {
3210 case Instruction::PtrToInt: {
3216 Type *Ty = CE->getType();
3225 if (
DL.getTypeAllocSize(Ty).getFixedValue() <=
3226 DL.getTypeAllocSize(
Op->getType()).getFixedValue())
3232 case Instruction::Sub: {
3242 const MCExpr *RelocExpr =
3254 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3268 case Instruction::Add: {
3285 OS <<
"Unsupported expression in static initializer: ";
3286 CE->printAsOperand(
OS,
false,
3305 assert(!
Data.empty() &&
"Empty aggregates should be CAZ node");
3307 for (
unsigned i = 1, e =
Data.size(); i != e; ++i)
3308 if (
Data[i] !=
C)
return -1;
3309 return static_cast<uint8_t
>(
C);
3316 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3322 if (!
Value.isSplat(8))
3325 return Value.zextOrTrunc(8).getZExtValue();
3330 assert(CA->getNumOperands() != 0 &&
"Should be a CAZ");
3337 for (
unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
3338 if (CA->getOperand(i) != Op0)
3353 if (AliasIt != AliasList->
end()) {
3397 unsigned EmittedSize =
3399 assert(EmittedSize <=
Size &&
"Size cannot be less than EmittedSize!");
3400 if (
unsigned Padding =
Size - EmittedSize)
3430 uint64_t ElementSizeInBits =
DL.getTypeSizeInBits(ElementType);
3431 uint64_t ElementAllocSizeInBits =
DL.getTypeAllocSizeInBits(ElementType);
3433 if (ElementSizeInBits != ElementAllocSizeInBits) {
3445 "Cannot lower vector global with unusual element type");
3449 EmittedSize =
DL.getTypeStoreSize(CV->
getType());
3460 if (
unsigned Padding =
Size - EmittedSize)
3484 SizeSoFar += FieldSize + PadSize;
3492 "Layout of constant struct may be incorrect!");
3496 assert(ET &&
"Unknown float type");
3505 AP.
OutStreamer->getCommentOS() <<
' ' << StrVal <<
'\n';
3512 unsigned TrailingBytes = NumBytes %
sizeof(
uint64_t);
3521 AP.
OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
3523 for (; Chunk >= 0; --Chunk)
3527 for (Chunk = 0; Chunk < NumBytes /
sizeof(
uint64_t); ++Chunk)
3531 AP.
OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
3536 AP.
OutStreamer->emitZeros(
DL.getTypeAllocSize(ET) -
DL.getTypeStoreSize(ET));
3551 unsigned ExtraBitsSize =
BitWidth & 63;
3553 if (ExtraBitsSize) {
3561 if (
DL.isBigEndian()) {
3570 ExtraBitsSize =
alignTo(ExtraBitsSize, 8);
3572 (((
uint64_t)-1) >> (64 - ExtraBitsSize));
3583 for (
unsigned i = 0, e =
BitWidth / 64; i != e; ++i) {
3584 uint64_t Val =
DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
3588 if (ExtraBitsSize) {
3595 (ExtraBits & (((
uint64_t)-1) >> (64 - ExtraBitsSize)))
3596 == ExtraBits &&
"Directive too small for extra bits.");
3628 if (!(*ME)->evaluateAsRelocatable(MV,
nullptr,
nullptr) || MV.
isAbsolute())
3639 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
3647 if (!SymB || BaseSym != &SymB->
getSymbol())
3675 int NumUses = (int)Result.second;
3698 BaseCV = dyn_cast<Constant>(CV->
user_back());
3700 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
3703 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3706 if (StoreSize <= 8) {
3709 <<
format(
"0x%" PRIx64
"\n", CI->getZExtValue());
3710 AP.
OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3716 if (
Size != StoreSize)
3722 if (
const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
3725 if (isa<ConstantPointerNull>(CV)) {
3739 if (
const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3742 if (CE->getOpcode() == Instruction::BitCast)
3786 for (
auto &AliasPair : *AliasList) {
3845 if (
Sym->isUndefined())
3887 unsigned FunctionNumber) {
3891 <<
"Parent Loop BB" << FunctionNumber <<
"_"
3899 unsigned FunctionNumber) {
3903 <<
"Child Loop BB" << FunctionNumber <<
"_"
3904 << CL->getHeader()->getNumber() <<
" Depth " << CL->getLoopDepth()
3919 assert(Header &&
"No header for loop");
3923 if (Header != &
MBB) {
3924 AP.
OutStreamer->AddComment(
" in Loop: Header=BB" +
3955 Handler->endFunclet();
3956 Handler->beginFunclet(
MBB);
3971 Handler->beginCodeAlignment(
MBB);
3975 if (Alignment !=
Align(1))
3997 if (BB->hasName()) {
3999 false, BB->getModule());
4004 assert(
MLI !=
nullptr &&
"MachineLoopInfo should has been computed");
4009 if (shouldEmitLabelForBasicBlock(
MBB)) {
4011 OutStreamer->AddComment(
"Label of block must be emitted");
4031 Handler->beginBasicBlockSection(
MBB);
4033 Handler->beginBasicBlockSection(
MBB);
4042 Handler->endBasicBlockSection(
MBB);
4044 Handler->endBasicBlockSection(
MBB);
4049 bool IsDefinition)
const {
4052 switch (Visibility) {
4069bool AsmPrinter::shouldEmitLabelForBasicBlock(
4112 if (!
MI.isBranch() ||
MI.isIndirectBranch())
4121 if (
OP->isMBB() &&
OP->getMBB() ==
MBB)
4133 auto [GCPI, Inserted] = GCMetadataPrinters.insert({&S,
nullptr});
4135 return GCPI->second.get();
4141 if (
Name == GCMetaPrinter.getName()) {
4142 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4144 GCPI->second = std::move(GMP);
4145 return GCPI->second.get();
4153 assert(
MI &&
"AsmPrinter didn't require GCModuleInfo?");
4154 bool NeedsDefault =
false;
4155 if (
MI->begin() ==
MI->end())
4157 NeedsDefault =
true;
4159 for (
const auto &
I : *
MI) {
4161 if (MP->emitStackMaps(
SM, *
this))
4165 NeedsDefault =
true;
4173 std::unique_ptr<AsmPrinterHandler> Handler) {
4192 auto Kind8 =
static_cast<uint8_t
>(
Kind);
4197 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
4198 assert(Padding >= 0 &&
"Instrumentation map entry > 4 * Word Size");
4206 auto PrevSection =
OutStreamer->getCurrentSectionOnly();
4212 if (TT.isOSBinFormatELF()) {
4216 if (
F.hasComdat()) {
4218 GroupName =
F.getComdat()->getName();
4221 Flags, 0, GroupName,
F.hasComdat(),
4250 for (
const auto &Sled :
Sleds) {
4251 MCSymbol *Dot = Ctx.createTempSymbol();
4281 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol(
"xray_fn_idx");
4297 auto Attr =
F.getFnAttribute(
"function-instrument");
4298 bool LogArgs =
F.hasFnAttribute(
"xray-log-args");
4299 bool AlwaysInstrument =
4300 Attr.isStringAttribute() && Attr.getValueAsString() ==
"xray-always";
4309 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
4310 (void)
F.getFnAttribute(
"patchable-function-prefix")
4312 .getAsInteger(10, PatchableFunctionPrefix);
4313 (void)
F.getFnAttribute(
"patchable-function-entry")
4315 .getAsInteger(10, PatchableFunctionEntry);
4316 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
4328 if (
F.hasComdat()) {
4330 GroupName =
F.getComdat()->getName();
4343 return OutStreamer->getContext().getDwarfVersion();
4373 const MCSymbol *BranchLabel)
const {
4375 const auto BaseExpr =
4377 const auto Base = &cast<MCSymbolRefExpr>(BaseExpr)->getSymbol();
4381 return std::make_tuple(
Base, 0, BranchLabel,
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
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE,...
static llvm::object::BBAddrMap::Features getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges)
static void emitGlobalConstantVector(const DataLayout &DL, const ConstantVector *CV, AsmPrinter &AP, AsmPrinter::AliasMapTy *AliasList)
static cl::bits< PGOMapFeaturesEnum > PgoAnalysisMapFeatures("pgo-analysis-map", cl::Hidden, cl::CommaSeparated, cl::values(clEnumValN(PGOMapFeaturesEnum::FuncEntryCount, "func-entry-count", "Function Entry Count"), clEnumValN(PGOMapFeaturesEnum::BBFreq, "bb-freq", "Basic Block Frequency"), clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability")), cl::desc("Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is " "extracted from PGO related analysis."))
static uint32_t getBBAddrMapMetadata(const MachineBasicBlock &MBB)
Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section for a given basic block.
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
static bool isGOTEquivalentCandidate(const GlobalVariable *GV, unsigned &NumGOTEquivUsers)
Only consider global GOT equivalents if at least one user is a cstexpr inside an initializer of anoth...
static unsigned getNumGlobalVariableUses(const Constant *C)
Compute the number of Global Variables that uses a Constant.
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, const Constant *BaseCst, uint64_t Offset)
Transform a not absolute MCExpr containing a reference to a GOT equivalent global,...
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm)
Returns true if function begin and end labels should be emitted.
static void PrintChildLoopComment(raw_ostream &OS,