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