LLVM 24.0.0git
AsmPrinter.cpp
Go to the documentation of this file.
1//===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AsmPrinter class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "CodeViewDebug.h"
15#include "DwarfDebug.h"
16#include "DwarfException.h"
17#include "PseudoProbePrinter.h"
18#include "WasmException.h"
19#include "WinCFGuard.h"
20#include "WinException.h"
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/Twine.h"
68#include "llvm/Config/config.h"
69#include "llvm/IR/BasicBlock.h"
70#include "llvm/IR/Comdat.h"
71#include "llvm/IR/Constant.h"
72#include "llvm/IR/Constants.h"
73#include "llvm/IR/DataLayout.h"
77#include "llvm/IR/Function.h"
78#include "llvm/IR/GCStrategy.h"
79#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalIFunc.h"
82#include "llvm/IR/GlobalValue.h"
84#include "llvm/IR/Instruction.h"
87#include "llvm/IR/Mangler.h"
88#include "llvm/IR/Metadata.h"
89#include "llvm/IR/Module.h"
90#include "llvm/IR/Operator.h"
91#include "llvm/IR/PseudoProbe.h"
92#include "llvm/IR/Type.h"
93#include "llvm/IR/Value.h"
94#include "llvm/IR/ValueHandle.h"
95#include "llvm/MC/MCAsmInfo.h"
96#include "llvm/MC/MCContext.h"
98#include "llvm/MC/MCExpr.h"
99#include "llvm/MC/MCInst.h"
100#include "llvm/MC/MCSchedule.h"
101#include "llvm/MC/MCSection.h"
103#include "llvm/MC/MCSectionELF.h"
106#include "llvm/MC/MCStreamer.h"
108#include "llvm/MC/MCSymbol.h"
109#include "llvm/MC/MCSymbolELF.h"
111#include "llvm/MC/MCValue.h"
112#include "llvm/MC/SectionKind.h"
114#include "llvm/Object/ELFTypes.h"
115#include "llvm/Pass.h"
117#include "llvm/Support/Casting.h"
122#include "llvm/Support/Format.h"
124#include "llvm/Support/Path.h"
125#include "llvm/Support/VCSRevision.h"
131#include <algorithm>
132#include <cassert>
133#include <cinttypes>
134#include <cstdint>
135#include <iterator>
136#include <memory>
137#include <optional>
138#include <string>
139#include <utility>
140#include <vector>
141
142using namespace llvm;
143
144#define DEBUG_TYPE "asm-printer"
145
155 "pgo-analysis-map", cl::Hidden, cl::CommaSeparated,
157 clEnumValN(PGOMapFeaturesEnum::None, "none", "Disable all options"),
159 "Function Entry Count"),
161 "Basic Block Frequency"),
162 clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability"),
163 clEnumValN(PGOMapFeaturesEnum::All, "all", "Enable all options")),
164 cl::desc(
165 "Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is "
166 "extracted from PGO related analysis."));
167
169 "pgo-analysis-map-emit-bb-sections-cfg",
170 cl::desc("Enable the post-link cfg information from the basic block "
171 "sections profile in the PGO analysis map"),
172 cl::Hidden, cl::init(false));
173
175 "basic-block-address-map-skip-bb-entries",
176 cl::desc("Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP "
177 "section. It's used to save binary size when BB entries are "
178 "unnecessary for some PGOAnalysisMap features."),
179 cl::Hidden, cl::init(false));
180
182 "basic-block-address-map-emit-func-guid",
183 cl::desc("Emit the function GUID in the SHT_LLVM_BB_ADDR_MAP section for "
184 "functions with local linkage. This allows identifying them "
185 "without relying on their (possibly non-unique) symbol names."),
186 cl::Hidden, cl::init(false));
187
189 "emit-jump-table-sizes-section",
190 cl::desc("Emit a section containing jump table addresses and sizes"),
191 cl::Hidden, cl::init(false));
192
193// This isn't turned on by default, since several of the scheduling models are
194// not completely accurate, and we don't want to be misleading.
196 "asm-print-latency",
197 cl::desc("Print instruction latencies as verbose asm comments"), cl::Hidden,
198 cl::init(false));
199
201 StackUsageFile("stack-usage-file",
202 cl::desc("Output filename for stack usage information"),
203 cl::value_desc("filename"), cl::Hidden);
204
205STATISTIC(EmittedInsts, "Number of machine instrs printed");
206
207char AsmPrinter::ID = 0;
208
209namespace {
210class AddrLabelMapCallbackPtr final : CallbackVH {
211 AddrLabelMap *Map = nullptr;
212
213public:
214 AddrLabelMapCallbackPtr() = default;
215 AddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
216
217 void setPtr(BasicBlock *BB) {
219 }
220
221 void setMap(AddrLabelMap *map) { Map = map; }
222
223 void deleted() override;
224 void allUsesReplacedWith(Value *V2) override;
225};
226} // namespace
227
229 MCContext &Context;
230 struct AddrLabelSymEntry {
231 /// The symbols for the label.
233
234 Function *Fn; // The containing function of the BasicBlock.
235 unsigned Index; // The index in BBCallbacks for the BasicBlock.
236 };
237
238 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
239
240 /// Callbacks for the BasicBlock's that we have entries for. We use this so
241 /// we get notified if a block is deleted or RAUWd.
242 std::vector<AddrLabelMapCallbackPtr> BBCallbacks;
243
244 /// This is a per-function list of symbols whose corresponding BasicBlock got
245 /// deleted. These symbols need to be emitted at some point in the file, so
246 /// AsmPrinter emits them after the function body.
247 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>
248 DeletedAddrLabelsNeedingEmission;
249
250public:
251 AddrLabelMap(MCContext &context) : Context(context) {}
252
254 assert(DeletedAddrLabelsNeedingEmission.empty() &&
255 "Some labels for deleted blocks never got emitted");
256 }
257
259
261 std::vector<MCSymbol *> &Result);
262
265};
266
268 assert(BB->hasAddressTaken() &&
269 "Shouldn't get label for block without address taken");
270 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
271
272 // If we already had an entry for this block, just return it.
273 if (!Entry.Symbols.empty()) {
274 assert(BB->getParent() == Entry.Fn && "Parent changed");
275 return Entry.Symbols;
276 }
277
278 // Otherwise, this is a new entry, create a new symbol for it and add an
279 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
280 BBCallbacks.emplace_back(BB);
281 BBCallbacks.back().setMap(this);
282 Entry.Index = BBCallbacks.size() - 1;
283 Entry.Fn = BB->getParent();
284 MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
285 : Context.createTempSymbol();
286 Entry.Symbols.push_back(Sym);
287 return Entry.Symbols;
288}
289
290/// If we have any deleted symbols for F, return them.
292 Function *F, std::vector<MCSymbol *> &Result) {
293 DenseMap<AssertingVH<Function>, std::vector<MCSymbol *>>::iterator I =
294 DeletedAddrLabelsNeedingEmission.find(F);
295
296 // If there are no entries for the function, just return.
297 if (I == DeletedAddrLabelsNeedingEmission.end())
298 return;
299
300 // Otherwise, take the list.
301 std::swap(Result, I->second);
302 DeletedAddrLabelsNeedingEmission.erase(I);
303}
304
305//===- Address of Block Management ----------------------------------------===//
306
309 // Lazily create AddrLabelSymbols.
310 if (!AddrLabelSymbols)
311 AddrLabelSymbols = std::make_unique<AddrLabelMap>(OutContext);
312 return AddrLabelSymbols->getAddrLabelSymbolToEmit(
313 const_cast<BasicBlock *>(BB));
314}
315
317 const Function *F, std::vector<MCSymbol *> &Result) {
318 // If no blocks have had their addresses taken, we're done.
319 if (!AddrLabelSymbols)
320 return;
321 return AddrLabelSymbols->takeDeletedSymbolsForFunction(
322 const_cast<Function *>(F), Result);
323}
324
326 // If the block got deleted, there is no need for the symbol. If the symbol
327 // was already emitted, we can just forget about it, otherwise we need to
328 // queue it up for later emission when the function is output.
329 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
330 AddrLabelSymbols.erase(BB);
331 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
332 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
333
334#if !LLVM_MEMORY_SANITIZER_BUILD
335 // BasicBlock is destroyed already, so this access is UB detectable by msan.
336 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
337 "Block/parent mismatch");
338#endif
339
340 for (MCSymbol *Sym : Entry.Symbols) {
341 if (Sym->isDefined())
342 return;
343
344 // If the block is not yet defined, we need to emit it at the end of the
345 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
346 // for the containing Function. Since the block is being deleted, its
347 // parent may already be removed, we have to get the function from 'Entry'.
348 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
349 }
350}
351
353 // Get the entry for the RAUW'd block and remove it from our map.
354 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
355 AddrLabelSymbols.erase(Old);
356 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
357
358 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
359
360 // If New is not address taken, just move our symbol over to it.
361 if (NewEntry.Symbols.empty()) {
362 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
363 NewEntry = std::move(OldEntry); // Set New's entry.
364 return;
365 }
366
367 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
368
369 // Otherwise, we need to add the old symbols to the new block's set.
370 llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
371}
372
373void AddrLabelMapCallbackPtr::deleted() {
374 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
375}
376
377void AddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
378 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
379}
380
381/// getGVAlignment - Return the alignment to use for the specified global
382/// value. This rounds up to the preferred alignment if possible and legal.
384 Align InAlign) {
385 Align Alignment;
386 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
387 Alignment = DL.getPreferredAlign(GVar);
388
389 // If InAlign is specified, round it to it.
390 if (InAlign > Alignment)
391 Alignment = InAlign;
392
393 // If the GV has a specified alignment, take it into account.
394 MaybeAlign GVAlign;
395 if (auto *GVar = dyn_cast<GlobalVariable>(GV))
396 GVAlign = GVar->getAlign();
397 else if (auto *F = dyn_cast<Function>(GV))
398 GVAlign = F->getAlign();
399 if (!GVAlign)
400 return Alignment;
401
402 assert(GVAlign && "GVAlign must be set");
403
404 // If the GVAlign is larger than NumBits, or if we are required to obey
405 // NumBits because the GV has an assigned section, obey it.
406 if (*GVAlign > Alignment || GV->hasSection())
407 Alignment = *GVAlign;
408 return Alignment;
409}
410
411AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer,
412 char &ID)
413 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
415 PointerSize(tm.getTargetTriple().getArchPointerBitWidth() / 8),
416 SM(*this) {
417 VerboseAsm = OutStreamer->isVerboseAsm();
418 DwarfUsesRelocationsAcrossSections =
419 MAI.doesDwarfUseRelocationsAcrossSections();
420 GetMMI = [this]() {
422 return MMIWP ? &MMIWP->getMMI() : nullptr;
423 };
424 GetORE = [this](MachineFunction &MF) {
426 };
427 GetMDT = [this](MachineFunction &MF) {
428 auto *MDTWrapper =
430 return MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
431 };
432 GetMLI = [this](MachineFunction &MF) {
434 return MLIWrapper ? &MLIWrapper->getLI() : nullptr;
435 };
436 GetMBPI = [this](MachineFunction &MF) {
438 };
439 GetMBFI = [this](MachineFunction &MF) {
441 };
442 GetMBHI = [this](MachineFunction &MF) {
443 return &getAnalysis<MachineBlockHashInfo>().getMBHI();
444 };
445 GetBBSPR = [this](MachineFunction &MF) {
446 auto *BBSPRPass =
448 return BBSPRPass ? &BBSPRPass->getBBSPR() : nullptr;
449 };
450 BeginGCAssembly = [this](Module &M) {
452 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
453 for (const auto &I : *MI)
454 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*I))
455 MP->beginAssembly(M, *MI, *this);
456 };
457 FinishGCAssembly = [this](Module &M) {
459 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
460 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E;)
461 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(**--I))
462 MP->finishAssembly(M, *MI, *this);
463 };
464 EmitStackMaps = [this](Module &M) {
466 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
468 for (const auto &I : *MI)
469 Strategies.push_back(I.get());
471 };
472 AssertDebugEHFinalized = [&]() {
473 assert(!DD && Handlers.size() == NumUserHandlers &&
474 "Debug/EH info didn't get finalized");
475 };
476}
477
479
481 return TM.isPositionIndependent();
482}
483
484/// getFunctionNumber - Return a unique ID for the current function.
486 return MF->getFunctionNumber();
487}
488
490 return *TM.getObjFileLowering();
491}
492
494 assert(MMI && "MMI could not be nullptr!");
495 return MMI->getModule()->getDataLayout();
496}
497
499 assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
500 return MF->getSubtarget<MCSubtargetInfo>();
501}
502
506
507/// getCurrentSection() - Return the current section we are emitting to.
509 return OutStreamer->getCurrentSectionOnly();
510}
511
512/// createDwarfDebug() - Create the DwarfDebug handler.
514
526
528 MMI = GetMMI();
529 PointerSize = M.getDataLayout().getPointerSize(0);
530 HasSplitStack = false;
531 HasNoSplitStack = false;
532 DbgInfoAvailable = !M.debug_compile_units().empty();
533 ModuleExceptionModel = M.getExceptionModel();
534 const Triple &Target = M.getTargetTriple();
535
536 AddrLabelSymbols = nullptr;
537
538 // On AIX, we delay emitting any section information until
539 // after emitting the .file pseudo-op. This allows additional
540 // information (such as the embedded command line) to be associated
541 // with all sections in the object file rather than a single section.
542 if (!Target.isOSBinFormatXCOFF())
543 OutStreamer->initSections(TM.getMCSubtargetInfo());
544
545 // Emit the version-min deployment target directive if needed.
546 //
547 // FIXME: If we end up with a collection of these sorts of Darwin-specific
548 // or ELF-specific things, it may make sense to have a platform helper class
549 // that will work with the target helper class. For now keep it here, as the
550 // alternative is duplicated code in each of the target asm printers that
551 // use the directive, where it would need the same conditionalization
552 // anyway.
553 if (Target.isOSBinFormatMachO() && Target.isOSDarwin()) {
554 Triple TVT(M.getDarwinTargetVariantTriple());
555 OutStreamer->emitVersionForTarget(
556 Target, M.getSDKVersion(),
557 M.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT,
558 M.getDarwinTargetVariantSDKVersion());
559 }
560
561 // Allow the target to emit any magic that it wants at the start of the file.
563
564 // Very minimal debug info. It is ignored if we emit actual debug info. If we
565 // don't, this at least helps the user find where a global came from.
566 if (MAI.hasSingleParameterDotFile()) {
567 // .file "foo.c"
568 if (MAI.isAIX()) {
569 const char VerStr[] =
570#ifdef PACKAGE_VENDOR
571 PACKAGE_VENDOR " "
572#endif
573 PACKAGE_NAME " version " PACKAGE_VERSION
574#ifdef LLVM_REVISION
575 " (" LLVM_REVISION ")"
576#endif
577 ;
578 // TODO: Add timestamp and description.
579 OutStreamer->emitFileDirective(M.getSourceFileName(), VerStr, "", "");
580 } else {
581 OutStreamer->emitFileDirective(
582 llvm::sys::path::filename(M.getSourceFileName()));
583 }
584 }
585
586 // On AIX, emit bytes for llvm.commandline metadata after .file so that the
587 // C_INFO symbol is preserved if any csect is kept by the linker.
588 if (Target.isOSBinFormatXCOFF()) {
589 emitModuleCommandLines(M);
590 // Now we can generate section information.
591 OutStreamer->switchSection(
592 OutContext.getObjectFileInfo()->getTextSection());
593
594 // To work around an AIX assembler and/or linker bug, generate
595 // a rename for the default text-section symbol name. This call has
596 // no effect when generating object code directly.
597 MCSection *TextSection =
598 OutStreamer->getContext().getObjectFileInfo()->getTextSection();
599 MCSymbolXCOFF *XSym =
600 static_cast<MCSectionXCOFF *>(TextSection)->getQualNameSymbol();
601 if (XSym->hasRename())
602 OutStreamer->emitXCOFFRenameDirective(XSym, XSym->getSymbolTableName());
603 }
604
606
607 // Emit module-level inline asm if it exists.
608 if (M.hasModuleInlineAsm()) {
609 OutStreamer->AddComment("Start of file scope inline assembly");
610 OutStreamer->addBlankLine();
611 for (const Module::GlobalAsmFragment &Frag : M.getModuleInlineAsm()) {
612 const MCSubtargetInfo &AsmSTI = TM.getMCSubtargetInfo(
613 Frag.Props.TargetCPU, Frag.Props.TargetFeatures);
614 bool DidPush = emitTargetFeaturePush(AsmSTI);
615 emitInlineAsm(
616 Frag.Asm, AsmSTI, TM.Options.MCOptions, nullptr,
617 InlineAsm::AsmDialect(TM.getMCAsmInfo().getAssemblerDialect()));
618 emitTargetFeaturePop(AsmSTI, DidPush);
619 }
620 OutStreamer->AddComment("End of file scope inline assembly");
621 OutStreamer->addBlankLine();
622 }
623
624 if (MAI.doesSupportDebugInformation()) {
625 bool EmitCodeView = M.getCodeViewFlag();
626 // On Windows and UEFI targets, emit minimal CodeView compiler info even
627 // when debug info is disabled. UEFI follows the MSVC toolchain
628 // conventions, so it is treated the same way as Windows here.
629 if ((Target.isOSWindows() || Target.isUEFI()) &&
630 M.getNamedMetadata("llvm.dbg.cu"))
631 Handlers.push_back(std::make_unique<CodeViewDebug>(this));
632 if (!EmitCodeView || M.getDwarfVersion()) {
633 if (hasDebugInfo()) {
634 DD = createDwarfDebug();
635 Handlers.push_back(std::unique_ptr<DwarfDebug>(DD));
636 }
637 }
638 }
639
640 if (M.getNamedMetadata(PseudoProbeDescMetadataName))
641 PP = std::make_unique<PseudoProbeHandler>(this);
642
643 switch (ModuleExceptionModel) {
645 // We may want to emit CFI for debug.
646 [[fallthrough]];
650 for (auto &F : M.getFunctionList()) {
652 ModuleCFISection = getFunctionCFISectionType(F);
653 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
654 // the module needs .eh_frame. If we have found that case, we are done.
655 if (ModuleCFISection == CFISection::EH)
656 break;
657 }
658 assert(ModuleExceptionModel == ExceptionHandling::DwarfCFI ||
659 usesCFIWithoutEH() || ModuleCFISection != CFISection::EH);
660 break;
661 default:
662 break;
663 }
664
665 EHStreamer *ES = nullptr;
666 switch (ModuleExceptionModel) {
668 llvm_unreachable("should have resolved exception model kind");
671 // Emscripten EH is handled in JS glue code and emits no EH tables here.
672 if (!usesCFIWithoutEH())
673 break;
674 [[fallthrough]];
678 ES = new DwarfCFIException(this);
679 break;
681 ES = new ARMException(this);
682 break;
684 switch (MAI.getWinEHEncodingType()) {
685 default: llvm_unreachable("unsupported unwinding information encoding");
687 break;
690 ES = new WinException(this);
691 break;
692 }
693 break;
695 ES = new WasmException(this);
696 break;
698 ES = new AIXException(this);
699 break;
700 }
701 if (ES)
702 EHHandlers.push_back(std::unique_ptr<EHStreamer>(ES));
703
704 // All CFG modes required the tables emitted.
705 if (M.getControlFlowGuardMode() != ControlFlowGuardMode::Disabled)
706 Handlers.push_back(std::make_unique<WinCFGuard>(this));
707
708 for (auto &Handler : Handlers)
709 Handler->beginModule(&M);
710 for (auto &Handler : EHHandlers)
711 Handler->beginModule(&M);
712
713 return false;
714}
715
716static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
718 return false;
719
720 return GV->canBeOmittedFromSymbolTable();
721}
722
723void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
725 switch (Linkage) {
731 if (MAI.isMachO()) {
732 // .globl _foo
733 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
734
735 if (!canBeHidden(GV, MAI))
736 // .weak_definition _foo
737 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
738 else
739 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
740 } else if (MAI.avoidWeakIfComdat() && GV->hasComdat()) {
741 // .globl _foo
742 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
743 //NOTE: linkonce is handled by the section the symbol was assigned to.
744 } else {
745 // .weak _foo
746 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
747 }
748 return;
750 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
751 return;
754 return;
758 llvm_unreachable("Should never emit this");
759 }
760 llvm_unreachable("Unknown linkage type!");
761}
762
764 const GlobalValue *GV) const {
765 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
766}
767
769 return TM.getSymbol(GV);
770}
771
773 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
774 // exact definion (intersection of GlobalValue::hasExactDefinition() and
775 // !isInterposable()). These linkages include: external, appending, internal,
776 // private. It may be profitable to use a local alias for external. The
777 // assembler would otherwise be conservative and assume a global default
778 // visibility symbol can be interposable, even if the code generator already
779 // assumed it.
780 const Module &M = *GV.getParent();
781 if (M.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
782 if (TM.getRelocationModel() != Reloc::Static &&
783 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
784 return getSymbolWithGlobalValueBase(&GV, "$local");
785 }
786 return TM.getSymbol(&GV);
787}
788
789/// EmitGlobalVariable - Emit the specified global variable to the .s file.
791 MaybeAlign AlignmentGranule = getRequiredGlobalAlignmentGranule(*GV);
792 emitGlobalVariable(GV, AlignmentGranule);
793 if (AlignmentGranule)
794 OutStreamer->emitValueToAlignment(*AlignmentGranule);
795}
796
798 MaybeAlign AlignmentGranule) {
799 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
800 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
801 "No emulated TLS variables in the common section");
802
803 // Never emit TLS variable xyz in emulated TLS model.
804 // The initialization value is in __emutls_t.xyz instead of xyz.
805 if (IsEmuTLSVar)
806 return;
807
808 if (GV->hasInitializer()) {
809 // Check to see if this is a special global used by LLVM, if so, emit it.
810 if (emitSpecialLLVMGlobal(GV))
811 return;
812
813 // Skip the emission of global equivalents. The symbol can be emitted later
814 // on by emitGlobalGOTEquivs in case it turns out to be needed.
815 if (GlobalGOTEquivs.count(getSymbol(GV)))
816 return;
817
818 if (isVerbose()) {
819 // When printing the control variable __emutls_v.*,
820 // we don't need to print the original TLS variable name.
821 GV->printAsOperand(OutStreamer->getCommentOS(),
822 /*PrintType=*/false, GV->getParent());
823 OutStreamer->getCommentOS() << '\n';
824 }
825 }
826
827 MCSymbol *GVSym = getSymbol(GV);
828 MCSymbol *EmittedSym = GVSym;
829
830 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
831 // attributes.
832 // GV's or GVSym's attributes will be used for the EmittedSym.
833 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
834
835 if (GV->isTagged()) {
836 if (TM.getTargetTriple().getArch() != Triple::aarch64)
837 OutContext.reportError(SMLoc(),
838 "tagged symbols (-fsanitize=memtag-globals) are "
839 "only supported on AArch64");
840 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_Memtag);
841 }
842
843 if (!GV->hasInitializer()) // External globals require no extra code.
844 return;
845
846 GVSym->redefineIfPossible();
847 if (GVSym->isDefined() || GVSym->isVariable())
848 OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
849 "' is already defined");
850
851 if (MAI.hasDotTypeDotSizeDirective())
852 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
853
855
856 const DataLayout &DL = GV->getDataLayout();
857 uint64_t Size = GV->getGlobalSize(DL);
858
859 // If the alignment is specified, we *must* obey it. Overaligning a global
860 // with a specified alignment is a prompt way to break globals emitted to
861 // sections and expected to be contiguous (e.g. ObjC metadata).
862 //
863 // If we get passed in an explicit alignment granule, it is up to the caller
864 // to ensure that is not the case (i.e. that the GV is not in a section).
865 Align Alignment = getGVAlignment(GV, DL);
866
867 if (AlignmentGranule) {
868 assert(!GV->hasSection());
869 Size = alignTo(Size, *AlignmentGranule);
870 if (Alignment < *AlignmentGranule)
871 Alignment = *AlignmentGranule;
872 }
873
874 for (auto &Handler : Handlers)
875 Handler->setSymbolSize(GVSym, Size);
876
877 // Handle common symbols
878 if (GVKind.isCommon()) {
879 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
880 // .comm _foo, 42, 4
881 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
882 return;
883 }
884
885 // Determine to which section this global should be emitted.
886 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
887
888 // If we have a bss global going to a section that supports the
889 // zerofill directive, do so here.
890 if (GVKind.isBSS() && MAI.isMachO() && TheSection->isBssSection()) {
891 if (Size == 0)
892 Size = 1; // zerofill of 0 bytes is undefined.
893 emitLinkage(GV, GVSym);
894 // .zerofill __DATA, __bss, _foo, 400, 5
895 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment);
896 return;
897 }
898
899 // If this is a BSS local symbol and we are emitting in the BSS
900 // section use .lcomm/.comm directive.
901 if (GVKind.isBSSLocal() &&
902 getObjFileLowering().getBSSSection() == TheSection) {
903 if (Size == 0)
904 Size = 1; // .comm Foo, 0 is undefined, avoid it.
905
906 // Use .lcomm only if it supports user-specified alignment.
907 // Otherwise, while it would still be correct to use .lcomm in some
908 // cases (e.g. when Align == 1), the external assembler might enfore
909 // some -unknown- default alignment behavior, which could cause
910 // spurious differences between external and integrated assembler.
911 // Prefer to simply fall back to .local / .comm in this case.
912 if (MAI.getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
913 // .lcomm _foo, 42
914 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment);
915 return;
916 }
917
918 // .local _foo
919 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
920 // .comm _foo, 42, 4
921 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
922 return;
923 }
924
925 // Handle thread local data for mach-o which requires us to output an
926 // additional structure of data and mangle the original symbol so that we
927 // can reference it later.
928 //
929 // TODO: This should become an "emit thread local global" method on TLOF.
930 // All of this macho specific stuff should be sunk down into TLOFMachO and
931 // stuff like "TLSExtraDataSection" should no longer be part of the parent
932 // TLOF class. This will also make it more obvious that stuff like
933 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
934 // specific code.
935 if (GVKind.isThreadLocal() && MAI.isMachO()) {
936 // Emit the .tbss symbol
937 MCSymbol *MangSym =
938 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
939
940 if (GVKind.isThreadBSS()) {
941 TheSection = getObjFileLowering().getTLSBSSSection();
942 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment);
943 } else if (GVKind.isThreadData()) {
944 OutStreamer->switchSection(TheSection);
945
946 emitAlignment(Alignment, GV);
947 OutStreamer->emitLabel(MangSym);
948
950 GV->getInitializer());
951 }
952
953 OutStreamer->addBlankLine();
954
955 // Emit the variable struct for the runtime.
957
958 OutStreamer->switchSection(TLVSect);
959 // Emit the linkage here.
960 emitLinkage(GV, GVSym);
961 OutStreamer->emitLabel(GVSym);
962
963 // Three pointers in size:
964 // - __tlv_bootstrap - used to make sure support exists
965 // - spare pointer, used when mapped by the runtime
966 // - pointer to mangled symbol above with initializer
967 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
968 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
969 PtrSize);
970 OutStreamer->emitIntValue(0, PtrSize);
971 OutStreamer->emitSymbolValue(MangSym, PtrSize);
972
973 OutStreamer->addBlankLine();
974 return;
975 }
976
977 MCSymbol *EmittedInitSym = GVSym;
978
979 OutStreamer->switchSection(TheSection);
980
981 emitLinkage(GV, EmittedInitSym);
982 emitAlignment(Alignment, GV);
983
984 OutStreamer->emitLabel(EmittedInitSym);
985 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
986 if (LocalAlias != EmittedInitSym)
987 OutStreamer->emitLabel(LocalAlias);
988
990
991 if (MAI.hasDotTypeDotSizeDirective())
992 // .size foo, 42
993 OutStreamer->emitELFSize(EmittedInitSym,
995
996 OutStreamer->addBlankLine();
997}
998
999/// Emit the directive and value for debug thread local expression
1000///
1001/// \p Value - The value to emit.
1002/// \p Size - The size of the integer (in bytes) to emit.
1003void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
1004 OutStreamer->emitValue(Value, Size);
1005}
1006
1007void AsmPrinter::emitFunctionHeaderComment() {}
1008
1009void AsmPrinter::emitFunctionPrefix(ArrayRef<const Constant *> Prefix) {
1010 const Function &F = MF->getFunction();
1012 for (auto &C : Prefix)
1013 emitGlobalConstant(F.getDataLayout(), C);
1014 return;
1015 }
1016 // Preserving prefix-like data on platforms which use subsections-via-symbols
1017 // is a bit tricky. Here we introduce a symbol for the prefix-like data
1018 // and use the .alt_entry attribute to mark the function's real entry point
1019 // as an alternative entry point to the symbol that precedes the function..
1020 OutStreamer->emitLabel(OutContext.createLinkerPrivateTempSymbol());
1021
1022 for (auto &C : Prefix) {
1023 emitGlobalConstant(F.getDataLayout(), C);
1024 }
1025
1026 // Emit an .alt_entry directive for the actual function symbol.
1027 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
1028}
1029
1030/// EmitFunctionHeader - This method emits the header for the current
1031/// function.
1032void AsmPrinter::emitFunctionHeader() {
1033 const Function &F = MF->getFunction();
1034
1035 if (isVerbose())
1036 OutStreamer->getCommentOS()
1037 << "-- Begin function "
1038 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
1039
1040 // Print out constants referenced by the function
1042
1043 // Print the 'header' of function.
1044 // If basic block sections are desired, explicitly request a unique section
1045 // for this function's entry block.
1046 if (MF->front().isBeginSection())
1047 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
1048 else
1049 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
1050 OutStreamer->switchSection(MF->getSection());
1051
1052 if (MAI.isAIX())
1054 else
1055 emitVisibility(CurrentFnSym, F.getVisibility());
1056
1058 if (MAI.hasFunctionAlignment()) {
1059 Align PrefAlign = MF->getPreferredAlignment();
1060 if (MAI.useIntegratedAssembler() && MAI.hasPreferredAlignment()) {
1061 // Emit .p2align for the effective minimum alignment (which accounts for
1062 // F's own align attribute via getGVAlignment), then emit .prefalign only
1063 // when the preferred alignment is greater. The end symbol must be
1064 // created here, before the function body, so that .prefalign can
1065 // reference it; emitFunctionBody will emit the label at the function
1066 // end.
1067 Align MinAlign = emitAlignment(MF->getAlignment(), &F);
1068 if (MinAlign < PrefAlign) {
1069 CurrentFnEnd = createTempSymbol("func_end");
1070 OutStreamer->emitPrefAlign(PrefAlign, *CurrentFnEnd,
1071 /*EmitNops=*/true, /*Fill=*/0,
1073 }
1074 } else {
1075 emitAlignment(PrefAlign, &F);
1076 }
1077 }
1078
1079 if (MAI.hasDotTypeDotSizeDirective())
1080 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
1081
1082 if (F.hasFnAttribute(Attribute::Cold))
1083 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
1084
1085 // Emit the prefix data.
1086 if (F.hasPrefixData())
1087 emitFunctionPrefix({F.getPrefixData()});
1088
1089 // Emit KCFI type information before patchable-function-prefix nops.
1091
1092 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
1093 // place prefix data before NOPs.
1094 unsigned PatchableFunctionPrefix =
1095 F.getFnAttributeAsParsedInteger("patchable-function-prefix");
1096 unsigned PatchableFunctionEntry =
1097 F.getFnAttributeAsParsedInteger("patchable-function-entry");
1098 if (PatchableFunctionPrefix) {
1100 OutContext.createLinkerPrivateTempSymbol();
1102 emitNops(PatchableFunctionPrefix);
1103 } else if (PatchableFunctionEntry) {
1104 // May be reassigned when emitting the body, to reference the label after
1105 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
1107 }
1108
1109 // Emit the function prologue data for the indirect call sanitizer.
1110 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_func_sanitize)) {
1111 assert(MD->getNumOperands() == 2);
1112
1113 auto *PrologueSig = mdconst::extract<Constant>(MD->getOperand(0));
1114 auto *TypeHash = mdconst::extract<Constant>(MD->getOperand(1));
1115 emitFunctionPrefix({PrologueSig, TypeHash});
1116 }
1117
1118 if (isVerbose()) {
1119 F.printAsOperand(OutStreamer->getCommentOS(),
1120 /*PrintType=*/false, F.getParent());
1121 emitFunctionHeaderComment();
1122 OutStreamer->getCommentOS() << '\n';
1123 }
1124
1125 // Emit the function descriptor. This is a virtual function to allow targets
1126 // to emit their specific function descriptor. Right now it is only used by
1127 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
1128 // descriptors and should be converted to use this hook as well.
1129 if (MAI.isAIX())
1131
1132 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
1133 // their wild and crazy things as required.
1135
1136 // If the function had address-taken blocks that got deleted, then we have
1137 // references to the dangling symbols. Emit them at the start of the function
1138 // so that we don't get references to undefined symbols.
1139 std::vector<MCSymbol*> DeadBlockSyms;
1140 takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
1141 for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
1142 OutStreamer->AddComment("Address taken block that was later removed");
1143 OutStreamer->emitLabel(DeadBlockSym);
1144 }
1145
1146 if (CurrentFnBegin) {
1147 if (MAI.useAssignmentForEHBegin()) {
1148 MCSymbol *CurPos = OutContext.createTempSymbol();
1149 OutStreamer->emitLabel(CurPos);
1150 OutStreamer->emitAssignment(CurrentFnBegin,
1152 } else {
1153 OutStreamer->emitLabel(CurrentFnBegin);
1154 }
1155 }
1156
1157 // Emit pre-function debug and/or EH information.
1158 for (auto &Handler : Handlers) {
1159 Handler->beginFunction(MF);
1160 Handler->beginBasicBlockSection(MF->front());
1161 }
1162 for (auto &Handler : EHHandlers) {
1163 Handler->beginFunction(MF);
1164 Handler->beginBasicBlockSection(MF->front());
1165 }
1166
1167 // Emit the prologue data.
1168 if (F.hasPrologueData())
1169 emitGlobalConstant(F.getDataLayout(), F.getPrologueData());
1170}
1171
1172/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
1173/// function. This can be overridden by targets as required to do custom stuff.
1175 CurrentFnSym->redefineIfPossible();
1176 OutStreamer->emitLabel(CurrentFnSym);
1177
1178 if (TM.getTargetTriple().isOSBinFormatELF()) {
1179 MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
1180 if (Sym != CurrentFnSym) {
1181 CurrentFnBeginLocal = Sym;
1182 OutStreamer->emitLabel(Sym);
1183 OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
1184 }
1185 }
1186}
1187
1188/// emitComments - Pretty-print comments for instructions.
1189static void emitComments(const MachineInstr &MI, const MCSubtargetInfo *STI,
1190 raw_ostream &CommentOS) {
1191 const MachineFunction *MF = MI.getMF();
1193
1194 // Check for spills and reloads
1195
1196 // We assume a single instruction only has a spill or reload, not
1197 // both.
1198 std::optional<LocationSize> Size;
1199 if ((Size = MI.getRestoreSize(TII))) {
1200 CommentOS << Size->getValue() << "-byte Reload\n";
1201 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
1202 if (!Size->hasValue())
1203 CommentOS << "Unknown-size Folded Reload\n";
1204 else if (Size->getValue())
1205 CommentOS << Size->getValue() << "-byte Folded Reload\n";
1206 } else if ((Size = MI.getSpillSize(TII))) {
1207 CommentOS << Size->getValue() << "-byte Spill\n";
1208 } else if ((Size = MI.getFoldedSpillSize(TII))) {
1209 if (!Size->hasValue())
1210 CommentOS << "Unknown-size Folded Spill\n";
1211 else if (Size->getValue())
1212 CommentOS << Size->getValue() << "-byte Folded Spill\n";
1213 }
1214
1215 // Check for spill-induced copies
1216 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
1217 CommentOS << " Reload Reuse\n";
1218
1219 if (PrintLatency) {
1221 const MCSchedModel &SCModel = STI->getSchedModel();
1224 *STI, *TII, MI);
1225 // Report only interesting latencies.
1226 if (1 < Latency)
1227 CommentOS << " Latency: " << Latency << "\n";
1228 }
1229}
1230
1231/// emitImplicitDef - This method emits the specified machine instruction
1232/// that is an implicit def.
1234 Register RegNo = MI->getOperand(0).getReg();
1235
1236 SmallString<128> Str;
1237 raw_svector_ostream OS(Str);
1238 OS << "implicit-def: "
1239 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
1240
1241 OutStreamer->AddComment(OS.str());
1242 OutStreamer->addBlankLine();
1243}
1244
1245static void emitFreeze(const MachineInstr *MI, AsmPrinter &AP) {
1246 AP.OutStreamer->getCommentOS()
1247 << "freeze: "
1248 << printReg(MI->getOperand(0).getReg(),
1250 << '\n';
1251 AP.OutStreamer->addBlankLine();
1252}
1253
1254static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
1255 std::string Str;
1256 raw_string_ostream OS(Str);
1257 OS << "kill:";
1258 for (const MachineOperand &Op : MI->operands()) {
1259 assert(Op.isReg() && "KILL instruction must have only register operands");
1260 OS << ' ' << (Op.isDef() ? "def " : "killed ")
1261 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1262 }
1263 AP.OutStreamer->AddComment(Str);
1264 AP.OutStreamer->addBlankLine();
1265}
1266
1267static void emitFakeUse(const MachineInstr *MI, AsmPrinter &AP) {
1268 std::string Str;
1269 raw_string_ostream OS(Str);
1270 OS << "fake_use:";
1271 for (const MachineOperand &Op : MI->operands()) {
1272 // In some circumstances we can end up with fake uses of constants; skip
1273 // these.
1274 if (!Op.isReg())
1275 continue;
1276 OS << ' ' << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
1277 }
1278 AP.OutStreamer->AddComment(OS.str());
1279 AP.OutStreamer->addBlankLine();
1280}
1281
1282/// emitDebugValueComment - This method handles the target-independent form
1283/// of DBG_VALUE, returning true if it was able to do so. A false return
1284/// means the target will need to handle MI in EmitInstruction.
1286 // This code handles only the 4-operand target-independent form.
1287 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
1288 return false;
1289
1290 SmallString<128> Str;
1291 raw_svector_ostream OS(Str);
1292 OS << "DEBUG_VALUE: ";
1293
1294 const DILocalVariable *V = MI->getDebugVariable();
1295 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
1296 StringRef Name = SP->getName();
1297 if (!Name.empty())
1298 OS << Name << ":";
1299 }
1300 OS << V->getName();
1301 OS << " <- ";
1302
1303 const DIExpression *Expr = MI->getDebugExpression();
1304 // First convert this to a non-variadic expression if possible, to simplify
1305 // the output.
1306 if (auto NonVariadicExpr = DIExpression::convertToNonVariadicExpression(Expr))
1307 Expr = *NonVariadicExpr;
1308 // Then, output the possibly-simplified expression.
1309 if (Expr->getNumElements()) {
1310 OS << '[';
1311 ListSeparator LS;
1312 for (auto &Op : Expr->expr_ops()) {
1313 OS << LS << dwarf::OperationEncodingString(Op.getOp());
1314 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
1315 OS << ' ' << Op.getArg(I);
1316 }
1317 OS << "] ";
1318 }
1319
1320 // Register or immediate value. Register 0 means undef.
1321 for (const MachineOperand &Op : MI->debug_operands()) {
1322 if (&Op != MI->debug_operands().begin())
1323 OS << ", ";
1324 switch (Op.getType()) {
1326 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
1327 Type *ImmTy = Op.getFPImm()->getType();
1328 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
1329 ImmTy->isDoubleTy()) {
1330 OS << APF.convertToDouble();
1331 } else {
1332 // There is no good way to print long double. Convert a copy to
1333 // double. Ah well, it's only a comment.
1334 bool ignored;
1336 &ignored);
1337 OS << "(long double) " << APF.convertToDouble();
1338 }
1339 break;
1340 }
1342 OS << Op.getImm();
1343 break;
1344 }
1346 Op.getCImm()->getValue().print(OS, false /*isSigned*/);
1347 break;
1348 }
1350 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
1351 break;
1352 }
1354 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false);
1355 if (Op.getOffset())
1356 OS << '+' << Op.getOffset();
1357 break;
1358 }
1361 Register Reg;
1362 std::optional<StackOffset> Offset;
1363 if (Op.isReg()) {
1364 Reg = Op.getReg();
1365 } else {
1366 const TargetFrameLowering *TFI =
1368 Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1369 }
1370 if (!Reg) {
1371 // Suppress offset, it is not meaningful here.
1372 OS << "undef";
1373 break;
1374 }
1375 // The second operand is only an offset if it's an immediate.
1376 if (MI->isIndirectDebugValue())
1377 Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1378 if (Offset)
1379 OS << '[';
1380 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1381 if (Offset)
1382 OS << '+' << Offset->getFixed() << ']';
1383 break;
1384 }
1385 default:
1386 llvm_unreachable("Unknown operand type");
1387 }
1388 }
1389
1390 // NOTE: Want this comment at start of line, don't emit with AddComment.
1391 AP.OutStreamer->emitRawComment(Str);
1392 return true;
1393}
1394
1395/// This method handles the target-independent form of DBG_LABEL, returning
1396/// true if it was able to do so. A false return means the target will need
1397/// to handle MI in EmitInstruction.
1399 if (MI->getNumOperands() != 1)
1400 return false;
1401
1402 SmallString<128> Str;
1403 raw_svector_ostream OS(Str);
1404 OS << "DEBUG_LABEL: ";
1405
1406 const DILabel *V = MI->getDebugLabel();
1407 if (auto *SP = dyn_cast<DISubprogram>(
1408 V->getScope()->getNonLexicalBlockFileScope())) {
1409 StringRef Name = SP->getName();
1410 if (!Name.empty())
1411 OS << Name << ":";
1412 }
1413 OS << V->getName();
1414
1415 // NOTE: Want this comment at start of line, don't emit with AddComment.
1416 AP.OutStreamer->emitRawComment(OS.str());
1417 return true;
1418}
1419
1422 // Ignore functions that won't get emitted.
1423 if (F.isDeclarationForLinker())
1424 return CFISection::None;
1425
1426 if (ModuleExceptionModel == ExceptionHandling::DwarfCFI &&
1427 F.needsUnwindTableEntry())
1428 return CFISection::EH;
1429
1430 if (MAI.usesCFIWithoutEH(ModuleExceptionModel) && F.hasUWTable())
1431 return CFISection::EH;
1432
1433 if (hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
1434 return CFISection::Debug;
1435
1436 return CFISection::None;
1437}
1438
1443
1445 return MAI.usesCFIWithoutEH(ModuleExceptionModel) &&
1446 ModuleCFISection != CFISection::None;
1447}
1448
1450 if (!usesCFIWithoutEH() &&
1451 ModuleExceptionModel != ExceptionHandling::DwarfCFI &&
1452 ModuleExceptionModel != ExceptionHandling::ARM)
1453 return;
1454
1456 return;
1457
1458 // If there is no "real" instruction following this CFI instruction, skip
1459 // emitting it; it would be beyond the end of the function's FDE range.
1460 auto *MBB = MI.getParent();
1461 auto I = std::next(MI.getIterator());
1462 while (I != MBB->end() && I->isTransient())
1463 ++I;
1464 if (I == MBB->instr_end() &&
1465 MBB->getReverseIterator() == MBB->getParent()->rbegin())
1466 return;
1467
1468 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1469 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1470 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1471 emitCFIInstruction(CFI);
1472}
1473
1475 // The operands are the MCSymbol and the frame offset of the allocation.
1476 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1477 int FrameOffset = MI.getOperand(1).getImm();
1478
1479 // Emit a symbol assignment.
1480 OutStreamer->emitAssignment(FrameAllocSym,
1481 MCConstantExpr::create(FrameOffset, OutContext));
1482}
1483
1484/// Returns the BB metadata to be emitted in the SHT_LLVM_BB_ADDR_MAP section
1485/// for a given basic block. This can be used to capture more precise profile
1486/// information.
1488 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
1490 MBB.isReturnBlock(), !MBB.empty() && TII->isTailCall(MBB.back()),
1491 MBB.isEHPad(), const_cast<MachineBasicBlock &>(MBB).canFallThrough(),
1492 !MBB.empty() && MBB.rbegin()->isIndirectBranch()}
1493 .encode();
1494}
1495
1497getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges,
1498 bool HasCalls, const CFGProfile *FuncCFGProfile) {
1499 // Ensure that the user has not passed in additional options while also
1500 // specifying all or none.
1501 auto IsSet = [](PGOMapFeaturesEnum F) {
1503 };
1504 bool NoFeatures = IsSet(PGOMapFeaturesEnum::None);
1506 if ((NoFeatures || AllFeatures) && !all_equal(PgoAnalysisMapFeatures)) {
1508 "-pgo-analysis-map can accept only all or none with no additional "
1509 "values.");
1510 }
1511
1512 bool FuncEntryCountEnabled =
1513 AllFeatures || (!NoFeatures && IsSet(PGOMapFeaturesEnum::FuncEntryCount));
1514 bool BBFreqEnabled =
1515 AllFeatures || (!NoFeatures && IsSet(PGOMapFeaturesEnum::BBFreq));
1516 bool BrProbEnabled =
1517 AllFeatures || (!NoFeatures && IsSet(PGOMapFeaturesEnum::BrProb));
1518 bool PostLinkCfgEnabled = FuncCFGProfile && PgoAnalysisMapEmitBBSectionsCfg;
1519 // Only emit the GUID for functions with local linkage, whose symbol names
1520 // may not be unique across translation units. Other functions can be
1521 // identified by their symbol names.
1522 bool FuncGUIDEnabled =
1524
1525 if ((BBFreqEnabled || BrProbEnabled) && BBAddrMapSkipEmitBBEntries) {
1527 "BB entries info is required for BBFreq and BrProb features");
1528 }
1529 return {FuncEntryCountEnabled, BBFreqEnabled, BrProbEnabled,
1530 MF.hasBBSections() && NumMBBSectionRanges > 1,
1531 // Use static_cast to avoid breakage of tests on windows.
1532 static_cast<bool>(BBAddrMapSkipEmitBBEntries), HasCalls,
1533 shouldEmitBBHash(), PostLinkCfgEnabled, FuncGUIDEnabled};
1534}
1535
1537 MCSection *BBAddrMapSection =
1538 getObjFileLowering().getBBAddrMapSection(*MF.getSection());
1539 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1540 bool HasCalls = !CurrentFnCallsiteEndSymbols.empty();
1541
1542 const BasicBlockSectionsProfileReader *BBSPR = GetBBSPR(*this->MF);
1543 const CFGProfile *FuncCFGProfile = nullptr;
1544 if (BBSPR)
1545 FuncCFGProfile = BBSPR->getFunctionCFGProfile(MF.getFunction().getName());
1546
1547 const MCSymbol *FunctionSymbol = getFunctionBegin();
1548
1549 OutStreamer->pushSection();
1550 OutStreamer->switchSection(BBAddrMapSection);
1551 OutStreamer->AddComment("version");
1552 uint8_t BBAddrMapVersion = OutStreamer->getContext().getBBAddrMapVersion();
1553 OutStreamer->emitInt8(BBAddrMapVersion);
1554 OutStreamer->AddComment("feature");
1555 auto Features = getBBAddrMapFeature(MF, MBBSectionRanges.size(), HasCalls,
1556 FuncCFGProfile);
1557 OutStreamer->emitInt16(Features.encode());
1558 if (Features.FuncGUID) {
1559 // Use the GUID assigned by AssignGUIDPass if available. Otherwise, compute
1560 // it from the source file name and the function name.
1561 OutStreamer->AddComment("function GUID");
1562 OutStreamer->emitInt64(MF.getFunction().getGUIDOrFallback());
1563 }
1564 // Emit BB Information for each basic block in the function.
1565 if (Features.MultiBBRange) {
1566 OutStreamer->AddComment("number of basic block ranges");
1567 OutStreamer->emitULEB128IntValue(MBBSectionRanges.size());
1568 }
1569 // Number of blocks in each MBB section.
1570 DenseMap<MBBSectionID, unsigned> MBBSectionNumBlocks;
1571 const MCSymbol *PrevMBBEndSymbol = nullptr;
1572 if (!Features.MultiBBRange) {
1573 OutStreamer->AddComment("function address");
1574 OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1575 OutStreamer->AddComment("number of basic blocks");
1576 OutStreamer->emitULEB128IntValue(MF.size());
1577 PrevMBBEndSymbol = FunctionSymbol;
1578 } else {
1579 unsigned BBCount = 0;
1580 for (const MachineBasicBlock &MBB : MF) {
1581 BBCount++;
1582 if (MBB.isEndSection()) {
1583 // Store each section's basic block count when it ends.
1584 MBBSectionNumBlocks[MBB.getSectionID()] = BBCount;
1585 // Reset the count for the next section.
1586 BBCount = 0;
1587 }
1588 }
1589 }
1590 // Emit the BB entry for each basic block in the function.
1591 for (const MachineBasicBlock &MBB : MF) {
1592 const MCSymbol *MBBSymbol =
1593 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1594 bool IsBeginSection =
1595 Features.MultiBBRange && (MBB.isBeginSection() || MBB.isEntryBlock());
1596 if (IsBeginSection) {
1597 OutStreamer->AddComment("base address");
1598 OutStreamer->emitSymbolValue(MBBSymbol, getPointerSize());
1599 OutStreamer->AddComment("number of basic blocks");
1600 OutStreamer->emitULEB128IntValue(MBBSectionNumBlocks[MBB.getSectionID()]);
1601 PrevMBBEndSymbol = MBBSymbol;
1602 }
1603
1604 const MachineBlockHashInfoResult *MBHI =
1605 Features.BBHash ? GetMBHI(*this->MF) : nullptr;
1606
1607 if (!Features.OmitBBEntries) {
1608 OutStreamer->AddComment("BB id");
1609 // Emit the BB ID for this basic block.
1610 // We only emit BaseID since CloneID is unset for
1611 // -basic-block-adress-map.
1612 // TODO: Emit the full BBID when labels and sections can be mixed
1613 // together.
1614 OutStreamer->emitULEB128IntValue(MBB.getBBID()->BaseID);
1615 // Emit the basic block offset relative to the end of the previous block.
1616 // This is zero unless the block is padded due to alignment.
1617 emitLabelDifferenceAsULEB128(MBBSymbol, PrevMBBEndSymbol);
1618 const MCSymbol *CurrentLabel = MBBSymbol;
1619 if (HasCalls) {
1620 auto CallsiteEndSymbols = CurrentFnCallsiteEndSymbols.lookup(&MBB);
1621 OutStreamer->AddComment("number of callsites");
1622 OutStreamer->emitULEB128IntValue(CallsiteEndSymbols.size());
1623 for (const MCSymbol *CallsiteEndSymbol : CallsiteEndSymbols) {
1624 // Emit the callsite offset.
1625 emitLabelDifferenceAsULEB128(CallsiteEndSymbol, CurrentLabel);
1626 CurrentLabel = CallsiteEndSymbol;
1627 }
1628 }
1629 // Emit the offset to the end of the block, which can be used to compute
1630 // the total block size.
1631 emitLabelDifferenceAsULEB128(MBB.getEndSymbol(), CurrentLabel);
1632 // Emit the Metadata.
1633 OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1634 // Emit the Hash.
1635 if (MBHI) {
1636 OutStreamer->emitInt64(MBHI->getMBBHash(MBB));
1637 }
1638 }
1639 PrevMBBEndSymbol = MBB.getEndSymbol();
1640 }
1641
1642 if (Features.hasPGOAnalysis()) {
1643 assert(BBAddrMapVersion >= 2 &&
1644 "PGOAnalysisMap only supports version 2 or later");
1645
1646 if (Features.FuncEntryCount) {
1647 OutStreamer->AddComment("function entry count");
1648 auto MaybeEntryCount = MF.getFunction().getEntryCount();
1649 OutStreamer->emitULEB128IntValue(MaybeEntryCount ? *MaybeEntryCount : 0);
1650 }
1651 const MachineBlockFrequencyInfo *MBFI =
1652 Features.BBFreq ? GetMBFI(*this->MF) : nullptr;
1653 const MachineBranchProbabilityInfo *MBPI =
1654 Features.BrProb ? GetMBPI(*this->MF) : nullptr;
1655
1656 if (Features.BBFreq || Features.BrProb) {
1657 for (const MachineBasicBlock &MBB : MF) {
1658 if (Features.BBFreq) {
1659 OutStreamer->AddComment("basic block frequency");
1660 OutStreamer->emitULEB128IntValue(
1661 MBFI->getBlockFreq(&MBB).getFrequency());
1662 if (Features.PostLinkCfg) {
1663 OutStreamer->AddComment("basic block frequency (propeller)");
1664 OutStreamer->emitULEB128IntValue(
1665 FuncCFGProfile->getBlockCount(*MBB.getBBID()));
1666 }
1667 }
1668 if (Features.BrProb) {
1669 unsigned SuccCount = MBB.succ_size();
1670 OutStreamer->AddComment("basic block successor count");
1671 OutStreamer->emitULEB128IntValue(SuccCount);
1672 for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
1673 OutStreamer->AddComment("successor BB ID");
1674 OutStreamer->emitULEB128IntValue(SuccMBB->getBBID()->BaseID);
1675 OutStreamer->AddComment("successor branch probability");
1676 OutStreamer->emitULEB128IntValue(
1677 MBPI->getEdgeProbability(&MBB, SuccMBB).getNumerator());
1678 if (Features.PostLinkCfg) {
1679 OutStreamer->AddComment("successor branch frequency (propeller)");
1680 OutStreamer->emitULEB128IntValue(FuncCFGProfile->getEdgeCount(
1681 *MBB.getBBID(), *SuccMBB->getBBID()));
1682 }
1683 }
1684 }
1685 }
1686 }
1687 }
1688
1689 OutStreamer->popSection();
1690}
1691
1693 const MCSymbol *Symbol) {
1694 MCSection *Section =
1695 getObjFileLowering().getKCFITrapSection(*MF.getSection());
1696 if (!Section)
1697 return;
1698
1699 OutStreamer->pushSection();
1700 OutStreamer->switchSection(Section);
1701
1702 MCSymbol *Loc = OutContext.createLinkerPrivateTempSymbol();
1703 OutStreamer->emitLabel(Loc);
1704 OutStreamer->emitAbsoluteSymbolDiff(Symbol, Loc, 4);
1705
1706 OutStreamer->popSection();
1707}
1708
1710 const Function &F = MF.getFunction();
1711 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_kcfi_type))
1712 emitGlobalConstant(F.getDataLayout(),
1713 mdconst::extract<ConstantInt>(MD->getOperand(0)));
1714}
1715
1717 if (PP) {
1718 auto GUID = MI.getOperand(0).getImm();
1719 auto Index = MI.getOperand(1).getImm();
1720 auto Type = MI.getOperand(2).getImm();
1721 auto Attr = MI.getOperand(3).getImm();
1722 DILocation *DebugLoc = MI.getDebugLoc();
1723 PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1724 }
1725}
1726
1728 if (!MF.getTarget().Options.EmitStackSizeSection)
1729 return;
1730
1731 MCSection *StackSizeSection =
1733 if (!StackSizeSection)
1734 return;
1735
1736 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1737 // Don't emit functions with dynamic stack allocations.
1738 if (FrameInfo.hasVarSizedObjects())
1739 return;
1740
1741 OutStreamer->pushSection();
1742 OutStreamer->switchSection(StackSizeSection);
1743
1744 const MCSymbol *FunctionSymbol = getFunctionBegin();
1745 uint64_t StackSize =
1746 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1747 const DataLayout &DL = getDataLayout();
1748 OutStreamer->emitSymbolValue(FunctionSymbol,
1749 DL.getPointerSize(DL.getProgramAddressSpace()));
1750 OutStreamer->emitULEB128IntValue(StackSize);
1751
1752 OutStreamer->popSection();
1753}
1754
1756 const std::string OutputFilename =
1758 : MF.getTarget().Options.StackUsageFile;
1759
1760 // OutputFilename empty implies -fstack-usage is not passed.
1761 if (OutputFilename.empty())
1762 return;
1763
1764 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1765 uint64_t StackSize =
1766 FrameInfo.getStackSize() + FrameInfo.getUnsafeStackSize();
1767
1768 if (StackUsageStream == nullptr) {
1769 std::error_code EC;
1770 StackUsageStream =
1771 std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1772 if (EC) {
1773 errs() << "Could not open file: " << EC.message();
1774 return;
1775 }
1776 }
1777
1778 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1779 *StackUsageStream << DSP->getFilename() << ':' << DSP->getLine();
1780 else
1781 *StackUsageStream << MF.getFunction().getParent()->getName();
1782
1783 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1784 if (FrameInfo.hasVarSizedObjects())
1785 *StackUsageStream << "dynamic\n";
1786 else
1787 *StackUsageStream << "static\n";
1788}
1789
1790/// Extracts a numeric type identifier of a Function's type from
1791/// callgraph metadata. Returns null if metadata cannot be found.
1794 F.getMetadata(LLVMContext::MD_callgraph, Types);
1795 for (const auto &Type : Types) {
1796 if (Type->getNumOperands() == 1 && isa<MDString>(Type->getOperand(0))) {
1797 MDString *MDTypeId = cast<MDString>(Type->getOperand(0));
1798 uint64_t TypeIdVal = llvm::MD5Hash(MDTypeId->getString());
1799 IntegerType *Int64Ty = Type::getInt64Ty(F.getContext());
1800 return ConstantInt::get(Int64Ty, TypeIdVal);
1801 }
1802 }
1803 return nullptr;
1804}
1805
1806/// Emits .llvm.callgraph section.
1808 FunctionCallGraphInfo &FuncCGInfo) {
1809 if (!MF.getTarget().Options.EmitCallGraphSection)
1810 return;
1811
1812 // Switch to the call graph section for the function
1813 MCSection *FuncCGSection =
1815 assert(FuncCGSection && "null callgraph section");
1816 OutStreamer->pushSection();
1817 OutStreamer->switchSection(FuncCGSection);
1818
1819 const Function &F = MF.getFunction();
1820 // If this function has external linkage or has its address taken and
1821 // it is not a callback, then anything could call it.
1822 bool IsIndirectTarget =
1823 !F.hasLocalLinkage() || F.hasAddressTaken(nullptr,
1824 /*IgnoreCallbackUses=*/true,
1825 /*IgnoreAssumeLikeCalls=*/true,
1826 /*IgnoreLLVMUsed=*/false);
1827
1828 const auto &DirectCallees = FuncCGInfo.DirectCallees;
1829 const auto &IndirectCalleeTypeIDs = FuncCGInfo.IndirectCalleeTypeIDs;
1830
1831 using namespace callgraph;
1832 Flags CGFlags = Flags::None;
1833 if (IsIndirectTarget)
1834 CGFlags |= Flags::IsIndirectTarget;
1835 if (DirectCallees.size() > 0)
1836 CGFlags |= Flags::HasDirectCallees;
1837 if (IndirectCalleeTypeIDs.size() > 0)
1838 CGFlags |= Flags::HasIndirectCallees;
1839
1840 // Emit function's call graph information.
1841 // 1) CallGraphSectionFormatVersion
1842 // 2) Flags
1843 // a. LSB bit 0 is set to 1 if the function is a potential indirect
1844 // target.
1845 // b. LSB bit 1 is set to 1 if there are direct callees.
1846 // c. LSB bit 2 is set to 1 if there are indirect callees.
1847 // d. Rest of the 5 bits in Flags are reserved for any future use.
1848 // 3) Function entry PC.
1849 // 4) FunctionTypeID if the function is indirect target and its type id
1850 // is known, otherwise it is set to 0.
1851 // 5) Number of unique direct callees, if at least one exists.
1852 // 6) For each unique direct callee, the callee's PC.
1853 // 7) Number of unique indirect target type IDs, if at least one exists.
1854 // 8) Each unique indirect target type id.
1855 const DataLayout &DL = getDataLayout();
1856 unsigned ProgramPointerSize = DL.getPointerSize(DL.getProgramAddressSpace());
1857 OutStreamer->emitInt8(CallGraphSectionFormatVersion::V_0);
1858 OutStreamer->emitInt8(static_cast<uint8_t>(CGFlags));
1859 OutStreamer->emitSymbolValue(getSymbol(&F), ProgramPointerSize);
1860 const auto *TypeId = extractNumericCGTypeId(F);
1861 if (IsIndirectTarget && TypeId)
1862 OutStreamer->emitInt64(TypeId->getZExtValue());
1863 else
1864 OutStreamer->emitInt64(0);
1865
1866 if (DirectCallees.size() > 0) {
1867 OutStreamer->emitULEB128IntValue(DirectCallees.size());
1868 for (const auto &CalleeSymbol : DirectCallees)
1869 OutStreamer->emitSymbolValue(CalleeSymbol, ProgramPointerSize);
1870 FuncCGInfo.DirectCallees.clear();
1871 }
1872 if (IndirectCalleeTypeIDs.size() > 0) {
1873 OutStreamer->emitULEB128IntValue(IndirectCalleeTypeIDs.size());
1874 for (const auto &CalleeTypeId : IndirectCalleeTypeIDs)
1875 OutStreamer->emitInt64(CalleeTypeId);
1876 FuncCGInfo.IndirectCalleeTypeIDs.clear();
1877 }
1878 // End of emitting call graph section contents.
1879 OutStreamer->popSection();
1880}
1881
1883 const MDNode &MD) {
1884 MCSymbol *S = MF.getContext().createTempSymbol("pcsection");
1885 OutStreamer->emitLabel(S);
1886 PCSectionsSymbols[&MD].emplace_back(S);
1887}
1888
1890 const Function &F = MF.getFunction();
1891 if (PCSectionsSymbols.empty() && !F.hasMetadata(LLVMContext::MD_pcsections))
1892 return;
1893
1894 const CodeModel::Model CM = MF.getTarget().getCodeModel();
1895 const unsigned RelativeRelocSize =
1897 : 4;
1898
1899 // Switch to PCSection, short-circuiting the common case where the current
1900 // section is still valid (assume most MD_pcsections contain just 1 section).
1901 auto SwitchSection = [&, Prev = StringRef()](const StringRef &Sec) mutable {
1902 if (Sec == Prev)
1903 return;
1904 MCSection *S = getObjFileLowering().getPCSection(Sec, MF.getSection());
1905 assert(S && "PC section is not initialized");
1906 OutStreamer->switchSection(S);
1907 Prev = Sec;
1908 };
1909 // Emit records into sections as specified in the pcsections MDNode. A record
1910 // is the PC of an instruction, or the start and size of a function, followed
1911 // by the auxiliary data of the section.
1912 auto EmitForMD = [&](const MDNode &MD, ArrayRef<const MCSymbol *> Syms,
1913 bool IsFunction) {
1914 // Expect the first operand to be a section name. After that, a tuple of
1915 // constants may appear, which will simply be emitted into the current
1916 // section (the user of MD_pcsections decides the format of encoded data).
1917 assert(isa<MDString>(MD.getOperand(0)) && "first operand not a string");
1918 const ArrayRef<MDOperand> Ops = MD.operands();
1919 for (size_t I = 0; I < Ops.size();) {
1920 // Found string, start of new section!
1921 // Find options for this section "<section>!<opts>" - supported options:
1922 // C = Compress constant integers of size 2-8 bytes as ULEB128.
1923 const StringRef SecWithOpt = cast<MDString>(Ops[I++])->getString();
1924 const size_t OptStart = SecWithOpt.find('!'); // likely npos
1925 const StringRef Sec = SecWithOpt.substr(0, OptStart);
1926 const StringRef Opts = SecWithOpt.substr(OptStart); // likely empty
1927 const bool ConstULEB128 = Opts.contains('C');
1928#ifndef NDEBUG
1929 for (char O : Opts)
1930 assert((O == '!' || O == 'C') && "Invalid !pcsections options");
1931#endif
1932 // The auxiliary data of this section are the tuples up to the next
1933 // section name.
1934 const size_t AuxBegin = I;
1935 while (I < Ops.size() && !isa<MDString>(Ops[I]))
1936 ++I;
1937 const ArrayRef<MDOperand> Aux = Ops.slice(AuxBegin, I - AuxBegin);
1938
1939 // Metadata does not keep globals alive, and passes such as ThinLTO
1940 // function import do not follow references from metadata, so a constant
1941 // may have been dropped (nulled). Omit the records rather than emit them
1942 // without their auxiliary data.
1943 if (any_of(Aux, [](const MDOperand &MDO) {
1944 const auto *AuxMDs = dyn_cast<MDNode>(MDO);
1945 return AuxMDs && is_contained(AuxMDs->operands(), nullptr);
1946 }))
1947 continue;
1948
1949 auto EmitAux = [&] {
1950 for (const MDOperand &MDO : Aux) {
1951 assert(isa<MDNode>(MDO) && "expecting either string or tuple");
1952 for (const MDOperand &AuxMDO : cast<MDNode>(MDO)->operands()) {
1953 assert(isa<ConstantAsMetadata>(AuxMDO) && "expecting a constant");
1954 const Constant *C = cast<ConstantAsMetadata>(AuxMDO)->getValue();
1955 const DataLayout &DL = F.getDataLayout();
1956 const uint64_t Size = DL.getTypeStoreSize(C->getType());
1957
1958 if (auto *CI = dyn_cast<ConstantInt>(C);
1959 CI && ConstULEB128 && Size > 1 && Size <= 8) {
1960 emitULEB128(CI->getZExtValue());
1961 } else {
1963 }
1964 }
1965 }
1966 };
1967 // Emit the address of Sym relative to the entry itself, which avoids a
1968 // dynamic relocation in the final binary. User will get the address with
1969 // `base + addr`.
1970 auto EmitRelativePC = [&](const MCSymbol *Sym) {
1971 MCSymbol *Base = MF.getContext().createTempSymbol("pcsection_base");
1972 OutStreamer->emitLabel(Base);
1973 emitLabelDifference(Sym, Base, RelativeRelocSize);
1974 };
1975
1976 SwitchSection(Sec);
1977 if (IsFunction) {
1978 // One record: function start, function size, auxiliary data.
1979 assert(Syms.size() == 2 && "expecting function begin and end");
1980 EmitRelativePC(Syms[0]);
1981 if (ConstULEB128)
1982 emitLabelDifferenceAsULEB128(Syms[1], Syms[0]);
1983 else
1984 emitLabelDifference(Syms[1], Syms[0], 4);
1985 EmitAux();
1986 } else {
1987 // One record per instruction: PC, auxiliary data.
1988 for (const MCSymbol *Sym : Syms) {
1989 EmitRelativePC(Sym);
1990 EmitAux();
1991 }
1992 }
1993 }
1994 };
1995
1996 OutStreamer->pushSection();
1997 // Emit PCs for function start and function size.
1998 if (const MDNode *MD = F.getMetadata(LLVMContext::MD_pcsections))
1999 EmitForMD(*MD, {getFunctionBegin(), getFunctionEnd()}, true);
2000 // Emit PCs for instructions collected.
2001 for (const auto &MS : PCSectionsSymbols)
2002 EmitForMD(*MS.first, MS.second, false);
2003 OutStreamer->popSection();
2004 PCSectionsSymbols.clear();
2005}
2006
2007/// Returns true if function begin and end labels should be emitted.
2008static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm) {
2009 if (Asm.hasDebugInfo() || !MF.getLandingPads().empty() ||
2010 MF.hasEHFunclets() ||
2011 MF.getFunction().hasMetadata(LLVMContext::MD_pcsections))
2012 return true;
2013
2014 // We might emit an EH table that uses function begin and end labels even if
2015 // we don't have any landingpads.
2016 if (!MF.getFunction().hasPersonalityFn())
2017 return false;
2018 return !isNoOpWithoutInvoke(
2020}
2021
2022// Return the mnemonic of a MachineInstr if available, or the MachineInstr
2023// opcode name otherwise.
2025 const TargetInstrInfo *TII =
2026 MI.getParent()->getParent()->getSubtarget().getInstrInfo();
2027 MCInst MCI;
2028 MCI.setOpcode(MI.getOpcode());
2029 if (StringRef Name = Streamer.getMnemonic(MCI); !Name.empty())
2030 return Name;
2031 StringRef Name = TII->getName(MI.getOpcode());
2032 assert(!Name.empty() && "Missing mnemonic and name for opcode");
2033 return Name;
2034}
2035
2037 FunctionCallGraphInfo &FuncCGInfo,
2038 const MachineFunction::CallSiteInfoMap &CallSitesInfoMap,
2039 const MachineInstr &MI) {
2040 assert(MI.isCall() && "This method is meant for call instructions only.");
2041 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2042 const MachineOperand &CalleeOperand = TII->getCalleeOperand(MI);
2043 if (CalleeOperand.isGlobal() || CalleeOperand.isSymbol()) {
2044 // Handle direct calls.
2045 MCSymbol *CalleeSymbol = nullptr;
2046 switch (CalleeOperand.getType()) {
2048 CalleeSymbol = getSymbol(CalleeOperand.getGlobal());
2049 break;
2051 CalleeSymbol = GetExternalSymbolSymbol(CalleeOperand.getSymbolName());
2052 break;
2053 default:
2055 "Expected to only handle direct call instructions here.");
2056 }
2057 FuncCGInfo.DirectCallees.insert(CalleeSymbol);
2058 return; // Early exit after handling the direct call instruction.
2059 }
2060 const auto &CallSiteInfo = CallSitesInfoMap.find(&MI);
2061 if (CallSiteInfo == CallSitesInfoMap.end())
2062 return;
2063 // Handle indirect callsite info.
2064 // Only indirect calls have type identifiers set.
2065 for (ConstantInt *CalleeTypeId : CallSiteInfo->second.CalleeTypeIds) {
2066 uint64_t CalleeTypeIdVal = CalleeTypeId->getZExtValue();
2067 FuncCGInfo.IndirectCalleeTypeIDs.insert(CalleeTypeIdVal);
2068 }
2069}
2070
2071/// Helper to emit a symbol for the prefetch target associated with the given
2072/// BBID and callsite index.
2074 unsigned CallsiteIndex) {
2075 SmallString<128> FunctionName;
2076 getNameWithPrefix(FunctionName, &MF->getFunction());
2077 MCSymbol *PrefetchTargetSymbol = OutContext.getOrCreateSymbol(
2078 getPrefetchTargetSymbolName(FunctionName, BBID, CallsiteIndex));
2079 // If the function is weak-linkage it may be replaced by a strong
2080 // version, in which case the prefetch targets should also be replaced.
2081 OutStreamer->emitSymbolAttribute(
2082 PrefetchTargetSymbol,
2083 MF->getFunction().isWeakForLinker() ? MCSA_Weak : MCSA_Global);
2084 OutStreamer->emitLabel(PrefetchTargetSymbol);
2085}
2086
2087/// Emit dangling prefetch targets that were not mapped to any basic block.
2089 const DenseMap<UniqueBBID, SmallVector<unsigned>> &MFPrefetchTargets =
2090 MF->getPrefetchTargets();
2091 if (MFPrefetchTargets.empty())
2092 return;
2093 DenseSet<UniqueBBID> MFBBIDs;
2094 for (const MachineBasicBlock &MBB : *MF)
2095 if (std::optional<UniqueBBID> BBID = MBB.getBBID())
2096 MFBBIDs.insert(*BBID);
2097
2098 for (const auto &[BBID, CallsiteIndexes] : MFPrefetchTargets) {
2099 if (MFBBIDs.contains(BBID))
2100 continue;
2101 for (unsigned CallsiteIndex : CallsiteIndexes)
2103 }
2104}
2105
2106/// EmitFunctionBody - This method emits the body and trailer for a
2107/// function.
2109 emitFunctionHeader();
2110
2111 // Emit target-specific gunk before the function body.
2113
2114 if (isVerbose()) {
2115 MDT = GetMDT(*MF);
2116 // Get MachineLoopInfo or compute it on the fly if it's unavailable, which
2117 // needs a MachineDominatorTree only for an irreducible CFG.
2118 MLI = GetMLI(*MF);
2119 if (!MLI) {
2120 OwnedMLI = std::make_unique<MachineLoopInfo>();
2121 OwnedMLI->calculate(*MF, [&]() -> const MachineDominatorTree & {
2122 if (!MDT) {
2123 OwnedMDT = std::make_unique<MachineDominatorTree>();
2124 OwnedMDT->recalculate(*MF);
2125 MDT = OwnedMDT.get();
2126 }
2127 return *MDT;
2128 });
2129 MLI = OwnedMLI.get();
2130 }
2131 }
2132
2133 // Print out code for the function.
2134 bool HasAnyRealCode = false;
2135 int NumInstsInFunction = 0;
2136 // Only x86 needs this padding; the Arm unwinders back the PC up themselves.
2137 const Module *M = MMI->getModule();
2138 bool NeedsEHaNops =
2139 M->getTargetTriple().isX86() && M->getModuleFlag("eh-asynch");
2140
2141 const MCSubtargetInfo *STI = nullptr;
2142 if (this->MF)
2143 STI = &getSubtargetInfo();
2144 else
2145 STI = &TM.getMCSubtargetInfo();
2146
2147 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
2148 // Create a slot for the entry basic block section so that the section
2149 // order is preserved when iterating over MBBSectionRanges.
2150 if (!MF->empty())
2151 MBBSectionRanges[MF->front().getSectionID()] =
2153
2154 FunctionCallGraphInfo FuncCGInfo;
2155 const auto &CallSitesInfoMap = MF->getCallSitesInfo();
2156
2157 // Dangling targets are not mapped to any blocks and must be emitted at the
2158 // beginning of the function.
2160
2161 const auto &MFPrefetchTargets = MF->getPrefetchTargets();
2162 for (auto &MBB : *MF) {
2163 // Print a label for the basic block.
2165 DenseMap<StringRef, unsigned> MnemonicCounts;
2166
2167 const SmallVector<unsigned> *PrefetchTargets = nullptr;
2168 if (auto BBID = MBB.getBBID()) {
2169 auto R = MFPrefetchTargets.find(*BBID);
2170 if (R != MFPrefetchTargets.end())
2171 PrefetchTargets = &R->second;
2172 }
2173 auto PrefetchTargetIt =
2174 PrefetchTargets ? PrefetchTargets->begin() : nullptr;
2175 auto PrefetchTargetEnd = PrefetchTargets ? PrefetchTargets->end() : nullptr;
2176 unsigned LastCallsiteIndex = 0;
2177
2178 for (auto &MI : MBB) {
2179 if (PrefetchTargetIt != PrefetchTargetEnd &&
2180 *PrefetchTargetIt == LastCallsiteIndex) {
2181 emitPrefetchTargetSymbol(*MBB.getBBID(), *PrefetchTargetIt);
2182 ++PrefetchTargetIt;
2183 }
2184
2185 // Print the assembly for the instruction.
2186 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
2187 !MI.isDebugInstr()) {
2188 HasAnyRealCode = true;
2189 }
2190
2191 // If there is a pre-instruction symbol, emit a label for it here.
2192 if (MCSymbol *S = MI.getPreInstrSymbol())
2193 OutStreamer->emitLabel(S);
2194
2195 if (MDNode *MD = MI.getPCSections())
2196 emitPCSectionsLabel(*MF, *MD);
2197
2198 for (auto &Handler : Handlers)
2199 Handler->beginInstruction(&MI);
2200
2201 if (isVerbose())
2202 emitComments(MI, STI, OutStreamer->getCommentOS());
2203
2204#ifndef NDEBUG
2205 MCFragment *OldFragment = OutStreamer->getCurrentFragment();
2206 size_t OldFragSize = OldFragment->getFixedSize();
2207#endif
2208
2209 switch (MI.getOpcode()) {
2210 case TargetOpcode::CFI_INSTRUCTION:
2212 break;
2213 case TargetOpcode::LOCAL_ESCAPE:
2215 break;
2216 case TargetOpcode::ANNOTATION_LABEL:
2217 case TargetOpcode::GC_LABEL:
2218 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2219 break;
2220 case TargetOpcode::EH_LABEL:
2221 OutStreamer->AddComment("EH_LABEL");
2222 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2223 // For AsynchEH, insert a Nop if followed by a trap inst
2224 // Or the exception won't be caught.
2225 // (see MCConstantExpr::create(1,..) in WinException.cpp)
2226 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
2227 // must have being turned into an UndefValue.
2228 // Div with variable opnds won't be the first instruction in
2229 // an EH region as it must be led by at least a Load
2230 {
2231 auto MI2 = std::next(MI.getIterator());
2232 if (NeedsEHaNops && MI2 != MBB.end() &&
2233 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
2234 emitNops(1);
2235 }
2236 break;
2237 case TargetOpcode::INLINEASM:
2238 case TargetOpcode::INLINEASM_BR:
2239 emitInlineAsm(&MI);
2240 break;
2241 case TargetOpcode::DBG_VALUE:
2242 case TargetOpcode::DBG_VALUE_LIST:
2243 if (isVerbose()) {
2244 if (!emitDebugValueComment(&MI, *this))
2246 }
2247 break;
2248 case TargetOpcode::DBG_INSTR_REF:
2249 // This instruction reference will have been resolved to a machine
2250 // location, and a nearby DBG_VALUE created. We can safely ignore
2251 // the instruction reference.
2252 break;
2253 case TargetOpcode::DBG_PHI:
2254 // This instruction is only used to label a program point, it's purely
2255 // meta information.
2256 break;
2257 case TargetOpcode::DBG_LABEL:
2258 if (isVerbose()) {
2259 if (!emitDebugLabelComment(&MI, *this))
2261 }
2262 break;
2263 case TargetOpcode::IMPLICIT_DEF:
2264 if (isVerbose()) emitImplicitDef(&MI);
2265 break;
2266 case TargetOpcode::KILL:
2267 if (isVerbose()) emitKill(&MI, *this);
2268 break;
2269 case TargetOpcode::FAKE_USE:
2270 if (isVerbose())
2271 emitFakeUse(&MI, *this);
2272 break;
2273 case TargetOpcode::PSEUDO_PROBE:
2275 break;
2276 case TargetOpcode::ARITH_FENCE:
2277 if (isVerbose())
2278 OutStreamer->emitRawComment("ARITH_FENCE");
2279 break;
2280 case TargetOpcode::MEMBARRIER:
2281 OutStreamer->emitRawComment("MEMBARRIER");
2282 break;
2283 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
2284 // This instruction is only used to note jump table debug info, it's
2285 // purely meta information.
2286 break;
2287 case TargetOpcode::INIT_UNDEF:
2288 // This is only used to influence register allocation behavior, no
2289 // actual initialization is needed.
2290 break;
2291 case TargetOpcode::FREEZE:
2292 // Only a FREEZE of an undefined value is left. Whatever the register
2293 // holds is a valid frozen value.
2294 if (isVerbose())
2295 emitFreeze(&MI, *this);
2296 break;
2297 case TargetOpcode::RELOC_NONE: {
2298 // Generate a temporary label for the current PC.
2299 MCSymbol *Sym = OutContext.createTempSymbol("reloc_none");
2300 OutStreamer->emitLabel(Sym);
2301 const MCExpr *Dot = MCSymbolRefExpr::create(Sym, OutContext);
2303 OutContext.getOrCreateSymbol(MI.getOperand(0).getSymbolName()),
2304 OutContext);
2305 OutStreamer->emitRelocDirective(*Dot, "BFD_RELOC_NONE", Value, SMLoc());
2306 break;
2307 }
2308 default:
2310
2311 auto CountInstruction = [&](const MachineInstr &MI) {
2312 // Skip Meta instructions inside bundles.
2313 if (MI.isMetaInstruction())
2314 return;
2315 ++NumInstsInFunction;
2316 if (CanDoExtraAnalysis) {
2318 ++MnemonicCounts[Name];
2319 }
2320 };
2321 if (!MI.isBundle()) {
2322 CountInstruction(MI);
2323 break;
2324 }
2325 // Separately count all the instructions in a bundle.
2326 for (auto It = std::next(MI.getIterator());
2327 It != MBB.end() && It->isInsideBundle(); ++It) {
2328 CountInstruction(*It);
2329 }
2330 break;
2331 }
2332
2333#ifndef NDEBUG
2334 // Verify that the instruction size reported by InstrInfo matches the
2335 // actually emitted size. Many backends performing branch relaxation
2336 // on the MIR level rely on this for correctness.
2337 // TODO: We currently can't distinguish whether a parse error occurred
2338 // when handling INLINEASM.
2339 if (OutStreamer->isObj() && !OutContext.hadError() &&
2340 (MI.getOpcode() != TargetOpcode::INLINEASM &&
2341 MI.getOpcode() != TargetOpcode::INLINEASM_BR)) {
2342 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2344 TII->getInstSizeVerifyMode(MI);
2346 unsigned ExpectedSize = TII->getInstSizeInBytes(MI);
2347 MCFragment *NewFragment = OutStreamer->getCurrentFragment();
2348 unsigned ActualSize;
2349 if (OldFragment == NewFragment) {
2350 ActualSize = NewFragment->getFixedSize() - OldFragSize;
2351 } else {
2352 ActualSize = OldFragment->getFixedSize() - OldFragSize;
2353 const MCFragment *F = OldFragment->getNext();
2354 for (; F != NewFragment; F = F->getNext())
2355 ActualSize += F->getFixedSize();
2356 ActualSize += NewFragment->getFixedSize();
2357 }
2358 bool AllowOverEstimate =
2360 bool Valid = AllowOverEstimate ? ActualSize <= ExpectedSize
2361 : ActualSize == ExpectedSize;
2362 if (!Valid) {
2363 dbgs() << "In function: " << MF->getName() << "\n";
2364 dbgs() << "Size mismatch for: " << MI;
2365 if (MI.isBundled()) {
2366 dbgs() << "{\n";
2367 auto It = MI.getIterator(), End = MBB.instr_end();
2368 for (++It; It != End && It->isInsideBundle(); ++It)
2369 dbgs().indent(2) << *It;
2370 dbgs() << "}\n";
2371 }
2372 dbgs() << "Expected " << (AllowOverEstimate ? "maximum" : "exact")
2373 << " size: " << ExpectedSize << "\n";
2374 dbgs() << "Actual size: " << ActualSize << "\n";
2375 abort();
2376 }
2377 }
2378 }
2379#endif
2380
2381 if (MI.isCall()) {
2382 if (MF->getTarget().Options.BBAddrMap)
2384 LastCallsiteIndex++;
2385 }
2386
2387 if (TM.Options.EmitCallGraphSection && MI.isCall())
2388 handleCallsiteForCallgraph(FuncCGInfo, CallSitesInfoMap, MI);
2389
2390 // If there is a post-instruction symbol, emit a label for it here.
2391 if (MCSymbol *S = MI.getPostInstrSymbol()) {
2392 // Emit the weak symbol attribute used for the prefetch target fallback.
2393 if (M->getTargetTriple().isOSBinFormatELF()) {
2394 MCSymbolELF *ESym = static_cast<MCSymbolELF *>(S);
2395 if (ESym->getBinding() == ELF::STB_WEAK)
2396 OutStreamer->emitSymbolAttribute(S, MCSA_Weak);
2397 }
2398 OutStreamer->emitLabel(S);
2399 }
2400
2401 for (auto &Handler : Handlers)
2402 Handler->endInstruction();
2403 }
2404 // Emit the remaining prefetch targets for this block. This includes
2405 // nonexisting callsite indexes.
2406 while (PrefetchTargetIt != PrefetchTargetEnd) {
2407 emitPrefetchTargetSymbol(*MBB.getBBID(), *PrefetchTargetIt);
2408 ++PrefetchTargetIt;
2409 }
2410
2411 // We must emit temporary symbol for the end of this basic block, if either
2412 // we have BBLabels enabled or if this basic blocks marks the end of a
2413 // section.
2414 if (MF->getTarget().Options.BBAddrMap ||
2415 (MAI.hasDotTypeDotSizeDirective() && MBB.isEndSection()))
2416 OutStreamer->emitLabel(MBB.getEndSymbol());
2417
2418 if (MBB.isEndSection()) {
2419 // The size directive for the section containing the entry block is
2420 // handled separately by the function section.
2421 if (!MBB.sameSection(&MF->front())) {
2422 if (MAI.hasDotTypeDotSizeDirective()) {
2423 // Emit the size directive for the basic block section.
2424 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2425 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
2426 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
2427 OutContext);
2428 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
2429 }
2430 assert(!MBBSectionRanges.contains(MBB.getSectionID()) &&
2431 "Overwrite section range");
2432 MBBSectionRanges[MBB.getSectionID()] =
2433 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
2434 }
2435 }
2437
2438 if (CanDoExtraAnalysis) {
2439 // Skip empty blocks.
2440 if (MBB.empty())
2441 continue;
2442
2444 MBB.begin()->getDebugLoc(), &MBB);
2445
2446 // Generate instruction mix remark. First, sort counts in descending order
2447 // by count and name.
2449 for (auto &KV : MnemonicCounts)
2450 MnemonicVec.emplace_back(KV.first, KV.second);
2451
2452 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
2453 const std::pair<StringRef, unsigned> &B) {
2454 if (A.second > B.second)
2455 return true;
2456 if (A.second == B.second)
2457 return StringRef(A.first) < StringRef(B.first);
2458 return false;
2459 });
2460 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
2461 for (auto &KV : MnemonicVec) {
2462 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
2463 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
2464 }
2465 ORE->emit(R);
2466 }
2467 }
2468
2469 EmittedInsts += NumInstsInFunction;
2470 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
2471 MF->getFunction().getSubprogram(),
2472 &MF->front());
2473 R << ore::NV("NumInstructions", NumInstsInFunction)
2474 << " instructions in function";
2475 ORE->emit(R);
2476
2477 if (ORE->allowExtraAnalysis("target-features")) {
2478 const Function &F = MF->getFunction();
2479 std::string FunctionName;
2480 raw_string_ostream OS(FunctionName);
2481 F.printAsOperand(OS, /*PrintType=*/false);
2482
2484 "target-features", "EnabledFeatures", F.getSubprogram(), &MF->front());
2485 Remark << "Enabled features for " << ore::NV("Function", FunctionName)
2486 << ": ";
2487 // The processor feature table is sorted by feature name.
2488 ListSeparator LS(",");
2489 for (const auto *Feature : MF->getSubtarget().getEnabledProcessorFeatures())
2490 Remark << LS << ore::NV("Feature", Feature->key());
2491 ORE->emit(Remark);
2492 }
2493
2494 // If the function is empty and the object file uses .subsections_via_symbols,
2495 // then we need to emit *something* to the function body to prevent the
2496 // labels from collapsing together. Just emit a noop.
2497 // Similarly, don't emit empty functions on Windows either. It can lead to
2498 // duplicate entries (two functions with the same RVA) in the Guard CF Table
2499 // after linking, causing the kernel not to load the binary:
2500 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
2501 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
2502 const Triple &TT = M->getTargetTriple();
2503 if (!HasAnyRealCode && (MAI.hasSubsectionsViaSymbols() ||
2504 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2505 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
2506
2507 // Targets can opt-out of emitting the noop here by leaving the opcode
2508 // unspecified.
2509 if (Noop.getOpcode()) {
2510 OutStreamer->AddComment("avoids zero-length function");
2511 emitNops(1);
2512 }
2513 }
2514
2515 // Switch to the original section in case basic block sections was used.
2516 OutStreamer->switchSection(MF->getSection());
2517
2518 const Function &F = MF->getFunction();
2519 for (const auto &BB : F) {
2520 if (!BB.hasAddressTaken())
2521 continue;
2522 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
2523 if (Sym->isDefined())
2524 continue;
2525 OutStreamer->AddComment("Address of block that was removed by CodeGen");
2526 OutStreamer->emitLabel(Sym);
2527 }
2528
2529 // Emit target-specific gunk after the function body.
2531
2532 // Tail-pad functions that want it.
2533 if (F.hasFnAttribute("tail-pad-to-size")) {
2534 auto *FnEndSym = createTempSymbol("tail_pad_start");
2535 OutStreamer->emitLabel(FnEndSym);
2536
2537 uint64_t PadToSize = F.getFnAttributeAsParsedInteger("tail-pad-to-size");
2538 uint64_t FillValue =
2539 PadToSize ? F.getFnAttributeAsParsedInteger("tail-pad-value") : 0;
2540
2541 // .fill ((PadToSize - FuncSize) & (PadToSize - FuncSize >= 0)) FillValue
2542 const MCExpr *FuncSize = MCBinaryExpr::createSub(
2545 const MCExpr *SizeConst = MCConstantExpr::create(PadToSize, OutContext);
2547 const MCExpr *SubExpr =
2548 MCBinaryExpr::createSub(SizeConst, FuncSize, OutContext);
2549 const MCExpr *Cmp = MCBinaryExpr::createGTE(SubExpr, Zero, OutContext);
2550 const MCExpr *FillExpr = MCBinaryExpr::createAnd(SubExpr, Cmp, OutContext);
2551 OutStreamer->emitFill(*FillExpr, FillValue);
2552 }
2553
2554 // Even though wasm supports .type and .size in general, function symbols
2555 // are automatically sized.
2556 bool EmitFunctionSize = MAI.hasDotTypeDotSizeDirective() && !TT.isWasm();
2557
2558 // SPIR-V supports label instructions only inside a block, not after the
2559 // function body.
2560 if (TT.getObjectFormat() != Triple::SPIRV &&
2561 (EmitFunctionSize || needFuncLabels(*MF, *this) || CurrentFnEnd)) {
2562 // Create a symbol for the end of function, if not already pre-created
2563 // (e.g. for .prefalign directive).
2564 if (!CurrentFnEnd)
2565 CurrentFnEnd = createTempSymbol("func_end");
2566 OutStreamer->emitLabel(CurrentFnEnd);
2567 }
2568
2569 // If the target wants a .size directive for the size of the function, emit
2570 // it.
2571 if (EmitFunctionSize) {
2572 // We can get the size as difference between the function label and the
2573 // temp label.
2574 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2575 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
2577 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
2579 OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
2580 }
2581
2582 // Call endBasicBlockSection on the last block now, if it wasn't already
2583 // called.
2584 if (!MF->back().isEndSection()) {
2585 for (auto &Handler : Handlers)
2586 Handler->endBasicBlockSection(MF->back());
2587 for (auto &Handler : EHHandlers)
2588 Handler->endBasicBlockSection(MF->back());
2589 }
2590 for (auto &Handler : Handlers)
2591 Handler->markFunctionEnd();
2592 for (auto &Handler : EHHandlers)
2593 Handler->markFunctionEnd();
2594 // Update the end label of the entry block's section.
2595 MBBSectionRanges[MF->front().getSectionID()].EndLabel = CurrentFnEnd;
2596
2597 // Print out jump tables referenced by the function.
2599
2600 // Emit post-function debug and/or EH information.
2601 for (auto &Handler : Handlers)
2602 Handler->endFunction(MF);
2603 for (auto &Handler : EHHandlers)
2604 Handler->endFunction(MF);
2605
2606 // Emit section containing BB address offsets and their metadata, when
2607 // BB labels are requested for this function. Skip empty functions.
2608 if (HasAnyRealCode) {
2609 if (MF->getTarget().Options.BBAddrMap)
2611 else if (!PgoAnalysisMapFeatures.empty())
2612 MF->getContext().reportWarning(
2613 SMLoc(), "pgo-analysis-map is enabled for function " + MF->getName() +
2614 " but it does not have labels");
2615 }
2616
2617 // Emit sections containing instruction and function PCs.
2619
2620 // Emit section containing stack size metadata.
2622
2623 // Emit section containing call graph metadata.
2624 emitCallGraphSection(*MF, FuncCGInfo);
2625
2626 // Emit .su file containing function stack size information.
2628
2630
2631 if (isVerbose())
2632 OutStreamer->getCommentOS() << "-- End function\n";
2633
2634 OutStreamer->addBlankLine();
2635}
2636
2637/// Compute the number of Global Variables that uses a Constant.
2638static unsigned getNumGlobalVariableUses(const Constant *C,
2639 bool &HasNonGlobalUsers) {
2640 if (!C) {
2641 HasNonGlobalUsers = true;
2642 return 0;
2643 }
2644
2646 return 1;
2647
2648 unsigned NumUses = 0;
2649 for (const auto *CU : C->users())
2650 NumUses +=
2651 getNumGlobalVariableUses(dyn_cast<Constant>(CU), HasNonGlobalUsers);
2652
2653 return NumUses;
2654}
2655
2656/// Only consider global GOT equivalents if at least one user is a
2657/// cstexpr inside an initializer of another global variables. Also, don't
2658/// handle cstexpr inside instructions. During global variable emission,
2659/// candidates are skipped and are emitted later in case at least one cstexpr
2660/// isn't replaced by a PC relative GOT entry access.
2662 unsigned &NumGOTEquivUsers,
2663 bool &HasNonGlobalUsers) {
2664 // Global GOT equivalents are unnamed private globals with a constant
2665 // pointer initializer to another global symbol. They must point to a
2666 // GlobalVariable or Function, i.e., as GlobalValue.
2667 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2668 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2670 return false;
2671
2672 // To be a got equivalent, at least one of its users need to be a constant
2673 // expression used by another global variable.
2674 for (const auto *U : GV->users())
2675 NumGOTEquivUsers +=
2676 getNumGlobalVariableUses(dyn_cast<Constant>(U), HasNonGlobalUsers);
2677
2678 return NumGOTEquivUsers > 0;
2679}
2680
2681/// Unnamed constant global variables solely contaning a pointer to
2682/// another globals variable is equivalent to a GOT table entry; it contains the
2683/// the address of another symbol. Optimize it and replace accesses to these
2684/// "GOT equivalents" by using the GOT entry for the final global instead.
2685/// Compute GOT equivalent candidates among all global variables to avoid
2686/// emitting them if possible later on, after it use is replaced by a GOT entry
2687/// access.
2689 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2690 return;
2691
2692 for (const auto &G : M.globals()) {
2693 unsigned NumGOTEquivUsers = 0;
2694 bool HasNonGlobalUsers = false;
2695 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers, HasNonGlobalUsers))
2696 continue;
2697 // If non-global variables use it, we still need to emit it.
2698 // Add 1 here, then emit it in `emitGlobalGOTEquivs`.
2699 if (HasNonGlobalUsers)
2700 NumGOTEquivUsers += 1;
2701 const MCSymbol *GOTEquivSym = getSymbol(&G);
2702 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
2703 }
2704}
2705
2706/// Constant expressions using GOT equivalent globals may not be eligible
2707/// for PC relative GOT entry conversion, in such cases we need to emit such
2708/// globals we previously omitted in EmitGlobalVariable.
2710 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2711 return;
2712
2714 for (auto &I : GlobalGOTEquivs) {
2715 const GlobalVariable *GV = I.second.first;
2716 unsigned Cnt = I.second.second;
2717 if (Cnt)
2718 FailedCandidates.push_back(GV);
2719 }
2720 GlobalGOTEquivs.clear();
2721
2722 for (const auto *GV : FailedCandidates)
2724}
2725
2727 MCSymbol *Name = getSymbol(&GA);
2728 const GlobalObject *BaseObject = GA.getAliaseeObject();
2729
2730 bool IsFunction = GA.getValueType()->isFunctionTy();
2731 // Treat bitcasts of functions as functions also. This is important at least
2732 // on WebAssembly where object and function addresses can't alias each other.
2733 if (!IsFunction)
2734 IsFunction = isa_and_nonnull<Function>(BaseObject);
2735
2736 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2737 // so AIX has to use the extra-label-at-definition strategy. At this
2738 // point, all the extra label is emitted, we just have to emit linkage for
2739 // those labels.
2740 if (M.getTargetTriple().isOSBinFormatXCOFF()) {
2741 // Linkage for alias of global variable has been emitted.
2742 if (isa_and_nonnull<GlobalVariable>(BaseObject))
2743 return;
2744
2745 emitLinkage(&GA, Name);
2746 // If it's a function, also emit linkage for aliases of function entry
2747 // point.
2748 if (IsFunction)
2749 emitLinkage(&GA,
2750 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
2751 return;
2752 }
2753
2754 if (GA.hasExternalLinkage() || !MAI.getWeakRefDirective())
2755 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
2756 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2757 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
2758 else
2759 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2760
2761 // Set the symbol type to function if the alias has a function type.
2762 // This affects codegen when the aliasee is not a function.
2763 if (IsFunction) {
2764 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
2765 if (M.getTargetTriple().isOSBinFormatCOFF()) {
2766 OutStreamer->beginCOFFSymbolDef(Name);
2767 OutStreamer->emitCOFFSymbolStorageClass(
2772 OutStreamer->endCOFFSymbolDef();
2773 }
2774 }
2775
2776 emitVisibility(Name, GA.getVisibility());
2777
2778 const MCExpr *Expr = lowerConstant(GA.getAliasee());
2779
2780 if (MAI.isMachO() && isa<MCBinaryExpr>(Expr))
2781 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
2782
2783 // Emit the directives as assignments aka .set:
2784 OutStreamer->emitAssignment(Name, Expr);
2785 MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
2786 if (LocalAlias != Name)
2787 OutStreamer->emitAssignment(LocalAlias, Expr);
2788
2789 // If the aliasee does not correspond to a symbol in the output, i.e. the
2790 // alias is not of an object or the aliased object is private, then set the
2791 // size of the alias symbol from the type of the alias. We don't do this in
2792 // other situations as the alias and aliasee having differing types but same
2793 // size may be intentional.
2794 if (MAI.hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
2795 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2796 const DataLayout &DL = M.getDataLayout();
2797 uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
2798 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
2799 }
2800}
2801
2802void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2803 auto EmitLinkage = [&](MCSymbol *Sym) {
2805 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
2806 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2807 OutStreamer->emitSymbolAttribute(Sym, MCSA_WeakReference);
2808 else
2809 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2810 };
2811
2812 if (M.getTargetTriple().isOSBinFormatELF()) {
2813 MCSymbol *Name = getSymbol(&GI);
2814 EmitLinkage(Name);
2815 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
2816 emitVisibility(Name, GI.getVisibility());
2817
2818 // Emit the directives as assignments aka .set:
2819 const MCExpr *Expr = lowerConstant(GI.getResolver());
2820 OutStreamer->emitAssignment(Name, Expr);
2821 MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
2822 if (LocalAlias != Name)
2823 OutStreamer->emitAssignment(LocalAlias, Expr);
2824
2825 return;
2826 }
2827
2828 if (!M.getTargetTriple().isOSBinFormatMachO() || !getIFuncMCSubtargetInfo())
2829 reportFatalUsageError("IFuncs are not supported on this platform");
2830
2831 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2832 // implements the symbol resolution duties of the IFunc.
2833 //
2834 // Normally, this would be handled by linker magic, but unfortunately there
2835 // are a few limitations in ld64 and ld-prime's implementation of
2836 // .symbol_resolver that mean we can't always use them:
2837 //
2838 // * resolvers cannot be the target of an alias
2839 // * resolvers cannot have private linkage
2840 // * resolvers cannot have linkonce linkage
2841 // * resolvers cannot appear in executables
2842 // * resolvers cannot appear in bundles
2843 //
2844 // This works around that by emitting a close approximation of what the
2845 // linker would have done.
2846
2847 MCSymbol *LazyPointer =
2848 GetExternalSymbolSymbol(GI.getName() + ".lazy_pointer");
2849 MCSymbol *StubHelper = GetExternalSymbolSymbol(GI.getName() + ".stub_helper");
2850
2851 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
2852
2853 const DataLayout &DL = M.getDataLayout();
2854 emitAlignment(Align(DL.getPointerSize()));
2855 OutStreamer->emitLabel(LazyPointer);
2856 emitVisibility(LazyPointer, GI.getVisibility());
2857 OutStreamer->emitValue(MCSymbolRefExpr::create(StubHelper, OutContext), 8);
2858
2859 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getTextSection());
2860
2861 const TargetSubtargetInfo *STI =
2862 TM.getSubtargetImpl(*GI.getResolverFunction());
2863 const TargetLowering *TLI = STI->getTargetLowering();
2864 Align TextAlign(TLI->getMinFunctionAlignment());
2865
2866 MCSymbol *Stub = getSymbol(&GI);
2867 EmitLinkage(Stub);
2868 OutStreamer->emitCodeAlignment(TextAlign, *getIFuncMCSubtargetInfo());
2869 OutStreamer->emitLabel(Stub);
2870 emitVisibility(Stub, GI.getVisibility());
2871 emitMachOIFuncStubBody(M, GI, LazyPointer);
2872
2873 OutStreamer->emitCodeAlignment(TextAlign, *getIFuncMCSubtargetInfo());
2874 OutStreamer->emitLabel(StubHelper);
2875 emitVisibility(StubHelper, GI.getVisibility());
2876 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2877}
2878
2880 if (!RS.wantsSection())
2881 return;
2882 if (!RS.getFilename())
2883 return;
2884
2885 MCSection *RemarksSection =
2886 OutContext.getObjectFileInfo()->getRemarksSection();
2887 if (!RemarksSection && RS.needsSection()) {
2888 OutContext.reportWarning(SMLoc(), "Current object file format does not "
2889 "support remarks sections.");
2890 }
2891 if (!RemarksSection)
2892 return;
2893
2894 SmallString<128> Filename = *RS.getFilename();
2895 assert(!Filename.empty() && "The filename can't be empty.");
2897 "The remarks filename must be absolute.");
2898
2899 std::string Buf;
2900 raw_string_ostream OS(Buf);
2901
2902 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2903 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2904 RemarkSerializer.metaSerializer(OS, Filename);
2905 MetaSerializer->emit();
2906
2907 // Switch to the remarks section.
2908 OutStreamer->switchSection(RemarksSection);
2909 OutStreamer->emitBinaryData(Buf);
2910}
2911
2913 const Constant *Initializer = G.getInitializer();
2914 return G.getDataLayout().getTypeAllocSize(Initializer->getType());
2915}
2916
2918 // We used to do this in clang, but there are optimization passes that turn
2919 // non-constant globals into constants. So now, clang only tells us whether
2920 // it would *like* a global to be tagged, but we still make the decision here.
2921 //
2922 // For now, don't instrument constant data, as it'll be in .rodata anyway. It
2923 // may be worth instrumenting these in future to stop them from being used as
2924 // gadgets.
2925 if (G.getName().starts_with("llvm.") || G.isThreadLocal() || G.isConstant())
2926 return false;
2927
2928 // Globals can be placed implicitly or explicitly in sections. There's two
2929 // different types of globals that meet this criteria that cause problems:
2930 // 1. Function pointers that are going into various init arrays (either
2931 // explicitly through `__attribute__((section(<foo>)))` or implicitly
2932 // through `__attribute__((constructor)))`, such as ".(pre)init(_array)",
2933 // ".fini(_array)", ".ctors", and ".dtors". These function pointers end up
2934 // overaligned and overpadded, making iterating over them problematic, and
2935 // each function pointer is individually tagged (so the iteration over
2936 // them causes SIGSEGV/MTE[AS]ERR).
2937 // 2. Global variables put into an explicit section, where the section's name
2938 // is a valid C-style identifier. The linker emits a `__start_<name>` and
2939 // `__stop_<name>` symbol for the section, so that you can iterate over
2940 // globals within this section. Unfortunately, again, these globals would
2941 // be tagged and so iteration causes SIGSEGV/MTE[AS]ERR.
2942 //
2943 // To mitigate both these cases, and because specifying a section is rare
2944 // outside of these two cases, disable MTE protection for globals in any
2945 // section.
2946 if (G.hasSection())
2947 return false;
2948
2949 return globalSize(G) > 0;
2950}
2951
2953 uint64_t SizeInBytes = globalSize(*G);
2954
2955 uint64_t NewSize = alignTo(SizeInBytes, 16);
2956 if (SizeInBytes != NewSize) {
2957 // Pad the initializer out to the next multiple of 16 bytes.
2958 llvm::SmallVector<uint8_t> Init(NewSize - SizeInBytes, 0);
2959 Constant *Padding = ConstantDataArray::get(M.getContext(), Init);
2960 Constant *Initializer = G->getInitializer();
2961 Initializer = ConstantStruct::getAnon({Initializer, Padding});
2962 auto *NewGV = new GlobalVariable(
2963 M, Initializer->getType(), G->isConstant(), G->getLinkage(),
2964 Initializer, "", G, G->getThreadLocalMode(), G->getAddressSpace());
2965 NewGV->copyAttributesFrom(G);
2966 NewGV->setComdat(G->getComdat());
2967 NewGV->copyMetadata(G, 0);
2968
2969 NewGV->takeName(G);
2970 G->replaceAllUsesWith(NewGV);
2971 G->eraseFromParent();
2972 G = NewGV;
2973 }
2974
2975 if (G->getAlign().valueOrOne() < 16)
2976 G->setAlignment(Align(16));
2977
2978 // Ensure that tagged globals don't get merged by ICF - as they should have
2979 // different tags at runtime.
2980 G->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2981}
2982
2984 auto Meta = G.getSanitizerMetadata();
2985 Meta.Memtag = false;
2986 G.setSanitizerMetadata(Meta);
2987}
2988
2990 // Set the MachineFunction to nullptr so that we can catch attempted
2991 // accesses to MF specific features at the module level and so that
2992 // we can conditionalize accesses based on whether or not it is nullptr.
2993 MF = nullptr;
2994 const Triple &Target = M.getTargetTriple();
2995
2996 std::vector<GlobalVariable *> GlobalsToTag;
2997 for (GlobalVariable &G : M.globals()) {
2998 if (G.isDeclaration() || !G.isTagged())
2999 continue;
3000 if (!shouldTagGlobal(G)) {
3001 assert(G.hasSanitizerMetadata()); // because isTagged.
3003 assert(!G.isTagged());
3004 continue;
3005 }
3006 GlobalsToTag.push_back(&G);
3007 }
3008 for (GlobalVariable *G : GlobalsToTag)
3010
3011 // Gather all GOT equivalent globals in the module. We really need two
3012 // passes over the globals: one to compute and another to avoid its emission
3013 // in EmitGlobalVariable, otherwise we would not be able to handle cases
3014 // where the got equivalent shows up before its use.
3016
3017 // Emit global variables.
3018 for (const auto &G : M.globals())
3020
3021 // Emit remaining GOT equivalent globals.
3023
3025
3026 // Emit linkage(XCOFF) and visibility info for declarations
3027 for (const Function &F : M) {
3028 if (!F.isDeclarationForLinker())
3029 continue;
3030
3031 MCSymbol *Name = getSymbol(&F);
3032 // Function getSymbol gives us the function descriptor symbol for XCOFF.
3033
3034 if (!Target.isOSBinFormatXCOFF()) {
3035 GlobalValue::VisibilityTypes V = F.getVisibility();
3037 continue;
3038
3039 emitVisibility(Name, V, false);
3040 continue;
3041 }
3042
3043 if (F.isIntrinsic())
3044 continue;
3045
3046 // Handle the XCOFF case.
3047 // Variable `Name` is the function descriptor symbol (see above). Get the
3048 // function entry point symbol.
3049 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
3050 // Emit linkage for the function entry point.
3051 emitLinkage(&F, FnEntryPointSym);
3052
3053 // If a function's address is taken, which means it may be called via a
3054 // function pointer, we need the function descriptor for it.
3055 if (F.hasAddressTaken())
3056 emitLinkage(&F, Name);
3057 }
3058
3059 // Emit the remarks section contents.
3060 // FIXME: Figure out when is the safest time to emit this section. It should
3061 // not come after debug info.
3062 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
3063 emitRemarksSection(*RS);
3064
3066
3067 // Emit raw section data from llvm.raw.sections metadata. Each operand is
3068 // a tuple of {section_name, alignment, flags, data}.
3069 if (const NamedMDNode *RawSections =
3070 M.getNamedMetadata("llvm.raw.sections")) {
3071 for (const MDNode *Op : RawSections->operands()) {
3072 auto *SectionName = cast<MDString>(Op->getOperand(0));
3073 auto *AlignCI = mdconst::extract<ConstantInt>(Op->getOperand(1));
3074 auto *Data = cast<MDString>(Op->getOperand(3));
3075
3076 MCSection *Section = TLOF.getNamedSection(SectionName->getString(),
3078 if (!Section) {
3079 M.getContext().emitError("llvm.raw.sections entry '" +
3080 SectionName->getString() +
3081 "' is not supported on this target");
3082 continue;
3083 }
3084 OutStreamer->pushSection();
3085 OutStreamer->switchSection(Section);
3086 OutStreamer->emitValueToAlignment(Align(AlignCI->getZExtValue()));
3087 OutStreamer->emitBytes(Data->getString());
3088 OutStreamer->popSection();
3089 }
3090 }
3091
3092 if (Target.isOSBinFormatELF()) {
3093 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
3094
3095 // Output stubs for external and common global variables.
3097 if (!Stubs.empty()) {
3098 OutStreamer->switchSection(TLOF.getDataSection());
3099 const DataLayout &DL = M.getDataLayout();
3100
3101 emitAlignment(Align(DL.getPointerSize()));
3102 for (const auto &Stub : Stubs) {
3103 OutStreamer->emitLabel(Stub.first);
3104 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
3105 DL.getPointerSize());
3106 }
3107 }
3108 }
3109
3110 if (Target.isOSBinFormatCOFF()) {
3111 MachineModuleInfoCOFF &MMICOFF =
3112 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
3113
3114 // Output stubs for external and common global variables.
3116 if (!Stubs.empty()) {
3117 const DataLayout &DL = M.getDataLayout();
3118
3119 for (const auto &Stub : Stubs) {
3121 SectionName += Stub.first->getName();
3122 OutStreamer->switchSection(OutContext.getCOFFSection(
3126 Stub.first->getName(), COFF::IMAGE_COMDAT_SELECT_ANY));
3127 emitAlignment(Align(DL.getPointerSize()));
3128 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
3129 OutStreamer->emitLabel(Stub.first);
3130 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
3131 DL.getPointerSize());
3132 }
3133 }
3134 }
3135
3136 // This needs to happen before emitting debug information since that can end
3137 // arbitrary sections.
3138 if (auto *TS = OutStreamer->getTargetStreamer())
3139 TS->emitConstantPools();
3140
3141 // Emit Stack maps before any debug info. Mach-O requires that no data or
3142 // text sections come after debug info has been emitted. This matters for
3143 // stack maps as they are arbitrary data, and may even have a custom format
3144 // through user plugins.
3145 EmitStackMaps(M);
3146
3147 // Print aliases in topological order, that is, for each alias a = b,
3148 // b must be printed before a.
3149 // This is because on some targets (e.g. PowerPC) linker expects aliases in
3150 // such an order to generate correct TOC information.
3153 for (const auto &Alias : M.aliases()) {
3154 if (Alias.hasAvailableExternallyLinkage())
3155 continue;
3156 for (const GlobalAlias *Cur = &Alias; Cur;
3157 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
3158 if (!AliasVisited.insert(Cur).second)
3159 break;
3160 AliasStack.push_back(Cur);
3161 }
3162 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
3163 emitGlobalAlias(M, *AncestorAlias);
3164 AliasStack.clear();
3165 }
3166
3167 // IFuncs must come before deubginfo in case the backend decides to emit them
3168 // as actual functions, since on Mach-O targets, we cannot create regular
3169 // sections after DWARF.
3170 for (const auto &IFunc : M.ifuncs())
3171 emitGlobalIFunc(M, IFunc);
3172 if (M.getTargetTriple().isOSBinFormatXCOFF() && hasDebugInfo()) {
3173 // Emit section end. This is used to tell the debug line section where the
3174 // end is for a text section if we don't use .loc to represent the debug
3175 // line.
3176 auto *Sec = OutContext.getObjectFileInfo()->getTextSection();
3177 OutStreamer->switchSectionNoPrint(Sec);
3178 MCSymbol *Sym = Sec->getEndSymbol(OutContext);
3179 OutStreamer->emitLabel(Sym);
3180 }
3181
3182 // Finalize debug and EH information.
3183 for (auto &Handler : Handlers)
3184 Handler->endModule();
3185 for (auto &Handler : EHHandlers)
3186 Handler->endModule();
3187
3188 // This deletes all the ephemeral handlers that AsmPrinter added, while
3189 // keeping all the user-added handlers alive until the AsmPrinter is
3190 // destroyed.
3191 EHHandlers.clear();
3192 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
3193 DD = nullptr;
3194
3195 // If the target wants to know about weak references, print them all.
3196 if (MAI.getWeakRefDirective()) {
3197 // FIXME: This is not lazy, it would be nice to only print weak references
3198 // to stuff that is actually used. Note that doing so would require targets
3199 // to notice uses in operands (due to constant exprs etc). This should
3200 // happen with the MC stuff eventually.
3201
3202 // Print out module-level global objects here.
3203 for (const auto &GO : M.global_objects()) {
3204 if (!GO.hasExternalWeakLinkage())
3205 continue;
3206 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
3207 }
3209 auto SymbolName = "swift_async_extendedFramePointerFlags";
3210 auto Global = M.getGlobalVariable(SymbolName);
3211 if (!Global) {
3212 auto PtrTy = PointerType::getUnqual(M.getContext());
3213 Global = new GlobalVariable(M, PtrTy, false,
3215 SymbolName);
3216 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
3217 }
3218 }
3219 }
3220
3222
3223 // Emit llvm.ident metadata in an '.ident' directive.
3224 emitModuleIdents(M);
3225
3226 // Emit bytes for llvm.commandline metadata.
3227 // The command line metadata is emitted earlier on XCOFF.
3228 if (!Target.isOSBinFormatXCOFF())
3229 emitModuleCommandLines(M);
3230
3231 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
3232 // split-stack is used.
3233 if (M.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
3234 OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
3235 ELF::SHT_PROGBITS, 0));
3236 if (HasNoSplitStack)
3237 OutStreamer->switchSection(OutContext.getELFSection(
3238 ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
3239 }
3240
3241 // If we don't have any trampolines, then we don't require stack memory
3242 // to be executable. Some targets have a directive to declare this.
3243 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
3244 bool HasTrampolineUses =
3245 InitTrampolineIntrinsic && !InitTrampolineIntrinsic->use_empty();
3246 MCSection *S = MAI.getStackSection(OutContext, /*Exec=*/HasTrampolineUses);
3247 if (S)
3248 OutStreamer->switchSection(S);
3249
3250 if (TM.Options.EmitAddrsig && MAI.hasAddrsigDirective()) {
3251 // Emit address-significance attributes for all globals.
3252 OutStreamer->emitAddrsig();
3253 for (const GlobalValue &GV : M.global_values()) {
3254 if (!GV.use_empty() && !GV.isThreadLocal() &&
3255 !GV.hasDLLImportStorageClass() &&
3256 !GV.getName().starts_with("llvm.") &&
3257 !GV.hasAtLeastLocalUnnamedAddr())
3258 OutStreamer->emitAddrsigSym(getSymbol(&GV));
3259 }
3260 }
3261
3262 // Emit symbol partition specifications (ELF only).
3263 if (Target.isOSBinFormatELF()) {
3264 unsigned UniqueID = 0;
3265 for (const GlobalValue &GV : M.global_values()) {
3266 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
3267 GV.getVisibility() != GlobalValue::DefaultVisibility)
3268 continue;
3269
3270 OutStreamer->switchSection(
3271 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
3272 "", false, ++UniqueID, nullptr));
3273 OutStreamer->emitBytes(GV.getPartition());
3274 OutStreamer->emitZeros(1);
3275 OutStreamer->emitValue(
3277 MAI.getCodePointerSize());
3278 }
3279 }
3280
3281 // Allow the target to emit any magic that it wants at the end of the file,
3282 // after everything else has gone out.
3284
3285 MMI = nullptr;
3286 AddrLabelSymbols = nullptr;
3287
3288 OutStreamer->finish();
3289 OutStreamer->reset();
3290 OwnedMLI.reset();
3291 OwnedMDT.reset();
3292
3293 return false;
3294}
3295
3297 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionID());
3298 if (Res.second)
3299 Res.first->second = createTempSymbol("exception");
3300 return Res.first->second;
3301}
3302
3304 MCContext &Ctx = MF->getContext();
3305 MCSymbol *Sym = Ctx.createTempSymbol("BB" + Twine(MF->getFunctionNumber()) +
3306 "_" + Twine(MBB.getNumber()) + "_CS");
3307 CurrentFnCallsiteEndSymbols[&MBB].push_back(Sym);
3308 return Sym;
3309}
3310
3312 this->MF = &MF;
3313 const Function &F = MF.getFunction();
3314
3315 // Record that there are split-stack functions, so we will emit a special
3316 // section to tell the linker.
3317 if (MF.shouldSplitStack()) {
3318 HasSplitStack = true;
3319
3320 if (!MF.getFrameInfo().needsSplitStackProlog())
3321 HasNoSplitStack = true;
3322 } else
3323 HasNoSplitStack = true;
3324
3325 // Get the function symbol.
3326 if (!MAI.isAIX()) {
3327 CurrentFnSym = getSymbol(&MF.getFunction());
3328 } else {
3329 assert(TM.getTargetTriple().isOSAIX() &&
3330 "Only AIX uses the function descriptor hooks.");
3331 // AIX is unique here in that the name of the symbol emitted for the
3332 // function body does not have the same name as the source function's
3333 // C-linkage name.
3334 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
3335 " initalized first.");
3336
3337 // Get the function entry point symbol.
3339 }
3340
3342 CurrentFnBegin = nullptr;
3343 CurrentFnBeginLocal = nullptr;
3344 CurrentFnEnd = nullptr;
3345 CurrentSectionBeginSym = nullptr;
3347 MBBSectionRanges.clear();
3348 MBBSectionExceptionSyms.clear();
3349 bool NeedsLocalForSize = MAI.needsLocalForSize();
3350 if (F.hasFnAttribute("patchable-function-entry") ||
3351 F.hasFnAttribute("tail-pad-to-size") ||
3352 F.hasFnAttribute("function-instrument") ||
3353 F.hasFnAttribute("xray-instruction-threshold") ||
3354 needFuncLabels(MF, *this) || NeedsLocalForSize ||
3355 MF.getTarget().Options.EmitStackSizeSection ||
3356 MF.getTarget().Options.EmitCallGraphSection ||
3357 MF.getTarget().Options.BBAddrMap) {
3358 CurrentFnBegin = createTempSymbol("func_begin");
3359 if (NeedsLocalForSize)
3361 }
3362
3363 ORE = GetORE(MF);
3364}
3365
3366namespace {
3367
3368// Keep track the alignment, constpool entries per Section.
3369 struct SectionCPs {
3370 MCSection *S;
3371 Align Alignment;
3373
3374 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
3375 };
3376
3377} // end anonymous namespace
3378
3380 if (TM.Options.EnableStaticDataPartitioning && C && SDPI && PSI)
3381 return SDPI->getConstantSectionPrefix(C, PSI);
3382
3383 return "";
3384}
3385
3386/// EmitConstantPool - Print to the current output stream assembly
3387/// representations of the constants in the constant pool MCP. This is
3388/// used to print out constants which have been "spilled to memory" by
3389/// the code generator.
3391 const MachineConstantPool *MCP = MF->getConstantPool();
3392 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
3393 if (CP.empty()) return;
3394
3395 // Calculate sections for constant pool entries. We collect entries to go into
3396 // the same section together to reduce amount of section switch statements.
3397 SmallVector<SectionCPs, 4> CPSections;
3398 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
3399 const MachineConstantPoolEntry &CPE = CP[i];
3400 Align Alignment = CPE.getAlign();
3401
3403
3404 const Constant *C = nullptr;
3405 if (!CPE.isMachineConstantPoolEntry())
3406 C = CPE.Val.ConstVal;
3407
3409 getDataLayout(), Kind, C, Alignment, &MF->getFunction(),
3411
3412 // The number of sections are small, just do a linear search from the
3413 // last section to the first.
3414 bool Found = false;
3415 unsigned SecIdx = CPSections.size();
3416 while (SecIdx != 0) {
3417 if (CPSections[--SecIdx].S == S) {
3418 Found = true;
3419 break;
3420 }
3421 }
3422 if (!Found) {
3423 SecIdx = CPSections.size();
3424 CPSections.push_back(SectionCPs(S, Alignment));
3425 }
3426
3427 if (Alignment > CPSections[SecIdx].Alignment)
3428 CPSections[SecIdx].Alignment = Alignment;
3429 CPSections[SecIdx].CPEs.push_back(i);
3430 }
3431
3432 // Now print stuff into the calculated sections.
3433 const MCSection *CurSection = nullptr;
3434 unsigned Offset = 0;
3435 for (const SectionCPs &CPSection : CPSections) {
3436 for (unsigned CPI : CPSection.CPEs) {
3437 MCSymbol *Sym = GetCPISymbol(CPI);
3438 if (!Sym->isUndefined())
3439 continue;
3440
3441 if (CurSection != CPSection.S) {
3442 OutStreamer->switchSection(CPSection.S);
3443 emitAlignment(Align(CPSection.Alignment));
3444 CurSection = CPSection.S;
3445 Offset = 0;
3446 }
3447
3448 MachineConstantPoolEntry CPE = CP[CPI];
3449
3450 // Emit inter-object padding for alignment.
3451 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
3452 OutStreamer->emitZeros(NewOffset - Offset);
3453
3454 if (MAI.hasDotTypeDotSizeDirective())
3455 OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeObject);
3456 OutStreamer->emitLabel(Sym);
3457
3460 else
3462
3463 unsigned EntrySize = CPE.getSizeInBytes(getDataLayout());
3464 if (MAI.hasDotTypeDotSizeDirective())
3465 OutStreamer->emitELFSize(Sym,
3467
3468 Offset = NewOffset + EntrySize;
3469 }
3470 }
3471}
3472
3473// Print assembly representations of the jump tables used by the current
3474// function.
3476 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
3477 if (!MJTI) return;
3478
3479 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
3480 if (JT.empty()) return;
3481
3482 if (!TM.Options.EnableStaticDataPartitioning) {
3483 emitJumpTableImpl(*MJTI, llvm::to_vector(llvm::seq<unsigned>(JT.size())));
3484 return;
3485 }
3486
3487 SmallVector<unsigned> HotJumpTableIndices, ColdJumpTableIndices;
3488 // When static data partitioning is enabled, collect jump table entries that
3489 // go into the same section together to reduce the amount of section switch
3490 // statements.
3491 for (unsigned JTI = 0, JTSize = JT.size(); JTI < JTSize; ++JTI) {
3492 if (JT[JTI].Hotness == MachineFunctionDataHotness::Cold) {
3493 ColdJumpTableIndices.push_back(JTI);
3494 } else {
3495 HotJumpTableIndices.push_back(JTI);
3496 }
3497 }
3498
3499 emitJumpTableImpl(*MJTI, HotJumpTableIndices);
3500 emitJumpTableImpl(*MJTI, ColdJumpTableIndices);
3501}
3502
3503void AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
3504 ArrayRef<unsigned> JumpTableIndices) {
3506 JumpTableIndices.empty())
3507 return;
3508
3510 const Function &F = MF->getFunction();
3511 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3512 MCSection *JumpTableSection = nullptr;
3513
3514 const bool UseLabelDifference =
3517 // Pick the directive to use to print the jump table entries, and switch to
3518 // the appropriate section.
3519 const bool JTInDiffSection =
3520 !TLOF.shouldPutJumpTableInFunctionSection(UseLabelDifference, F);
3521 if (JTInDiffSection) {
3523 JumpTableSection =
3524 TLOF.getSectionForJumpTable(F, TM, &JT[JumpTableIndices.front()]);
3525 } else {
3526 JumpTableSection = TLOF.getSectionForJumpTable(F, TM);
3527 }
3528 OutStreamer->switchSection(JumpTableSection);
3529 }
3530
3531 const DataLayout &DL = MF->getDataLayout();
3533
3534 // Jump tables in code sections are marked with a data_region directive
3535 // where that's supported.
3536 if (!JTInDiffSection)
3537 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
3538
3539 for (const unsigned JumpTableIndex : JumpTableIndices) {
3540 ArrayRef<MachineBasicBlock *> JTBBs = JT[JumpTableIndex].MBBs;
3541
3542 // If this jump table was deleted, ignore it.
3543 if (JTBBs.empty())
3544 continue;
3545
3546 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
3547 /// emit a .set directive for each unique entry.
3549 MAI.doesSetDirectiveSuppressReloc()) {
3550 SmallPtrSet<const MachineBasicBlock *, 16> EmittedSets;
3551 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3552 const MCExpr *Base =
3553 TLI->getPICJumpTableRelocBaseExpr(MF, JumpTableIndex, OutContext);
3554 for (const MachineBasicBlock *MBB : JTBBs) {
3555 if (!EmittedSets.insert(MBB).second)
3556 continue;
3557
3558 // .set LJTSet, LBB32-base
3559 const MCExpr *LHS =
3561 OutStreamer->emitAssignment(
3562 GetJTSetSymbol(JumpTableIndex, MBB->getNumber()),
3564 }
3565 }
3566
3567 // On some targets (e.g. Darwin) we want to emit two consecutive labels
3568 // before each jump table. The first label is never referenced, but tells
3569 // the assembler and linker the extents of the jump table object. The
3570 // second label is actually referenced by the code.
3571 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
3572 // FIXME: This doesn't have to have any specific name, just any randomly
3573 // named and numbered local label started with 'l' would work. Simplify
3574 // GetJTISymbol.
3575 OutStreamer->emitLabel(GetJTISymbol(JumpTableIndex, true));
3576
3577 MCSymbol *JTISymbol = GetJTISymbol(JumpTableIndex);
3578 if (JTInDiffSection && MAI.hasDotTypeDotSizeDirective())
3579 OutStreamer->emitSymbolAttribute(JTISymbol, MCSA_ELF_TypeObject);
3580 OutStreamer->emitLabel(JTISymbol);
3581
3582 // Defer MCAssembler based constant folding due to a performance issue. The
3583 // label differences will be evaluated at write time.
3584 for (const MachineBasicBlock *MBB : JTBBs)
3585 emitJumpTableEntry(MJTI, MBB, JumpTableIndex);
3586
3587 if (JTInDiffSection && MAI.hasDotTypeDotSizeDirective())
3588 OutStreamer->emitELFSize(
3589 JTISymbol, MCConstantExpr::create(
3590 JTBBs.size() * MJTI.getEntrySize(DL), OutContext));
3591 }
3592
3594 emitJumpTableSizesSection(MJTI, MF->getFunction());
3595
3596 if (!JTInDiffSection)
3597 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
3598}
3599
3600void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
3601 const Function &F) const {
3602 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3603
3604 if (JT.empty())
3605 return;
3606
3607 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
3608 MCSection *JumpTableSizesSection = nullptr;
3609 StringRef sectionName = ".llvm_jump_table_sizes";
3610
3611 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
3612 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
3613
3614 if (!isCoff && !isElf)
3615 return;
3616
3617 if (isElf) {
3618 auto *LinkedToSym = static_cast<MCSymbolELF *>(CurrentFnSym);
3619 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
3620
3621 JumpTableSizesSection = OutContext.getELFSection(
3622 sectionName, ELF::SHT_LLVM_JT_SIZES, Flags, 0, GroupName, F.hasComdat(),
3623 MCSection::NonUniqueID, LinkedToSym);
3624 } else if (isCoff) {
3625 if (F.hasComdat()) {
3626 JumpTableSizesSection = OutContext.getCOFFSection(
3627 sectionName,
3630 F.getComdat()->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
3631 } else {
3632 JumpTableSizesSection = OutContext.getCOFFSection(
3636 }
3637 }
3638
3639 OutStreamer->switchSection(JumpTableSizesSection);
3640
3641 const DataLayout &DL = getDataLayout();
3642 unsigned ProgramPointerSize = DL.getPointerSize(DL.getProgramAddressSpace());
3643 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
3644 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
3645 OutStreamer->emitSymbolValue(GetJTISymbol(JTI), ProgramPointerSize);
3646 OutStreamer->emitIntValue(JTBBs.size(), ProgramPointerSize);
3647 }
3648}
3649
3650/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
3651/// current stream.
3653 const MachineBasicBlock *MBB,
3654 unsigned UID) const {
3655 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
3656 const MCExpr *Value = nullptr;
3657 switch (MJTI.getEntryKind()) {
3659 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3662 llvm_unreachable("MIPS specific");
3664 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
3665 &MJTI, MBB, UID, OutContext);
3666 break;
3668 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3669 // .word LBB123
3671 break;
3672
3675 // Each entry is the address of the block minus the address of the jump
3676 // table. This is used for PIC jump tables where gprel32 is not supported.
3677 // e.g.:
3678 // .word LBB123 - LJTI1_2
3679 // If the .set directive avoids relocations, this is emitted as:
3680 // .set L4_5_set_123, LBB123 - LJTI1_2
3681 // .word L4_5_set_123
3683 MAI.doesSetDirectiveSuppressReloc()) {
3684 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
3685 OutContext);
3686 break;
3687 }
3689 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3690 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
3692 break;
3693 }
3694 }
3695
3696 assert(Value && "Unknown entry kind!");
3697
3698 unsigned EntrySize = MJTI.getEntrySize(getDataLayout());
3699 OutStreamer->emitValue(Value, EntrySize);
3700}
3701
3702/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3703/// special global used by LLVM. If so, emit it and return true, otherwise
3704/// do nothing and return false.
3706 if (GV->getName() == "llvm.used") {
3707 if (MAI.hasNoDeadStrip()) // No need to emit this at all.
3708 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
3709 return true;
3710 }
3711
3712 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3713 if (GV->getSection() == "llvm.metadata" ||
3715 return true;
3716
3717 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3718 // For ARM64EC, print the table that maps between symbols and the
3719 // corresponding thunks to translate between x64 and AArch64 code.
3720 // This table is generated by AArch64Arm64ECCallLowering.
3721 OutStreamer->switchSection(
3722 OutContext.getCOFFSection(".hybmp$x", COFF::IMAGE_SCN_LNK_INFO));
3723 auto *Arr = cast<ConstantArray>(GV->getInitializer());
3724 for (auto &U : Arr->operands()) {
3725 auto *C = cast<Constant>(U);
3726 auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
3727 auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
3728 int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
3729
3730 if (Src->hasDLLImportStorageClass()) {
3731 // For now, we assume dllimport functions aren't directly called.
3732 // (We might change this later to match MSVC.)
3733 OutStreamer->emitCOFFSymbolIndex(
3734 OutContext.getOrCreateSymbol("__imp_" + Src->getName()));
3735 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3736 OutStreamer->emitInt32(Kind);
3737 } else {
3738 // FIXME: For non-dllimport functions, MSVC emits the same entry
3739 // twice, for reasons I don't understand. I have to assume the linker
3740 // ignores the redundant entry; there aren't any reasonable semantics
3741 // to attach to it.
3742 OutStreamer->emitCOFFSymbolIndex(getSymbol(Src));
3743 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3744 OutStreamer->emitInt32(Kind);
3745 }
3746 }
3747 return true;
3748 }
3749
3750 if (!GV->hasAppendingLinkage()) return false;
3751
3752 assert(GV->hasInitializer() && "Not a special LLVM global!");
3753
3754 if (GV->getName() == "llvm.global_ctors") {
3756 /* isCtor */ true);
3757
3758 return true;
3759 }
3760
3761 if (GV->getName() == "llvm.global_dtors") {
3763 /* isCtor */ false);
3764
3765 return true;
3766 }
3767
3768 GV->getContext().emitError(
3769 "unknown special variable with appending linkage: " +
3770 GV->getNameOrAsOperand());
3771 return true;
3772}
3773
3774/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3775/// global in the specified llvm.used list.
3776void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3777 // Should be an array of 'i8*'.
3778 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3779 const GlobalValue *GV =
3781 if (GV)
3782 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
3783 }
3784}
3785
3787 const Constant *List,
3788 SmallVector<Structor, 8> &Structors) {
3789 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3790 // the init priority.
3792 return;
3793
3794 // Gather the structors in a form that's convenient for sorting by priority.
3795 for (Value *O : cast<ConstantArray>(List)->operands()) {
3796 auto *CS = cast<ConstantStruct>(O);
3797 if (CS->getOperand(1)->isNullValue())
3798 break; // Found a null terminator, skip the rest.
3799 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3800 if (!Priority)
3801 continue; // Malformed.
3802 Structors.push_back(Structor());
3803 Structor &S = Structors.back();
3804 S.Priority = Priority->getLimitedValue(65535);
3805 S.Func = CS->getOperand(1);
3806 if (!CS->getOperand(2)->isNullValue()) {
3807 if (TM.getTargetTriple().isOSAIX()) {
3808 CS->getContext().emitError(
3809 "associated data of XXStructor list is not yet supported on AIX");
3810 }
3811
3812 S.ComdatKey =
3813 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3814 }
3815 }
3816
3817 // Emit the function pointers in the target-specific order
3818 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
3819 return L.Priority < R.Priority;
3820 });
3821}
3822
3823/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3824/// priority.
3826 bool IsCtor) {
3827 SmallVector<Structor, 8> Structors;
3828 preprocessXXStructorList(DL, List, Structors);
3829 if (Structors.empty())
3830 return;
3831
3832 // Emit the structors in reverse order if we are using the .ctor/.dtor
3833 // initialization scheme.
3834 if (!TM.Options.UseInitArray)
3835 std::reverse(Structors.begin(), Structors.end());
3836
3837 const Align Align = DL.getPointerPrefAlignment(DL.getProgramAddressSpace());
3838 for (Structor &S : Structors) {
3840 const MCSymbol *KeySym = nullptr;
3841 if (GlobalValue *GV = S.ComdatKey) {
3842 if (GV->isDeclarationForLinker())
3843 // If the associated variable is not defined in this module
3844 // (it might be available_externally, or have been an
3845 // available_externally definition that was dropped by the
3846 // EliminateAvailableExternally pass), some other TU
3847 // will provide its dynamic initializer.
3848 continue;
3849
3850 KeySym = getSymbol(GV);
3851 }
3852
3853 MCSection *OutputSection =
3854 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
3855 : Obj.getStaticDtorSection(S.Priority, KeySym));
3856 OutStreamer->switchSection(OutputSection);
3857 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3859 emitXXStructor(DL, S.Func);
3860 }
3861}
3862
3863void AsmPrinter::emitModuleIdents(Module &M) {
3864 if (!MAI.hasIdentDirective())
3865 return;
3866
3867 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
3868 for (const MDNode *N : NMD->operands()) {
3869 assert(N->getNumOperands() == 1 &&
3870 "llvm.ident metadata entry can have only one operand");
3871 const MDString *S = cast<MDString>(N->getOperand(0));
3872 OutStreamer->emitIdent(S->getString());
3873 }
3874 }
3875}
3876
3877void AsmPrinter::emitModuleCommandLines(Module &M) {
3878 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3879 if (!CommandLine)
3880 return;
3881
3882 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3883 if (!NMD || !NMD->getNumOperands())
3884 return;
3885
3886 OutStreamer->pushSection();
3887 OutStreamer->switchSection(CommandLine);
3888 OutStreamer->emitZeros(1);
3889 for (const MDNode *N : NMD->operands()) {
3890 assert(N->getNumOperands() == 1 &&
3891 "llvm.commandline metadata entry can have only one operand");
3892 const MDString *S = cast<MDString>(N->getOperand(0));
3893 OutStreamer->emitBytes(S->getString());
3894 OutStreamer->emitZeros(1);
3895 }
3896 OutStreamer->popSection();
3897}
3898
3899//===--------------------------------------------------------------------===//
3900// Emission and print routines
3901//
3902
3903/// Emit a byte directive and value.
3904///
3905void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3906
3907/// Emit a short directive and value.
3908void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3909
3910/// Emit a long directive and value.
3911void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3912
3913/// EmitSLEB128 - emit the specified signed leb128 value.
3914void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3915 if (isVerbose() && Desc)
3916 OutStreamer->AddComment(Desc);
3917
3918 OutStreamer->emitSLEB128IntValue(Value);
3919}
3920
3921void AsmPrinter::emitULEB128(uint64_t Value, const char *Desc,
3922 unsigned PadTo) const {
3923 if (isVerbose() && Desc)
3924 OutStreamer->AddComment(Desc);
3925
3926 OutStreamer->emitULEB128IntValue(Value, PadTo);
3927}
3928
3929/// Emit a long long directive and value.
3930void AsmPrinter::emitInt64(uint64_t Value) const {
3931 OutStreamer->emitInt64(Value);
3932}
3933
3934/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3935/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3936/// .set if it avoids relocations.
3938 unsigned Size) const {
3939 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3940}
3941
3942/// Emit something like ".uleb128 Hi-Lo".
3944 const MCSymbol *Lo) const {
3945 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3946}
3947
3948/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3949/// where the size in bytes of the directive is specified by Size and Label
3950/// specifies the label. This implicitly uses .set if it is available.
3952 unsigned Size,
3953 bool IsSectionRelative) const {
3954 if (IsSectionRelative) {
3955 OutStreamer->emitDwarfSectionOffset(Label, Offset, Size);
3956 return;
3957 }
3958
3959 // Emit Label+Offset (or just Label if Offset is zero)
3960 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
3961 if (Offset)
3964
3965 OutStreamer->emitValue(Expr, Size);
3966}
3967
3968//===----------------------------------------------------------------------===//
3969
3970// EmitAlignment - Emit an alignment directive to the specified power of
3971// two boundary. If a global value is specified, and if that global has
3972// an explicit alignment requested, it will override the alignment request
3973// if required for correctness.
3975 unsigned MaxBytesToEmit) const {
3976 if (GV)
3977 Alignment = getGVAlignment(GV, GV->getDataLayout(), Alignment);
3978
3979 if (Alignment == Align(1))
3980 return Alignment; // 1-byte aligned: no need to emit alignment.
3981
3982 if (getCurrentSection()->isText()) {
3983 const MCSubtargetInfo *STI = nullptr;
3984 if (this->MF)
3985 STI = &getSubtargetInfo();
3986 else
3987 STI = &TM.getMCSubtargetInfo();
3988 OutStreamer->emitCodeAlignment(Alignment, *STI, MaxBytesToEmit);
3989 } else
3990 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3991 return Alignment;
3992}
3993
3994//===----------------------------------------------------------------------===//
3995// Constant emission.
3996//===----------------------------------------------------------------------===//
3997
3999 const Constant *BaseCV,
4000 uint64_t Offset) {
4001 MCContext &Ctx = OutContext;
4002
4003 if (CV->isNullValue() || isa<UndefValue>(CV))
4004 return MCConstantExpr::create(0, Ctx);
4005
4006 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
4007 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
4008
4009 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV))
4010 return MCConstantExpr::create(CB->getZExtValue(), Ctx);
4011
4012 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV))
4013 return lowerConstantPtrAuth(*CPA);
4014
4015 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
4016 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
4017
4018 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
4019 return lowerBlockAddressConstant(*BA);
4020
4021 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
4023 getSymbol(Equiv->getGlobalValue()), nullptr, 0, std::nullopt, TM);
4024
4025 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
4026 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
4027
4028 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
4029 if (!CE) {
4030 llvm_unreachable("Unknown constant value to lower!");
4031 }
4032
4033 // The constant expression opcodes are limited to those that are necessary
4034 // to represent relocations on supported targets. Expressions involving only
4035 // constant addresses are constant folded instead.
4036 switch (CE->getOpcode()) {
4037 default:
4038 break; // Error
4039 case Instruction::AddrSpaceCast: {
4040 const Constant *Op = CE->getOperand(0);
4041 unsigned DstAS = CE->getType()->getPointerAddressSpace();
4042 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
4043 if (TM.isNoopAddrSpaceCast(getDataLayout(), SrcAS, DstAS))
4044 return lowerConstant(Op);
4045
4046 break; // Error
4047 }
4048 case Instruction::GetElementPtr: {
4049 // Generate a symbolic expression for the byte address
4050 APInt OffsetAI(getDataLayout().getIndexTypeSizeInBits(CE->getType()), 0);
4051 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
4052
4053 const MCExpr *Base = lowerConstant(CE->getOperand(0));
4054 if (!OffsetAI)
4055 return Base;
4056
4057 int64_t Offset = OffsetAI.getSExtValue();
4059 Ctx);
4060 }
4061
4062 case Instruction::Trunc:
4063 // We emit the value and depend on the assembler to truncate the generated
4064 // expression properly. This is important for differences between
4065 // blockaddress labels. Since the two labels are in the same function, it
4066 // is reasonable to treat their delta as a 32-bit value.
4067 [[fallthrough]];
4068 case Instruction::BitCast:
4069 return lowerConstant(CE->getOperand(0), BaseCV, Offset);
4070
4071 case Instruction::IntToPtr: {
4072 const DataLayout &DL = getDataLayout();
4073
4074 // Handle casts to pointers by changing them into casts to the appropriate
4075 // integer type. This promotes constant folding and simplifies this code.
4076 Constant *Op = CE->getOperand(0);
4077 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
4078 /*IsSigned*/ false, DL);
4079 if (Op)
4080 return lowerConstant(Op);
4081
4082 break; // Error
4083 }
4084
4085 case Instruction::PtrToAddr:
4086 case Instruction::PtrToInt: {
4087 const DataLayout &DL = getDataLayout();
4088
4089 // Support only foldable casts to/from pointers that can be eliminated by
4090 // changing the pointer to the appropriately sized integer type.
4091 Constant *Op = CE->getOperand(0);
4092 Type *Ty = CE->getType();
4093
4094 const MCExpr *OpExpr = lowerConstant(Op);
4095
4096 // We can emit the pointer value into this slot if the slot is an
4097 // integer slot equal to the size of the pointer.
4098 //
4099 // If the pointer is larger than the resultant integer, then
4100 // as with Trunc just depend on the assembler to truncate it.
4101 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
4102 DL.getTypeAllocSize(Op->getType()).getFixedValue())
4103 return OpExpr;
4104
4105 break; // Error
4106 }
4107
4108 case Instruction::Sub: {
4109 GlobalValue *LHSGV, *RHSGV;
4110 APInt LHSOffset, RHSOffset;
4111 DSOLocalEquivalent *DSOEquiv;
4112 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
4113 getDataLayout(), &DSOEquiv) &&
4114 IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
4115 getDataLayout())) {
4116 auto *LHSSym = getSymbol(LHSGV);
4117 auto *RHSSym = getSymbol(RHSGV);
4118 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
4119 std::optional<int64_t> PCRelativeOffset;
4120 if (getObjFileLowering().hasPLTPCRelative() && RHSGV == BaseCV)
4121 PCRelativeOffset = Offset;
4122
4123 // Try the generic symbol difference first.
4125 LHSGV, RHSGV, Addend, PCRelativeOffset, TM);
4126
4127 // (ELF-specific) If the generic symbol difference does not apply, and
4128 // LHS is a dso_local_equivalent of a function, reference the PLT entry
4129 // instead. Note: A default visibility symbol is by default preemptible
4130 // during linking, and should not be referenced with PC-relative
4131 // relocations. Therefore, use a PLT relocation even if the function is
4132 // dso_local.
4133 if (DSOEquiv && TM.getTargetTriple().isOSBinFormatELF())
4135 LHSSym, RHSSym, Addend, PCRelativeOffset, TM);
4136
4137 // Otherwise, return LHS-RHS+Addend.
4138 if (!Res) {
4139 Res =
4141 MCSymbolRefExpr::create(RHSSym, Ctx), Ctx);
4142 if (Addend != 0)
4144 Res, MCConstantExpr::create(Addend, Ctx), Ctx);
4145 }
4146 return Res;
4147 }
4148
4149 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4150 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4151 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
4152 break;
4153 }
4154
4155 case Instruction::Add: {
4156 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4157 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4158 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
4159 }
4160 }
4161
4162 // If the code isn't optimized, there may be outstanding folding
4163 // opportunities. Attempt to fold the expression using DataLayout as a
4164 // last resort before giving up.
4166 if (C != CE)
4167 return lowerConstant(C);
4168
4169 // Otherwise report the problem to the user.
4170 std::string S;
4171 raw_string_ostream OS(S);
4172 OS << "unsupported expression in static initializer: ";
4173 CE->printAsOperand(OS, /*PrintType=*/false,
4174 !MF ? nullptr : MF->getFunction().getParent());
4175 CE->getContext().emitError(S);
4176 return MCConstantExpr::create(0, Ctx);
4177}
4178
4179static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
4180 AsmPrinter &AP,
4181 const Constant *BaseCV = nullptr,
4182 uint64_t Offset = 0,
4183 AsmPrinter::AliasMapTy *AliasList = nullptr);
4184
4185static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
4186static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
4187
4188/// isRepeatedByteSequence - Determine whether the given value is
4189/// composed of a repeated sequence of identical bytes and return the
4190/// byte value. If it is not a repeated sequence, return -1.
4192 StringRef Data = V->getRawDataValues();
4193 assert(!Data.empty() && "Empty aggregates should be CAZ node");
4194 char C = Data[0];
4195 for (unsigned i = 1, e = Data.size(); i != e; ++i)
4196 if (Data[i] != C) return -1;
4197 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
4198}
4199
4200/// isRepeatedByteSequence - Determine whether the given value is
4201/// composed of a repeated sequence of identical bytes and return the
4202/// byte value. If it is not a repeated sequence, return -1.
4203static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
4204 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
4205 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
4206 assert(Size % 8 == 0);
4207
4208 // Extend the element to take zero padding into account.
4209 APInt Value = CI->getValue().zext(Size);
4210 if (!Value.isSplat(8))
4211 return -1;
4212
4213 return Value.zextOrTrunc(8).getZExtValue();
4214 }
4215 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
4216 // Make sure all array elements are sequences of the same repeated
4217 // byte.
4218 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
4219 Constant *Op0 = CA->getOperand(0);
4220 int Byte = isRepeatedByteSequence(Op0, DL);
4221 if (Byte == -1)
4222 return -1;
4223
4224 // All array elements must be equal.
4225 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
4226 if (CA->getOperand(i) != Op0)
4227 return -1;
4228 return Byte;
4229 }
4230
4232 return isRepeatedByteSequence(CDS);
4233
4234 return -1;
4235}
4236
4238 AsmPrinter::AliasMapTy *AliasList) {
4239 if (AliasList) {
4240 auto AliasIt = AliasList->find(Offset);
4241 if (AliasIt != AliasList->end()) {
4242 for (const GlobalAlias *GA : AliasIt->second)
4243 AP.OutStreamer->emitLabel(AP.getSymbol(GA));
4244 AliasList->erase(Offset);
4245 }
4246 }
4247}
4248
4250 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
4251 AsmPrinter::AliasMapTy *AliasList) {
4252 // See if we can aggregate this into a .fill, if so, emit it as such.
4253 int Value = isRepeatedByteSequence(CDS, DL);
4254 if (Value != -1) {
4255 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
4256 // Don't emit a 1-byte object as a .fill.
4257 if (Bytes > 1)
4258 return AP.OutStreamer->emitFill(Bytes, Value);
4259 }
4260
4261 // If this can be emitted with .ascii/.asciz, emit it as such.
4262 if (CDS->isString())
4263 return AP.OutStreamer->emitBytes(CDS->getAsString());
4264
4265 // Otherwise, emit the values in successive locations.
4266 uint64_t ElementByteSize = CDS->getElementByteSize();
4267 if (isa<IntegerType>(CDS->getElementType()) ||
4268 isa<ByteType>(CDS->getElementType())) {
4269 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4270 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4271 if (AP.isVerbose())
4272 AP.OutStreamer->getCommentOS()
4273 << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
4274 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
4275 ElementByteSize);
4276 }
4277 } else {
4278 Type *ET = CDS->getElementType();
4279 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4280 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4282 }
4283 }
4284
4285 unsigned Size = DL.getTypeAllocSize(CDS->getType());
4286 unsigned EmittedSize =
4287 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
4288 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
4289 if (unsigned Padding = Size - EmittedSize)
4290 AP.OutStreamer->emitZeros(Padding);
4291}
4292
4294 const ConstantArray *CA, AsmPrinter &AP,
4295 const Constant *BaseCV, uint64_t Offset,
4296 AsmPrinter::AliasMapTy *AliasList) {
4297 // See if we can aggregate some values. Make sure it can be
4298 // represented as a series of bytes of the constant value.
4299 int Value = isRepeatedByteSequence(CA, DL);
4300
4301 if (Value != -1) {
4302 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
4303 AP.OutStreamer->emitFill(Bytes, Value);
4304 } else {
4305 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
4306 emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
4307 AliasList);
4308 Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
4309 }
4310 }
4311}
4312
4313static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
4314
4315static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
4316 AsmPrinter &AP,
4317 AsmPrinter::AliasMapTy *AliasList) {
4318 uint64_t AllocSize = DL.getTypeAllocSize(CV->getType());
4319
4320 if (CV->isNullValue())
4321 return AP.OutStreamer->emitZeros(AllocSize);
4322
4323 auto *VTy = cast<FixedVectorType>(CV->getType());
4324 Type *ElementType = VTy->getElementType();
4325 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
4326 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
4327 uint64_t EmittedSize;
4328 if (ElementSizeInBits != ElementAllocSizeInBits) {
4329 // If the allocation size of an element is different from the size in bits,
4330 // printing each element separately will insert incorrect padding.
4331 //
4332 // The general algorithm here is complicated; instead of writing it out
4333 // here, just use the existing code in ConstantFolding.
4334 Type *IntT =
4335 IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
4337 ConstantExpr::getBitCast(const_cast<Constant *>(CV), IntT), DL));
4338 if (!CI) {
4340 "Cannot lower vector global with unusual element type");
4341 }
4342 emitGlobalAliasInline(AP, 0, AliasList);
4344 EmittedSize = DL.getTypeStoreSize(CV->getType());
4345 } else {
4346 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
4347 emitGlobalAliasInline(AP, AllocSize * I, AliasList);
4349 }
4350 EmittedSize = DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
4351 }
4352
4353 if (unsigned Padding = AllocSize - EmittedSize)
4354 AP.OutStreamer->emitZeros(Padding);
4355}
4356
4358 const ConstantStruct *CS, AsmPrinter &AP,
4359 const Constant *BaseCV, uint64_t Offset,
4360 AsmPrinter::AliasMapTy *AliasList) {
4361 // Print the fields in successive locations. Pad to align if needed!
4362 uint64_t Size = DL.getTypeAllocSize(CS->getType());
4363 const StructLayout *Layout = DL.getStructLayout(CS->getType());
4364 uint64_t SizeSoFar = 0;
4365 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
4366 const Constant *Field = CS->getOperand(I);
4367
4368 // Print the actual field value.
4369 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
4370 AliasList);
4371
4372 // Check if padding is needed and insert one or more 0s.
4373 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
4374 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
4375 Layout->getElementOffset(I)) -
4376 FieldSize;
4377 SizeSoFar += FieldSize + PadSize;
4378
4379 // Insert padding - this may include padding to increase the size of the
4380 // current field up to the ABI size (if the struct is not packed) as well
4381 // as padding to ensure that the next field starts at the right offset.
4382 AP.OutStreamer->emitZeros(PadSize);
4383 }
4384 assert(SizeSoFar == Layout->getSizeInBytes() &&
4385 "Layout of constant struct may be incorrect!");
4386}
4387
4388static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
4389 assert(ET && "Unknown float type");
4390 APInt API = APF.bitcastToAPInt();
4391
4392 // First print a comment with what we think the original floating-point value
4393 // should have been.
4394 if (AP.isVerbose()) {
4395 SmallString<8> StrVal;
4396 APF.toString(StrVal);
4397 ET->print(AP.OutStreamer->getCommentOS());
4398 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
4399 }
4400
4401 // Now iterate through the APInt chunks, emitting them in endian-correct
4402 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
4403 // floats).
4404 unsigned NumBytes = API.getBitWidth() / 8;
4405 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
4406 const uint64_t *p = API.getRawData();
4407
4408 // PPC's long double has odd notions of endianness compared to how LLVM
4409 // handles it: p[0] goes first for *big* endian on PPC.
4410 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
4411 int Chunk = API.getNumWords() - 1;
4412
4413 if (TrailingBytes)
4414 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
4415
4416 for (; Chunk >= 0; --Chunk)
4417 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4418 } else {
4419 unsigned Chunk;
4420 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
4421 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4422
4423 if (TrailingBytes)
4424 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
4425 }
4426
4427 // Emit the tail padding for the long double.
4428 const DataLayout &DL = AP.getDataLayout();
4429 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
4430}
4431
4432static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
4433 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
4434}
4435
4437 uint64_t TypeStoreSize,
4438 AsmPrinter &AP) {
4439 const DataLayout &DL = AP.getDataLayout();
4440 unsigned BitWidth = Val.getBitWidth();
4441
4442 // Copy the value as we may massage the layout for constants whose bit width
4443 // is not a multiple of 64-bits.
4444 APInt Realigned(Val);
4445 uint64_t ExtraBits = 0;
4446 unsigned ExtraBitsSize = BitWidth & 63;
4447
4448 if (ExtraBitsSize) {
4449 // The bit width of the data is not a multiple of 64-bits.
4450 // The extra bits are expected to be at the end of the chunk of the memory.
4451 // Little endian:
4452 // * Nothing to be done, just record the extra bits to emit.
4453 // Big endian:
4454 // * Record the extra bits to emit.
4455 // * Realign the raw data to emit the chunks of 64-bits.
4456 if (DL.isBigEndian()) {
4457 // Basically the structure of the raw data is a chunk of 64-bits cells:
4458 // 0 1 BitWidth / 64
4459 // [chunk1][chunk2] ... [chunkN].
4460 // The most significant chunk is chunkN and it should be emitted first.
4461 // However, due to the alignment issue chunkN contains useless bits.
4462 // Realign the chunks so that they contain only useful information:
4463 // ExtraBits 0 1 (BitWidth / 64) - 1
4464 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
4465 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
4466 ExtraBits =
4467 Realigned.getRawData()[0] & (((uint64_t)-1) >> (64 - ExtraBitsSize));
4468 if (BitWidth >= 64)
4469 Realigned.lshrInPlace(ExtraBitsSize);
4470 } else
4471 ExtraBits = Realigned.getRawData()[BitWidth / 64];
4472 }
4473
4474 // We don't expect assemblers to support data directives
4475 // for more than 64 bits, so we emit the data in at most 64-bit
4476 // quantities at a time.
4477 const uint64_t *RawData = Realigned.getRawData();
4478 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
4479 uint64_t ChunkVal = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
4480 AP.OutStreamer->emitIntValue(ChunkVal, 8);
4481 }
4482
4483 if (ExtraBitsSize) {
4484 // Emit the extra bits after the 64-bits chunks.
4485
4486 // Emit a directive that fills the expected size.
4487 uint64_t Size = TypeStoreSize - (BitWidth / 64) * 8;
4488 assert(Size && Size * 8 >= ExtraBitsSize &&
4489 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) ==
4490 ExtraBits &&
4491 "Directive too small for extra bits.");
4492 AP.OutStreamer->emitIntValue(ExtraBits, Size);
4493 }
4494}
4495
4497 AsmPrinter &AP) {
4499 CB->getValue(), AP.getDataLayout().getTypeStoreSize(CB->getType()), AP);
4500}
4501
4506
4507/// Transform a not absolute MCExpr containing a reference to a GOT
4508/// equivalent global, by a target specific GOT pc relative access to the
4509/// final symbol.
4511 const Constant *BaseCst,
4512 uint64_t Offset) {
4513 // The global @foo below illustrates a global that uses a got equivalent.
4514 //
4515 // @bar = global i32 42
4516 // @gotequiv = private unnamed_addr constant i32* @bar
4517 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
4518 // i64 ptrtoint (i32* @foo to i64))
4519 // to i32)
4520 //
4521 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
4522 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
4523 // form:
4524 //
4525 // foo = cstexpr, where
4526 // cstexpr := <gotequiv> - "." + <cst>
4527 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
4528 //
4529 // After canonicalization by evaluateAsRelocatable `ME` turns into:
4530 //
4531 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
4532 // gotpcrelcst := <offset from @foo base> + <cst>
4533 MCValue MV;
4534 if (!(*ME)->evaluateAsRelocatable(MV, nullptr) || MV.isAbsolute())
4535 return;
4536 const MCSymbol *GOTEquivSym = MV.getAddSym();
4537 if (!GOTEquivSym)
4538 return;
4539
4540 // Check that GOT equivalent symbol is cached.
4541 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
4542 return;
4543
4544 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
4545 if (!BaseGV)
4546 return;
4547
4548 // Check for a valid base symbol
4549 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
4550 const MCSymbol *SymB = MV.getSubSym();
4551
4552 if (!SymB || BaseSym != SymB)
4553 return;
4554
4555 // Make sure to match:
4556 //
4557 // gotpcrelcst := <offset from @foo base> + <cst>
4558 //
4559 int64_t GOTPCRelCst = Offset + MV.getConstant();
4560 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
4561 return;
4562
4563 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
4564 //
4565 // bar:
4566 // .long 42
4567 // gotequiv:
4568 // .quad bar
4569 // foo:
4570 // .long gotequiv - "." + <cst>
4571 //
4572 // is replaced by the target specific equivalent to:
4573 //
4574 // bar:
4575 // .long 42
4576 // foo:
4577 // .long bar@GOTPCREL+<gotpcrelcst>
4578 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
4579 const GlobalVariable *GV = Result.first;
4580 int NumUses = (int)Result.second;
4581 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
4582 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
4584 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
4585
4586 // Update GOT equivalent usage information
4587 --NumUses;
4588 if (NumUses >= 0)
4589 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
4590}
4591
4592static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
4593 AsmPrinter &AP, const Constant *BaseCV,
4595 AsmPrinter::AliasMapTy *AliasList) {
4596 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
4597 "AliasList only expected for XCOFF");
4598 emitGlobalAliasInline(AP, Offset, AliasList);
4599 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4600
4601 // Globals with sub-elements such as combinations of arrays and structs
4602 // are handled recursively by emitGlobalConstantImpl. Keep track of the
4603 // constant symbol base and the current position with BaseCV and Offset.
4604 if (!BaseCV && CV->hasOneUse())
4605 BaseCV = dyn_cast<Constant>(CV->user_back());
4606
4608 StructType *structType;
4609 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->getType()))) {
4610 unsigned numElements = {structType->getNumElements()};
4611 if (numElements != 0) {
4612 // Handle cases of aliases to direct struct elements
4613 const StructLayout *Layout = DL.getStructLayout(structType);
4614 uint64_t SizeSoFar = 0;
4615 for (unsigned int i = 0; i < numElements - 1; ++i) {
4616 uint64_t GapToNext = Layout->getElementOffset(i + 1) - SizeSoFar;
4617 AP.OutStreamer->emitZeros(GapToNext);
4618 SizeSoFar += GapToNext;
4619 emitGlobalAliasInline(AP, Offset + SizeSoFar, AliasList);
4620 }
4621 AP.OutStreamer->emitZeros(Size - SizeSoFar);
4622 return;
4623 }
4624 }
4625 return AP.OutStreamer->emitZeros(Size);
4626 }
4627
4628 if (isa<UndefValue>(CV))
4629 return AP.OutStreamer->emitZeros(Size);
4630
4631 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
4632 if (isa<VectorType>(CV->getType()))
4633 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4634
4635 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4636 if (StoreSize <= 8) {
4637 if (AP.isVerbose())
4638 AP.OutStreamer->getCommentOS()
4639 << format("0x%" PRIx64 "\n", CI->getZExtValue());
4640 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
4641 } else {
4643 }
4644
4645 // Emit tail padding if needed
4646 if (Size != StoreSize)
4647 AP.OutStreamer->emitZeros(Size - StoreSize);
4648
4649 return;
4650 }
4651
4652 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV)) {
4653 if (isa<VectorType>(CV->getType()))
4654 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4655
4656 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4657 if (StoreSize <= 8) {
4658 if (AP.isVerbose())
4659 AP.OutStreamer->getCommentOS()
4660 << format("0x%" PRIx64 "\n", CB->getZExtValue());
4661 AP.OutStreamer->emitIntValue(CB->getZExtValue(), StoreSize);
4662 } else {
4664 }
4665
4666 // Emit tail padding if needed
4667 if (Size != StoreSize)
4668 AP.OutStreamer->emitZeros(Size - StoreSize);
4669
4670 return;
4671 }
4672
4673 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
4674 if (isa<VectorType>(CV->getType()))
4675 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4676 else
4677 return emitGlobalConstantFP(CFP, AP);
4678 }
4679
4680 if (isa<ConstantPointerNull>(CV)) {
4681 if (isa<VectorType>(CV->getType()))
4682 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4683 AP.OutStreamer->emitIntValue(0, Size);
4684 return;
4685 }
4686
4688 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
4689
4690 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
4691 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
4692
4693 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
4694 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
4695
4696 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
4697 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
4698 // vectors).
4699 if (CE->getOpcode() == Instruction::BitCast)
4700 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
4701
4702 if (Size > 8) {
4703 // If the constant expression's size is greater than 64-bits, then we have
4704 // to emit the value in chunks. Try to constant fold the value and emit it
4705 // that way.
4706 Constant *New = ConstantFoldConstant(CE, DL);
4707 if (New != CE)
4708 return emitGlobalConstantImpl(DL, New, AP);
4709 }
4710 }
4711
4712 if (isa<ConstantVector>(CV))
4713 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4714
4715 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4716 // thread the streamer with EmitValue.
4717 const MCExpr *ME = AP.lowerConstant(CV, BaseCV, Offset);
4718
4719 // Since lowerConstant already folded and got rid of all IR pointer and
4720 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4721 // directly.
4723 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
4724
4725 AP.OutStreamer->emitValue(ME, Size);
4726}
4727
4728/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4730 AliasMapTy *AliasList) {
4731 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4732 if (Size)
4733 emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
4734 else if (MAI.hasSubsectionsViaSymbols()) {
4735 // If the global has zero size, emit a single byte so that two labels don't
4736 // look like they are at the same location.
4737 OutStreamer->emitIntValue(0, 1);
4738 }
4739 if (!AliasList)
4740 return;
4741 // TODO: These remaining aliases are not emitted in the correct location. Need
4742 // to handle the case where the alias offset doesn't refer to any sub-element.
4743 for (auto &AliasPair : *AliasList) {
4744 for (const GlobalAlias *GA : AliasPair.second)
4745 OutStreamer->emitLabel(getSymbol(GA));
4746 }
4747}
4748
4750 // Target doesn't support this yet!
4751 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4752}
4753
4755 if (Offset > 0)
4756 OS << '+' << Offset;
4757 else if (Offset < 0)
4758 OS << Offset;
4759}
4760
4761void AsmPrinter::emitNops(unsigned N) {
4762 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
4763 for (; N; --N)
4765}
4766
4767//===----------------------------------------------------------------------===//
4768// Symbol Lowering Routines.
4769//===----------------------------------------------------------------------===//
4770
4772 return OutContext.createTempSymbol(Name, true);
4773}
4774
4776 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4777 BA->getBasicBlock());
4778}
4779
4781 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4782}
4783
4787
4788/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4789MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4790 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment() ||
4791 getSubtargetInfo().getTargetTriple().isUEFI()) {
4792 const MachineConstantPoolEntry &CPE =
4793 MF->getConstantPool()->getConstants()[CPID];
4794 if (!CPE.isMachineConstantPoolEntry()) {
4795 const DataLayout &DL = MF->getDataLayout();
4796 SectionKind Kind = CPE.getSectionKind(&DL);
4797 const Constant *C = CPE.Val.ConstVal;
4798 Align Alignment = CPE.Alignment;
4800 DL, Kind, C, Alignment, &MF->getFunction());
4801 if (S && TM.getTargetTriple().isOSBinFormatCOFF()) {
4802 if (MCSymbol *Sym =
4803 static_cast<const MCSectionCOFF *>(S)->getCOMDATSymbol()) {
4804 if (Sym->isUndefined())
4805 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
4806 return Sym;
4807 }
4808 }
4809 }
4810 }
4811
4812 const DataLayout &DL = getDataLayout();
4813 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4814 "CPI" + Twine(getFunctionNumber()) + "_" +
4815 Twine(CPID));
4816}
4817
4818/// GetJTISymbol - Return the symbol for the specified jump table entry.
4819MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4820 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
4821}
4822
4823/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4824/// FIXME: privatize to AsmPrinter.
4825MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4826 const DataLayout &DL = getDataLayout();
4827 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4828 Twine(getFunctionNumber()) + "_" +
4829 Twine(UID) + "_set_" + Twine(MBBID));
4830}
4831
4836
4837/// Return the MCSymbol for the specified ExternalSymbol.
4839 SmallString<60> NameStr;
4841 return OutContext.getOrCreateSymbol(NameStr);
4842}
4843
4844/// PrintParentLoopComment - Print comments about parent loops of this one.
4846 unsigned FunctionNumber) {
4847 if (!Loop) return;
4848 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
4849 OS.indent(Loop->getLoopDepth()*2)
4850 << "Parent Loop BB" << FunctionNumber << "_"
4851 << Loop->getHeader()->getNumber()
4852 << " Depth=" << Loop->getLoopDepth() << '\n';
4853}
4854
4855/// PrintChildLoopComment - Print comments about child loops within
4856/// the loop for this basic block, with nesting.
4858 unsigned FunctionNumber) {
4859 // Add child loop information
4860 for (const MachineLoop *CL : *Loop) {
4861 OS.indent(CL->getLoopDepth()*2)
4862 << "Child Loop BB" << FunctionNumber << "_"
4863 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4864 << '\n';
4865 PrintChildLoopComment(OS, CL, FunctionNumber);
4866 }
4867}
4868
4869/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4871 const MachineLoopInfo *LI,
4872 const AsmPrinter &AP) {
4873 // Add loop depth information
4874 const MachineLoop *Loop = LI->getLoopFor(&MBB);
4875 if (!Loop) return;
4876
4877 MachineBasicBlock *Header = Loop->getHeader();
4878 assert(Header && "No header for loop");
4879
4880 // If this block is not a loop header, just print out what is the loop header
4881 // and return.
4882 if (Header != &MBB) {
4883 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
4884 Twine(AP.getFunctionNumber())+"_" +
4886 " Depth="+Twine(Loop->getLoopDepth()));
4887 return;
4888 }
4889
4890 // Otherwise, it is a loop header. Print out information about child and
4891 // parent loops.
4892 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4893
4895
4896 OS << "=>";
4897 OS.indent(Loop->getLoopDepth()*2-2);
4898
4899 OS << "This ";
4900 if (Loop->isInnermost())
4901 OS << "Inner ";
4902 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4903
4905}
4906
4907/// emitBasicBlockStart - This method prints the label for the specified
4908/// MachineBasicBlock, an alignment (if present) and a comment describing
4909/// it if appropriate.
4911 // End the previous funclet and start a new one.
4912 if (MBB.isEHFuncletEntry()) {
4913 for (auto &Handler : Handlers) {
4914 Handler->endFunclet();
4915 Handler->beginFunclet(MBB);
4916 }
4917 for (auto &Handler : EHHandlers) {
4918 Handler->endFunclet();
4919 Handler->beginFunclet(MBB);
4920 }
4921 }
4922
4923 // Switch to a new section if this basic block must begin a section. The
4924 // entry block is always placed in the function section and is handled
4925 // separately.
4926 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4927 OutStreamer->switchSection(
4928 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
4929 MBB, TM));
4930 CurrentSectionBeginSym = MBB.getSymbol();
4931 }
4932
4933 for (auto &Handler : Handlers)
4934 Handler->beginCodeAlignment(MBB);
4935
4936 // Emit an alignment directive for this block, if needed.
4937 const Align Alignment = MBB.getAlignment();
4938 if (Alignment != Align(1))
4939 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
4940
4941 // If the block has its address taken, emit any labels that were used to
4942 // reference the block. It is possible that there is more than one label
4943 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4944 // the references were generated.
4945 if (MBB.isIRBlockAddressTaken()) {
4946 if (isVerbose())
4947 OutStreamer->AddComment("Block address taken");
4948
4949 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4950 assert(BB && BB->hasAddressTaken() && "Missing BB");
4951 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4952 OutStreamer->emitLabel(Sym);
4953 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4954 OutStreamer->AddComment("Block address taken");
4955 } else if (isVerbose() && MBB.isInlineAsmBrIndirectTarget()) {
4956 OutStreamer->AddComment("Inline asm indirect target");
4957 }
4958
4959 // Print some verbose block comments.
4960 if (isVerbose()) {
4961 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4962 if (BB->hasName()) {
4963 BB->printAsOperand(OutStreamer->getCommentOS(),
4964 /*PrintType=*/false, BB->getModule());
4965 OutStreamer->getCommentOS() << '\n';
4966 }
4967 }
4968
4969 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4971 }
4972
4973 // Print the main label for the block.
4974 if (shouldEmitLabelForBasicBlock(MBB)) {
4975 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4976 OutStreamer->AddComment("Label of block must be emitted");
4977 OutStreamer->emitLabel(MBB.getSymbol());
4978 } else {
4979 if (isVerbose()) {
4980 // NOTE: Want this comment at start of line, don't emit with AddComment.
4981 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
4982 false);
4983 }
4984 }
4985
4986 if (MBB.isEHContTarget() &&
4987 ModuleExceptionModel == ExceptionHandling::WinEH) {
4988 OutStreamer->emitLabel(MBB.getEHContSymbol());
4989 }
4990
4991 // With BB sections, each basic block must handle CFI information on its own
4992 // if it begins a section (Entry block call is handled separately, next to
4993 // beginFunction).
4994 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4995 for (auto &Handler : Handlers)
4996 Handler->beginBasicBlockSection(MBB);
4997 for (auto &Handler : EHHandlers)
4998 Handler->beginBasicBlockSection(MBB);
4999 }
5000}
5001
5003 // Check if CFI information needs to be updated for this MBB with basic block
5004 // sections.
5005 if (MBB.isEndSection()) {
5006 for (auto &Handler : Handlers)
5007 Handler->endBasicBlockSection(MBB);
5008 for (auto &Handler : EHHandlers)
5009 Handler->endBasicBlockSection(MBB);
5010 }
5011}
5012
5013void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
5014 bool IsDefinition) const {
5016
5017 switch (Visibility) {
5018 default: break;
5020 if (IsDefinition)
5021 Attr = MAI.getHiddenVisibilityAttr();
5022 else
5023 Attr = MAI.getHiddenDeclarationVisibilityAttr();
5024 break;
5026 Attr = MAI.getProtectedVisibilityAttr();
5027 break;
5028 }
5029
5030 if (Attr != MCSA_Invalid)
5031 OutStreamer->emitSymbolAttribute(Sym, Attr);
5032}
5033
5034bool AsmPrinter::shouldEmitLabelForBasicBlock(
5035 const MachineBasicBlock &MBB) const {
5036 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
5037 // in the labels mode (option `=labels`) and every section beginning in the
5038 // sections mode (`=all` and `=list=`).
5039 if ((MF->getTarget().Options.BBAddrMap || MBB.isBeginSection()) &&
5040 !MBB.isEntryBlock())
5041 return true;
5042 // A label is needed for any block with at least one predecessor (when that
5043 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
5044 // entry, or if a label is forced).
5045 return !MBB.pred_empty() &&
5046 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
5047 MBB.hasLabelMustBeEmitted());
5048}
5049
5050/// isBlockOnlyReachableByFallthough - Return true if the basic block has
5051/// exactly one predecessor and the control transfer mechanism between
5052/// the predecessor and this block is a fall-through.
5055 // If this is a landing pad, it isn't a fall through. If it has no preds,
5056 // then nothing falls through to it.
5057 if (MBB->isEHPad() || MBB->pred_empty())
5058 return false;
5059
5060 // If there isn't exactly one predecessor, it can't be a fall through.
5061 if (MBB->pred_size() > 1)
5062 return false;
5063
5064 // The predecessor has to be immediately before this block.
5065 MachineBasicBlock *Pred = *MBB->pred_begin();
5066 if (!Pred->isLayoutSuccessor(MBB))
5067 return false;
5068
5069 // If the block is completely empty, then it definitely does fall through.
5070 if (Pred->empty())
5071 return true;
5072
5073 // Check the terminators in the previous blocks
5074 for (const auto &MI : Pred->terminators()) {
5075 // If it is not a simple branch, we are in a table somewhere.
5076 if (!MI.isBranch() || MI.isIndirectBranch())
5077 return false;
5078
5079 // If we are the operands of one of the branches, this is not a fall
5080 // through. Note that targets with delay slots will usually bundle
5081 // terminators with the delay slot instruction.
5082 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
5083 if (OP->isJTI())
5084 return false;
5085 if (OP->isMBB() && OP->getMBB() == MBB)
5086 return false;
5087 }
5088 }
5089
5090 return true;
5091}
5092
5094 ArrayRef<GCStrategy *> Strategies) {
5095 bool NeedsDefault = false;
5096 if (Strategies.empty())
5097 // No GC strategy, use the default format.
5098 NeedsDefault = true;
5099 else {
5100 for (GCStrategy *S : Strategies) {
5101 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*S))
5102 if (MP->emitStackMaps(SM, *this))
5103 continue;
5104 // The strategy doesn't have printer or doesn't emit custom stack maps.
5105 // Use the default format.
5106 NeedsDefault = true;
5107 }
5108 }
5109
5110 if (NeedsDefault)
5111 SM.serializeToStackMapSection();
5112}
5113
5114GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
5115 if (!S.usesMetadata())
5116 return nullptr;
5117
5118 auto [GCPI, Inserted] = GCMetadataPrinters.try_emplace(&S);
5119 if (!Inserted)
5120 return GCPI->second.get();
5121
5122 auto Name = S.getName();
5123
5124 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
5126 if (Name == GCMetaPrinter.getName()) {
5127 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
5128 GMP->S = &S;
5129 GCPI->second = std::move(GMP);
5130 return GCPI->second.get();
5131 }
5132
5133 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
5134}
5135
5137 std::unique_ptr<AsmPrinterHandler> Handler) {
5138 Handlers.insert(Handlers.begin(), std::move(Handler));
5140}
5141
5142/// Pin vtables to this file.
5144
5146
5147// In the binary's "xray_instr_map" section, an array of these function entries
5148// describes each instrumentation point. When XRay patches your code, the index
5149// into this table will be given to your handler as a patch point identifier.
5151 auto Kind8 = static_cast<uint8_t>(Kind);
5152 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
5153 Out->emitBinaryData(
5154 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
5155 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
5156 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
5157 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
5158 Out->emitZeros(Padding);
5159}
5160
5162 if (Sleds.empty())
5163 return;
5164
5165 auto PrevSection = OutStreamer->getCurrentSectionOnly();
5166 const Function &F = MF->getFunction();
5167 MCSection *InstMap = nullptr;
5168 MCSection *FnSledIndex = nullptr;
5169 const Triple &TT = TM.getTargetTriple();
5170 // Use PC-relative addresses on all targets.
5171 if (TT.isOSBinFormatELF()) {
5172 auto LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5173 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
5174 StringRef GroupName;
5175 if (F.hasComdat()) {
5176 Flags |= ELF::SHF_GROUP;
5177 GroupName = F.getComdat()->getName();
5178 }
5179 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
5180 Flags, 0, GroupName, F.hasComdat(),
5181 MCSection::NonUniqueID, LinkedToSym);
5182
5183 if (TM.Options.XRayFunctionIndex)
5184 FnSledIndex = OutContext.getELFSection(
5185 "xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5186 MCSection::NonUniqueID, LinkedToSym);
5187 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
5188 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map",
5191 if (TM.Options.XRayFunctionIndex)
5192 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx",
5195 } else {
5196 llvm_unreachable("Unsupported target");
5197 }
5198
5199 auto WordSizeBytes = MAI.getCodePointerSize();
5200
5201 // Now we switch to the instrumentation map section. Because this is done
5202 // per-function, we are able to create an index entry that will represent the
5203 // range of sleds associated with a function.
5204 auto &Ctx = OutContext;
5205 MCSymbol *SledsStart =
5206 OutContext.createLinkerPrivateSymbol("xray_sleds_start");
5207 OutStreamer->switchSection(InstMap);
5208 OutStreamer->emitLabel(SledsStart);
5209 for (const auto &Sled : Sleds) {
5210 MCSymbol *Dot = Ctx.createTempSymbol();
5211 OutStreamer->emitLabel(Dot);
5212 OutStreamer->emitValueImpl(
5214 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5215 WordSizeBytes);
5216 OutStreamer->emitValueImpl(
5220 MCConstantExpr::create(WordSizeBytes, Ctx),
5221 Ctx),
5222 Ctx),
5223 WordSizeBytes);
5224 Sled.emit(WordSizeBytes, OutStreamer.get());
5225 }
5226 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
5227 OutStreamer->emitLabel(SledsEnd);
5228
5229 // We then emit a single entry in the index per function. We use the symbols
5230 // that bound the instrumentation map as the range for a specific function.
5231 // Each entry contains 2 words and needs to be word-aligned.
5232 if (FnSledIndex) {
5233 OutStreamer->switchSection(FnSledIndex);
5234 OutStreamer->emitValueToAlignment(Align(WordSizeBytes));
5235 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
5236 // difference uses a SUBTRACTOR external relocation which references the
5237 // symbol.
5238 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol("xray_fn_idx");
5239 OutStreamer->emitLabel(Dot);
5240 OutStreamer->emitValueImpl(
5242 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5243 WordSizeBytes);
5244 OutStreamer->emitValueImpl(MCConstantExpr::create(Sleds.size(), Ctx),
5245 WordSizeBytes);
5246 OutStreamer->switchSection(PrevSection);
5247 }
5248 Sleds.clear();
5249}
5250
5252 SledKind Kind, uint8_t Version) {
5253 const Function &F = MI.getMF()->getFunction();
5254 auto Attr = F.getFnAttribute("function-instrument");
5255 bool LogArgs = F.hasFnAttribute("xray-log-args");
5256 bool AlwaysInstrument =
5257 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
5258 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
5260 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
5261 AlwaysInstrument, &F, Version});
5262}
5263
5265 const Function &F = MF->getFunction();
5266 unsigned PatchableFunctionPrefix =
5267 F.getFnAttributeAsParsedInteger("patchable-function-prefix");
5268 unsigned PatchableFunctionEntry =
5269 F.getFnAttributeAsParsedInteger("patchable-function-entry");
5270 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
5271 return;
5272 const unsigned PointerSize = getPointerSize();
5273 if (TM.getTargetTriple().isOSBinFormatELF()) {
5274 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
5275 const MCSymbolELF *LinkedToSym = nullptr;
5276 StringRef GroupName, SectionName;
5277
5278 if (F.hasFnAttribute("patchable-function-entry-section"))
5279 SectionName = F.getFnAttribute("patchable-function-entry-section")
5280 .getValueAsString();
5281 if (SectionName.empty())
5282 SectionName = "__patchable_function_entries";
5283
5284 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
5285 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
5286 if (MAI.useIntegratedAssembler() || MAI.binutilsIsAtLeast(2, 36)) {
5287 Flags |= ELF::SHF_LINK_ORDER;
5288 if (F.hasComdat()) {
5289 Flags |= ELF::SHF_GROUP;
5290 GroupName = F.getComdat()->getName();
5291 }
5292 LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5293 }
5294 OutStreamer->switchSection(OutContext.getELFSection(
5295 SectionName, ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5296 MCSection::NonUniqueID, LinkedToSym));
5299 }
5300}
5301
5303 return OutStreamer->getContext().getDwarfVersion();
5304}
5305
5307 OutStreamer->getContext().setDwarfVersion(Version);
5308}
5309
5311 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
5312}
5313
5316 OutStreamer->getContext().getDwarfFormat());
5317}
5318
5320 return {getDwarfVersion(), uint8_t(MAI.getCodePointerSize()),
5321 OutStreamer->getContext().getDwarfFormat(),
5323}
5324
5327 OutStreamer->getContext().getDwarfFormat());
5328}
5329
5330std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
5333 const MCSymbol *BranchLabel) const {
5334 const auto TLI = MF->getSubtarget().getTargetLowering();
5335 const auto BaseExpr =
5336 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, MMI->getContext());
5337 const auto Base = &cast<MCSymbolRefExpr>(BaseExpr)->getSymbol();
5338
5339 // By default, for the architectures that support CodeView,
5340 // EK_LabelDifference32 is implemented as an Int32 from the base address.
5341 return std::make_tuple(Base, 0, BranchLabel,
5343}
5344
5346 const Triple &TT = M.getTargetTriple();
5347 assert(TT.isOSBinFormatCOFF());
5348
5349 bool IsTargetArm64EC = TT.isWindowsArm64EC();
5351 SmallVector<MCSymbol *> FuncOverrideDefaultSymbols;
5352 bool SwitchedToDirectiveSection = false;
5353 for (const Function &F : M.functions()) {
5354 if (F.hasFnAttribute("loader-replaceable")) {
5355 if (!SwitchedToDirectiveSection) {
5356 OutStreamer->switchSection(
5357 OutContext.getObjectFileInfo()->getDrectveSection());
5358 SwitchedToDirectiveSection = true;
5359 }
5360
5361 StringRef Name = F.getName();
5362
5363 // For hybrid-patchable targets, strip the prefix so that we can mark
5364 // the real function as replaceable.
5365 if (IsTargetArm64EC && Name.ends_with(HybridPatchableTargetSuffix)) {
5366 Name = Name.drop_back(HybridPatchableTargetSuffix.size());
5367 }
5368
5369 MCSymbol *FuncOverrideSymbol =
5370 MMI->getContext().getOrCreateSymbol(Name + "_$fo$");
5371 OutStreamer->beginCOFFSymbolDef(FuncOverrideSymbol);
5372 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5373 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5374 OutStreamer->endCOFFSymbolDef();
5375
5376 MCSymbol *FuncOverrideDefaultSymbol =
5377 MMI->getContext().getOrCreateSymbol(Name + "_$fo_default$");
5378 OutStreamer->beginCOFFSymbolDef(FuncOverrideDefaultSymbol);
5379 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5380 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5381 OutStreamer->endCOFFSymbolDef();
5382 FuncOverrideDefaultSymbols.push_back(FuncOverrideDefaultSymbol);
5383
5384 OutStreamer->emitBytes((Twine(" /ALTERNATENAME:") +
5385 FuncOverrideSymbol->getName() + "=" +
5386 FuncOverrideDefaultSymbol->getName())
5387 .toStringRef(Buf));
5388 Buf.clear();
5389 }
5390 }
5391
5392 if (SwitchedToDirectiveSection)
5393 OutStreamer->popSection();
5394
5395 if (FuncOverrideDefaultSymbols.empty())
5396 return;
5397
5398 // MSVC emits the symbols for the default variables pointing at the start of
5399 // the .data section, but doesn't actually allocate any space for them. LLVM
5400 // can't do this, so have all of the variables pointing at a single byte
5401 // instead.
5402 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
5403 for (MCSymbol *Symbol : FuncOverrideDefaultSymbols) {
5404 OutStreamer->emitLabel(Symbol);
5405 }
5406 OutStreamer->emitZeros(1);
5407 OutStreamer->popSection();
5408}
5409
5411 const Triple &TT = M.getTargetTriple();
5412 assert(TT.isOSBinFormatCOFF());
5413
5414 // Emit an absolute @feat.00 symbol.
5415 MCSymbol *S = MMI->getContext().getOrCreateSymbol(StringRef("@feat.00"));
5416 OutStreamer->beginCOFFSymbolDef(S);
5417 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
5418 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5419 OutStreamer->endCOFFSymbolDef();
5420 int64_t Feat00Value = 0;
5421
5422 if (TT.getArch() == Triple::x86) {
5423 // According to the PE-COFF spec, the LSB of this value marks the object
5424 // for "registered SEH". This means that all SEH handler entry points
5425 // must be registered in .sxdata. Use of any unregistered handlers will
5426 // cause the process to terminate immediately. LLVM does not know how to
5427 // register any SEH handlers, so its object files should be safe.
5428 Feat00Value |= COFF::Feat00Flags::SafeSEH;
5429 }
5430
5431 if (M.getControlFlowGuardMode() == ControlFlowGuardMode::Enabled) {
5432 // Object is CFG-aware. Only set if we actually inserted the checks.
5433 Feat00Value |= COFF::Feat00Flags::GuardCF;
5434 }
5435
5436 if (M.getModuleFlag("ehcontguard")) {
5437 // Object also has EHCont.
5438 Feat00Value |= COFF::Feat00Flags::GuardEHCont;
5439 }
5440
5441 if (M.getModuleFlag("ms-kernel")) {
5442 // Object is compiled with /kernel.
5443 Feat00Value |= COFF::Feat00Flags::Kernel;
5444 }
5445
5446 OutStreamer->emitSymbolAttribute(S, MCSA_Global);
5447 OutStreamer->emitAssignment(
5448 S, MCConstantExpr::create(Feat00Value, MMI->getContext()));
5449}
5450
5451namespace llvm {
5452namespace {
5454 return MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
5455}
5456
5458 MachineFunction &MF) {
5460 .getManager();
5461}
5462
5464 MachineFunction &MF) {
5466 getFAM(M, MAM)
5468 MF.getFunction())
5469 .getManager();
5470 return MFAM;
5471}
5472} // anonymous namespace
5473
5476 MachineModuleInfo &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
5477 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5478 AsmPrinter.MMI = &MMI;
5479 AsmPrinter.GetORE = [&MAM, &M](MachineFunction &MF) {
5480 return &getMFAM(M, MAM, MF)
5482 };
5483 AsmPrinter.GetMDT = [&MAM, &M](MachineFunction &MF) {
5484 return &getMFAM(M, MAM, MF).getResult<MachineDominatorTreeAnalysis>(MF);
5485 };
5486 AsmPrinter.GetMLI = [&MAM, &M](MachineFunction &MF) {
5487 return &getMFAM(M, MAM, MF).getResult<MachineLoopAnalysis>(MF);
5488 };
5489 AsmPrinter.GetMBPI = [&MAM, &M](MachineFunction &MF) {
5490 return &getMFAM(M, MAM, MF).getResult<MachineBranchProbabilityAnalysis>(MF);
5491 };
5492 AsmPrinter.GetMBFI = [&MAM, &M](MachineFunction &MF) {
5493 return &getMFAM(M, MAM, MF).getResult<MachineBlockFrequencyAnalysis>(MF);
5494 };
5495 AsmPrinter.GetMBHI = [&MAM, &M](MachineFunction &MF) {
5496 return &getMFAM(M, MAM, MF).getResult<MachineBlockHashInfoAnalysis>(MF);
5497 };
5498 AsmPrinter.GetBBSPR = [&MAM, &M](MachineFunction &MF) {
5499 return getFAM(M, MAM)
5501 MF.getFunction());
5502 };
5503 // TODO(boomanaiden154): Get GC working with the new pass manager.
5504 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5508 for (auto &[Name, S] : MAM.getResult<CollectorMetadataAnalysis>(M))
5509 Strategies.push_back(S.get());
5511 };
5513}
5514
5516 MachineFunction &MF,
5518 const ModuleAnalysisManagerMachineFunctionProxy::Result &MAMProxy =
5520 MachineModuleInfo &MMI =
5521 MAMProxy
5522 .getCachedResult<MachineModuleAnalysis>(*MF.getFunction().getParent())
5523 ->getMMI();
5524 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5525 AsmPrinter.MMI = &MMI;
5526 AsmPrinter.GetORE = [&MFAM](MachineFunction &MF) {
5528 };
5529 AsmPrinter.GetMDT = [&MFAM](MachineFunction &MF) {
5530 return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
5531 };
5532 AsmPrinter.GetMLI = [&MFAM](MachineFunction &MF) {
5533 return &MFAM.getResult<MachineLoopAnalysis>(MF);
5534 };
5535 AsmPrinter.GetMBPI = [&MFAM](MachineFunction &MF) {
5537 };
5538 AsmPrinter.GetMBFI = [&MFAM](MachineFunction &MF) {
5539 return &MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
5540 };
5541 AsmPrinter.GetMBHI = [&MFAM](MachineFunction &MF) {
5542 return &MFAM.getResult<MachineBlockHashInfoAnalysis>(MF);
5543 };
5544 AsmPrinter.GetBBSPR = [&MFAM](MachineFunction &MF) {
5545 return getFAM(MFAM, MF)
5547 MF.getFunction());
5548 };
5549 // TODO(boomanaiden154): Get GC working with the new pass manager.
5550 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5552 AsmPrinter.EmitStackMaps = [&MAMProxy, &AsmPrinter](Module &M) {
5554 if (auto *Map = MAMProxy.getCachedResult<CollectorMetadataAnalysis>(M))
5555 for (auto &[Name, S] : *Map)
5556 Strategies.push_back(S.get());
5558 };
5560}
5561
5563
5564} // namespace llvm
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< bool > PgoAnalysisMapEmitBBSectionsCfg("pgo-analysis-map-emit-bb-sections-cfg", cl::desc("Enable the post-link cfg information from the basic block " "sections profile in the PGO analysis map"), cl::Hidden, cl::init(false))
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE,...
static cl::opt< std::string > StackUsageFile("stack-usage-file", cl::desc("Output filename for stack usage information"), cl::value_desc("filename"), cl::Hidden)
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 cl::opt< bool > BBAddrMapSkipEmitBBEntries("basic-block-address-map-skip-bb-entries", cl::desc("Skip emitting basic block entries in the SHT_LLVM_BB_ADDR_MAP " "section. It's used to save binary size when BB entries are " "unnecessary for some PGOAnalysisMap features."), cl::Hidden, cl::init(false))
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
static void emitFakeUse(const MachineInstr *MI, AsmPrinter &AP)
static bool isGOTEquivalentCandidate(const GlobalVariable *GV, unsigned &NumGOTEquivUsers, bool &HasNonGlobalUsers)
Only consider global GOT equivalents if at least one user is a cstexpr inside an initializer of anoth...
static void emitGlobalConstantLargeByte(const ConstantByte *CB, AsmPrinter &AP)
static void tagGlobalDefinition(Module &M, GlobalVariable *G)
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
static void emitGlobalConstantLargeAPInt(const APInt &Val, uint64_t TypeStoreSize, AsmPrinter &AP)
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 llvm::object::BBAddrMap::Features getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges, bool HasCalls, const CFGProfile *FuncCFGProfile)
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 unsigned getNumGlobalVariableUses(const Constant *C, bool &HasNonGlobalUsers)
Compute the number of Global Variables that uses a Constant.
static void removeMemtagFromGlobal(GlobalVariable &G)
static uint64_t globalSize(const llvm::GlobalVariable &G)
static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintChildLoopComment - Print comments about child loops within the loop for this basic block,...
static StringRef getMIMnemonic(const MachineInstr &MI, MCStreamer &Streamer)
PGOMapFeaturesEnum
static void emitComments(const MachineInstr &MI, const MCSubtargetInfo *STI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintParentLoopComment - Print comments about parent loops of this one.
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP, AsmPrinter::AliasMapTy *AliasList)
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
static bool shouldTagGlobal(const llvm::GlobalVariable &G)
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, AsmPrinter &AP, const Constant *BaseCV=nullptr, uint64_t Offset=0, AsmPrinter::AliasMapTy *AliasList=nullptr)
static cl::list< PGOMapFeaturesEnum > PgoAnalysisMapFeatures("pgo-analysis-map", cl::Hidden, cl::CommaSeparated, cl::values(clEnumValN(PGOMapFeaturesEnum::None, "none", "Disable all options"), clEnumValN(PGOMapFeaturesEnum::FuncEntryCount, "func-entry-count", "Function Entry Count"), clEnumValN(PGOMapFeaturesEnum::BBFreq, "bb-freq", "Basic Block Frequency"), clEnumValN(PGOMapFeaturesEnum::BrProb, "br-prob", "Branch Probability"), clEnumValN(PGOMapFeaturesEnum::All, "all", "Enable all options")), cl::desc("Enable extended information within the SHT_LLVM_BB_ADDR_MAP that is " "extracted from PGO related analysis."))
static ConstantInt * extractNumericCGTypeId(const Function &F)
Extracts a numeric type identifier of a Function's type from callgraph metadata.
static cl::opt< bool > PrintLatency("asm-print-latency", cl::desc("Print instruction latencies as verbose asm comments"), cl::Hidden, cl::init(false))
static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP)
This method handles the target-independent form of DBG_LABEL, returning true if it was able to do so.
static cl::opt< bool > BBAddrMapEmitFuncGUID("basic-block-address-map-emit-func-guid", cl::desc("Emit the function GUID in the SHT_LLVM_BB_ADDR_MAP section for " "functions with local linkage. This allows identifying them " "without relying on their (possibly non-unique) symbol names."), cl::Hidden, cl::init(false))
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV, AsmPrinter &AP, AsmPrinter::AliasMapTy *AliasList)
static void emitFreeze(const MachineInstr *MI, AsmPrinter &AP)
static cl::opt< bool > EmitJumpTableSizesSection("emit-jump-table-sizes-section", cl::desc("Emit a section containing jump table addresses and sizes"), cl::Hidden, cl::init(false))
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
#define DEBUG_TYPE
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This file contains common utilities for code prefetch insertion.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
const FeatureInfo AllFeatures[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
static constexpr StringLiteral Filename
OptimizedStructLayoutField Field
ModuleAnalysisManager MAM
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
std::unique_ptr< MCStreamer > && Streamer
This file describes how to lower LLVM code to machine code.
Defines the virtual file system interface vfs::FileSystem.
Value * LHS
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:380
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:306
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6106
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6339
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1649
APInt bitcastToAPInt() const
Definition APFloat.h:1504
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
unsigned getNumWords() const
Get the number of words.
Definition APInt.h:1515
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition APInt.h:571
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
AddrLabelMap(MCContext &context)
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New)
void takeDeletedSymbolsForFunction(Function *F, std::vector< MCSymbol * > &Result)
If we have any deleted symbols for F, return them.
void UpdateForDeletedBlock(BasicBlock *BB)
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(BasicBlock *BB)
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 & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI AnalysisKey Key
virtual ~AsmPrinterHandler()
Pin vtables to this file.
virtual void markFunctionEnd()
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:94
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition AsmPrinter.h:672
void emitDanglingPrefetchTargets()
Emit prefetch targets that were not mapped to any basic block.
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
MCSymbol * getSymbol(const GlobalValue *GV) const
void emitULEB128(uint64_t Value, const char *Desc=nullptr, unsigned PadTo=0) const
Emit the specified unsigned leb128 value.
SmallVector< XRayFunctionEntry, 4 > Sleds
Definition AsmPrinter.h:452
MapVector< MBBSectionID, MBBSectionRange > MBBSectionRanges
Definition AsmPrinter.h:164
bool isDwarf64() const
void emitNops(unsigned N)
Emit N NOP instructions.
MCSymbol * CurrentFnBegin
Definition AsmPrinter.h:247
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition AsmPrinter.h:124
virtual void emitDebugValue(const MCExpr *Value, unsigned Size) const
Emit the directive and value for debug thread local expression.
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
virtual void emitConstantPool()
Print to the current output stream assembly representations of the constants in the constant pool MCP...
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
std::function< MachineOptimizationRemarkEmitter *(MachineFunction &)> GetORE
Definition AsmPrinter.h:183
virtual const MCExpr * lowerConstantPtrAuth(const ConstantPtrAuth &CPA)
Definition AsmPrinter.h:693
unsigned int getUnitLengthFieldByteSize() const
Returns 4 for DWARF32 and 12 for DWARF64.
void emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label+Offset" where the size in bytes of the directive is specified by Siz...
unsigned getPointerSize() const
Return the pointer size in bytes from the target triple.
Definition AsmPrinter.h:382
virtual bool emitTargetFeaturePush(const MCSubtargetInfo &STI)
Emit necessary directives to allow use of instructions that are permitted by target features enabled ...
Definition AsmPrinter.h:971
~AsmPrinter() override
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:97
void emitXRayTable()
Emit a table with all XRay instrumentation points.
virtual void emitGlobalAlias(const Module &M, const GlobalAlias &GA)
DenseMap< const MachineBasicBlock *, SmallVector< MCSymbol *, 1 > > CurrentFnCallsiteEndSymbols
Vector of symbols marking the end of the callsites in the current function, keyed by their containing...
Definition AsmPrinter.h:150
virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
Align emitAlignment(Align Alignment, const GlobalObject *GV=nullptr, unsigned MaxBytesToEmit=0) const
Emit an alignment directive to the specified power of two boundary.
virtual void emitJumpTableEntry(const MachineJumpTableInfo &MJTI, const MachineBasicBlock *MBB, unsigned uid) const
EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the current stream.
MCSymbol * CurrentFnDescSym
The symbol for the current function descriptor on AIX.
Definition AsmPrinter.h:138
MCSymbol * CurrentFnBeginLocal
For dso_local functions, the current $local alias for the function.
Definition AsmPrinter.h:250
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition AsmPrinter.h:169
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
void emitGlobalGOTEquivs()
Constant expressions using GOT equivalent globals may not be eligible for PC relative GOT entry conve...
MCSymbol * getFunctionBegin() const
Definition AsmPrinter.h:345
void emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const
Emit something like ".long Hi-Lo" where the size in bytes of the directive is specified by Size and H...
void emitKCFITrapEntry(const MachineFunction &MF, const MCSymbol *Symbol)
virtual void emitMachOIFuncStubHelperBody(Module &M, const GlobalIFunc &GI, MCSymbol *LazyPointer)
Definition AsmPrinter.h:724
MCSymbol * getMBBExceptionSym(const MachineBasicBlock &MBB)
std::function< void(Module &)> EmitStackMaps
Definition AsmPrinter.h:194
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
Definition AsmPrinter.h:355
virtual DwarfDebug * createDwarfDebug()
Create the DwarfDebug handler.
std::function< BasicBlockSectionsProfileReader *(MachineFunction &)> GetBBSPR
Returns the basic block sections profile reader if available, nullptr otherwise.
Definition AsmPrinter.h:191
SmallVector< std::unique_ptr< AsmPrinterHandler >, 2 > Handlers
Definition AsmPrinter.h:258
bool emitSpecialLLVMGlobal(const GlobalVariable *GV)
Check to see if the specified global is a special global used by LLVM.
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:112
virtual void emitJumpTableInfo()
Print assembly representations of the jump tables used by the current function to the current output ...
void computeGlobalGOTEquivs(Module &M)
Unnamed constant global variables solely contaning a pointer to another globals variable act like a g...
static Align getGVAlignment(const GlobalObject *GV, const DataLayout &DL, Align InAlign=Align(1))
Return the alignment for the specified GV.
MCSymbol * createCallsiteEndSymbol(const MachineBasicBlock &MBB)
Creates a new symbol to be used for the end of a callsite at the specified basic block.
virtual const MCExpr * lowerConstant(const Constant *CV, const Constant *BaseCV=nullptr, uint64_t Offset=0)
Lower the specified LLVM Constant to an MCExpr.
void emitCallGraphSection(const MachineFunction &MF, FunctionCallGraphInfo &FuncCGInfo)
Emits .llvm.callgraph section.
void emitInt8(int Value) const
Emit a byte directive and value.
CFISection getFunctionCFISectionType(const Function &F) const
Get the CFISection type for a function.
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
void emitFunctionBody()
This method emits the body and trailer for a function.
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
void emitBBAddrMapSection(const MachineFunction &MF)
void emitPCSections(const MachineFunction &MF)
Emits the PC sections collected from instructions.
MachineDominatorTree * MDT
This is a pointer to the current MachineDominatorTree.
Definition AsmPrinter.h:121
virtual void emitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
Definition AsmPrinter.h:648
unsigned PointerSize
The pointer size in bytes for the default address space.
Definition AsmPrinter.h:118
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
std::function< void(Module &)> FinishGCAssembly
Definition AsmPrinter.h:193
virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition AsmPrinter.h:546
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition AsmPrinter.h:656
std::function< MachineDominatorTree *(MachineFunction &)> GetMDT
Definition AsmPrinter.h:184
std::pair< const GlobalVariable *, unsigned > GOTEquivUsePair
Map global GOT equivalent MCSymbols to GlobalVariables and keep track of its number of uses by other ...
Definition AsmPrinter.h:168
void emitPatchableFunctionEntries()
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
virtual void emitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
Definition AsmPrinter.h:652
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
virtual void emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI, MCSymbol *LazyPointer)
Definition AsmPrinter.h:718
virtual void emitImplicitDef(const MachineInstr *MI) const
Targets can override this to customize the output of IMPLICIT_DEF instructions in verbose mode.
virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target.
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
unsigned getFunctionNumber() const
Return a unique ID for the current function.
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition AsmPrinter.h:127
DenseMap< uint64_t, SmallVector< const GlobalAlias *, 1 > > AliasMapTy
Print a general LLVM constant to the .s file.
Definition AsmPrinter.h:618
virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const
std::function< MachineBlockHashInfoResult *(MachineFunction &)> GetMBHI
Definition AsmPrinter.h:188
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer, char &ID=AsmPrinter::ID)
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
void emitGlobalConstant(const DataLayout &DL, const Constant *CV, AliasMapTy *AliasList=nullptr)
EmitGlobalConstant - Print a general LLVM constant to the .s file.
void emitFrameAlloc(const MachineInstr &MI)
void emitStackSizeSection(const MachineFunction &MF)
MCSymbol * getSymbolPreferLocal(const GlobalValue &GV) const
Similar to getSymbol() but preferred for references.
std::function< void(Module &)> BeginGCAssembly
Definition AsmPrinter.h:192
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition AsmPrinter.h:134
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition AsmPrinter.h:115
void emitSLEB128(int64_t Value, const char *Desc=nullptr) const
Emit the specified signed leb128 value.
std::function< MachineBlockFrequencyInfo *(MachineFunction &)> GetMBFI
Definition AsmPrinter.h:187
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:104
const StaticDataProfileInfo * SDPI
Provides the profile information for constants.
Definition AsmPrinter.h:153
void emitCFIInstruction(const MachineInstr &MI)
MCSymbol * createTempSymbol(const Twine &Name) const
bool doFinalization(Module &M) override
Shut down the asmprinter.
virtual const MCSubtargetInfo * getIFuncMCSubtargetInfo() const
getSubtargetInfo() cannot be used where this is needed because we don't have a MachineFunction when w...
Definition AsmPrinter.h:714
void emitStackUsage(const MachineFunction &MF)
virtual void emitKCFITypeId(const MachineFunction &MF)
bool isPositionIndependent() const
virtual void emitTargetFeaturePop(const MCSubtargetInfo &STI, bool DidPush)
Emit necessary directives to restore target feature state.
Definition AsmPrinter.h:978
virtual void emitXXStructorList(const DataLayout &DL, const Constant *List, bool IsCtor)
This method emits llvm.global_ctors or llvm.global_dtors list.
void emitPCSectionsLabel(const MachineFunction &MF, const MDNode &MD)
Emits a label as reference for PC sections.
MCSymbol * CurrentPatchableFunctionEntrySym
The symbol for the entry in __patchable_function_entires.
Definition AsmPrinter.h:130
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
void takeDeletedSymbolsForFunction(const Function *F, std::vector< MCSymbol * > &Result)
If the specified function has had any references to address-taken blocks generated,...
void emitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition=true) const
This emits visibility information about symbol, if this is supported by the target.
void emitInt32(int Value) const
Emit a long directive and value.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:109
const ProfileSummaryInfo * PSI
The profile summary information.
Definition AsmPrinter.h:156
const MCAsmInfo & MAI
Target Asm Printer information.
Definition AsmPrinter.h:100
std::function< void()> AssertDebugEHFinalized
Definition AsmPrinter.h:195
void emitStackMapsForGCStrategies(ArrayRef< GCStrategy * > Strategies)
virtual void emitFunctionDescriptor()
Definition AsmPrinter.h:681
const MCSection * getCurrentSection() const
Return the current section we are emitting to.
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
size_t NumUserHandlers
Definition AsmPrinter.h:259
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition AsmPrinter.h:143
std::function< MachineLoopInfo *(MachineFunction &)> GetMLI
Definition AsmPrinter.h:185
std::function< MachineModuleInfo *()> GetMMI
Definition AsmPrinter.h:182
bool isVerbose() const
Return true if assembly output should contain comments.
Definition AsmPrinter.h:336
MCSymbol * getFunctionEnd() const
Definition AsmPrinter.h:346
virtual void emitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition AsmPrinter.h:689
void preprocessXXStructorList(const DataLayout &DL, const Constant *List, SmallVector< Structor, 8 > &Structors)
This method gathers an array of Structors and then sorts them out by Priority.
void emitInt16(int Value) const
Emit a short directive and value.
void setDwarfVersion(uint16_t Version)
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
StringRef getConstantSectionSuffix(const Constant *C) const
Returns a section suffix (hot or unlikely) for the constant if profiles are available.
SmallVector< std::unique_ptr< AsmPrinterHandler >, 1 > EHHandlers
A handle to the EH info emitter (if present).
Definition AsmPrinter.h:253
void emitPseudoProbe(const MachineInstr &MI)
void emitRemarksSection(remarks::RemarkStreamer &RS)
virtual MaybeAlign getRequiredGlobalAlignmentGranule(const GlobalVariable &GV)
Returns a optional minimum alignment that applies to both the address and the allocation size of the ...
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
virtual void emitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition AsmPrinter.h:660
const DataLayout & getDataLayout() const
Return information about data layout.
void emitCOFFFeatureSymbol(Module &M)
Emits the @feat.00 symbol indicating the features enabled in this module.
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
MCSymbol * GetExternalSymbolSymbol(const Twine &Sym) const
Return the MCSymbol for the specified ExternalSymbol.
void handleCallsiteForCallgraph(FunctionCallGraphInfo &FuncCGInfo, const MachineFunction::CallSiteInfoMap &CallSitesInfoMap, const MachineInstr &MI)
If MI is an indirect call, add expected type IDs to indirect type ids list.
void emitPrefetchTargetSymbol(const UniqueBBID &BBID, unsigned CallsiteIndex)
Helper to emit a symbol for the prefetch target associated with the given BBID and callsite index.
void emitInt64(uint64_t Value) const
Emit a long long directive and value.
uint16_t getDwarfVersion() const
dwarf::FormParams getDwarfFormParams() const
Returns information about the byte size of DW_FORM values.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
void emitCOFFReplaceableFunctionData(Module &M)
Emits symbols and data to allow functions marked with the loader-replaceable attribute to be replacea...
bool usesCFIWithoutEH() const
Since emitting CFI unwind information is entangled with supporting the exceptions,...
bool doesDwarfUseRelocationsAcrossSections() const
Definition AsmPrinter.h:402
@ None
Do not emit either .eh_frame or .debug_frame.
Definition AsmPrinter.h:173
@ Debug
Emit .debug_frame.
Definition AsmPrinter.h:175
std::function< MachineBranchProbabilityInfo *(MachineFunction &)> GetMBPI
Definition AsmPrinter.h:186
void addAsmPrinterHandler(std::unique_ptr< AsmPrinterHandler > Handler)
virtual std::tuple< const MCSymbol *, uint64_t, const MCSymbol *, codeview::JumpTableEntrySize > getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr, const MCSymbol *BranchLabel) const
Gets information required to create a CodeView debug symbol for a jump table.
void emitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const
Emit something like ".uleb128 Hi-Lo".
virtual const MCExpr * lowerBlockAddressConstant(const BlockAddress &BA)
Lower the specified BlockAddress to an MCExpr.
Analysis pass providing the BasicBlockSectionsProfileReader.
const CFGProfile * getFunctionCFGProfile(StringRef FuncName) const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
The address of a basic block.
Definition Constants.h:1088
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
uint32_t getNumerator() const
Value handle with callbacks on RAUW and destruction.
An analysis pass which caches information about the entire Module.
Definition GCMetadata.h:202
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:609
Class for constant bytes.
Definition Constants.h:281
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:345
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
LLVM_ABI APFloat getElementAsAPFloat(uint64_t i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
LLVM_ABI uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
LLVM_ABI bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers or bytes.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
LLVM_ABI Type * getElementType() const
Return the element type of the array/vector.
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A signed pointer, in the ptrauth sense.
Definition Constants.h:1223
StructType * getType() const
Specialization - reduce amount of casting.
Definition Constants.h:661
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:643
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
DWARF expression.
iterator_range< expr_op_iterator > expr_ops() const
unsigned getNumElements() const
static LLVM_ABI std::optional< const DIExpression * > convertToNonVariadicExpression(const DIExpression *Expr)
If Expr is a valid single-location expression, i.e.
Subprogram description. Uses SubclassData1.
Wrapper for a function that represents a value that functionally represents the original function.
Definition Constants.h:1143
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isBigEndian() const
Definition DataLayout.h:221
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:582
A debug info location.
Definition DebugLoc.h:127
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
Emits exception handling directives.
Definition EHStreamer.h:30
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
Constant * getPersonalityFn() const
Get the personality function associated with this function.
const Function & getFunction() const
Definition Function.h:167
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
GCMetadataPrinter - Emits GC metadata as assembly code.
An analysis pass which caches information about the entire Module.
Definition GCMetadata.h:237
SmallVector< std::unique_ptr< GCStrategy >, 1 >::const_iterator iterator
Definition GCMetadata.h:266
GCStrategy describes a garbage collector algorithm's code generation requirements,...
Definition GCStrategy.h:64
bool usesMetadata() const
If set, appropriate metadata tables must be emitted by the back-end (assembler, JIT,...
Definition GCStrategy.h:120
const std::string & getName() const
Return the name of the GC strategy.
Definition GCStrategy.h:90
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:759
const Constant * getResolver() const
Definition GlobalIFunc.h:73
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
bool hasSection() const
Check if this global has a custom object file section.
bool hasLinkOnceLinkage() const
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
VisibilityTypes getVisibility() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasPrivateLinkage() const
bool isTagged() const
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
LLVM_ABI bool canBenefitFromLocalAlias() const
Definition Globals.cpp:187
bool hasComdat() const
bool hasWeakLinkage() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:546
bool hasAvailableExternallyLinkage() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Itinerary data supplied by a subtarget to be used by a target.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
This is an alternative analysis pass to MachineBlockFrequencyInfo.
A helper class to return the specified delimiter string after the first invocation of operator String...
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:67
bool hasWeakDefCanBeHiddenDirective() const
Definition MCAsmInfo.h:647
bool hasSubsectionsViaSymbols() const
Definition MCAsmInfo.h:471
const char * getWeakRefDirective() const
Definition MCAsmInfo.h:645
bool hasIdentDirective() const
Definition MCAsmInfo.h:642
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:347
static const MCBinaryExpr * createGTE(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:367
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:427
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:84
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
MCFragment * getNext() const
Definition MCSection.h:177
size_t getFixedSize() const
Definition MCSection.h:223
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getOpcode() const
Definition MCInst.h:202
void setOpcode(unsigned Op)
Definition MCInst.h:201
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
MCSection * getTLSBSSSection() const
MCSection * getStackSizesSection(const MCSection &TextSec) const
MCSection * getBBAddrMapSection(const MCSection &TextSec) const
MCSection * getTLSExtraDataSection() const
MCSection * getKCFITrapSection(const MCSection &TextSec) const
MCSection * getPCSection(StringRef Name, const MCSection *TextSec) const
MCSection * getCallGraphSection(const MCSection &TextSec) const
MCSection * getDataSection() const
This represents a section on Windows.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
bool isBssSection() const
Check whether this section is "virtual", that is has no actual object file contents.
Definition MCSection.h:704
static constexpr unsigned NonUniqueID
Definition MCSection.h:585
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
Generic base class for all target subtargets.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
LLVM_ABI unsigned getBinding() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
StringRef getSymbolTableName() const
bool hasRename() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition MCSymbol.h:233
bool isUndefined() const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition MCSymbol.h:243
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition MCSymbol.h:267
void redefineIfPossible()
Prepare this symbol to be redefined.
Definition MCSymbol.h:212
const MCSymbol * getAddSym() const
Definition MCValue.h:49
int64_t getConstant() const
Definition MCValue.h:44
const MCSymbol * getSubSym() const
Definition MCValue.h:51
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition MCValue.h:54
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
Tracking metadata reference owned by Metadata.
Definition Metadata.h:908
A single uniqued string.
Definition Metadata.h:734
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
Result object for MachineBlockHashInfo.
LLVM_ABI uint64_t getMBBHash(const MachineBasicBlock &MBB) const
Legacy MachineFunctionPass for MachineBlockHashInfo.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
This class is a data container for one entry in a MachineConstantPool.
union llvm::MachineConstantPoolEntry::@004270020304201266316354007027341142157160323045 Val
The constant itself.
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
MachineConstantPoolValue * MachineCPVal
Align Alignment
The required alignment for this entry.
LLVM_ABI unsigned getSizeInBytes(const DataLayout &DL) const
LLVM_ABI SectionKind getSectionKind(const DataLayout *DL) const
Abstract base class for all machine specific constantpool value subclasses.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
const std::vector< MachineConstantPoolEntry > & getConstants() const
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
DenseMap< const MachineInstr *, CallSiteInfo > CallSiteInfoMap
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
LLVM_ABI unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_LabelDifference64
EK_LabelDifference64 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
LLVM_ABI unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
Analysis pass that exposes the MachineLoopInfo for a machine function.
An analysis that produces MachineModuleInfo for a module.
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_CImmediate
Immediate >64bit operand.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_FPImmediate
Floating-point immediate operand.
Diagnostic information for optimization analysis remarks.
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition Mangler.cpp:121
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1806
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition Constants.h:1182
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SimpleRegistryEntry< GCMetadataPrinter, CtorParamTypes... > entry
Definition Registry.h:123
static iterator_range< iterator > entries()
Definition Registry.h:183
Represents a location in source code.
Definition SMLoc.h:22
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition SectionKind.h:22
bool isCommon() const
bool isBSS() const
static SectionKind getMetadata()
static SectionKind getReadOnlyWithRel()
bool isBSSLocal() const
bool isThreadBSS() const
bool isThreadLocal() const
bool isThreadData() const
static SectionKind getReadOnly()
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:438
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:746
TypeSize getSizeInBytes() const
Definition DataLayout.h:755
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:777
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Information about stack frame layout on the target.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
@ AllowOverEstimate
Allow the reported instruction size to be larger than the actual size.
@ NoVerify
Do not verify instruction size.
Align getMinFunctionAlignment() const
Return the minimum function alignment.
virtual const MCExpr * lowerDSOLocalEquivalent(const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
virtual const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Get the target specific PC relative GOT entry relocation.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment, const Function *F) const
Given a constant with the SectionKind, return a section that it should be placed in.
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset?
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol,...
virtual void emitModuleMetadata(MCStreamer &Streamer, const Module &M) const
Emit the module-level metadata that the platform cares about.
virtual MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const
If supported, return the function entry point symbol.
virtual MCSection * getNamedSection(StringRef Name, SectionKind Kind) const
Get a section with the given name and kind, using format-appropriate defaults for section flags.
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
TargetOptions Options
unsigned EnableStaticDataPartitioning
Enables the StaticDataSplitter pass.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
Target - Wrapper for Target specific information.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition Triple.h:884
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
Value * operator=(Value *RHS)
Definition ValueHandle.h:81
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:456
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
User * user_back()
Definition Value.h:414
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
Definition Dwarf.cpp:138
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ IMAGE_SCN_MEM_READ
Definition COFF.h:336
@ IMAGE_SCN_MEM_DISCARDABLE
Definition COFF.h:331
@ IMAGE_SCN_LNK_INFO
Definition COFF.h:307
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition COFF.h:304
@ IMAGE_SCN_LNK_COMDAT
Definition COFF.h:309
@ IMAGE_SYM_CLASS_EXTERNAL
External symbol.
Definition COFF.h:224
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition COFF.h:225
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition COFF.h:459
@ IMAGE_COMDAT_SELECT_ANY
Definition COFF.h:456
@ SafeSEH
Definition COFF.h:847
@ GuardEHCont
Definition COFF.h:855
@ GuardCF
Definition COFF.h:853
@ Kernel
Definition COFF.h:857
@ IMAGE_SYM_DTYPE_NULL
No complex type; simple scalar variable.
Definition COFF.h:274
@ IMAGE_SYM_DTYPE_FUNCTION
A function that returns a base type.
Definition COFF.h:276
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition COFF.h:280
@ SHF_ALLOC
Definition ELF.h:1098
@ SHF_LINK_ORDER
Definition ELF.h:1113
@ SHF_GROUP
Definition ELF.h:1120
@ SHF_WRITE
Definition ELF.h:1095
@ SHT_LLVM_JT_SIZES
Definition ELF.h:1037
@ SHT_PROGBITS
Definition ELF.h:996
@ SHT_LLVM_SYMPART
Definition ELF.h:1029
@ STB_WEAK
Definition ELF.h:1262
constexpr uint32_t S_ATTR_LIVE_SUPPORT
Blocks are live if they reference live blocks.
Definition MachO.h:200
@ Itanium
Windows CE ARM, PowerPC, SH3, SH4.
Definition MCAsmInfo.h:52
@ X86
Windows x64, Windows Itanium (IA-64)
Definition MCAsmInfo.h:53
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
uint8_t getUnitLengthFieldByteSize(DwarfFormat Format)
Get the byte size of the unit length field depending on the DWARF format.
Definition Dwarf.h:1250
@ DWARF64
Definition Dwarf.h:93
uint8_t getDwarfOffsetByteSize(DwarfFormat Format)
The size of a reference determined by the DWARF 32/64-bit format.
Definition Dwarf.h:1208
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
DiagnosticInfoOptimizationBase::Argument NV
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:793
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI bool shouldEmitBBHash()
Returns whether -emit-bb-hash is set.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
@ MCDR_DataRegionEnd
.end_data_region
@ MCDR_DataRegionJT32
.data_region jt32
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI SmallString< 128 > getPrefetchTargetSymbolName(StringRef FunctionName, const UniqueBBID &BBID, unsigned CallsiteIndex)
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...
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
InnerAnalysisManagerProxy< MachineFunctionAnalysisManager, Function > MachineFunctionAnalysisManagerFunctionProxy
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
constexpr std::string_view HybridPatchableTargetSuffix
Definition Mangler.h:37
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:64
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ AIX
AIX Exception Handling.
Definition CodeGen.h:63
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ TypeHash
Token ID based on allocated type hash.
Definition AllocToken.h:32
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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 Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
@ MCSA_Local
.local (ELF)
@ MCSA_WeakDefAutoPrivate
.weak_def_can_be_hidden (MachO)
@ MCSA_Memtag
.memtag (ELF)
@ MCSA_WeakReference
.weak_reference (MachO)
@ MCSA_AltEntry
.alt_entry (MachO)
@ MCSA_ELF_TypeIndFunction
.type _foo, STT_GNU_IFUNC
@ MCSA_Weak
.weak
@ MCSA_WeakDefinition
.weak_definition (MachO)
@ MCSA_Global
.type _foo, @gnu_unique_object
@ MCSA_Cold
.cold (MachO)
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
@ MCSA_Invalid
Not a valid directive.
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
constexpr const char * PseudoProbeDescMetadataName
Definition PseudoProbe.h:26
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Map a basic block section ID to the begin and end symbols of that section which determine the section...
Definition AsmPrinter.h:160
llvm.global_ctors and llvm.global_dtors are arrays of Structor structs.
Definition AsmPrinter.h:581
LLVM_ABI void emit(int, MCStreamer *) const
uint64_t getEdgeCount(const UniqueBBID &SrcBBID, const UniqueBBID &SinkBBID) const
uint64_t getBlockCount(const UniqueBBID &BBID) const
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:268
static LLVM_ABI int computeInstrLatency(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Returns the latency value for the scheduling class.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition Dwarf.h:1221
This is the base class for a remark serializer.
virtual std::unique_ptr< MetaSerializer > metaSerializer(raw_ostream &OS, StringRef ExternalFilename)=0
Return the corresponding metadata serializer.