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