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 if (MAI.emitELFStackSection()) {
3244 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
3245 bool HasTrampolineUses =
3246 InitTrampolineIntrinsic && !InitTrampolineIntrinsic->use_empty();
3247 OutStreamer->switchSection(
3248 OutContext.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS,
3249 HasTrampolineUses ? ELF::SHF_EXECINSTR : 0U));
3250 }
3251
3252 if (TM.Options.EmitAddrsig && MAI.hasAddrsigDirective()) {
3253 // Emit address-significance attributes for all globals.
3254 OutStreamer->emitAddrsig();
3255 for (const GlobalValue &GV : M.global_values()) {
3256 if (!GV.use_empty() && !GV.isThreadLocal() &&
3257 !GV.hasDLLImportStorageClass() &&
3258 !GV.getName().starts_with("llvm.") &&
3259 !GV.hasAtLeastLocalUnnamedAddr())
3260 OutStreamer->emitAddrsigSym(getSymbol(&GV));
3261 }
3262 }
3263
3264 // Emit symbol partition specifications (ELF only).
3265 if (Target.isOSBinFormatELF()) {
3266 unsigned UniqueID = 0;
3267 for (const GlobalValue &GV : M.global_values()) {
3268 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
3269 GV.getVisibility() != GlobalValue::DefaultVisibility)
3270 continue;
3271
3272 OutStreamer->switchSection(
3273 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
3274 "", false, ++UniqueID, nullptr));
3275 OutStreamer->emitBytes(GV.getPartition());
3276 OutStreamer->emitZeros(1);
3277 OutStreamer->emitValue(
3279 MAI.getCodePointerSize());
3280 }
3281 }
3282
3283 // Allow the target to emit any magic that it wants at the end of the file,
3284 // after everything else has gone out.
3286
3287 MMI = nullptr;
3288 AddrLabelSymbols = nullptr;
3289
3290 OutStreamer->finish();
3291 OutStreamer->reset();
3292 OwnedMLI.reset();
3293 OwnedMDT.reset();
3294
3295 return false;
3296}
3297
3299 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionID());
3300 if (Res.second)
3301 Res.first->second = createTempSymbol("exception");
3302 return Res.first->second;
3303}
3304
3306 MCContext &Ctx = MF->getContext();
3307 MCSymbol *Sym = Ctx.createTempSymbol("BB" + Twine(MF->getFunctionNumber()) +
3308 "_" + Twine(MBB.getNumber()) + "_CS");
3309 CurrentFnCallsiteEndSymbols[&MBB].push_back(Sym);
3310 return Sym;
3311}
3312
3314 this->MF = &MF;
3315 const Function &F = MF.getFunction();
3316
3317 // Record that there are split-stack functions, so we will emit a special
3318 // section to tell the linker.
3319 if (MF.shouldSplitStack()) {
3320 HasSplitStack = true;
3321
3322 if (!MF.getFrameInfo().needsSplitStackProlog())
3323 HasNoSplitStack = true;
3324 } else
3325 HasNoSplitStack = true;
3326
3327 // Get the function symbol.
3328 if (!MAI.isAIX()) {
3329 CurrentFnSym = getSymbol(&MF.getFunction());
3330 } else {
3331 assert(TM.getTargetTriple().isOSAIX() &&
3332 "Only AIX uses the function descriptor hooks.");
3333 // AIX is unique here in that the name of the symbol emitted for the
3334 // function body does not have the same name as the source function's
3335 // C-linkage name.
3336 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
3337 " initalized first.");
3338
3339 // Get the function entry point symbol.
3341 }
3342
3344 CurrentFnBegin = nullptr;
3345 CurrentFnBeginLocal = nullptr;
3346 CurrentFnEnd = nullptr;
3347 CurrentSectionBeginSym = nullptr;
3349 MBBSectionRanges.clear();
3350 MBBSectionExceptionSyms.clear();
3351 bool NeedsLocalForSize = MAI.needsLocalForSize();
3352 if (F.hasFnAttribute("patchable-function-entry") ||
3353 F.hasFnAttribute("tail-pad-to-size") ||
3354 F.hasFnAttribute("function-instrument") ||
3355 F.hasFnAttribute("xray-instruction-threshold") ||
3356 needFuncLabels(MF, *this) || NeedsLocalForSize ||
3357 MF.getTarget().Options.EmitStackSizeSection ||
3358 MF.getTarget().Options.EmitCallGraphSection ||
3359 MF.getTarget().Options.BBAddrMap) {
3360 CurrentFnBegin = createTempSymbol("func_begin");
3361 if (NeedsLocalForSize)
3363 }
3364
3365 ORE = GetORE(MF);
3366}
3367
3368namespace {
3369
3370// Keep track the alignment, constpool entries per Section.
3371 struct SectionCPs {
3372 MCSection *S;
3373 Align Alignment;
3375
3376 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
3377 };
3378
3379} // end anonymous namespace
3380
3382 if (TM.Options.EnableStaticDataPartitioning && C && SDPI && PSI)
3383 return SDPI->getConstantSectionPrefix(C, PSI);
3384
3385 return "";
3386}
3387
3388/// EmitConstantPool - Print to the current output stream assembly
3389/// representations of the constants in the constant pool MCP. This is
3390/// used to print out constants which have been "spilled to memory" by
3391/// the code generator.
3393 const MachineConstantPool *MCP = MF->getConstantPool();
3394 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
3395 if (CP.empty()) return;
3396
3397 // Calculate sections for constant pool entries. We collect entries to go into
3398 // the same section together to reduce amount of section switch statements.
3399 SmallVector<SectionCPs, 4> CPSections;
3400 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
3401 const MachineConstantPoolEntry &CPE = CP[i];
3402 Align Alignment = CPE.getAlign();
3403
3405
3406 const Constant *C = nullptr;
3407 if (!CPE.isMachineConstantPoolEntry())
3408 C = CPE.Val.ConstVal;
3409
3411 getDataLayout(), Kind, C, Alignment, &MF->getFunction(),
3413
3414 // The number of sections are small, just do a linear search from the
3415 // last section to the first.
3416 bool Found = false;
3417 unsigned SecIdx = CPSections.size();
3418 while (SecIdx != 0) {
3419 if (CPSections[--SecIdx].S == S) {
3420 Found = true;
3421 break;
3422 }
3423 }
3424 if (!Found) {
3425 SecIdx = CPSections.size();
3426 CPSections.push_back(SectionCPs(S, Alignment));
3427 }
3428
3429 if (Alignment > CPSections[SecIdx].Alignment)
3430 CPSections[SecIdx].Alignment = Alignment;
3431 CPSections[SecIdx].CPEs.push_back(i);
3432 }
3433
3434 // Now print stuff into the calculated sections.
3435 const MCSection *CurSection = nullptr;
3436 unsigned Offset = 0;
3437 for (const SectionCPs &CPSection : CPSections) {
3438 for (unsigned CPI : CPSection.CPEs) {
3439 MCSymbol *Sym = GetCPISymbol(CPI);
3440 if (!Sym->isUndefined())
3441 continue;
3442
3443 if (CurSection != CPSection.S) {
3444 OutStreamer->switchSection(CPSection.S);
3445 emitAlignment(Align(CPSection.Alignment));
3446 CurSection = CPSection.S;
3447 Offset = 0;
3448 }
3449
3450 MachineConstantPoolEntry CPE = CP[CPI];
3451
3452 // Emit inter-object padding for alignment.
3453 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
3454 OutStreamer->emitZeros(NewOffset - Offset);
3455
3456 if (MAI.hasDotTypeDotSizeDirective())
3457 OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeObject);
3458 OutStreamer->emitLabel(Sym);
3459
3462 else
3464
3465 unsigned EntrySize = CPE.getSizeInBytes(getDataLayout());
3466 if (MAI.hasDotTypeDotSizeDirective())
3467 OutStreamer->emitELFSize(Sym,
3469
3470 Offset = NewOffset + EntrySize;
3471 }
3472 }
3473}
3474
3475// Print assembly representations of the jump tables used by the current
3476// function.
3478 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
3479 if (!MJTI) return;
3480
3481 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
3482 if (JT.empty()) return;
3483
3484 if (!TM.Options.EnableStaticDataPartitioning) {
3485 emitJumpTableImpl(*MJTI, llvm::to_vector(llvm::seq<unsigned>(JT.size())));
3486 return;
3487 }
3488
3489 SmallVector<unsigned> HotJumpTableIndices, ColdJumpTableIndices;
3490 // When static data partitioning is enabled, collect jump table entries that
3491 // go into the same section together to reduce the amount of section switch
3492 // statements.
3493 for (unsigned JTI = 0, JTSize = JT.size(); JTI < JTSize; ++JTI) {
3494 if (JT[JTI].Hotness == MachineFunctionDataHotness::Cold) {
3495 ColdJumpTableIndices.push_back(JTI);
3496 } else {
3497 HotJumpTableIndices.push_back(JTI);
3498 }
3499 }
3500
3501 emitJumpTableImpl(*MJTI, HotJumpTableIndices);
3502 emitJumpTableImpl(*MJTI, ColdJumpTableIndices);
3503}
3504
3505void AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
3506 ArrayRef<unsigned> JumpTableIndices) {
3508 JumpTableIndices.empty())
3509 return;
3510
3512 const Function &F = MF->getFunction();
3513 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3514 MCSection *JumpTableSection = nullptr;
3515
3516 const bool UseLabelDifference =
3519 // Pick the directive to use to print the jump table entries, and switch to
3520 // the appropriate section.
3521 const bool JTInDiffSection =
3522 !TLOF.shouldPutJumpTableInFunctionSection(UseLabelDifference, F);
3523 if (JTInDiffSection) {
3525 JumpTableSection =
3526 TLOF.getSectionForJumpTable(F, TM, &JT[JumpTableIndices.front()]);
3527 } else {
3528 JumpTableSection = TLOF.getSectionForJumpTable(F, TM);
3529 }
3530 OutStreamer->switchSection(JumpTableSection);
3531 }
3532
3533 const DataLayout &DL = MF->getDataLayout();
3535
3536 // Jump tables in code sections are marked with a data_region directive
3537 // where that's supported.
3538 if (!JTInDiffSection)
3539 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
3540
3541 for (const unsigned JumpTableIndex : JumpTableIndices) {
3542 ArrayRef<MachineBasicBlock *> JTBBs = JT[JumpTableIndex].MBBs;
3543
3544 // If this jump table was deleted, ignore it.
3545 if (JTBBs.empty())
3546 continue;
3547
3548 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
3549 /// emit a .set directive for each unique entry.
3551 MAI.doesSetDirectiveSuppressReloc()) {
3552 SmallPtrSet<const MachineBasicBlock *, 16> EmittedSets;
3553 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3554 const MCExpr *Base =
3555 TLI->getPICJumpTableRelocBaseExpr(MF, JumpTableIndex, OutContext);
3556 for (const MachineBasicBlock *MBB : JTBBs) {
3557 if (!EmittedSets.insert(MBB).second)
3558 continue;
3559
3560 // .set LJTSet, LBB32-base
3561 const MCExpr *LHS =
3563 OutStreamer->emitAssignment(
3564 GetJTSetSymbol(JumpTableIndex, MBB->getNumber()),
3566 }
3567 }
3568
3569 // On some targets (e.g. Darwin) we want to emit two consecutive labels
3570 // before each jump table. The first label is never referenced, but tells
3571 // the assembler and linker the extents of the jump table object. The
3572 // second label is actually referenced by the code.
3573 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
3574 // FIXME: This doesn't have to have any specific name, just any randomly
3575 // named and numbered local label started with 'l' would work. Simplify
3576 // GetJTISymbol.
3577 OutStreamer->emitLabel(GetJTISymbol(JumpTableIndex, true));
3578
3579 MCSymbol *JTISymbol = GetJTISymbol(JumpTableIndex);
3580 if (JTInDiffSection && MAI.hasDotTypeDotSizeDirective())
3581 OutStreamer->emitSymbolAttribute(JTISymbol, MCSA_ELF_TypeObject);
3582 OutStreamer->emitLabel(JTISymbol);
3583
3584 // Defer MCAssembler based constant folding due to a performance issue. The
3585 // label differences will be evaluated at write time.
3586 for (const MachineBasicBlock *MBB : JTBBs)
3587 emitJumpTableEntry(MJTI, MBB, JumpTableIndex);
3588
3589 if (JTInDiffSection && MAI.hasDotTypeDotSizeDirective())
3590 OutStreamer->emitELFSize(
3591 JTISymbol, MCConstantExpr::create(
3592 JTBBs.size() * MJTI.getEntrySize(DL), OutContext));
3593 }
3594
3596 emitJumpTableSizesSection(MJTI, MF->getFunction());
3597
3598 if (!JTInDiffSection)
3599 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
3600}
3601
3602void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
3603 const Function &F) const {
3604 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3605
3606 if (JT.empty())
3607 return;
3608
3609 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
3610 MCSection *JumpTableSizesSection = nullptr;
3611 StringRef sectionName = ".llvm_jump_table_sizes";
3612
3613 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
3614 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
3615
3616 if (!isCoff && !isElf)
3617 return;
3618
3619 if (isElf) {
3620 auto *LinkedToSym = static_cast<MCSymbolELF *>(CurrentFnSym);
3621 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
3622
3623 JumpTableSizesSection = OutContext.getELFSection(
3624 sectionName, ELF::SHT_LLVM_JT_SIZES, Flags, 0, GroupName, F.hasComdat(),
3625 MCSection::NonUniqueID, LinkedToSym);
3626 } else if (isCoff) {
3627 if (F.hasComdat()) {
3628 JumpTableSizesSection = OutContext.getCOFFSection(
3629 sectionName,
3632 F.getComdat()->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
3633 } else {
3634 JumpTableSizesSection = OutContext.getCOFFSection(
3638 }
3639 }
3640
3641 OutStreamer->switchSection(JumpTableSizesSection);
3642
3643 const DataLayout &DL = getDataLayout();
3644 unsigned ProgramPointerSize = DL.getPointerSize(DL.getProgramAddressSpace());
3645 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
3646 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
3647 OutStreamer->emitSymbolValue(GetJTISymbol(JTI), ProgramPointerSize);
3648 OutStreamer->emitIntValue(JTBBs.size(), ProgramPointerSize);
3649 }
3650}
3651
3652/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
3653/// current stream.
3655 const MachineBasicBlock *MBB,
3656 unsigned UID) const {
3657 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
3658 const MCExpr *Value = nullptr;
3659 switch (MJTI.getEntryKind()) {
3661 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3664 llvm_unreachable("MIPS specific");
3666 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
3667 &MJTI, MBB, UID, OutContext);
3668 break;
3670 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3671 // .word LBB123
3673 break;
3674
3677 // Each entry is the address of the block minus the address of the jump
3678 // table. This is used for PIC jump tables where gprel32 is not supported.
3679 // e.g.:
3680 // .word LBB123 - LJTI1_2
3681 // If the .set directive avoids relocations, this is emitted as:
3682 // .set L4_5_set_123, LBB123 - LJTI1_2
3683 // .word L4_5_set_123
3685 MAI.doesSetDirectiveSuppressReloc()) {
3686 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
3687 OutContext);
3688 break;
3689 }
3691 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3692 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
3694 break;
3695 }
3696 }
3697
3698 assert(Value && "Unknown entry kind!");
3699
3700 unsigned EntrySize = MJTI.getEntrySize(getDataLayout());
3701 OutStreamer->emitValue(Value, EntrySize);
3702}
3703
3704/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3705/// special global used by LLVM. If so, emit it and return true, otherwise
3706/// do nothing and return false.
3708 if (GV->getName() == "llvm.used") {
3709 if (MAI.hasNoDeadStrip()) // No need to emit this at all.
3710 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
3711 return true;
3712 }
3713
3714 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3715 if (GV->getSection() == "llvm.metadata" ||
3717 return true;
3718
3719 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3720 // For ARM64EC, print the table that maps between symbols and the
3721 // corresponding thunks to translate between x64 and AArch64 code.
3722 // This table is generated by AArch64Arm64ECCallLowering.
3723 OutStreamer->switchSection(
3724 OutContext.getCOFFSection(".hybmp$x", COFF::IMAGE_SCN_LNK_INFO));
3725 auto *Arr = cast<ConstantArray>(GV->getInitializer());
3726 for (auto &U : Arr->operands()) {
3727 auto *C = cast<Constant>(U);
3728 auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
3729 auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
3730 int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
3731
3732 if (Src->hasDLLImportStorageClass()) {
3733 // For now, we assume dllimport functions aren't directly called.
3734 // (We might change this later to match MSVC.)
3735 OutStreamer->emitCOFFSymbolIndex(
3736 OutContext.getOrCreateSymbol("__imp_" + Src->getName()));
3737 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3738 OutStreamer->emitInt32(Kind);
3739 } else {
3740 // FIXME: For non-dllimport functions, MSVC emits the same entry
3741 // twice, for reasons I don't understand. I have to assume the linker
3742 // ignores the redundant entry; there aren't any reasonable semantics
3743 // to attach to it.
3744 OutStreamer->emitCOFFSymbolIndex(getSymbol(Src));
3745 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3746 OutStreamer->emitInt32(Kind);
3747 }
3748 }
3749 return true;
3750 }
3751
3752 if (!GV->hasAppendingLinkage()) return false;
3753
3754 assert(GV->hasInitializer() && "Not a special LLVM global!");
3755
3756 if (GV->getName() == "llvm.global_ctors") {
3758 /* isCtor */ true);
3759
3760 return true;
3761 }
3762
3763 if (GV->getName() == "llvm.global_dtors") {
3765 /* isCtor */ false);
3766
3767 return true;
3768 }
3769
3770 GV->getContext().emitError(
3771 "unknown special variable with appending linkage: " +
3772 GV->getNameOrAsOperand());
3773 return true;
3774}
3775
3776/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3777/// global in the specified llvm.used list.
3778void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3779 // Should be an array of 'i8*'.
3780 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3781 const GlobalValue *GV =
3783 if (GV)
3784 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
3785 }
3786}
3787
3789 const Constant *List,
3790 SmallVector<Structor, 8> &Structors) {
3791 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3792 // the init priority.
3794 return;
3795
3796 // Gather the structors in a form that's convenient for sorting by priority.
3797 for (Value *O : cast<ConstantArray>(List)->operands()) {
3798 auto *CS = cast<ConstantStruct>(O);
3799 if (CS->getOperand(1)->isNullValue())
3800 break; // Found a null terminator, skip the rest.
3801 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3802 if (!Priority)
3803 continue; // Malformed.
3804 Structors.push_back(Structor());
3805 Structor &S = Structors.back();
3806 S.Priority = Priority->getLimitedValue(65535);
3807 S.Func = CS->getOperand(1);
3808 if (!CS->getOperand(2)->isNullValue()) {
3809 if (TM.getTargetTriple().isOSAIX()) {
3810 CS->getContext().emitError(
3811 "associated data of XXStructor list is not yet supported on AIX");
3812 }
3813
3814 S.ComdatKey =
3815 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3816 }
3817 }
3818
3819 // Emit the function pointers in the target-specific order
3820 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
3821 return L.Priority < R.Priority;
3822 });
3823}
3824
3825/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3826/// priority.
3828 bool IsCtor) {
3829 SmallVector<Structor, 8> Structors;
3830 preprocessXXStructorList(DL, List, Structors);
3831 if (Structors.empty())
3832 return;
3833
3834 // Emit the structors in reverse order if we are using the .ctor/.dtor
3835 // initialization scheme.
3836 if (!TM.Options.UseInitArray)
3837 std::reverse(Structors.begin(), Structors.end());
3838
3839 const Align Align = DL.getPointerPrefAlignment(DL.getProgramAddressSpace());
3840 for (Structor &S : Structors) {
3842 const MCSymbol *KeySym = nullptr;
3843 if (GlobalValue *GV = S.ComdatKey) {
3844 if (GV->isDeclarationForLinker())
3845 // If the associated variable is not defined in this module
3846 // (it might be available_externally, or have been an
3847 // available_externally definition that was dropped by the
3848 // EliminateAvailableExternally pass), some other TU
3849 // will provide its dynamic initializer.
3850 continue;
3851
3852 KeySym = getSymbol(GV);
3853 }
3854
3855 MCSection *OutputSection =
3856 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
3857 : Obj.getStaticDtorSection(S.Priority, KeySym));
3858 OutStreamer->switchSection(OutputSection);
3859 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3861 emitXXStructor(DL, S.Func);
3862 }
3863}
3864
3865void AsmPrinter::emitModuleIdents(Module &M) {
3866 if (!MAI.hasIdentDirective())
3867 return;
3868
3869 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
3870 for (const MDNode *N : NMD->operands()) {
3871 assert(N->getNumOperands() == 1 &&
3872 "llvm.ident metadata entry can have only one operand");
3873 const MDString *S = cast<MDString>(N->getOperand(0));
3874 OutStreamer->emitIdent(S->getString());
3875 }
3876 }
3877}
3878
3879void AsmPrinter::emitModuleCommandLines(Module &M) {
3880 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3881 if (!CommandLine)
3882 return;
3883
3884 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3885 if (!NMD || !NMD->getNumOperands())
3886 return;
3887
3888 OutStreamer->pushSection();
3889 OutStreamer->switchSection(CommandLine);
3890 OutStreamer->emitZeros(1);
3891 for (const MDNode *N : NMD->operands()) {
3892 assert(N->getNumOperands() == 1 &&
3893 "llvm.commandline metadata entry can have only one operand");
3894 const MDString *S = cast<MDString>(N->getOperand(0));
3895 OutStreamer->emitBytes(S->getString());
3896 OutStreamer->emitZeros(1);
3897 }
3898 OutStreamer->popSection();
3899}
3900
3901//===--------------------------------------------------------------------===//
3902// Emission and print routines
3903//
3904
3905/// Emit a byte directive and value.
3906///
3907void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3908
3909/// Emit a short directive and value.
3910void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3911
3912/// Emit a long directive and value.
3913void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3914
3915/// EmitSLEB128 - emit the specified signed leb128 value.
3916void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3917 if (isVerbose() && Desc)
3918 OutStreamer->AddComment(Desc);
3919
3920 OutStreamer->emitSLEB128IntValue(Value);
3921}
3922
3923void AsmPrinter::emitULEB128(uint64_t Value, const char *Desc,
3924 unsigned PadTo) const {
3925 if (isVerbose() && Desc)
3926 OutStreamer->AddComment(Desc);
3927
3928 OutStreamer->emitULEB128IntValue(Value, PadTo);
3929}
3930
3931/// Emit a long long directive and value.
3932void AsmPrinter::emitInt64(uint64_t Value) const {
3933 OutStreamer->emitInt64(Value);
3934}
3935
3936/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3937/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3938/// .set if it avoids relocations.
3940 unsigned Size) const {
3941 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3942}
3943
3944/// Emit something like ".uleb128 Hi-Lo".
3946 const MCSymbol *Lo) const {
3947 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3948}
3949
3950/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3951/// where the size in bytes of the directive is specified by Size and Label
3952/// specifies the label. This implicitly uses .set if it is available.
3954 unsigned Size,
3955 bool IsSectionRelative) const {
3956 if (IsSectionRelative) {
3957 OutStreamer->emitDwarfSectionOffset(Label, Offset, Size);
3958 return;
3959 }
3960
3961 // Emit Label+Offset (or just Label if Offset is zero)
3962 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
3963 if (Offset)
3966
3967 OutStreamer->emitValue(Expr, Size);
3968}
3969
3970//===----------------------------------------------------------------------===//
3971
3972// EmitAlignment - Emit an alignment directive to the specified power of
3973// two boundary. If a global value is specified, and if that global has
3974// an explicit alignment requested, it will override the alignment request
3975// if required for correctness.
3977 unsigned MaxBytesToEmit) const {
3978 if (GV)
3979 Alignment = getGVAlignment(GV, GV->getDataLayout(), Alignment);
3980
3981 if (Alignment == Align(1))
3982 return Alignment; // 1-byte aligned: no need to emit alignment.
3983
3984 if (getCurrentSection()->isText()) {
3985 const MCSubtargetInfo *STI = nullptr;
3986 if (this->MF)
3987 STI = &getSubtargetInfo();
3988 else
3989 STI = &TM.getMCSubtargetInfo();
3990 OutStreamer->emitCodeAlignment(Alignment, *STI, MaxBytesToEmit);
3991 } else
3992 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3993 return Alignment;
3994}
3995
3996//===----------------------------------------------------------------------===//
3997// Constant emission.
3998//===----------------------------------------------------------------------===//
3999
4001 const Constant *BaseCV,
4002 uint64_t Offset) {
4003 MCContext &Ctx = OutContext;
4004
4005 if (CV->isNullValue() || isa<UndefValue>(CV))
4006 return MCConstantExpr::create(0, Ctx);
4007
4008 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
4009 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
4010
4011 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV))
4012 return MCConstantExpr::create(CB->getZExtValue(), Ctx);
4013
4014 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV))
4015 return lowerConstantPtrAuth(*CPA);
4016
4017 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
4018 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
4019
4020 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
4021 return lowerBlockAddressConstant(*BA);
4022
4023 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
4025 getSymbol(Equiv->getGlobalValue()), nullptr, 0, std::nullopt, TM);
4026
4027 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
4028 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
4029
4030 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
4031 if (!CE) {
4032 llvm_unreachable("Unknown constant value to lower!");
4033 }
4034
4035 // The constant expression opcodes are limited to those that are necessary
4036 // to represent relocations on supported targets. Expressions involving only
4037 // constant addresses are constant folded instead.
4038 switch (CE->getOpcode()) {
4039 default:
4040 break; // Error
4041 case Instruction::AddrSpaceCast: {
4042 const Constant *Op = CE->getOperand(0);
4043 unsigned DstAS = CE->getType()->getPointerAddressSpace();
4044 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
4045 if (TM.isNoopAddrSpaceCast(getDataLayout(), SrcAS, DstAS))
4046 return lowerConstant(Op);
4047
4048 break; // Error
4049 }
4050 case Instruction::GetElementPtr: {
4051 // Generate a symbolic expression for the byte address
4052 APInt OffsetAI(getDataLayout().getIndexTypeSizeInBits(CE->getType()), 0);
4053 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
4054
4055 const MCExpr *Base = lowerConstant(CE->getOperand(0));
4056 if (!OffsetAI)
4057 return Base;
4058
4059 int64_t Offset = OffsetAI.getSExtValue();
4061 Ctx);
4062 }
4063
4064 case Instruction::Trunc:
4065 // We emit the value and depend on the assembler to truncate the generated
4066 // expression properly. This is important for differences between
4067 // blockaddress labels. Since the two labels are in the same function, it
4068 // is reasonable to treat their delta as a 32-bit value.
4069 [[fallthrough]];
4070 case Instruction::BitCast:
4071 return lowerConstant(CE->getOperand(0), BaseCV, Offset);
4072
4073 case Instruction::IntToPtr: {
4074 const DataLayout &DL = getDataLayout();
4075
4076 // Handle casts to pointers by changing them into casts to the appropriate
4077 // integer type. This promotes constant folding and simplifies this code.
4078 Constant *Op = CE->getOperand(0);
4079 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
4080 /*IsSigned*/ false, DL);
4081 if (Op)
4082 return lowerConstant(Op);
4083
4084 break; // Error
4085 }
4086
4087 case Instruction::PtrToAddr:
4088 case Instruction::PtrToInt: {
4089 const DataLayout &DL = getDataLayout();
4090
4091 // Support only foldable casts to/from pointers that can be eliminated by
4092 // changing the pointer to the appropriately sized integer type.
4093 Constant *Op = CE->getOperand(0);
4094 Type *Ty = CE->getType();
4095
4096 const MCExpr *OpExpr = lowerConstant(Op);
4097
4098 // We can emit the pointer value into this slot if the slot is an
4099 // integer slot equal to the size of the pointer.
4100 //
4101 // If the pointer is larger than the resultant integer, then
4102 // as with Trunc just depend on the assembler to truncate it.
4103 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
4104 DL.getTypeAllocSize(Op->getType()).getFixedValue())
4105 return OpExpr;
4106
4107 break; // Error
4108 }
4109
4110 case Instruction::Sub: {
4111 GlobalValue *LHSGV, *RHSGV;
4112 APInt LHSOffset, RHSOffset;
4113 DSOLocalEquivalent *DSOEquiv;
4114 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
4115 getDataLayout(), &DSOEquiv) &&
4116 IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
4117 getDataLayout())) {
4118 auto *LHSSym = getSymbol(LHSGV);
4119 auto *RHSSym = getSymbol(RHSGV);
4120 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
4121 std::optional<int64_t> PCRelativeOffset;
4122 if (getObjFileLowering().hasPLTPCRelative() && RHSGV == BaseCV)
4123 PCRelativeOffset = Offset;
4124
4125 // Try the generic symbol difference first.
4127 LHSGV, RHSGV, Addend, PCRelativeOffset, TM);
4128
4129 // (ELF-specific) If the generic symbol difference does not apply, and
4130 // LHS is a dso_local_equivalent of a function, reference the PLT entry
4131 // instead. Note: A default visibility symbol is by default preemptible
4132 // during linking, and should not be referenced with PC-relative
4133 // relocations. Therefore, use a PLT relocation even if the function is
4134 // dso_local.
4135 if (DSOEquiv && TM.getTargetTriple().isOSBinFormatELF())
4137 LHSSym, RHSSym, Addend, PCRelativeOffset, TM);
4138
4139 // Otherwise, return LHS-RHS+Addend.
4140 if (!Res) {
4141 Res =
4143 MCSymbolRefExpr::create(RHSSym, Ctx), Ctx);
4144 if (Addend != 0)
4146 Res, MCConstantExpr::create(Addend, Ctx), Ctx);
4147 }
4148 return Res;
4149 }
4150
4151 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4152 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4153 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
4154 break;
4155 }
4156
4157 case Instruction::Add: {
4158 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4159 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4160 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
4161 }
4162 }
4163
4164 // If the code isn't optimized, there may be outstanding folding
4165 // opportunities. Attempt to fold the expression using DataLayout as a
4166 // last resort before giving up.
4168 if (C != CE)
4169 return lowerConstant(C);
4170
4171 // Otherwise report the problem to the user.
4172 std::string S;
4173 raw_string_ostream OS(S);
4174 OS << "unsupported expression in static initializer: ";
4175 CE->printAsOperand(OS, /*PrintType=*/false,
4176 !MF ? nullptr : MF->getFunction().getParent());
4177 CE->getContext().emitError(S);
4178 return MCConstantExpr::create(0, Ctx);
4179}
4180
4181static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
4182 AsmPrinter &AP,
4183 const Constant *BaseCV = nullptr,
4184 uint64_t Offset = 0,
4185 AsmPrinter::AliasMapTy *AliasList = nullptr);
4186
4187static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
4188static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
4189
4190/// isRepeatedByteSequence - Determine whether the given value is
4191/// composed of a repeated sequence of identical bytes and return the
4192/// byte value. If it is not a repeated sequence, return -1.
4194 StringRef Data = V->getRawDataValues();
4195 assert(!Data.empty() && "Empty aggregates should be CAZ node");
4196 char C = Data[0];
4197 for (unsigned i = 1, e = Data.size(); i != e; ++i)
4198 if (Data[i] != C) return -1;
4199 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
4200}
4201
4202/// isRepeatedByteSequence - Determine whether the given value is
4203/// composed of a repeated sequence of identical bytes and return the
4204/// byte value. If it is not a repeated sequence, return -1.
4205static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
4206 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
4207 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
4208 assert(Size % 8 == 0);
4209
4210 // Extend the element to take zero padding into account.
4211 APInt Value = CI->getValue().zext(Size);
4212 if (!Value.isSplat(8))
4213 return -1;
4214
4215 return Value.zextOrTrunc(8).getZExtValue();
4216 }
4217 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
4218 // Make sure all array elements are sequences of the same repeated
4219 // byte.
4220 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
4221 Constant *Op0 = CA->getOperand(0);
4222 int Byte = isRepeatedByteSequence(Op0, DL);
4223 if (Byte == -1)
4224 return -1;
4225
4226 // All array elements must be equal.
4227 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
4228 if (CA->getOperand(i) != Op0)
4229 return -1;
4230 return Byte;
4231 }
4232
4234 return isRepeatedByteSequence(CDS);
4235
4236 return -1;
4237}
4238
4240 AsmPrinter::AliasMapTy *AliasList) {
4241 if (AliasList) {
4242 auto AliasIt = AliasList->find(Offset);
4243 if (AliasIt != AliasList->end()) {
4244 for (const GlobalAlias *GA : AliasIt->second)
4245 AP.OutStreamer->emitLabel(AP.getSymbol(GA));
4246 AliasList->erase(Offset);
4247 }
4248 }
4249}
4250
4252 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
4253 AsmPrinter::AliasMapTy *AliasList) {
4254 // See if we can aggregate this into a .fill, if so, emit it as such.
4255 int Value = isRepeatedByteSequence(CDS, DL);
4256 if (Value != -1) {
4257 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
4258 // Don't emit a 1-byte object as a .fill.
4259 if (Bytes > 1)
4260 return AP.OutStreamer->emitFill(Bytes, Value);
4261 }
4262
4263 // If this can be emitted with .ascii/.asciz, emit it as such.
4264 if (CDS->isString())
4265 return AP.OutStreamer->emitBytes(CDS->getAsString());
4266
4267 // Otherwise, emit the values in successive locations.
4268 uint64_t ElementByteSize = CDS->getElementByteSize();
4269 if (isa<IntegerType>(CDS->getElementType()) ||
4270 isa<ByteType>(CDS->getElementType())) {
4271 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4272 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4273 if (AP.isVerbose())
4274 AP.OutStreamer->getCommentOS()
4275 << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
4276 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
4277 ElementByteSize);
4278 }
4279 } else {
4280 Type *ET = CDS->getElementType();
4281 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4282 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4284 }
4285 }
4286
4287 unsigned Size = DL.getTypeAllocSize(CDS->getType());
4288 unsigned EmittedSize =
4289 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
4290 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
4291 if (unsigned Padding = Size - EmittedSize)
4292 AP.OutStreamer->emitZeros(Padding);
4293}
4294
4296 const ConstantArray *CA, AsmPrinter &AP,
4297 const Constant *BaseCV, uint64_t Offset,
4298 AsmPrinter::AliasMapTy *AliasList) {
4299 // See if we can aggregate some values. Make sure it can be
4300 // represented as a series of bytes of the constant value.
4301 int Value = isRepeatedByteSequence(CA, DL);
4302
4303 if (Value != -1) {
4304 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
4305 AP.OutStreamer->emitFill(Bytes, Value);
4306 } else {
4307 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
4308 emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
4309 AliasList);
4310 Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
4311 }
4312 }
4313}
4314
4315static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
4316
4317static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
4318 AsmPrinter &AP,
4319 AsmPrinter::AliasMapTy *AliasList) {
4320 uint64_t AllocSize = DL.getTypeAllocSize(CV->getType());
4321
4322 if (CV->isNullValue())
4323 return AP.OutStreamer->emitZeros(AllocSize);
4324
4325 auto *VTy = cast<FixedVectorType>(CV->getType());
4326 Type *ElementType = VTy->getElementType();
4327 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
4328 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
4329 uint64_t EmittedSize;
4330 if (ElementSizeInBits != ElementAllocSizeInBits) {
4331 // If the allocation size of an element is different from the size in bits,
4332 // printing each element separately will insert incorrect padding.
4333 //
4334 // The general algorithm here is complicated; instead of writing it out
4335 // here, just use the existing code in ConstantFolding.
4336 Type *IntT =
4337 IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
4339 ConstantExpr::getBitCast(const_cast<Constant *>(CV), IntT), DL));
4340 if (!CI) {
4342 "Cannot lower vector global with unusual element type");
4343 }
4344 emitGlobalAliasInline(AP, 0, AliasList);
4346 EmittedSize = DL.getTypeStoreSize(CV->getType());
4347 } else {
4348 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
4349 emitGlobalAliasInline(AP, AllocSize * I, AliasList);
4351 }
4352 EmittedSize = DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
4353 }
4354
4355 if (unsigned Padding = AllocSize - EmittedSize)
4356 AP.OutStreamer->emitZeros(Padding);
4357}
4358
4360 const ConstantStruct *CS, AsmPrinter &AP,
4361 const Constant *BaseCV, uint64_t Offset,
4362 AsmPrinter::AliasMapTy *AliasList) {
4363 // Print the fields in successive locations. Pad to align if needed!
4364 uint64_t Size = DL.getTypeAllocSize(CS->getType());
4365 const StructLayout *Layout = DL.getStructLayout(CS->getType());
4366 uint64_t SizeSoFar = 0;
4367 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
4368 const Constant *Field = CS->getOperand(I);
4369
4370 // Print the actual field value.
4371 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
4372 AliasList);
4373
4374 // Check if padding is needed and insert one or more 0s.
4375 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
4376 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
4377 Layout->getElementOffset(I)) -
4378 FieldSize;
4379 SizeSoFar += FieldSize + PadSize;
4380
4381 // Insert padding - this may include padding to increase the size of the
4382 // current field up to the ABI size (if the struct is not packed) as well
4383 // as padding to ensure that the next field starts at the right offset.
4384 AP.OutStreamer->emitZeros(PadSize);
4385 }
4386 assert(SizeSoFar == Layout->getSizeInBytes() &&
4387 "Layout of constant struct may be incorrect!");
4388}
4389
4390static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
4391 assert(ET && "Unknown float type");
4392 APInt API = APF.bitcastToAPInt();
4393
4394 // First print a comment with what we think the original floating-point value
4395 // should have been.
4396 if (AP.isVerbose()) {
4397 SmallString<8> StrVal;
4398 APF.toString(StrVal);
4399 ET->print(AP.OutStreamer->getCommentOS());
4400 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
4401 }
4402
4403 // Now iterate through the APInt chunks, emitting them in endian-correct
4404 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
4405 // floats).
4406 unsigned NumBytes = API.getBitWidth() / 8;
4407 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
4408 const uint64_t *p = API.getRawData();
4409
4410 // PPC's long double has odd notions of endianness compared to how LLVM
4411 // handles it: p[0] goes first for *big* endian on PPC.
4412 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
4413 int Chunk = API.getNumWords() - 1;
4414
4415 if (TrailingBytes)
4416 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
4417
4418 for (; Chunk >= 0; --Chunk)
4419 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4420 } else {
4421 unsigned Chunk;
4422 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
4423 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4424
4425 if (TrailingBytes)
4426 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
4427 }
4428
4429 // Emit the tail padding for the long double.
4430 const DataLayout &DL = AP.getDataLayout();
4431 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
4432}
4433
4434static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
4435 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
4436}
4437
4439 uint64_t TypeStoreSize,
4440 AsmPrinter &AP) {
4441 const DataLayout &DL = AP.getDataLayout();
4442 unsigned BitWidth = Val.getBitWidth();
4443
4444 // Copy the value as we may massage the layout for constants whose bit width
4445 // is not a multiple of 64-bits.
4446 APInt Realigned(Val);
4447 uint64_t ExtraBits = 0;
4448 unsigned ExtraBitsSize = BitWidth & 63;
4449
4450 if (ExtraBitsSize) {
4451 // The bit width of the data is not a multiple of 64-bits.
4452 // The extra bits are expected to be at the end of the chunk of the memory.
4453 // Little endian:
4454 // * Nothing to be done, just record the extra bits to emit.
4455 // Big endian:
4456 // * Record the extra bits to emit.
4457 // * Realign the raw data to emit the chunks of 64-bits.
4458 if (DL.isBigEndian()) {
4459 // Basically the structure of the raw data is a chunk of 64-bits cells:
4460 // 0 1 BitWidth / 64
4461 // [chunk1][chunk2] ... [chunkN].
4462 // The most significant chunk is chunkN and it should be emitted first.
4463 // However, due to the alignment issue chunkN contains useless bits.
4464 // Realign the chunks so that they contain only useful information:
4465 // ExtraBits 0 1 (BitWidth / 64) - 1
4466 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
4467 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
4468 ExtraBits =
4469 Realigned.getRawData()[0] & (((uint64_t)-1) >> (64 - ExtraBitsSize));
4470 if (BitWidth >= 64)
4471 Realigned.lshrInPlace(ExtraBitsSize);
4472 } else
4473 ExtraBits = Realigned.getRawData()[BitWidth / 64];
4474 }
4475
4476 // We don't expect assemblers to support data directives
4477 // for more than 64 bits, so we emit the data in at most 64-bit
4478 // quantities at a time.
4479 const uint64_t *RawData = Realigned.getRawData();
4480 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
4481 uint64_t ChunkVal = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
4482 AP.OutStreamer->emitIntValue(ChunkVal, 8);
4483 }
4484
4485 if (ExtraBitsSize) {
4486 // Emit the extra bits after the 64-bits chunks.
4487
4488 // Emit a directive that fills the expected size.
4489 uint64_t Size = TypeStoreSize - (BitWidth / 64) * 8;
4490 assert(Size && Size * 8 >= ExtraBitsSize &&
4491 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) ==
4492 ExtraBits &&
4493 "Directive too small for extra bits.");
4494 AP.OutStreamer->emitIntValue(ExtraBits, Size);
4495 }
4496}
4497
4499 AsmPrinter &AP) {
4501 CB->getValue(), AP.getDataLayout().getTypeStoreSize(CB->getType()), AP);
4502}
4503
4508
4509/// Transform a not absolute MCExpr containing a reference to a GOT
4510/// equivalent global, by a target specific GOT pc relative access to the
4511/// final symbol.
4513 const Constant *BaseCst,
4514 uint64_t Offset) {
4515 // The global @foo below illustrates a global that uses a got equivalent.
4516 //
4517 // @bar = global i32 42
4518 // @gotequiv = private unnamed_addr constant i32* @bar
4519 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
4520 // i64 ptrtoint (i32* @foo to i64))
4521 // to i32)
4522 //
4523 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
4524 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
4525 // form:
4526 //
4527 // foo = cstexpr, where
4528 // cstexpr := <gotequiv> - "." + <cst>
4529 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
4530 //
4531 // After canonicalization by evaluateAsRelocatable `ME` turns into:
4532 //
4533 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
4534 // gotpcrelcst := <offset from @foo base> + <cst>
4535 MCValue MV;
4536 if (!(*ME)->evaluateAsRelocatable(MV, nullptr) || MV.isAbsolute())
4537 return;
4538 const MCSymbol *GOTEquivSym = MV.getAddSym();
4539 if (!GOTEquivSym)
4540 return;
4541
4542 // Check that GOT equivalent symbol is cached.
4543 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
4544 return;
4545
4546 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
4547 if (!BaseGV)
4548 return;
4549
4550 // Check for a valid base symbol
4551 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
4552 const MCSymbol *SymB = MV.getSubSym();
4553
4554 if (!SymB || BaseSym != SymB)
4555 return;
4556
4557 // Make sure to match:
4558 //
4559 // gotpcrelcst := <offset from @foo base> + <cst>
4560 //
4561 int64_t GOTPCRelCst = Offset + MV.getConstant();
4562 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
4563 return;
4564
4565 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
4566 //
4567 // bar:
4568 // .long 42
4569 // gotequiv:
4570 // .quad bar
4571 // foo:
4572 // .long gotequiv - "." + <cst>
4573 //
4574 // is replaced by the target specific equivalent to:
4575 //
4576 // bar:
4577 // .long 42
4578 // foo:
4579 // .long bar@GOTPCREL+<gotpcrelcst>
4580 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
4581 const GlobalVariable *GV = Result.first;
4582 int NumUses = (int)Result.second;
4583 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
4584 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
4586 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
4587
4588 // Update GOT equivalent usage information
4589 --NumUses;
4590 if (NumUses >= 0)
4591 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
4592}
4593
4594static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
4595 AsmPrinter &AP, const Constant *BaseCV,
4597 AsmPrinter::AliasMapTy *AliasList) {
4598 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
4599 "AliasList only expected for XCOFF");
4600 emitGlobalAliasInline(AP, Offset, AliasList);
4601 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4602
4603 // Globals with sub-elements such as combinations of arrays and structs
4604 // are handled recursively by emitGlobalConstantImpl. Keep track of the
4605 // constant symbol base and the current position with BaseCV and Offset.
4606 if (!BaseCV && CV->hasOneUse())
4607 BaseCV = dyn_cast<Constant>(CV->user_back());
4608
4610 StructType *structType;
4611 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->getType()))) {
4612 unsigned numElements = {structType->getNumElements()};
4613 if (numElements != 0) {
4614 // Handle cases of aliases to direct struct elements
4615 const StructLayout *Layout = DL.getStructLayout(structType);
4616 uint64_t SizeSoFar = 0;
4617 for (unsigned int i = 0; i < numElements - 1; ++i) {
4618 uint64_t GapToNext = Layout->getElementOffset(i + 1) - SizeSoFar;
4619 AP.OutStreamer->emitZeros(GapToNext);
4620 SizeSoFar += GapToNext;
4621 emitGlobalAliasInline(AP, Offset + SizeSoFar, AliasList);
4622 }
4623 AP.OutStreamer->emitZeros(Size - SizeSoFar);
4624 return;
4625 }
4626 }
4627 return AP.OutStreamer->emitZeros(Size);
4628 }
4629
4630 if (isa<UndefValue>(CV))
4631 return AP.OutStreamer->emitZeros(Size);
4632
4633 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
4634 if (isa<VectorType>(CV->getType()))
4635 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4636
4637 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4638 if (StoreSize <= 8) {
4639 if (AP.isVerbose())
4640 AP.OutStreamer->getCommentOS()
4641 << format("0x%" PRIx64 "\n", CI->getZExtValue());
4642 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
4643 } else {
4645 }
4646
4647 // Emit tail padding if needed
4648 if (Size != StoreSize)
4649 AP.OutStreamer->emitZeros(Size - StoreSize);
4650
4651 return;
4652 }
4653
4654 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV)) {
4655 if (isa<VectorType>(CV->getType()))
4656 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4657
4658 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4659 if (StoreSize <= 8) {
4660 if (AP.isVerbose())
4661 AP.OutStreamer->getCommentOS()
4662 << format("0x%" PRIx64 "\n", CB->getZExtValue());
4663 AP.OutStreamer->emitIntValue(CB->getZExtValue(), StoreSize);
4664 } else {
4666 }
4667
4668 // Emit tail padding if needed
4669 if (Size != StoreSize)
4670 AP.OutStreamer->emitZeros(Size - StoreSize);
4671
4672 return;
4673 }
4674
4675 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
4676 if (isa<VectorType>(CV->getType()))
4677 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4678 else
4679 return emitGlobalConstantFP(CFP, AP);
4680 }
4681
4682 if (isa<ConstantPointerNull>(CV)) {
4683 if (isa<VectorType>(CV->getType()))
4684 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4685
4686 // The data layout only allows a null pointer with all bits zero or all
4687 // bits one. Some pointers can be wider than 64 bits.
4688 bool AllOnes =
4689 !DL.getNullPtrValue(CV->getType()->getPointerAddressSpace()).isZero();
4690 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4691 if (StoreSize <= 8)
4692 AP.OutStreamer->emitIntValue(AllOnes ? -1 : 0, StoreSize);
4693 else
4694 AP.OutStreamer->emitFill(StoreSize, AllOnes ? 0xFF : 0);
4695 // Emit tail padding if needed.
4696 if (Size != StoreSize)
4697 AP.OutStreamer->emitZeros(Size - StoreSize);
4698 return;
4699 }
4700
4702 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
4703
4704 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
4705 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
4706
4707 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
4708 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
4709
4710 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
4711 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
4712 // vectors).
4713 if (CE->getOpcode() == Instruction::BitCast)
4714 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
4715
4716 if (Size > 8) {
4717 // If the constant expression's size is greater than 64-bits, then we have
4718 // to emit the value in chunks. Try to constant fold the value and emit it
4719 // that way.
4720 Constant *New = ConstantFoldConstant(CE, DL);
4721 if (New != CE)
4722 return emitGlobalConstantImpl(DL, New, AP);
4723 }
4724 }
4725
4726 if (isa<ConstantVector>(CV))
4727 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4728
4729 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4730 // thread the streamer with EmitValue.
4731 const MCExpr *ME = AP.lowerConstant(CV, BaseCV, Offset);
4732
4733 // Since lowerConstant already folded and got rid of all IR pointer and
4734 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4735 // directly.
4737 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
4738
4739 AP.OutStreamer->emitValue(ME, Size);
4740}
4741
4742/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4744 AliasMapTy *AliasList) {
4745 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4746 if (Size)
4747 emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
4748 else if (MAI.hasSubsectionsViaSymbols()) {
4749 // If the global has zero size, emit a single byte so that two labels don't
4750 // look like they are at the same location.
4751 OutStreamer->emitIntValue(0, 1);
4752 }
4753 if (!AliasList)
4754 return;
4755 // TODO: These remaining aliases are not emitted in the correct location. Need
4756 // to handle the case where the alias offset doesn't refer to any sub-element.
4757 for (auto &AliasPair : *AliasList) {
4758 for (const GlobalAlias *GA : AliasPair.second)
4759 OutStreamer->emitLabel(getSymbol(GA));
4760 }
4761}
4762
4764 // Target doesn't support this yet!
4765 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4766}
4767
4769 if (Offset > 0)
4770 OS << '+' << Offset;
4771 else if (Offset < 0)
4772 OS << Offset;
4773}
4774
4775void AsmPrinter::emitNops(unsigned N) {
4776 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
4777 for (; N; --N)
4779}
4780
4781//===----------------------------------------------------------------------===//
4782// Symbol Lowering Routines.
4783//===----------------------------------------------------------------------===//
4784
4786 return OutContext.createTempSymbol(Name, true);
4787}
4788
4790 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4791 BA->getBasicBlock());
4792}
4793
4795 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4796}
4797
4801
4802/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4803MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4804 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment() ||
4805 getSubtargetInfo().getTargetTriple().isUEFI()) {
4806 const MachineConstantPoolEntry &CPE =
4807 MF->getConstantPool()->getConstants()[CPID];
4808 if (!CPE.isMachineConstantPoolEntry()) {
4809 const DataLayout &DL = MF->getDataLayout();
4810 SectionKind Kind = CPE.getSectionKind(&DL);
4811 const Constant *C = CPE.Val.ConstVal;
4812 Align Alignment = CPE.Alignment;
4814 DL, Kind, C, Alignment, &MF->getFunction());
4815 if (S && TM.getTargetTriple().isOSBinFormatCOFF()) {
4816 if (MCSymbol *Sym =
4817 static_cast<const MCSectionCOFF *>(S)->getCOMDATSymbol()) {
4818 if (Sym->isUndefined())
4819 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
4820 return Sym;
4821 }
4822 }
4823 }
4824 }
4825
4826 const DataLayout &DL = getDataLayout();
4827 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4828 "CPI" + Twine(getFunctionNumber()) + "_" +
4829 Twine(CPID));
4830}
4831
4832/// GetJTISymbol - Return the symbol for the specified jump table entry.
4833MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4834 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
4835}
4836
4837/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4838/// FIXME: privatize to AsmPrinter.
4839MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4840 const DataLayout &DL = getDataLayout();
4841 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4842 Twine(getFunctionNumber()) + "_" +
4843 Twine(UID) + "_set_" + Twine(MBBID));
4844}
4845
4850
4851/// Return the MCSymbol for the specified ExternalSymbol.
4853 SmallString<60> NameStr;
4855 return OutContext.getOrCreateSymbol(NameStr);
4856}
4857
4858/// PrintParentLoopComment - Print comments about parent loops of this one.
4860 unsigned FunctionNumber) {
4861 if (!Loop) return;
4862 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
4863 OS.indent(Loop->getLoopDepth()*2)
4864 << "Parent Loop BB" << FunctionNumber << "_"
4865 << Loop->getHeader()->getNumber()
4866 << " Depth=" << Loop->getLoopDepth() << '\n';
4867}
4868
4869/// PrintChildLoopComment - Print comments about child loops within
4870/// the loop for this basic block, with nesting.
4872 unsigned FunctionNumber) {
4873 // Add child loop information
4874 for (const MachineLoop *CL : *Loop) {
4875 OS.indent(CL->getLoopDepth()*2)
4876 << "Child Loop BB" << FunctionNumber << "_"
4877 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4878 << '\n';
4879 PrintChildLoopComment(OS, CL, FunctionNumber);
4880 }
4881}
4882
4883/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4885 const MachineLoopInfo *LI,
4886 const AsmPrinter &AP) {
4887 // Add loop depth information
4888 const MachineLoop *Loop = LI->getLoopFor(&MBB);
4889 if (!Loop) return;
4890
4891 MachineBasicBlock *Header = Loop->getHeader();
4892 assert(Header && "No header for loop");
4893
4894 // If this block is not a loop header, just print out what is the loop header
4895 // and return.
4896 if (Header != &MBB) {
4897 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
4898 Twine(AP.getFunctionNumber())+"_" +
4900 " Depth="+Twine(Loop->getLoopDepth()));
4901 return;
4902 }
4903
4904 // Otherwise, it is a loop header. Print out information about child and
4905 // parent loops.
4906 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4907
4909
4910 OS << "=>";
4911 OS.indent(Loop->getLoopDepth()*2-2);
4912
4913 OS << "This ";
4914 if (Loop->isInnermost())
4915 OS << "Inner ";
4916 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4917
4919}
4920
4921/// emitBasicBlockStart - This method prints the label for the specified
4922/// MachineBasicBlock, an alignment (if present) and a comment describing
4923/// it if appropriate.
4925 // End the previous funclet and start a new one.
4926 if (MBB.isEHFuncletEntry()) {
4927 for (auto &Handler : Handlers) {
4928 Handler->endFunclet();
4929 Handler->beginFunclet(MBB);
4930 }
4931 for (auto &Handler : EHHandlers) {
4932 Handler->endFunclet();
4933 Handler->beginFunclet(MBB);
4934 }
4935 }
4936
4937 // Switch to a new section if this basic block must begin a section. The
4938 // entry block is always placed in the function section and is handled
4939 // separately.
4940 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4941 OutStreamer->switchSection(
4942 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
4943 MBB, TM));
4944 CurrentSectionBeginSym = MBB.getSymbol();
4945 }
4946
4947 for (auto &Handler : Handlers)
4948 Handler->beginCodeAlignment(MBB);
4949
4950 // Emit an alignment directive for this block, if needed.
4951 const Align Alignment = MBB.getAlignment();
4952 if (Alignment != Align(1))
4953 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
4954
4955 // If the block has its address taken, emit any labels that were used to
4956 // reference the block. It is possible that there is more than one label
4957 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4958 // the references were generated.
4959 if (MBB.isIRBlockAddressTaken()) {
4960 if (isVerbose())
4961 OutStreamer->AddComment("Block address taken");
4962
4963 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4964 assert(BB && BB->hasAddressTaken() && "Missing BB");
4965 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4966 OutStreamer->emitLabel(Sym);
4967 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4968 OutStreamer->AddComment("Block address taken");
4969 } else if (isVerbose() && MBB.isInlineAsmBrIndirectTarget()) {
4970 OutStreamer->AddComment("Inline asm indirect target");
4971 }
4972
4973 // Print some verbose block comments.
4974 if (isVerbose()) {
4975 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4976 if (BB->hasName()) {
4977 BB->printAsOperand(OutStreamer->getCommentOS(),
4978 /*PrintType=*/false, BB->getModule());
4979 OutStreamer->getCommentOS() << '\n';
4980 }
4981 }
4982
4983 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4985 }
4986
4987 // Print the main label for the block.
4988 if (shouldEmitLabelForBasicBlock(MBB)) {
4989 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4990 OutStreamer->AddComment("Label of block must be emitted");
4991 OutStreamer->emitLabel(MBB.getSymbol());
4992 } else {
4993 if (isVerbose()) {
4994 // NOTE: Want this comment at start of line, don't emit with AddComment.
4995 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
4996 false);
4997 }
4998 }
4999
5000 if (MBB.isEHContTarget() &&
5001 ModuleExceptionModel == ExceptionHandling::WinEH) {
5002 OutStreamer->emitLabel(MBB.getEHContSymbol());
5003 }
5004
5005 // With BB sections, each basic block must handle CFI information on its own
5006 // if it begins a section (Entry block call is handled separately, next to
5007 // beginFunction).
5008 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
5009 for (auto &Handler : Handlers)
5010 Handler->beginBasicBlockSection(MBB);
5011 for (auto &Handler : EHHandlers)
5012 Handler->beginBasicBlockSection(MBB);
5013 }
5014}
5015
5017 // Check if CFI information needs to be updated for this MBB with basic block
5018 // sections.
5019 if (MBB.isEndSection()) {
5020 for (auto &Handler : Handlers)
5021 Handler->endBasicBlockSection(MBB);
5022 for (auto &Handler : EHHandlers)
5023 Handler->endBasicBlockSection(MBB);
5024 }
5025}
5026
5027void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
5028 bool IsDefinition) const {
5030
5031 switch (Visibility) {
5032 default: break;
5034 if (IsDefinition)
5035 Attr = MAI.getHiddenVisibilityAttr();
5036 else
5037 Attr = MAI.getHiddenDeclarationVisibilityAttr();
5038 break;
5040 Attr = MAI.getProtectedVisibilityAttr();
5041 break;
5042 }
5043
5044 if (Attr != MCSA_Invalid)
5045 OutStreamer->emitSymbolAttribute(Sym, Attr);
5046}
5047
5048bool AsmPrinter::shouldEmitLabelForBasicBlock(
5049 const MachineBasicBlock &MBB) const {
5050 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
5051 // in the labels mode (option `=labels`) and every section beginning in the
5052 // sections mode (`=all` and `=list=`).
5053 if ((MF->getTarget().Options.BBAddrMap || MBB.isBeginSection()) &&
5054 !MBB.isEntryBlock())
5055 return true;
5056 // A label is needed for any block with at least one predecessor (when that
5057 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
5058 // entry, or if a label is forced).
5059 return !MBB.pred_empty() &&
5060 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
5061 MBB.hasLabelMustBeEmitted());
5062}
5063
5064/// isBlockOnlyReachableByFallthough - Return true if the basic block has
5065/// exactly one predecessor and the control transfer mechanism between
5066/// the predecessor and this block is a fall-through.
5069 // If this is a landing pad, it isn't a fall through. If it has no preds,
5070 // then nothing falls through to it.
5071 if (MBB->isEHPad() || MBB->pred_empty())
5072 return false;
5073
5074 // If there isn't exactly one predecessor, it can't be a fall through.
5075 if (MBB->pred_size() > 1)
5076 return false;
5077
5078 // The predecessor has to be immediately before this block.
5079 MachineBasicBlock *Pred = *MBB->pred_begin();
5080 if (!Pred->isLayoutSuccessor(MBB))
5081 return false;
5082
5083 // If the block is completely empty, then it definitely does fall through.
5084 if (Pred->empty())
5085 return true;
5086
5087 // Check the terminators in the previous blocks
5088 for (const auto &MI : Pred->terminators()) {
5089 // If it is not a simple branch, we are in a table somewhere.
5090 if (!MI.isBranch() || MI.isIndirectBranch())
5091 return false;
5092
5093 // If we are the operands of one of the branches, this is not a fall
5094 // through. Note that targets with delay slots will usually bundle
5095 // terminators with the delay slot instruction.
5096 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
5097 if (OP->isJTI())
5098 return false;
5099 if (OP->isMBB() && OP->getMBB() == MBB)
5100 return false;
5101 }
5102 }
5103
5104 return true;
5105}
5106
5108 ArrayRef<GCStrategy *> Strategies) {
5109 bool NeedsDefault = false;
5110 if (Strategies.empty())
5111 // No GC strategy, use the default format.
5112 NeedsDefault = true;
5113 else {
5114 for (GCStrategy *S : Strategies) {
5115 if (GCMetadataPrinter *MP = getOrCreateGCPrinter(*S))
5116 if (MP->emitStackMaps(SM, *this))
5117 continue;
5118 // The strategy doesn't have printer or doesn't emit custom stack maps.
5119 // Use the default format.
5120 NeedsDefault = true;
5121 }
5122 }
5123
5124 if (NeedsDefault)
5125 SM.serializeToStackMapSection();
5126}
5127
5128GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
5129 if (!S.usesMetadata())
5130 return nullptr;
5131
5132 auto [GCPI, Inserted] = GCMetadataPrinters.try_emplace(&S);
5133 if (!Inserted)
5134 return GCPI->second.get();
5135
5136 auto Name = S.getName();
5137
5138 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
5140 if (Name == GCMetaPrinter.getName()) {
5141 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
5142 GMP->S = &S;
5143 GCPI->second = std::move(GMP);
5144 return GCPI->second.get();
5145 }
5146
5147 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
5148}
5149
5151 std::unique_ptr<AsmPrinterHandler> Handler) {
5152 Handlers.insert(Handlers.begin(), std::move(Handler));
5154}
5155
5156/// Pin vtables to this file.
5158
5160
5161// In the binary's "xray_instr_map" section, an array of these function entries
5162// describes each instrumentation point. When XRay patches your code, the index
5163// into this table will be given to your handler as a patch point identifier.
5165 auto Kind8 = static_cast<uint8_t>(Kind);
5166 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
5167 Out->emitBinaryData(
5168 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
5169 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
5170 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
5171 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
5172 Out->emitZeros(Padding);
5173}
5174
5176 if (Sleds.empty())
5177 return;
5178
5179 auto PrevSection = OutStreamer->getCurrentSectionOnly();
5180 const Function &F = MF->getFunction();
5181 MCSection *InstMap = nullptr;
5182 MCSection *FnSledIndex = nullptr;
5183 const Triple &TT = TM.getTargetTriple();
5184 // Use PC-relative addresses on all targets.
5185 if (TT.isOSBinFormatELF()) {
5186 auto LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5187 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
5188 StringRef GroupName;
5189 if (F.hasComdat()) {
5190 Flags |= ELF::SHF_GROUP;
5191 GroupName = F.getComdat()->getName();
5192 }
5193 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
5194 Flags, 0, GroupName, F.hasComdat(),
5195 MCSection::NonUniqueID, LinkedToSym);
5196
5197 if (TM.Options.XRayFunctionIndex)
5198 FnSledIndex = OutContext.getELFSection(
5199 "xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5200 MCSection::NonUniqueID, LinkedToSym);
5201 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
5202 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map",
5205 if (TM.Options.XRayFunctionIndex)
5206 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx",
5209 } else {
5210 llvm_unreachable("Unsupported target");
5211 }
5212
5213 auto WordSizeBytes = MAI.getCodePointerSize();
5214
5215 // Now we switch to the instrumentation map section. Because this is done
5216 // per-function, we are able to create an index entry that will represent the
5217 // range of sleds associated with a function.
5218 auto &Ctx = OutContext;
5219 MCSymbol *SledsStart =
5220 OutContext.createLinkerPrivateSymbol("xray_sleds_start");
5221 OutStreamer->switchSection(InstMap);
5222 OutStreamer->emitLabel(SledsStart);
5223 for (const auto &Sled : Sleds) {
5224 MCSymbol *Dot = Ctx.createTempSymbol();
5225 OutStreamer->emitLabel(Dot);
5226 OutStreamer->emitValueImpl(
5228 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5229 WordSizeBytes);
5230 OutStreamer->emitValueImpl(
5234 MCConstantExpr::create(WordSizeBytes, Ctx),
5235 Ctx),
5236 Ctx),
5237 WordSizeBytes);
5238 Sled.emit(WordSizeBytes, OutStreamer.get());
5239 }
5240 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
5241 OutStreamer->emitLabel(SledsEnd);
5242
5243 // We then emit a single entry in the index per function. We use the symbols
5244 // that bound the instrumentation map as the range for a specific function.
5245 // Each entry contains 2 words and needs to be word-aligned.
5246 if (FnSledIndex) {
5247 OutStreamer->switchSection(FnSledIndex);
5248 OutStreamer->emitValueToAlignment(Align(WordSizeBytes));
5249 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
5250 // difference uses a SUBTRACTOR external relocation which references the
5251 // symbol.
5252 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol("xray_fn_idx");
5253 OutStreamer->emitLabel(Dot);
5254 OutStreamer->emitValueImpl(
5256 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5257 WordSizeBytes);
5258 OutStreamer->emitValueImpl(MCConstantExpr::create(Sleds.size(), Ctx),
5259 WordSizeBytes);
5260 OutStreamer->switchSection(PrevSection);
5261 }
5262 Sleds.clear();
5263}
5264
5266 SledKind Kind, uint8_t Version) {
5267 const Function &F = MI.getMF()->getFunction();
5268 auto Attr = F.getFnAttribute("function-instrument");
5269 bool LogArgs = F.hasFnAttribute("xray-log-args");
5270 bool AlwaysInstrument =
5271 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
5272 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
5274 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
5275 AlwaysInstrument, &F, Version});
5276}
5277
5279 const Function &F = MF->getFunction();
5280 unsigned PatchableFunctionPrefix =
5281 F.getFnAttributeAsParsedInteger("patchable-function-prefix");
5282 unsigned PatchableFunctionEntry =
5283 F.getFnAttributeAsParsedInteger("patchable-function-entry");
5284 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
5285 return;
5286 const unsigned PointerSize = getPointerSize();
5287 if (TM.getTargetTriple().isOSBinFormatELF()) {
5288 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
5289 const MCSymbolELF *LinkedToSym = nullptr;
5290 StringRef GroupName, SectionName;
5291
5292 if (F.hasFnAttribute("patchable-function-entry-section"))
5293 SectionName = F.getFnAttribute("patchable-function-entry-section")
5294 .getValueAsString();
5295 if (SectionName.empty())
5296 SectionName = "__patchable_function_entries";
5297
5298 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
5299 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
5300 if (MAI.useIntegratedAssembler() || MAI.binutilsIsAtLeast(2, 36)) {
5301 Flags |= ELF::SHF_LINK_ORDER;
5302 if (F.hasComdat()) {
5303 Flags |= ELF::SHF_GROUP;
5304 GroupName = F.getComdat()->getName();
5305 }
5306 LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5307 }
5308 OutStreamer->switchSection(OutContext.getELFSection(
5309 SectionName, ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5310 MCSection::NonUniqueID, LinkedToSym));
5313 }
5314}
5315
5317 return OutStreamer->getContext().getDwarfVersion();
5318}
5319
5321 OutStreamer->getContext().setDwarfVersion(Version);
5322}
5323
5325 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
5326}
5327
5330 OutStreamer->getContext().getDwarfFormat());
5331}
5332
5334 return {getDwarfVersion(), uint8_t(MAI.getCodePointerSize()),
5335 OutStreamer->getContext().getDwarfFormat(),
5337}
5338
5341 OutStreamer->getContext().getDwarfFormat());
5342}
5343
5344std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
5347 const MCSymbol *BranchLabel) const {
5348 const auto TLI = MF->getSubtarget().getTargetLowering();
5349 const auto BaseExpr =
5350 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, MMI->getContext());
5351 const auto Base = &cast<MCSymbolRefExpr>(BaseExpr)->getSymbol();
5352
5353 // By default, for the architectures that support CodeView,
5354 // EK_LabelDifference32 is implemented as an Int32 from the base address.
5355 return std::make_tuple(Base, 0, BranchLabel,
5357}
5358
5360 const Triple &TT = M.getTargetTriple();
5361 assert(TT.isOSBinFormatCOFF());
5362
5363 bool IsTargetArm64EC = TT.isWindowsArm64EC();
5365 SmallVector<MCSymbol *> FuncOverrideDefaultSymbols;
5366 bool SwitchedToDirectiveSection = false;
5367 for (const Function &F : M.functions()) {
5368 if (F.hasFnAttribute("loader-replaceable")) {
5369 if (!SwitchedToDirectiveSection) {
5370 OutStreamer->switchSection(
5371 OutContext.getObjectFileInfo()->getDrectveSection());
5372 SwitchedToDirectiveSection = true;
5373 }
5374
5375 StringRef Name = F.getName();
5376
5377 // For hybrid-patchable targets, strip the prefix so that we can mark
5378 // the real function as replaceable.
5379 if (IsTargetArm64EC && Name.ends_with(HybridPatchableTargetSuffix)) {
5380 Name = Name.drop_back(HybridPatchableTargetSuffix.size());
5381 }
5382
5383 MCSymbol *FuncOverrideSymbol =
5384 MMI->getContext().getOrCreateSymbol(Name + "_$fo$");
5385 OutStreamer->beginCOFFSymbolDef(FuncOverrideSymbol);
5386 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5387 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5388 OutStreamer->endCOFFSymbolDef();
5389
5390 MCSymbol *FuncOverrideDefaultSymbol =
5391 MMI->getContext().getOrCreateSymbol(Name + "_$fo_default$");
5392 OutStreamer->beginCOFFSymbolDef(FuncOverrideDefaultSymbol);
5393 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5394 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5395 OutStreamer->endCOFFSymbolDef();
5396 FuncOverrideDefaultSymbols.push_back(FuncOverrideDefaultSymbol);
5397
5398 OutStreamer->emitBytes((Twine(" /ALTERNATENAME:") +
5399 FuncOverrideSymbol->getName() + "=" +
5400 FuncOverrideDefaultSymbol->getName())
5401 .toStringRef(Buf));
5402 Buf.clear();
5403 }
5404 }
5405
5406 if (SwitchedToDirectiveSection)
5407 OutStreamer->popSection();
5408
5409 if (FuncOverrideDefaultSymbols.empty())
5410 return;
5411
5412 // MSVC emits the symbols for the default variables pointing at the start of
5413 // the .data section, but doesn't actually allocate any space for them. LLVM
5414 // can't do this, so have all of the variables pointing at a single byte
5415 // instead.
5416 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
5417 for (MCSymbol *Symbol : FuncOverrideDefaultSymbols) {
5418 OutStreamer->emitLabel(Symbol);
5419 }
5420 OutStreamer->emitZeros(1);
5421 OutStreamer->popSection();
5422}
5423
5425 const Triple &TT = M.getTargetTriple();
5426 assert(TT.isOSBinFormatCOFF());
5427
5428 // Emit an absolute @feat.00 symbol.
5429 MCSymbol *S = MMI->getContext().getOrCreateSymbol(StringRef("@feat.00"));
5430 OutStreamer->beginCOFFSymbolDef(S);
5431 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
5432 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5433 OutStreamer->endCOFFSymbolDef();
5434 int64_t Feat00Value = 0;
5435
5436 if (TT.getArch() == Triple::x86) {
5437 // According to the PE-COFF spec, the LSB of this value marks the object
5438 // for "registered SEH". This means that all SEH handler entry points
5439 // must be registered in .sxdata. Use of any unregistered handlers will
5440 // cause the process to terminate immediately. LLVM does not know how to
5441 // register any SEH handlers, so its object files should be safe.
5442 Feat00Value |= COFF::Feat00Flags::SafeSEH;
5443 }
5444
5445 if (M.getControlFlowGuardMode() == ControlFlowGuardMode::Enabled) {
5446 // Object is CFG-aware. Only set if we actually inserted the checks.
5447 Feat00Value |= COFF::Feat00Flags::GuardCF;
5448 }
5449
5450 if (M.getModuleFlag("ehcontguard")) {
5451 // Object also has EHCont.
5452 Feat00Value |= COFF::Feat00Flags::GuardEHCont;
5453 }
5454
5455 if (M.getModuleFlag("ms-kernel")) {
5456 // Object is compiled with /kernel.
5457 Feat00Value |= COFF::Feat00Flags::Kernel;
5458 }
5459
5460 OutStreamer->emitSymbolAttribute(S, MCSA_Global);
5461 OutStreamer->emitAssignment(
5462 S, MCConstantExpr::create(Feat00Value, MMI->getContext()));
5463}
5464
5465namespace llvm {
5466namespace {
5468 return MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
5469}
5470
5472 MachineFunction &MF) {
5474 .getManager();
5475}
5476
5478 MachineFunction &MF) {
5480 getFAM(M, MAM)
5482 MF.getFunction())
5483 .getManager();
5484 return MFAM;
5485}
5486} // anonymous namespace
5487
5490 MachineModuleInfo &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
5491 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5492 AsmPrinter.MMI = &MMI;
5493 AsmPrinter.GetORE = [&MAM, &M](MachineFunction &MF) {
5494 return &getMFAM(M, MAM, MF)
5496 };
5497 AsmPrinter.GetMDT = [&MAM, &M](MachineFunction &MF) {
5498 return &getMFAM(M, MAM, MF).getResult<MachineDominatorTreeAnalysis>(MF);
5499 };
5500 AsmPrinter.GetMLI = [&MAM, &M](MachineFunction &MF) {
5501 return &getMFAM(M, MAM, MF).getResult<MachineLoopAnalysis>(MF);
5502 };
5503 AsmPrinter.GetMBPI = [&MAM, &M](MachineFunction &MF) {
5504 return &getMFAM(M, MAM, MF).getResult<MachineBranchProbabilityAnalysis>(MF);
5505 };
5506 AsmPrinter.GetMBFI = [&MAM, &M](MachineFunction &MF) {
5507 return &getMFAM(M, MAM, MF).getResult<MachineBlockFrequencyAnalysis>(MF);
5508 };
5509 AsmPrinter.GetMBHI = [&MAM, &M](MachineFunction &MF) {
5510 return &getMFAM(M, MAM, MF).getResult<MachineBlockHashInfoAnalysis>(MF);
5511 };
5512 AsmPrinter.GetBBSPR = [&MAM, &M](MachineFunction &MF) {
5513 return getFAM(M, MAM)
5515 MF.getFunction());
5516 };
5517 // TODO(boomanaiden154): Get GC working with the new pass manager.
5518 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5522 for (auto &[Name, S] : MAM.getResult<CollectorMetadataAnalysis>(M))
5523 Strategies.push_back(S.get());
5525 };
5527}
5528
5530 MachineFunction &MF,
5532 const ModuleAnalysisManagerMachineFunctionProxy::Result &MAMProxy =
5534 MachineModuleInfo &MMI =
5535 MAMProxy
5536 .getCachedResult<MachineModuleAnalysis>(*MF.getFunction().getParent())
5537 ->getMMI();
5538 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5539 AsmPrinter.MMI = &MMI;
5540 AsmPrinter.GetORE = [&MFAM](MachineFunction &MF) {
5542 };
5543 AsmPrinter.GetMDT = [&MFAM](MachineFunction &MF) {
5544 return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
5545 };
5546 AsmPrinter.GetMLI = [&MFAM](MachineFunction &MF) {
5547 return &MFAM.getResult<MachineLoopAnalysis>(MF);
5548 };
5549 AsmPrinter.GetMBPI = [&MFAM](MachineFunction &MF) {
5551 };
5552 AsmPrinter.GetMBFI = [&MFAM](MachineFunction &MF) {
5553 return &MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
5554 };
5555 AsmPrinter.GetMBHI = [&MFAM](MachineFunction &MF) {
5556 return &MFAM.getResult<MachineBlockHashInfoAnalysis>(MF);
5557 };
5558 AsmPrinter.GetBBSPR = [&MFAM](MachineFunction &MF) {
5559 return getFAM(MFAM, MF)
5561 MF.getFunction());
5562 };
5563 // TODO(boomanaiden154): Get GC working with the new pass manager.
5564 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5566 AsmPrinter.EmitStackMaps = [&MAMProxy, &AsmPrinter](Module &M) {
5568 if (auto *Map = MAMProxy.getCachedResult<CollectorMetadataAnalysis>(M))
5569 for (auto &[Name, S] : *Map)
5570 Strategies.push_back(S.get());
5572 };
5574}
5575
5577
5578} // namespace llvm
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
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...
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:170
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:379
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6336
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1653
APInt bitcastToAPInt() const
Definition APFloat.h:1508
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:93
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition AsmPrinter.h:673
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:451
MapVector< MBBSectionID, MBBSectionRange > MBBSectionRanges
Definition AsmPrinter.h:163
bool isDwarf64() const
void emitNops(unsigned N)
Emit N NOP instructions.
MCSymbol * CurrentFnBegin
Definition AsmPrinter.h:246
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition AsmPrinter.h:123
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:182
virtual const MCExpr * lowerConstantPtrAuth(const ConstantPtrAuth &CPA)
Definition AsmPrinter.h:694
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:381
virtual bool emitTargetFeaturePush(const MCSubtargetInfo &STI)
Emit necessary directives to allow use of instructions that are permitted by target features enabled ...
Definition AsmPrinter.h:972
~AsmPrinter() override
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:96
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:149
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:137
MCSymbol * CurrentFnBeginLocal
For dso_local functions, the current $local alias for the function.
Definition AsmPrinter.h:249
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition AsmPrinter.h:168
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:344
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:725
MCSymbol * getMBBExceptionSym(const MachineBasicBlock &MBB)
std::function< void(Module &)> EmitStackMaps
Definition AsmPrinter.h:193
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
Definition AsmPrinter.h:354
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:190
SmallVector< std::unique_ptr< AsmPrinterHandler >, 2 > Handlers
Definition AsmPrinter.h:257
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:111
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:120
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:649
unsigned PointerSize
The pointer size in bytes for the default address space.
Definition AsmPrinter.h:117
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:192
virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition AsmPrinter.h:545
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition AsmPrinter.h:657
std::function< MachineDominatorTree *(MachineFunction &)> GetMDT
Definition AsmPrinter.h:183
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:167
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:653
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:719
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:126
DenseMap< uint64_t, SmallVector< const GlobalAlias *, 1 > > AliasMapTy
Print a general LLVM constant to the .s file.
Definition AsmPrinter.h:619
virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const
std::function< MachineBlockHashInfoResult *(MachineFunction &)> GetMBHI
Definition AsmPrinter.h:187
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:191
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition AsmPrinter.h:133
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition AsmPrinter.h:114
void emitSLEB128(int64_t Value, const char *Desc=nullptr) const
Emit the specified signed leb128 value.
std::function< MachineBlockFrequencyInfo *(MachineFunction &)> GetMBFI
Definition AsmPrinter.h:186
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:103
const StaticDataProfileInfo * SDPI
Provides the profile information for constants.
Definition AsmPrinter.h:152
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:715
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:979
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:129
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:108
const ProfileSummaryInfo * PSI
The profile summary information.
Definition AsmPrinter.h:155
const MCAsmInfo & MAI
Target Asm Printer information.
Definition AsmPrinter.h:99
std::function< void()> AssertDebugEHFinalized
Definition AsmPrinter.h:194
void emitStackMapsForGCStrategies(ArrayRef< GCStrategy * > Strategies)
virtual void emitFunctionDescriptor()
Definition AsmPrinter.h:682
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:258
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition AsmPrinter.h:142
std::function< MachineLoopInfo *(MachineFunction &)> GetMLI
Definition AsmPrinter.h:184
std::function< MachineModuleInfo *()> GetMMI
Definition AsmPrinter.h:181
bool isVerbose() const
Return true if assembly output should contain comments.
Definition AsmPrinter.h:335
MCSymbol * getFunctionEnd() const
Definition AsmPrinter.h:345
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:690
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:252
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:661
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:401
@ None
Do not emit either .eh_frame or .debug_frame.
Definition AsmPrinter.h:172
@ Debug
Emit .debug_frame.
Definition AsmPrinter.h:174
std::function< MachineBranchProbabilityInfo *(MachineFunction &)> GetMBPI
Definition AsmPrinter.h:185
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:61
unsigned getNumber() const
Definition BasicBlock.h:94
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:665
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:63
bool isBigEndian() const
Definition DataLayout.h:220
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:581
A debug info location.
Definition DebugLoc.h:126
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:733
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:762
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:69
bool hasWeakDefCanBeHiddenDirective() const
Definition MCAsmInfo.h:669
bool hasSubsectionsViaSymbols() const
Definition MCAsmInfo.h:514
const char * getWeakRefDirective() const
Definition MCAsmInfo.h:667
bool hasIdentDirective() const
Definition MCAsmInfo.h:664
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:339
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:344
static const MCBinaryExpr * createGTE(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:364
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:424
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:31
MCFragment * getNext() const
Definition MCSection.h:174
size_t getFixedSize() const
Definition MCSection.h:220
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
unsigned getOpcode() const
Definition MCInst.h:201
void setOpcode(unsigned Op)
Definition MCInst.h:200
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:577
bool isBssSection() const
Check whether this section is "virtual", that is has no actual object file contents.
Definition MCSection.h:701
static constexpr unsigned NonUniqueID
Definition MCSection.h:582
Streaming machine code generation interface.
Definition MCStreamer.h:221
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:210
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:745
TypeSize getSizeInBytes() const
Definition DataLayout.h:754
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
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:885
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
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
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
@ SHF_EXECINSTR
Definition ELF.h:1101
@ 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:159
llvm.global_ctors and llvm.global_dtors are arrays of Structor structs.
Definition AsmPrinter.h:582
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.