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)
837 OutContext.reportError(SMLoc(),
838 "tagged symbols (-fsanitize=memtag-globals) are "
839 "only supported on AArch64");
840 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_Memtag);
841 }
842
843 if (!GV->hasInitializer()) // External globals require no extra code.
844 return;
845
846 GVSym->redefineIfPossible();
847 if (GVSym->isDefined() || GVSym->isVariable())
848 OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
849 "' is already defined");
850
851 if (MAI->hasDotTypeDotSizeDirective())
852 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
853
855
856 const DataLayout &DL = GV->getDataLayout();
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-analysis-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/// Helper to emit a symbol for the prefetch target associated with the given
2021/// BBID and callsite index.
2023 unsigned CallsiteIndex) {
2024 SmallString<128> FunctionName;
2025 getNameWithPrefix(FunctionName, &MF->getFunction());
2026 MCSymbol *PrefetchTargetSymbol = OutContext.getOrCreateSymbol(
2027 "__llvm_prefetch_target_" + FunctionName + "_" + Twine(BaseID) + "_" +
2029 // If the function is weak-linkage it may be replaced by a strong
2030 // version, in which case the prefetch targets should also be replaced.
2031 OutStreamer->emitSymbolAttribute(
2032 PrefetchTargetSymbol,
2033 MF->getFunction().isWeakForLinker() ? MCSA_Weak : MCSA_Global);
2034 OutStreamer->emitLabel(PrefetchTargetSymbol);
2035}
2036
2037/// Emit dangling prefetch targets that were not mapped to any basic block.
2039 const DenseMap<UniqueBBID, SmallVector<unsigned>> &MFPrefetchTargets =
2040 MF->getPrefetchTargets();
2041 if (MFPrefetchTargets.empty())
2042 return;
2043 DenseSet<UniqueBBID> MFBBIDs;
2044 for (const MachineBasicBlock &MBB : *MF)
2045 if (std::optional<UniqueBBID> BBID = MBB.getBBID())
2046 MFBBIDs.insert(*BBID);
2047
2048 for (const auto &[BBID, CallsiteIndexes] : MFPrefetchTargets) {
2049 if (MFBBIDs.contains(BBID))
2050 continue;
2051 for (unsigned CallsiteIndex : CallsiteIndexes)
2053 }
2054}
2055
2056/// EmitFunctionBody - This method emits the body and trailer for a
2057/// function.
2059 emitFunctionHeader();
2060
2061 // Emit target-specific gunk before the function body.
2063
2064 if (isVerbose()) {
2065 // Get MachineDominatorTree or compute it on the fly if it's unavailable
2066 MDT = GetMDT(*MF);
2067 if (!MDT) {
2068 OwnedMDT = std::make_unique<MachineDominatorTree>();
2069 OwnedMDT->recalculate(*MF);
2070 MDT = OwnedMDT.get();
2071 }
2072
2073 // Get MachineLoopInfo or compute it on the fly if it's unavailable
2074 MLI = GetMLI(*MF);
2075 if (!MLI) {
2076 OwnedMLI = std::make_unique<MachineLoopInfo>();
2077 OwnedMLI->analyze(*MDT);
2078 MLI = OwnedMLI.get();
2079 }
2080 }
2081
2082 // Print out code for the function.
2083 bool HasAnyRealCode = false;
2084 int NumInstsInFunction = 0;
2085 bool IsEHa = MMI->getModule()->getModuleFlag("eh-asynch");
2086
2087 const MCSubtargetInfo *STI = nullptr;
2088 if (this->MF)
2089 STI = &getSubtargetInfo();
2090 else
2091 STI = TM.getMCSubtargetInfo();
2092
2093 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
2094 // Create a slot for the entry basic block section so that the section
2095 // order is preserved when iterating over MBBSectionRanges.
2096 if (!MF->empty())
2097 MBBSectionRanges[MF->front().getSectionID()] =
2099
2100 FunctionCallGraphInfo FuncCGInfo;
2101 const auto &CallSitesInfoMap = MF->getCallSitesInfo();
2102
2103 // Dangling targets are not mapped to any blocks and must be emitted at the
2104 // beginning of the function.
2106
2107 const auto &MFPrefetchTargets = MF->getPrefetchTargets();
2108 for (auto &MBB : *MF) {
2109 // Print a label for the basic block.
2111 DenseMap<StringRef, unsigned> MnemonicCounts;
2112
2113 const SmallVector<unsigned> *PrefetchTargets = nullptr;
2114 if (auto BBID = MBB.getBBID()) {
2115 auto R = MFPrefetchTargets.find(*BBID);
2116 if (R != MFPrefetchTargets.end())
2117 PrefetchTargets = &R->second;
2118 }
2119 auto PrefetchTargetIt =
2120 PrefetchTargets ? PrefetchTargets->begin() : nullptr;
2121 auto PrefetchTargetEnd = PrefetchTargets ? PrefetchTargets->end() : nullptr;
2122 unsigned LastCallsiteIndex = 0;
2123
2124 for (auto &MI : MBB) {
2125 if (PrefetchTargetIt != PrefetchTargetEnd &&
2126 *PrefetchTargetIt == LastCallsiteIndex) {
2127 emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
2128 ++PrefetchTargetIt;
2129 }
2130
2131 // Print the assembly for the instruction.
2132 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
2133 !MI.isDebugInstr()) {
2134 HasAnyRealCode = true;
2135 }
2136
2137 // If there is a pre-instruction symbol, emit a label for it here.
2138 if (MCSymbol *S = MI.getPreInstrSymbol())
2139 OutStreamer->emitLabel(S);
2140
2141 if (MDNode *MD = MI.getPCSections())
2142 emitPCSectionsLabel(*MF, *MD);
2143
2144 for (auto &Handler : Handlers)
2145 Handler->beginInstruction(&MI);
2146
2147 if (isVerbose())
2148 emitComments(MI, STI, OutStreamer->getCommentOS());
2149
2150#ifndef NDEBUG
2151 MCFragment *OldFragment = OutStreamer->getCurrentFragment();
2152 size_t OldFragSize = OldFragment->getFixedSize();
2153#endif
2154
2155 switch (MI.getOpcode()) {
2156 case TargetOpcode::CFI_INSTRUCTION:
2158 break;
2159 case TargetOpcode::LOCAL_ESCAPE:
2161 break;
2162 case TargetOpcode::ANNOTATION_LABEL:
2163 case TargetOpcode::GC_LABEL:
2164 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2165 break;
2166 case TargetOpcode::EH_LABEL:
2167 OutStreamer->AddComment("EH_LABEL");
2168 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
2169 // For AsynchEH, insert a Nop if followed by a trap inst
2170 // Or the exception won't be caught.
2171 // (see MCConstantExpr::create(1,..) in WinException.cpp)
2172 // Ignore SDiv/UDiv because a DIV with Const-0 divisor
2173 // must have being turned into an UndefValue.
2174 // Div with variable opnds won't be the first instruction in
2175 // an EH region as it must be led by at least a Load
2176 {
2177 auto MI2 = std::next(MI.getIterator());
2178 if (IsEHa && MI2 != MBB.end() &&
2179 (MI2->mayLoadOrStore() || MI2->mayRaiseFPException()))
2180 emitNops(1);
2181 }
2182 break;
2183 case TargetOpcode::INLINEASM:
2184 case TargetOpcode::INLINEASM_BR:
2185 emitInlineAsm(&MI);
2186 break;
2187 case TargetOpcode::DBG_VALUE:
2188 case TargetOpcode::DBG_VALUE_LIST:
2189 if (isVerbose()) {
2190 if (!emitDebugValueComment(&MI, *this))
2192 }
2193 break;
2194 case TargetOpcode::DBG_INSTR_REF:
2195 // This instruction reference will have been resolved to a machine
2196 // location, and a nearby DBG_VALUE created. We can safely ignore
2197 // the instruction reference.
2198 break;
2199 case TargetOpcode::DBG_PHI:
2200 // This instruction is only used to label a program point, it's purely
2201 // meta information.
2202 break;
2203 case TargetOpcode::DBG_LABEL:
2204 if (isVerbose()) {
2205 if (!emitDebugLabelComment(&MI, *this))
2207 }
2208 break;
2209 case TargetOpcode::IMPLICIT_DEF:
2210 if (isVerbose()) emitImplicitDef(&MI);
2211 break;
2212 case TargetOpcode::KILL:
2213 if (isVerbose()) emitKill(&MI, *this);
2214 break;
2215 case TargetOpcode::FAKE_USE:
2216 if (isVerbose())
2217 emitFakeUse(&MI, *this);
2218 break;
2219 case TargetOpcode::PSEUDO_PROBE:
2221 break;
2222 case TargetOpcode::ARITH_FENCE:
2223 if (isVerbose())
2224 OutStreamer->emitRawComment("ARITH_FENCE");
2225 break;
2226 case TargetOpcode::MEMBARRIER:
2227 OutStreamer->emitRawComment("MEMBARRIER");
2228 break;
2229 case TargetOpcode::JUMP_TABLE_DEBUG_INFO:
2230 // This instruction is only used to note jump table debug info, it's
2231 // purely meta information.
2232 break;
2233 case TargetOpcode::INIT_UNDEF:
2234 // This is only used to influence register allocation behavior, no
2235 // actual initialization is needed.
2236 break;
2237 case TargetOpcode::RELOC_NONE: {
2238 // Generate a temporary label for the current PC.
2239 MCSymbol *Sym = OutContext.createTempSymbol("reloc_none");
2240 OutStreamer->emitLabel(Sym);
2241 const MCExpr *Dot = MCSymbolRefExpr::create(Sym, OutContext);
2243 OutContext.getOrCreateSymbol(MI.getOperand(0).getSymbolName()),
2244 OutContext);
2245 OutStreamer->emitRelocDirective(*Dot, "BFD_RELOC_NONE", Value, SMLoc());
2246 break;
2247 }
2248 default:
2250
2251 auto CountInstruction = [&](const MachineInstr &MI) {
2252 // Skip Meta instructions inside bundles.
2253 if (MI.isMetaInstruction())
2254 return;
2255 ++NumInstsInFunction;
2256 if (CanDoExtraAnalysis) {
2258 ++MnemonicCounts[Name];
2259 }
2260 };
2261 if (!MI.isBundle()) {
2262 CountInstruction(MI);
2263 break;
2264 }
2265 // Separately count all the instructions in a bundle.
2266 for (auto It = std::next(MI.getIterator());
2267 It != MBB.end() && It->isInsideBundle(); ++It) {
2268 CountInstruction(*It);
2269 }
2270 break;
2271 }
2272
2273#ifndef NDEBUG
2274 // Verify that the instruction size reported by InstrInfo matches the
2275 // actually emitted size. Many backends performing branch relaxation
2276 // on the MIR level rely on this for correctness.
2277 // TODO: We currently can't distinguish whether a parse error occurred
2278 // when handling INLINEASM.
2279 if (OutStreamer->isObj() && !OutContext.hadError() &&
2280 (MI.getOpcode() != TargetOpcode::INLINEASM &&
2281 MI.getOpcode() != TargetOpcode::INLINEASM_BR)) {
2282 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2283 MCFragment *NewFragment = OutStreamer->getCurrentFragment();
2285 TII->getInstSizeVerifyMode(MI);
2286 // Don't try to handle fragment splitting cases.
2287 if (NewFragment == OldFragment &&
2289 unsigned ExpectedSize = TII->getInstSizeInBytes(MI);
2290 if (MI.isBundled()) {
2291 // Bundled instructions are emitted together.
2292 auto It = MI.getIterator(), End = MBB.instr_end();
2293 for (++It; It != End && It->isInsideBundle(); ++It)
2294 ExpectedSize += TII->getInstSizeInBytes(*It);
2295 }
2296
2297 unsigned ActualSize = NewFragment->getFixedSize() - OldFragSize;
2298 bool AllowOverEstimate =
2300 bool Valid = AllowOverEstimate ? ActualSize <= ExpectedSize
2301 : ActualSize == ExpectedSize;
2302 if (!Valid) {
2303 dbgs() << "In function: " << MF->getName() << "\n";
2304 dbgs() << "Size mismatch for: " << MI;
2305 if (MI.isBundled()) {
2306 dbgs() << "{\n";
2307 auto It = MI.getIterator(), End = MBB.instr_end();
2308 for (++It; It != End && It->isInsideBundle(); ++It)
2309 dbgs().indent(2) << *It;
2310 dbgs() << "}\n";
2311 }
2312 dbgs() << "Expected " << (AllowOverEstimate ? "maximum" : "exact")
2313 << " size: " << ExpectedSize << "\n";
2314 dbgs() << "Actual size: " << ActualSize << "\n";
2315 abort();
2316 }
2317 }
2318 }
2319#endif
2320
2321 if (MI.isCall()) {
2322 if (MF->getTarget().Options.BBAddrMap)
2324 LastCallsiteIndex++;
2325 }
2326
2327 if (TM.Options.EmitCallGraphSection && MI.isCall())
2328 handleCallsiteForCallgraph(FuncCGInfo, CallSitesInfoMap, MI);
2329
2330 // If there is a post-instruction symbol, emit a label for it here.
2331 if (MCSymbol *S = MI.getPostInstrSymbol())
2332 OutStreamer->emitLabel(S);
2333
2334 for (auto &Handler : Handlers)
2335 Handler->endInstruction();
2336 }
2337 // Emit the remaining prefetch targets for this block. This includes
2338 // nonexisting callsite indexes.
2339 while (PrefetchTargetIt != PrefetchTargetEnd) {
2340 emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
2341 ++PrefetchTargetIt;
2342 }
2343
2344 // We must emit temporary symbol for the end of this basic block, if either
2345 // we have BBLabels enabled or if this basic blocks marks the end of a
2346 // section.
2347 if (MF->getTarget().Options.BBAddrMap ||
2348 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
2349 OutStreamer->emitLabel(MBB.getEndSymbol());
2350
2351 if (MBB.isEndSection()) {
2352 // The size directive for the section containing the entry block is
2353 // handled separately by the function section.
2354 if (!MBB.sameSection(&MF->front())) {
2355 if (MAI->hasDotTypeDotSizeDirective()) {
2356 // Emit the size directive for the basic block section.
2357 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2358 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
2359 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
2360 OutContext);
2361 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
2362 }
2363 assert(!MBBSectionRanges.contains(MBB.getSectionID()) &&
2364 "Overwrite section range");
2365 MBBSectionRanges[MBB.getSectionID()] =
2366 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
2367 }
2368 }
2370
2371 if (CanDoExtraAnalysis) {
2372 // Skip empty blocks.
2373 if (MBB.empty())
2374 continue;
2375
2377 MBB.begin()->getDebugLoc(), &MBB);
2378
2379 // Generate instruction mix remark. First, sort counts in descending order
2380 // by count and name.
2382 for (auto &KV : MnemonicCounts)
2383 MnemonicVec.emplace_back(KV.first, KV.second);
2384
2385 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
2386 const std::pair<StringRef, unsigned> &B) {
2387 if (A.second > B.second)
2388 return true;
2389 if (A.second == B.second)
2390 return StringRef(A.first) < StringRef(B.first);
2391 return false;
2392 });
2393 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
2394 for (auto &KV : MnemonicVec) {
2395 auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
2396 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
2397 }
2398 ORE->emit(R);
2399 }
2400 }
2401
2402 EmittedInsts += NumInstsInFunction;
2403 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
2404 MF->getFunction().getSubprogram(),
2405 &MF->front());
2406 R << ore::NV("NumInstructions", NumInstsInFunction)
2407 << " instructions in function";
2408 ORE->emit(R);
2409
2410 // If the function is empty and the object file uses .subsections_via_symbols,
2411 // then we need to emit *something* to the function body to prevent the
2412 // labels from collapsing together. Just emit a noop.
2413 // Similarly, don't emit empty functions on Windows either. It can lead to
2414 // duplicate entries (two functions with the same RVA) in the Guard CF Table
2415 // after linking, causing the kernel not to load the binary:
2416 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
2417 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
2418 const Triple &TT = TM.getTargetTriple();
2419 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
2420 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
2421 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
2422
2423 // Targets can opt-out of emitting the noop here by leaving the opcode
2424 // unspecified.
2425 if (Noop.getOpcode()) {
2426 OutStreamer->AddComment("avoids zero-length function");
2427 emitNops(1);
2428 }
2429 }
2430
2431 // Switch to the original section in case basic block sections was used.
2432 OutStreamer->switchSection(MF->getSection());
2433
2434 const Function &F = MF->getFunction();
2435 for (const auto &BB : F) {
2436 if (!BB.hasAddressTaken())
2437 continue;
2438 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
2439 if (Sym->isDefined())
2440 continue;
2441 OutStreamer->AddComment("Address of block that was removed by CodeGen");
2442 OutStreamer->emitLabel(Sym);
2443 }
2444
2445 // Emit target-specific gunk after the function body.
2447
2448 // Even though wasm supports .type and .size in general, function symbols
2449 // are automatically sized.
2450 bool EmitFunctionSize = MAI->hasDotTypeDotSizeDirective() && !TT.isWasm();
2451
2452 // SPIR-V supports label instructions only inside a block, not after the
2453 // function body.
2454 if (TT.getObjectFormat() != Triple::SPIRV &&
2455 (EmitFunctionSize || needFuncLabels(*MF, *this))) {
2456 // Create a symbol for the end of function.
2457 CurrentFnEnd = createTempSymbol("func_end");
2458 OutStreamer->emitLabel(CurrentFnEnd);
2459 }
2460
2461 // If the target wants a .size directive for the size of the function, emit
2462 // it.
2463 if (EmitFunctionSize) {
2464 // We can get the size as difference between the function label and the
2465 // temp label.
2466 const MCExpr *SizeExp = MCBinaryExpr::createSub(
2467 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
2469 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
2471 OutStreamer->emitELFSize(CurrentFnBeginLocal, SizeExp);
2472 }
2473
2474 // Call endBasicBlockSection on the last block now, if it wasn't already
2475 // called.
2476 if (!MF->back().isEndSection()) {
2477 for (auto &Handler : Handlers)
2478 Handler->endBasicBlockSection(MF->back());
2479 for (auto &Handler : EHHandlers)
2480 Handler->endBasicBlockSection(MF->back());
2481 }
2482 for (auto &Handler : Handlers)
2483 Handler->markFunctionEnd();
2484 for (auto &Handler : EHHandlers)
2485 Handler->markFunctionEnd();
2486 // Update the end label of the entry block's section.
2487 MBBSectionRanges[MF->front().getSectionID()].EndLabel = CurrentFnEnd;
2488
2489 // Print out jump tables referenced by the function.
2491
2492 // Emit post-function debug and/or EH information.
2493 for (auto &Handler : Handlers)
2494 Handler->endFunction(MF);
2495 for (auto &Handler : EHHandlers)
2496 Handler->endFunction(MF);
2497
2498 // Emit section containing BB address offsets and their metadata, when
2499 // BB labels are requested for this function. Skip empty functions.
2500 if (HasAnyRealCode) {
2501 if (MF->getTarget().Options.BBAddrMap)
2503 else if (PgoAnalysisMapFeatures.getBits() != 0)
2504 MF->getContext().reportWarning(
2505 SMLoc(), "pgo-analysis-map is enabled for function " + MF->getName() +
2506 " but it does not have labels");
2507 }
2508
2509 // Emit sections containing instruction and function PCs.
2511
2512 // Emit section containing stack size metadata.
2514
2515 // Emit section containing call graph metadata.
2516 emitCallGraphSection(*MF, FuncCGInfo);
2517
2518 // Emit .su file containing function stack size information.
2520
2522
2523 if (isVerbose())
2524 OutStreamer->getCommentOS() << "-- End function\n";
2525
2526 OutStreamer->addBlankLine();
2527}
2528
2529/// Compute the number of Global Variables that uses a Constant.
2530static unsigned getNumGlobalVariableUses(const Constant *C,
2531 bool &HasNonGlobalUsers) {
2532 if (!C) {
2533 HasNonGlobalUsers = true;
2534 return 0;
2535 }
2536
2538 return 1;
2539
2540 unsigned NumUses = 0;
2541 for (const auto *CU : C->users())
2542 NumUses +=
2543 getNumGlobalVariableUses(dyn_cast<Constant>(CU), HasNonGlobalUsers);
2544
2545 return NumUses;
2546}
2547
2548/// Only consider global GOT equivalents if at least one user is a
2549/// cstexpr inside an initializer of another global variables. Also, don't
2550/// handle cstexpr inside instructions. During global variable emission,
2551/// candidates are skipped and are emitted later in case at least one cstexpr
2552/// isn't replaced by a PC relative GOT entry access.
2554 unsigned &NumGOTEquivUsers,
2555 bool &HasNonGlobalUsers) {
2556 // Global GOT equivalents are unnamed private globals with a constant
2557 // pointer initializer to another global symbol. They must point to a
2558 // GlobalVariable or Function, i.e., as GlobalValue.
2559 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
2560 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
2562 return false;
2563
2564 // To be a got equivalent, at least one of its users need to be a constant
2565 // expression used by another global variable.
2566 for (const auto *U : GV->users())
2567 NumGOTEquivUsers +=
2568 getNumGlobalVariableUses(dyn_cast<Constant>(U), HasNonGlobalUsers);
2569
2570 return NumGOTEquivUsers > 0;
2571}
2572
2573/// Unnamed constant global variables solely contaning a pointer to
2574/// another globals variable is equivalent to a GOT table entry; it contains the
2575/// the address of another symbol. Optimize it and replace accesses to these
2576/// "GOT equivalents" by using the GOT entry for the final global instead.
2577/// Compute GOT equivalent candidates among all global variables to avoid
2578/// emitting them if possible later on, after it use is replaced by a GOT entry
2579/// access.
2581 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2582 return;
2583
2584 for (const auto &G : M.globals()) {
2585 unsigned NumGOTEquivUsers = 0;
2586 bool HasNonGlobalUsers = false;
2587 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers, HasNonGlobalUsers))
2588 continue;
2589 // If non-global variables use it, we still need to emit it.
2590 // Add 1 here, then emit it in `emitGlobalGOTEquivs`.
2591 if (HasNonGlobalUsers)
2592 NumGOTEquivUsers += 1;
2593 const MCSymbol *GOTEquivSym = getSymbol(&G);
2594 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
2595 }
2596}
2597
2598/// Constant expressions using GOT equivalent globals may not be eligible
2599/// for PC relative GOT entry conversion, in such cases we need to emit such
2600/// globals we previously omitted in EmitGlobalVariable.
2602 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
2603 return;
2604
2606 for (auto &I : GlobalGOTEquivs) {
2607 const GlobalVariable *GV = I.second.first;
2608 unsigned Cnt = I.second.second;
2609 if (Cnt)
2610 FailedCandidates.push_back(GV);
2611 }
2612 GlobalGOTEquivs.clear();
2613
2614 for (const auto *GV : FailedCandidates)
2616}
2617
2619 MCSymbol *Name = getSymbol(&GA);
2620 const GlobalObject *BaseObject = GA.getAliaseeObject();
2621
2622 bool IsFunction = GA.getValueType()->isFunctionTy();
2623 // Treat bitcasts of functions as functions also. This is important at least
2624 // on WebAssembly where object and function addresses can't alias each other.
2625 if (!IsFunction)
2626 IsFunction = isa_and_nonnull<Function>(BaseObject);
2627
2628 // AIX's assembly directive `.set` is not usable for aliasing purpose,
2629 // so AIX has to use the extra-label-at-definition strategy. At this
2630 // point, all the extra label is emitted, we just have to emit linkage for
2631 // those labels.
2632 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
2633 // Linkage for alias of global variable has been emitted.
2634 if (isa_and_nonnull<GlobalVariable>(BaseObject))
2635 return;
2636
2637 emitLinkage(&GA, Name);
2638 // If it's a function, also emit linkage for aliases of function entry
2639 // point.
2640 if (IsFunction)
2641 emitLinkage(&GA,
2642 getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
2643 return;
2644 }
2645
2646 if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
2647 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
2648 else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
2649 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
2650 else
2651 assert(GA.hasLocalLinkage() && "Invalid alias linkage");
2652
2653 // Set the symbol type to function if the alias has a function type.
2654 // This affects codegen when the aliasee is not a function.
2655 if (IsFunction) {
2656 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
2657 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
2658 OutStreamer->beginCOFFSymbolDef(Name);
2659 OutStreamer->emitCOFFSymbolStorageClass(
2664 OutStreamer->endCOFFSymbolDef();
2665 }
2666 }
2667
2668 emitVisibility(Name, GA.getVisibility());
2669
2670 const MCExpr *Expr = lowerConstant(GA.getAliasee());
2671
2672 if (MAI->isMachO() && isa<MCBinaryExpr>(Expr))
2673 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
2674
2675 // Emit the directives as assignments aka .set:
2676 OutStreamer->emitAssignment(Name, Expr);
2677 MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
2678 if (LocalAlias != Name)
2679 OutStreamer->emitAssignment(LocalAlias, Expr);
2680
2681 // If the aliasee does not correspond to a symbol in the output, i.e. the
2682 // alias is not of an object or the aliased object is private, then set the
2683 // size of the alias symbol from the type of the alias. We don't do this in
2684 // other situations as the alias and aliasee having differing types but same
2685 // size may be intentional.
2686 if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
2687 (!BaseObject || BaseObject->hasPrivateLinkage())) {
2688 const DataLayout &DL = M.getDataLayout();
2689 uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
2690 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
2691 }
2692}
2693
2694void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
2695 auto EmitLinkage = [&](MCSymbol *Sym) {
2697 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
2698 else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
2699 OutStreamer->emitSymbolAttribute(Sym, MCSA_WeakReference);
2700 else
2701 assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
2702 };
2703
2705 MCSymbol *Name = getSymbol(&GI);
2706 EmitLinkage(Name);
2707 OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
2708 emitVisibility(Name, GI.getVisibility());
2709
2710 // Emit the directives as assignments aka .set:
2711 const MCExpr *Expr = lowerConstant(GI.getResolver());
2712 OutStreamer->emitAssignment(Name, Expr);
2713 MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
2714 if (LocalAlias != Name)
2715 OutStreamer->emitAssignment(LocalAlias, Expr);
2716
2717 return;
2718 }
2719
2720 if (!TM.getTargetTriple().isOSBinFormatMachO() || !getIFuncMCSubtargetInfo())
2721 reportFatalUsageError("IFuncs are not supported on this platform");
2722
2723 // On Darwin platforms, emit a manually-constructed .symbol_resolver that
2724 // implements the symbol resolution duties of the IFunc.
2725 //
2726 // Normally, this would be handled by linker magic, but unfortunately there
2727 // are a few limitations in ld64 and ld-prime's implementation of
2728 // .symbol_resolver that mean we can't always use them:
2729 //
2730 // * resolvers cannot be the target of an alias
2731 // * resolvers cannot have private linkage
2732 // * resolvers cannot have linkonce linkage
2733 // * resolvers cannot appear in executables
2734 // * resolvers cannot appear in bundles
2735 //
2736 // This works around that by emitting a close approximation of what the
2737 // linker would have done.
2738
2739 MCSymbol *LazyPointer =
2740 GetExternalSymbolSymbol(GI.getName() + ".lazy_pointer");
2741 MCSymbol *StubHelper = GetExternalSymbolSymbol(GI.getName() + ".stub_helper");
2742
2743 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
2744
2745 const DataLayout &DL = M.getDataLayout();
2746 emitAlignment(Align(DL.getPointerSize()));
2747 OutStreamer->emitLabel(LazyPointer);
2748 emitVisibility(LazyPointer, GI.getVisibility());
2749 OutStreamer->emitValue(MCSymbolRefExpr::create(StubHelper, OutContext), 8);
2750
2751 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getTextSection());
2752
2753 const TargetSubtargetInfo *STI =
2754 TM.getSubtargetImpl(*GI.getResolverFunction());
2755 const TargetLowering *TLI = STI->getTargetLowering();
2756 Align TextAlign(TLI->getMinFunctionAlignment());
2757
2758 MCSymbol *Stub = getSymbol(&GI);
2759 EmitLinkage(Stub);
2760 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2761 OutStreamer->emitLabel(Stub);
2762 emitVisibility(Stub, GI.getVisibility());
2763 emitMachOIFuncStubBody(M, GI, LazyPointer);
2764
2765 OutStreamer->emitCodeAlignment(TextAlign, getIFuncMCSubtargetInfo());
2766 OutStreamer->emitLabel(StubHelper);
2767 emitVisibility(StubHelper, GI.getVisibility());
2768 emitMachOIFuncStubHelperBody(M, GI, LazyPointer);
2769}
2770
2772 if (!RS.wantsSection())
2773 return;
2774 if (!RS.getFilename())
2775 return;
2776
2777 MCSection *RemarksSection =
2778 OutContext.getObjectFileInfo()->getRemarksSection();
2779 if (!RemarksSection && RS.needsSection()) {
2780 OutContext.reportWarning(SMLoc(), "Current object file format does not "
2781 "support remarks sections.");
2782 }
2783 if (!RemarksSection)
2784 return;
2785
2786 SmallString<128> Filename = *RS.getFilename();
2788 assert(!Filename.empty() && "The filename can't be empty.");
2789
2790 std::string Buf;
2791 raw_string_ostream OS(Buf);
2792
2793 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
2794 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
2795 RemarkSerializer.metaSerializer(OS, Filename);
2796 MetaSerializer->emit();
2797
2798 // Switch to the remarks section.
2799 OutStreamer->switchSection(RemarksSection);
2800 OutStreamer->emitBinaryData(Buf);
2801}
2802
2804 const Constant *Initializer = G.getInitializer();
2805 return G.getParent()->getDataLayout().getTypeAllocSize(
2806 Initializer->getType());
2807}
2808
2810 // We used to do this in clang, but there are optimization passes that turn
2811 // non-constant globals into constants. So now, clang only tells us whether
2812 // it would *like* a global to be tagged, but we still make the decision here.
2813 //
2814 // For now, don't instrument constant data, as it'll be in .rodata anyway. It
2815 // may be worth instrumenting these in future to stop them from being used as
2816 // gadgets.
2817 if (G.getName().starts_with("llvm.") || G.isThreadLocal() || G.isConstant())
2818 return false;
2819
2820 // Globals can be placed implicitly or explicitly in sections. There's two
2821 // different types of globals that meet this criteria that cause problems:
2822 // 1. Function pointers that are going into various init arrays (either
2823 // explicitly through `__attribute__((section(<foo>)))` or implicitly
2824 // through `__attribute__((constructor)))`, such as ".(pre)init(_array)",
2825 // ".fini(_array)", ".ctors", and ".dtors". These function pointers end up
2826 // overaligned and overpadded, making iterating over them problematic, and
2827 // each function pointer is individually tagged (so the iteration over
2828 // them causes SIGSEGV/MTE[AS]ERR).
2829 // 2. Global variables put into an explicit section, where the section's name
2830 // is a valid C-style identifier. The linker emits a `__start_<name>` and
2831 // `__stop_<name>` symbol for the section, so that you can iterate over
2832 // globals within this section. Unfortunately, again, these globals would
2833 // be tagged and so iteration causes SIGSEGV/MTE[AS]ERR.
2834 //
2835 // To mitigate both these cases, and because specifying a section is rare
2836 // outside of these two cases, disable MTE protection for globals in any
2837 // section.
2838 if (G.hasSection())
2839 return false;
2840
2841 return globalSize(G) > 0;
2842}
2843
2845 uint64_t SizeInBytes = globalSize(*G);
2846
2847 uint64_t NewSize = alignTo(SizeInBytes, 16);
2848 if (SizeInBytes != NewSize) {
2849 // Pad the initializer out to the next multiple of 16 bytes.
2850 llvm::SmallVector<uint8_t> Init(NewSize - SizeInBytes, 0);
2851 Constant *Padding = ConstantDataArray::get(M.getContext(), Init);
2852 Constant *Initializer = G->getInitializer();
2853 Initializer = ConstantStruct::getAnon({Initializer, Padding});
2854 auto *NewGV = new GlobalVariable(
2855 M, Initializer->getType(), G->isConstant(), G->getLinkage(),
2856 Initializer, "", G, G->getThreadLocalMode(), G->getAddressSpace());
2857 NewGV->copyAttributesFrom(G);
2858 NewGV->setComdat(G->getComdat());
2859 NewGV->copyMetadata(G, 0);
2860
2861 NewGV->takeName(G);
2862 G->replaceAllUsesWith(NewGV);
2863 G->eraseFromParent();
2864 G = NewGV;
2865 }
2866
2867 if (G->getAlign().valueOrOne() < 16)
2868 G->setAlignment(Align(16));
2869
2870 // Ensure that tagged globals don't get merged by ICF - as they should have
2871 // different tags at runtime.
2872 G->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2873}
2874
2876 auto Meta = G.getSanitizerMetadata();
2877 Meta.Memtag = false;
2878 G.setSanitizerMetadata(Meta);
2879}
2880
2882 // Set the MachineFunction to nullptr so that we can catch attempted
2883 // accesses to MF specific features at the module level and so that
2884 // we can conditionalize accesses based on whether or not it is nullptr.
2885 MF = nullptr;
2886 const Triple &Target = TM.getTargetTriple();
2887
2888 std::vector<GlobalVariable *> GlobalsToTag;
2889 for (GlobalVariable &G : M.globals()) {
2890 if (G.isDeclaration() || !G.isTagged())
2891 continue;
2892 if (!shouldTagGlobal(G)) {
2893 assert(G.hasSanitizerMetadata()); // because isTagged.
2895 assert(!G.isTagged());
2896 continue;
2897 }
2898 GlobalsToTag.push_back(&G);
2899 }
2900 for (GlobalVariable *G : GlobalsToTag)
2902
2903 // Gather all GOT equivalent globals in the module. We really need two
2904 // passes over the globals: one to compute and another to avoid its emission
2905 // in EmitGlobalVariable, otherwise we would not be able to handle cases
2906 // where the got equivalent shows up before its use.
2908
2909 // Emit global variables.
2910 for (const auto &G : M.globals())
2912
2913 // Emit remaining GOT equivalent globals.
2915
2917
2918 // Emit linkage(XCOFF) and visibility info for declarations
2919 for (const Function &F : M) {
2920 if (!F.isDeclarationForLinker())
2921 continue;
2922
2923 MCSymbol *Name = getSymbol(&F);
2924 // Function getSymbol gives us the function descriptor symbol for XCOFF.
2925
2926 if (!Target.isOSBinFormatXCOFF()) {
2927 GlobalValue::VisibilityTypes V = F.getVisibility();
2929 continue;
2930
2931 emitVisibility(Name, V, false);
2932 continue;
2933 }
2934
2935 if (F.isIntrinsic())
2936 continue;
2937
2938 // Handle the XCOFF case.
2939 // Variable `Name` is the function descriptor symbol (see above). Get the
2940 // function entry point symbol.
2941 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
2942 // Emit linkage for the function entry point.
2943 emitLinkage(&F, FnEntryPointSym);
2944
2945 // If a function's address is taken, which means it may be called via a
2946 // function pointer, we need the function descriptor for it.
2947 if (F.hasAddressTaken())
2948 emitLinkage(&F, Name);
2949 }
2950
2951 // Emit the remarks section contents.
2952 // FIXME: Figure out when is the safest time to emit this section. It should
2953 // not come after debug info.
2954 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
2955 emitRemarksSection(*RS);
2956
2958
2959 if (Target.isOSBinFormatELF()) {
2960 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
2961
2962 // Output stubs for external and common global variables.
2964 if (!Stubs.empty()) {
2965 OutStreamer->switchSection(TLOF.getDataSection());
2966 const DataLayout &DL = M.getDataLayout();
2967
2968 emitAlignment(Align(DL.getPointerSize()));
2969 for (const auto &Stub : Stubs) {
2970 OutStreamer->emitLabel(Stub.first);
2971 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2972 DL.getPointerSize());
2973 }
2974 }
2975 }
2976
2977 if (Target.isOSBinFormatCOFF()) {
2978 MachineModuleInfoCOFF &MMICOFF =
2979 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
2980
2981 // Output stubs for external and common global variables.
2983 if (!Stubs.empty()) {
2984 const DataLayout &DL = M.getDataLayout();
2985
2986 for (const auto &Stub : Stubs) {
2988 SectionName += Stub.first->getName();
2989 OutStreamer->switchSection(OutContext.getCOFFSection(
2993 Stub.first->getName(), COFF::IMAGE_COMDAT_SELECT_ANY));
2994 emitAlignment(Align(DL.getPointerSize()));
2995 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
2996 OutStreamer->emitLabel(Stub.first);
2997 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
2998 DL.getPointerSize());
2999 }
3000 }
3001 }
3002
3003 // This needs to happen before emitting debug information since that can end
3004 // arbitrary sections.
3005 if (auto *TS = OutStreamer->getTargetStreamer())
3006 TS->emitConstantPools();
3007
3008 // Emit Stack maps before any debug info. Mach-O requires that no data or
3009 // text sections come after debug info has been emitted. This matters for
3010 // stack maps as they are arbitrary data, and may even have a custom format
3011 // through user plugins.
3012 EmitStackMaps(M);
3013
3014 // Print aliases in topological order, that is, for each alias a = b,
3015 // b must be printed before a.
3016 // This is because on some targets (e.g. PowerPC) linker expects aliases in
3017 // such an order to generate correct TOC information.
3020 for (const auto &Alias : M.aliases()) {
3021 if (Alias.hasAvailableExternallyLinkage())
3022 continue;
3023 for (const GlobalAlias *Cur = &Alias; Cur;
3024 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
3025 if (!AliasVisited.insert(Cur).second)
3026 break;
3027 AliasStack.push_back(Cur);
3028 }
3029 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
3030 emitGlobalAlias(M, *AncestorAlias);
3031 AliasStack.clear();
3032 }
3033
3034 // IFuncs must come before deubginfo in case the backend decides to emit them
3035 // as actual functions, since on Mach-O targets, we cannot create regular
3036 // sections after DWARF.
3037 for (const auto &IFunc : M.ifuncs())
3038 emitGlobalIFunc(M, IFunc);
3039 if (TM.getTargetTriple().isOSBinFormatXCOFF() && hasDebugInfo()) {
3040 // Emit section end. This is used to tell the debug line section where the
3041 // end is for a text section if we don't use .loc to represent the debug
3042 // line.
3043 auto *Sec = OutContext.getObjectFileInfo()->getTextSection();
3044 OutStreamer->switchSectionNoPrint(Sec);
3045 MCSymbol *Sym = Sec->getEndSymbol(OutContext);
3046 OutStreamer->emitLabel(Sym);
3047 }
3048
3049 // Finalize debug and EH information.
3050 for (auto &Handler : Handlers)
3051 Handler->endModule();
3052 for (auto &Handler : EHHandlers)
3053 Handler->endModule();
3054
3055 // This deletes all the ephemeral handlers that AsmPrinter added, while
3056 // keeping all the user-added handlers alive until the AsmPrinter is
3057 // destroyed.
3058 EHHandlers.clear();
3059 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
3060 DD = nullptr;
3061
3062 // If the target wants to know about weak references, print them all.
3063 if (MAI->getWeakRefDirective()) {
3064 // FIXME: This is not lazy, it would be nice to only print weak references
3065 // to stuff that is actually used. Note that doing so would require targets
3066 // to notice uses in operands (due to constant exprs etc). This should
3067 // happen with the MC stuff eventually.
3068
3069 // Print out module-level global objects here.
3070 for (const auto &GO : M.global_objects()) {
3071 if (!GO.hasExternalWeakLinkage())
3072 continue;
3073 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
3074 }
3076 auto SymbolName = "swift_async_extendedFramePointerFlags";
3077 auto Global = M.getGlobalVariable(SymbolName);
3078 if (!Global) {
3079 auto PtrTy = PointerType::getUnqual(M.getContext());
3080 Global = new GlobalVariable(M, PtrTy, false,
3082 SymbolName);
3083 OutStreamer->emitSymbolAttribute(getSymbol(Global), MCSA_WeakReference);
3084 }
3085 }
3086 }
3087
3089
3090 // Emit llvm.ident metadata in an '.ident' directive.
3091 emitModuleIdents(M);
3092
3093 // Emit bytes for llvm.commandline metadata.
3094 // The command line metadata is emitted earlier on XCOFF.
3095 if (!Target.isOSBinFormatXCOFF())
3096 emitModuleCommandLines(M);
3097
3098 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
3099 // split-stack is used.
3100 if (TM.getTargetTriple().isOSBinFormatELF() && HasSplitStack) {
3101 OutStreamer->switchSection(OutContext.getELFSection(".note.GNU-split-stack",
3102 ELF::SHT_PROGBITS, 0));
3103 if (HasNoSplitStack)
3104 OutStreamer->switchSection(OutContext.getELFSection(
3105 ".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
3106 }
3107
3108 // If we don't have any trampolines, then we don't require stack memory
3109 // to be executable. Some targets have a directive to declare this.
3110 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
3111 bool HasTrampolineUses =
3112 InitTrampolineIntrinsic && !InitTrampolineIntrinsic->use_empty();
3113 MCSection *S = MAI->getStackSection(OutContext, /*Exec=*/HasTrampolineUses);
3114 if (S)
3115 OutStreamer->switchSection(S);
3116
3117 if (TM.Options.EmitAddrsig) {
3118 // Emit address-significance attributes for all globals.
3119 OutStreamer->emitAddrsig();
3120 for (const GlobalValue &GV : M.global_values()) {
3121 if (!GV.use_empty() && !GV.isThreadLocal() &&
3122 !GV.hasDLLImportStorageClass() &&
3123 !GV.getName().starts_with("llvm.") &&
3124 !GV.hasAtLeastLocalUnnamedAddr())
3125 OutStreamer->emitAddrsigSym(getSymbol(&GV));
3126 }
3127 }
3128
3129 // Emit symbol partition specifications (ELF only).
3130 if (Target.isOSBinFormatELF()) {
3131 unsigned UniqueID = 0;
3132 for (const GlobalValue &GV : M.global_values()) {
3133 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
3134 GV.getVisibility() != GlobalValue::DefaultVisibility)
3135 continue;
3136
3137 OutStreamer->switchSection(
3138 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
3139 "", false, ++UniqueID, nullptr));
3140 OutStreamer->emitBytes(GV.getPartition());
3141 OutStreamer->emitZeros(1);
3142 OutStreamer->emitValue(
3144 MAI->getCodePointerSize());
3145 }
3146 }
3147
3148 // Allow the target to emit any magic that it wants at the end of the file,
3149 // after everything else has gone out.
3151
3152 MMI = nullptr;
3153 AddrLabelSymbols = nullptr;
3154
3155 OutStreamer->finish();
3156 OutStreamer->reset();
3157 OwnedMLI.reset();
3158 OwnedMDT.reset();
3159
3160 return false;
3161}
3162
3164 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionID());
3165 if (Res.second)
3166 Res.first->second = createTempSymbol("exception");
3167 return Res.first->second;
3168}
3169
3171 MCContext &Ctx = MF->getContext();
3172 MCSymbol *Sym = Ctx.createTempSymbol("BB" + Twine(MF->getFunctionNumber()) +
3173 "_" + Twine(MBB.getNumber()) + "_CS");
3174 CurrentFnCallsiteEndSymbols[&MBB].push_back(Sym);
3175 return Sym;
3176}
3177
3179 this->MF = &MF;
3180 const Function &F = MF.getFunction();
3181
3182 // Record that there are split-stack functions, so we will emit a special
3183 // section to tell the linker.
3184 if (MF.shouldSplitStack()) {
3185 HasSplitStack = true;
3186
3187 if (!MF.getFrameInfo().needsSplitStackProlog())
3188 HasNoSplitStack = true;
3189 } else
3190 HasNoSplitStack = true;
3191
3192 // Get the function symbol.
3193 if (!MAI->isAIX()) {
3194 CurrentFnSym = getSymbol(&MF.getFunction());
3195 } else {
3196 assert(TM.getTargetTriple().isOSAIX() &&
3197 "Only AIX uses the function descriptor hooks.");
3198 // AIX is unique here in that the name of the symbol emitted for the
3199 // function body does not have the same name as the source function's
3200 // C-linkage name.
3201 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
3202 " initalized first.");
3203
3204 // Get the function entry point symbol.
3206 }
3207
3209 CurrentFnBegin = nullptr;
3210 CurrentFnBeginLocal = nullptr;
3211 CurrentSectionBeginSym = nullptr;
3213 MBBSectionRanges.clear();
3214 MBBSectionExceptionSyms.clear();
3215 bool NeedsLocalForSize = MAI->needsLocalForSize();
3216 if (F.hasFnAttribute("patchable-function-entry") ||
3217 F.hasFnAttribute("function-instrument") ||
3218 F.hasFnAttribute("xray-instruction-threshold") ||
3219 needFuncLabels(MF, *this) || NeedsLocalForSize ||
3220 MF.getTarget().Options.EmitStackSizeSection ||
3221 MF.getTarget().Options.EmitCallGraphSection ||
3222 MF.getTarget().Options.BBAddrMap) {
3223 CurrentFnBegin = createTempSymbol("func_begin");
3224 if (NeedsLocalForSize)
3226 }
3227
3228 ORE = GetORE(MF);
3229}
3230
3231namespace {
3232
3233// Keep track the alignment, constpool entries per Section.
3234 struct SectionCPs {
3235 MCSection *S;
3236 Align Alignment;
3238
3239 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
3240 };
3241
3242} // end anonymous namespace
3243
3245 if (TM.Options.EnableStaticDataPartitioning && C && SDPI && PSI)
3246 return SDPI->getConstantSectionPrefix(C, PSI);
3247
3248 return "";
3249}
3250
3251/// EmitConstantPool - Print to the current output stream assembly
3252/// representations of the constants in the constant pool MCP. This is
3253/// used to print out constants which have been "spilled to memory" by
3254/// the code generator.
3256 const MachineConstantPool *MCP = MF->getConstantPool();
3257 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
3258 if (CP.empty()) return;
3259
3260 // Calculate sections for constant pool entries. We collect entries to go into
3261 // the same section together to reduce amount of section switch statements.
3262 SmallVector<SectionCPs, 4> CPSections;
3263 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
3264 const MachineConstantPoolEntry &CPE = CP[i];
3265 Align Alignment = CPE.getAlign();
3266
3268
3269 const Constant *C = nullptr;
3270 if (!CPE.isMachineConstantPoolEntry())
3271 C = CPE.Val.ConstVal;
3272
3274 getDataLayout(), Kind, C, Alignment, &MF->getFunction(),
3276
3277 // The number of sections are small, just do a linear search from the
3278 // last section to the first.
3279 bool Found = false;
3280 unsigned SecIdx = CPSections.size();
3281 while (SecIdx != 0) {
3282 if (CPSections[--SecIdx].S == S) {
3283 Found = true;
3284 break;
3285 }
3286 }
3287 if (!Found) {
3288 SecIdx = CPSections.size();
3289 CPSections.push_back(SectionCPs(S, Alignment));
3290 }
3291
3292 if (Alignment > CPSections[SecIdx].Alignment)
3293 CPSections[SecIdx].Alignment = Alignment;
3294 CPSections[SecIdx].CPEs.push_back(i);
3295 }
3296
3297 // Now print stuff into the calculated sections.
3298 const MCSection *CurSection = nullptr;
3299 unsigned Offset = 0;
3300 for (const SectionCPs &CPSection : CPSections) {
3301 for (unsigned CPI : CPSection.CPEs) {
3302 MCSymbol *Sym = GetCPISymbol(CPI);
3303 if (!Sym->isUndefined())
3304 continue;
3305
3306 if (CurSection != CPSection.S) {
3307 OutStreamer->switchSection(CPSection.S);
3308 emitAlignment(Align(CPSection.Alignment));
3309 CurSection = CPSection.S;
3310 Offset = 0;
3311 }
3312
3313 MachineConstantPoolEntry CPE = CP[CPI];
3314
3315 // Emit inter-object padding for alignment.
3316 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
3317 OutStreamer->emitZeros(NewOffset - Offset);
3318
3319 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
3320
3321 OutStreamer->emitLabel(Sym);
3324 else
3326 }
3327 }
3328}
3329
3330// Print assembly representations of the jump tables used by the current
3331// function.
3333 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
3334 if (!MJTI) return;
3335
3336 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
3337 if (JT.empty()) return;
3338
3339 if (!TM.Options.EnableStaticDataPartitioning) {
3340 emitJumpTableImpl(*MJTI, llvm::to_vector(llvm::seq<unsigned>(JT.size())));
3341 return;
3342 }
3343
3344 SmallVector<unsigned> HotJumpTableIndices, ColdJumpTableIndices;
3345 // When static data partitioning is enabled, collect jump table entries that
3346 // go into the same section together to reduce the amount of section switch
3347 // statements.
3348 for (unsigned JTI = 0, JTSize = JT.size(); JTI < JTSize; ++JTI) {
3349 if (JT[JTI].Hotness == MachineFunctionDataHotness::Cold) {
3350 ColdJumpTableIndices.push_back(JTI);
3351 } else {
3352 HotJumpTableIndices.push_back(JTI);
3353 }
3354 }
3355
3356 emitJumpTableImpl(*MJTI, HotJumpTableIndices);
3357 emitJumpTableImpl(*MJTI, ColdJumpTableIndices);
3358}
3359
3360void AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
3361 ArrayRef<unsigned> JumpTableIndices) {
3363 JumpTableIndices.empty())
3364 return;
3365
3367 const Function &F = MF->getFunction();
3368 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3369 MCSection *JumpTableSection = nullptr;
3370
3371 const bool UseLabelDifference =
3374 // Pick the directive to use to print the jump table entries, and switch to
3375 // the appropriate section.
3376 const bool JTInDiffSection =
3377 !TLOF.shouldPutJumpTableInFunctionSection(UseLabelDifference, F);
3378 if (JTInDiffSection) {
3380 JumpTableSection =
3381 TLOF.getSectionForJumpTable(F, TM, &JT[JumpTableIndices.front()]);
3382 } else {
3383 JumpTableSection = TLOF.getSectionForJumpTable(F, TM);
3384 }
3385 OutStreamer->switchSection(JumpTableSection);
3386 }
3387
3388 const DataLayout &DL = MF->getDataLayout();
3390
3391 // Jump tables in code sections are marked with a data_region directive
3392 // where that's supported.
3393 if (!JTInDiffSection)
3394 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
3395
3396 for (const unsigned JumpTableIndex : JumpTableIndices) {
3397 ArrayRef<MachineBasicBlock *> JTBBs = JT[JumpTableIndex].MBBs;
3398
3399 // If this jump table was deleted, ignore it.
3400 if (JTBBs.empty())
3401 continue;
3402
3403 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
3404 /// emit a .set directive for each unique entry.
3406 MAI->doesSetDirectiveSuppressReloc()) {
3407 SmallPtrSet<const MachineBasicBlock *, 16> EmittedSets;
3408 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3409 const MCExpr *Base =
3410 TLI->getPICJumpTableRelocBaseExpr(MF, JumpTableIndex, OutContext);
3411 for (const MachineBasicBlock *MBB : JTBBs) {
3412 if (!EmittedSets.insert(MBB).second)
3413 continue;
3414
3415 // .set LJTSet, LBB32-base
3416 const MCExpr *LHS =
3418 OutStreamer->emitAssignment(
3419 GetJTSetSymbol(JumpTableIndex, MBB->getNumber()),
3421 }
3422 }
3423
3424 // On some targets (e.g. Darwin) we want to emit two consecutive labels
3425 // before each jump table. The first label is never referenced, but tells
3426 // the assembler and linker the extents of the jump table object. The
3427 // second label is actually referenced by the code.
3428 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
3429 // FIXME: This doesn't have to have any specific name, just any randomly
3430 // named and numbered local label started with 'l' would work. Simplify
3431 // GetJTISymbol.
3432 OutStreamer->emitLabel(GetJTISymbol(JumpTableIndex, true));
3433
3434 MCSymbol *JTISymbol = GetJTISymbol(JumpTableIndex);
3435 OutStreamer->emitLabel(JTISymbol);
3436
3437 // Defer MCAssembler based constant folding due to a performance issue. The
3438 // label differences will be evaluated at write time.
3439 for (const MachineBasicBlock *MBB : JTBBs)
3440 emitJumpTableEntry(MJTI, MBB, JumpTableIndex);
3441 }
3442
3444 emitJumpTableSizesSection(MJTI, MF->getFunction());
3445
3446 if (!JTInDiffSection)
3447 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
3448}
3449
3450void AsmPrinter::emitJumpTableSizesSection(const MachineJumpTableInfo &MJTI,
3451 const Function &F) const {
3452 const std::vector<MachineJumpTableEntry> &JT = MJTI.getJumpTables();
3453
3454 if (JT.empty())
3455 return;
3456
3457 StringRef GroupName = F.hasComdat() ? F.getComdat()->getName() : "";
3458 MCSection *JumpTableSizesSection = nullptr;
3459 StringRef sectionName = ".llvm_jump_table_sizes";
3460
3461 bool isElf = TM.getTargetTriple().isOSBinFormatELF();
3462 bool isCoff = TM.getTargetTriple().isOSBinFormatCOFF();
3463
3464 if (!isCoff && !isElf)
3465 return;
3466
3467 if (isElf) {
3468 auto *LinkedToSym = static_cast<MCSymbolELF *>(CurrentFnSym);
3469 int Flags = F.hasComdat() ? static_cast<int>(ELF::SHF_GROUP) : 0;
3470
3471 JumpTableSizesSection = OutContext.getELFSection(
3472 sectionName, ELF::SHT_LLVM_JT_SIZES, Flags, 0, GroupName, F.hasComdat(),
3473 MCSection::NonUniqueID, LinkedToSym);
3474 } else if (isCoff) {
3475 if (F.hasComdat()) {
3476 JumpTableSizesSection = OutContext.getCOFFSection(
3477 sectionName,
3480 F.getComdat()->getName(), COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
3481 } else {
3482 JumpTableSizesSection = OutContext.getCOFFSection(
3486 }
3487 }
3488
3489 OutStreamer->switchSection(JumpTableSizesSection);
3490
3491 for (unsigned JTI = 0, E = JT.size(); JTI != E; ++JTI) {
3492 const std::vector<MachineBasicBlock *> &JTBBs = JT[JTI].MBBs;
3493 OutStreamer->emitSymbolValue(GetJTISymbol(JTI), TM.getProgramPointerSize());
3494 OutStreamer->emitIntValue(JTBBs.size(), TM.getProgramPointerSize());
3495 }
3496}
3497
3498/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
3499/// current stream.
3501 const MachineBasicBlock *MBB,
3502 unsigned UID) const {
3503 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
3504 const MCExpr *Value = nullptr;
3505 switch (MJTI.getEntryKind()) {
3507 llvm_unreachable("Cannot emit EK_Inline jump table entry");
3510 llvm_unreachable("MIPS specific");
3512 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
3513 &MJTI, MBB, UID, OutContext);
3514 break;
3516 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
3517 // .word LBB123
3519 break;
3520
3523 // Each entry is the address of the block minus the address of the jump
3524 // table. This is used for PIC jump tables where gprel32 is not supported.
3525 // e.g.:
3526 // .word LBB123 - LJTI1_2
3527 // If the .set directive avoids relocations, this is emitted as:
3528 // .set L4_5_set_123, LBB123 - LJTI1_2
3529 // .word L4_5_set_123
3531 MAI->doesSetDirectiveSuppressReloc()) {
3532 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
3533 OutContext);
3534 break;
3535 }
3537 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
3540 break;
3541 }
3542 }
3543
3544 assert(Value && "Unknown entry kind!");
3545
3546 unsigned EntrySize = MJTI.getEntrySize(getDataLayout());
3547 OutStreamer->emitValue(Value, EntrySize);
3548}
3549
3550/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
3551/// special global used by LLVM. If so, emit it and return true, otherwise
3552/// do nothing and return false.
3554 if (GV->getName() == "llvm.used") {
3555 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
3556 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
3557 return true;
3558 }
3559
3560 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
3561 if (GV->getSection() == "llvm.metadata" ||
3563 return true;
3564
3565 if (GV->getName() == "llvm.arm64ec.symbolmap") {
3566 // For ARM64EC, print the table that maps between symbols and the
3567 // corresponding thunks to translate between x64 and AArch64 code.
3568 // This table is generated by AArch64Arm64ECCallLowering.
3569 OutStreamer->switchSection(
3570 OutContext.getCOFFSection(".hybmp$x", COFF::IMAGE_SCN_LNK_INFO));
3571 auto *Arr = cast<ConstantArray>(GV->getInitializer());
3572 for (auto &U : Arr->operands()) {
3573 auto *C = cast<Constant>(U);
3574 auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
3575 auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
3576 int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
3577
3578 if (Src->hasDLLImportStorageClass()) {
3579 // For now, we assume dllimport functions aren't directly called.
3580 // (We might change this later to match MSVC.)
3581 OutStreamer->emitCOFFSymbolIndex(
3582 OutContext.getOrCreateSymbol("__imp_" + Src->getName()));
3583 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3584 OutStreamer->emitInt32(Kind);
3585 } else {
3586 // FIXME: For non-dllimport functions, MSVC emits the same entry
3587 // twice, for reasons I don't understand. I have to assume the linker
3588 // ignores the redundant entry; there aren't any reasonable semantics
3589 // to attach to it.
3590 OutStreamer->emitCOFFSymbolIndex(getSymbol(Src));
3591 OutStreamer->emitCOFFSymbolIndex(getSymbol(Dst));
3592 OutStreamer->emitInt32(Kind);
3593 }
3594 }
3595 return true;
3596 }
3597
3598 if (!GV->hasAppendingLinkage()) return false;
3599
3600 assert(GV->hasInitializer() && "Not a special LLVM global!");
3601
3602 if (GV->getName() == "llvm.global_ctors") {
3604 /* isCtor */ true);
3605
3606 return true;
3607 }
3608
3609 if (GV->getName() == "llvm.global_dtors") {
3611 /* isCtor */ false);
3612
3613 return true;
3614 }
3615
3616 GV->getContext().emitError(
3617 "unknown special variable with appending linkage: " +
3618 GV->getNameOrAsOperand());
3619 return true;
3620}
3621
3622/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
3623/// global in the specified llvm.used list.
3624void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
3625 // Should be an array of 'i8*'.
3626 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3627 const GlobalValue *GV =
3629 if (GV)
3630 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
3631 }
3632}
3633
3635 const Constant *List,
3636 SmallVector<Structor, 8> &Structors) {
3637 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
3638 // the init priority.
3640 return;
3641
3642 // Gather the structors in a form that's convenient for sorting by priority.
3643 for (Value *O : cast<ConstantArray>(List)->operands()) {
3644 auto *CS = cast<ConstantStruct>(O);
3645 if (CS->getOperand(1)->isNullValue())
3646 break; // Found a null terminator, skip the rest.
3647 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
3648 if (!Priority)
3649 continue; // Malformed.
3650 Structors.push_back(Structor());
3651 Structor &S = Structors.back();
3652 S.Priority = Priority->getLimitedValue(65535);
3653 S.Func = CS->getOperand(1);
3654 if (!CS->getOperand(2)->isNullValue()) {
3655 if (TM.getTargetTriple().isOSAIX()) {
3656 CS->getContext().emitError(
3657 "associated data of XXStructor list is not yet supported on AIX");
3658 }
3659
3660 S.ComdatKey =
3661 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
3662 }
3663 }
3664
3665 // Emit the function pointers in the target-specific order
3666 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
3667 return L.Priority < R.Priority;
3668 });
3669}
3670
3671/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
3672/// priority.
3674 bool IsCtor) {
3675 SmallVector<Structor, 8> Structors;
3676 preprocessXXStructorList(DL, List, Structors);
3677 if (Structors.empty())
3678 return;
3679
3680 // Emit the structors in reverse order if we are using the .ctor/.dtor
3681 // initialization scheme.
3682 if (!TM.Options.UseInitArray)
3683 std::reverse(Structors.begin(), Structors.end());
3684
3685 const Align Align = DL.getPointerPrefAlignment(DL.getProgramAddressSpace());
3686 for (Structor &S : Structors) {
3688 const MCSymbol *KeySym = nullptr;
3689 if (GlobalValue *GV = S.ComdatKey) {
3690 if (GV->isDeclarationForLinker())
3691 // If the associated variable is not defined in this module
3692 // (it might be available_externally, or have been an
3693 // available_externally definition that was dropped by the
3694 // EliminateAvailableExternally pass), some other TU
3695 // will provide its dynamic initializer.
3696 continue;
3697
3698 KeySym = getSymbol(GV);
3699 }
3700
3701 MCSection *OutputSection =
3702 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
3703 : Obj.getStaticDtorSection(S.Priority, KeySym));
3704 OutStreamer->switchSection(OutputSection);
3705 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
3707 emitXXStructor(DL, S.Func);
3708 }
3709}
3710
3711void AsmPrinter::emitModuleIdents(Module &M) {
3712 if (!MAI->hasIdentDirective())
3713 return;
3714
3715 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
3716 for (const MDNode *N : NMD->operands()) {
3717 assert(N->getNumOperands() == 1 &&
3718 "llvm.ident metadata entry can have only one operand");
3719 const MDString *S = cast<MDString>(N->getOperand(0));
3720 OutStreamer->emitIdent(S->getString());
3721 }
3722 }
3723}
3724
3725void AsmPrinter::emitModuleCommandLines(Module &M) {
3726 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
3727 if (!CommandLine)
3728 return;
3729
3730 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3731 if (!NMD || !NMD->getNumOperands())
3732 return;
3733
3734 OutStreamer->pushSection();
3735 OutStreamer->switchSection(CommandLine);
3736 OutStreamer->emitZeros(1);
3737 for (const MDNode *N : NMD->operands()) {
3738 assert(N->getNumOperands() == 1 &&
3739 "llvm.commandline metadata entry can have only one operand");
3740 const MDString *S = cast<MDString>(N->getOperand(0));
3741 OutStreamer->emitBytes(S->getString());
3742 OutStreamer->emitZeros(1);
3743 }
3744 OutStreamer->popSection();
3745}
3746
3747//===--------------------------------------------------------------------===//
3748// Emission and print routines
3749//
3750
3751/// Emit a byte directive and value.
3752///
3753void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
3754
3755/// Emit a short directive and value.
3756void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
3757
3758/// Emit a long directive and value.
3759void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
3760
3761/// EmitSLEB128 - emit the specified signed leb128 value.
3762void AsmPrinter::emitSLEB128(int64_t Value, const char *Desc) const {
3763 if (isVerbose() && Desc)
3764 OutStreamer->AddComment(Desc);
3765
3766 OutStreamer->emitSLEB128IntValue(Value);
3767}
3768
3770 unsigned PadTo) const {
3771 if (isVerbose() && Desc)
3772 OutStreamer->AddComment(Desc);
3773
3774 OutStreamer->emitULEB128IntValue(Value, PadTo);
3775}
3776
3777/// Emit a long long directive and value.
3779 OutStreamer->emitInt64(Value);
3780}
3781
3782/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
3783/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
3784/// .set if it avoids relocations.
3786 unsigned Size) const {
3787 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
3788}
3789
3790/// Emit something like ".uleb128 Hi-Lo".
3792 const MCSymbol *Lo) const {
3793 OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
3794}
3795
3796/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
3797/// where the size in bytes of the directive is specified by Size and Label
3798/// specifies the label. This implicitly uses .set if it is available.
3800 unsigned Size,
3801 bool IsSectionRelative) const {
3802 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
3803 OutStreamer->emitCOFFSecRel32(Label, Offset);
3804 if (Size > 4)
3805 OutStreamer->emitZeros(Size - 4);
3806 return;
3807 }
3808
3809 // Emit Label+Offset (or just Label if Offset is zero)
3810 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
3811 if (Offset)
3814
3815 OutStreamer->emitValue(Expr, Size);
3816}
3817
3818//===----------------------------------------------------------------------===//
3819
3820// EmitAlignment - Emit an alignment directive to the specified power of
3821// two boundary. If a global value is specified, and if that global has
3822// an explicit alignment requested, it will override the alignment request
3823// if required for correctness.
3825 unsigned MaxBytesToEmit) const {
3826 if (GV)
3827 Alignment = getGVAlignment(GV, GV->getDataLayout(), Alignment);
3828
3829 if (Alignment == Align(1))
3830 return; // 1-byte aligned: no need to emit alignment.
3831
3832 if (getCurrentSection()->isText()) {
3833 const MCSubtargetInfo *STI = nullptr;
3834 if (this->MF)
3835 STI = &getSubtargetInfo();
3836 else
3837 STI = TM.getMCSubtargetInfo();
3838 OutStreamer->emitCodeAlignment(Alignment, STI, MaxBytesToEmit);
3839 } else
3840 OutStreamer->emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
3841}
3842
3843//===----------------------------------------------------------------------===//
3844// Constant emission.
3845//===----------------------------------------------------------------------===//
3846
3848 const Constant *BaseCV,
3849 uint64_t Offset) {
3850 MCContext &Ctx = OutContext;
3851
3852 if (CV->isNullValue() || isa<UndefValue>(CV))
3853 return MCConstantExpr::create(0, Ctx);
3854
3855 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
3856 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
3857
3858 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV))
3859 return MCConstantExpr::create(CB->getZExtValue(), Ctx);
3860
3861 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV))
3862 return lowerConstantPtrAuth(*CPA);
3863
3864 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
3865 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
3866
3867 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
3868 return lowerBlockAddressConstant(*BA);
3869
3870 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
3872 getSymbol(Equiv->getGlobalValue()), nullptr, 0, std::nullopt, TM);
3873
3874 if (const NoCFIValue *NC = dyn_cast<NoCFIValue>(CV))
3875 return MCSymbolRefExpr::create(getSymbol(NC->getGlobalValue()), Ctx);
3876
3877 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
3878 if (!CE) {
3879 llvm_unreachable("Unknown constant value to lower!");
3880 }
3881
3882 // The constant expression opcodes are limited to those that are necessary
3883 // to represent relocations on supported targets. Expressions involving only
3884 // constant addresses are constant folded instead.
3885 switch (CE->getOpcode()) {
3886 default:
3887 break; // Error
3888 case Instruction::AddrSpaceCast: {
3889 const Constant *Op = CE->getOperand(0);
3890 unsigned DstAS = CE->getType()->getPointerAddressSpace();
3891 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
3892 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
3893 return lowerConstant(Op);
3894
3895 break; // Error
3896 }
3897 case Instruction::GetElementPtr: {
3898 // Generate a symbolic expression for the byte address
3899 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
3900 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
3901
3902 const MCExpr *Base = lowerConstant(CE->getOperand(0));
3903 if (!OffsetAI)
3904 return Base;
3905
3906 int64_t Offset = OffsetAI.getSExtValue();
3908 Ctx);
3909 }
3910
3911 case Instruction::Trunc:
3912 // We emit the value and depend on the assembler to truncate the generated
3913 // expression properly. This is important for differences between
3914 // blockaddress labels. Since the two labels are in the same function, it
3915 // is reasonable to treat their delta as a 32-bit value.
3916 [[fallthrough]];
3917 case Instruction::BitCast:
3918 return lowerConstant(CE->getOperand(0), BaseCV, Offset);
3919
3920 case Instruction::IntToPtr: {
3921 const DataLayout &DL = getDataLayout();
3922
3923 // Handle casts to pointers by changing them into casts to the appropriate
3924 // integer type. This promotes constant folding and simplifies this code.
3925 Constant *Op = CE->getOperand(0);
3926 Op = ConstantFoldIntegerCast(Op, DL.getIntPtrType(CV->getType()),
3927 /*IsSigned*/ false, DL);
3928 if (Op)
3929 return lowerConstant(Op);
3930
3931 break; // Error
3932 }
3933
3934 case Instruction::PtrToAddr:
3935 case Instruction::PtrToInt: {
3936 const DataLayout &DL = getDataLayout();
3937
3938 // Support only foldable casts to/from pointers that can be eliminated by
3939 // changing the pointer to the appropriately sized integer type.
3940 Constant *Op = CE->getOperand(0);
3941 Type *Ty = CE->getType();
3942
3943 const MCExpr *OpExpr = lowerConstant(Op);
3944
3945 // We can emit the pointer value into this slot if the slot is an
3946 // integer slot equal to the size of the pointer.
3947 //
3948 // If the pointer is larger than the resultant integer, then
3949 // as with Trunc just depend on the assembler to truncate it.
3950 if (DL.getTypeAllocSize(Ty).getFixedValue() <=
3951 DL.getTypeAllocSize(Op->getType()).getFixedValue())
3952 return OpExpr;
3953
3954 break; // Error
3955 }
3956
3957 case Instruction::Sub: {
3958 GlobalValue *LHSGV, *RHSGV;
3959 APInt LHSOffset, RHSOffset;
3960 DSOLocalEquivalent *DSOEquiv;
3961 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
3962 getDataLayout(), &DSOEquiv) &&
3963 IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
3964 getDataLayout())) {
3965 auto *LHSSym = getSymbol(LHSGV);
3966 auto *RHSSym = getSymbol(RHSGV);
3967 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
3968 std::optional<int64_t> PCRelativeOffset;
3969 if (getObjFileLowering().hasPLTPCRelative() && RHSGV == BaseCV)
3970 PCRelativeOffset = Offset;
3971
3972 // Try the generic symbol difference first.
3974 LHSGV, RHSGV, Addend, PCRelativeOffset, TM);
3975
3976 // (ELF-specific) If the generic symbol difference does not apply, and
3977 // LHS is a dso_local_equivalent of a function, reference the PLT entry
3978 // instead. Note: A default visibility symbol is by default preemptible
3979 // during linking, and should not be referenced with PC-relative
3980 // relocations. Therefore, use a PLT relocation even if the function is
3981 // dso_local.
3982 if (DSOEquiv && TM.getTargetTriple().isOSBinFormatELF())
3984 LHSSym, RHSSym, Addend, PCRelativeOffset, TM);
3985
3986 // Otherwise, return LHS-RHS+Addend.
3987 if (!Res) {
3988 Res =
3990 MCSymbolRefExpr::create(RHSSym, Ctx), Ctx);
3991 if (Addend != 0)
3993 Res, MCConstantExpr::create(Addend, Ctx), Ctx);
3994 }
3995 return Res;
3996 }
3997
3998 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
3999 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4000 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
4001 break;
4002 }
4003
4004 case Instruction::Add: {
4005 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
4006 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
4007 return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
4008 }
4009 }
4010
4011 // If the code isn't optimized, there may be outstanding folding
4012 // opportunities. Attempt to fold the expression using DataLayout as a
4013 // last resort before giving up.
4015 if (C != CE)
4016 return lowerConstant(C);
4017
4018 // Otherwise report the problem to the user.
4019 std::string S;
4020 raw_string_ostream OS(S);
4021 OS << "unsupported expression in static initializer: ";
4022 CE->printAsOperand(OS, /*PrintType=*/false,
4023 !MF ? nullptr : MF->getFunction().getParent());
4024 CE->getContext().emitError(S);
4025 return MCConstantExpr::create(0, Ctx);
4026}
4027
4028static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
4029 AsmPrinter &AP,
4030 const Constant *BaseCV = nullptr,
4031 uint64_t Offset = 0,
4032 AsmPrinter::AliasMapTy *AliasList = nullptr);
4033
4034static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
4035static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
4036
4037/// isRepeatedByteSequence - Determine whether the given value is
4038/// composed of a repeated sequence of identical bytes and return the
4039/// byte value. If it is not a repeated sequence, return -1.
4041 StringRef Data = V->getRawDataValues();
4042 assert(!Data.empty() && "Empty aggregates should be CAZ node");
4043 char C = Data[0];
4044 for (unsigned i = 1, e = Data.size(); i != e; ++i)
4045 if (Data[i] != C) return -1;
4046 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
4047}
4048
4049/// isRepeatedByteSequence - Determine whether the given value is
4050/// composed of a repeated sequence of identical bytes and return the
4051/// byte value. If it is not a repeated sequence, return -1.
4052static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
4053 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
4054 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
4055 assert(Size % 8 == 0);
4056
4057 // Extend the element to take zero padding into account.
4058 APInt Value = CI->getValue().zext(Size);
4059 if (!Value.isSplat(8))
4060 return -1;
4061
4062 return Value.zextOrTrunc(8).getZExtValue();
4063 }
4064 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
4065 // Make sure all array elements are sequences of the same repeated
4066 // byte.
4067 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
4068 Constant *Op0 = CA->getOperand(0);
4069 int Byte = isRepeatedByteSequence(Op0, DL);
4070 if (Byte == -1)
4071 return -1;
4072
4073 // All array elements must be equal.
4074 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
4075 if (CA->getOperand(i) != Op0)
4076 return -1;
4077 return Byte;
4078 }
4079
4081 return isRepeatedByteSequence(CDS);
4082
4083 return -1;
4084}
4085
4087 AsmPrinter::AliasMapTy *AliasList) {
4088 if (AliasList) {
4089 auto AliasIt = AliasList->find(Offset);
4090 if (AliasIt != AliasList->end()) {
4091 for (const GlobalAlias *GA : AliasIt->second)
4092 AP.OutStreamer->emitLabel(AP.getSymbol(GA));
4093 AliasList->erase(Offset);
4094 }
4095 }
4096}
4097
4099 const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP,
4100 AsmPrinter::AliasMapTy *AliasList) {
4101 // See if we can aggregate this into a .fill, if so, emit it as such.
4102 int Value = isRepeatedByteSequence(CDS, DL);
4103 if (Value != -1) {
4104 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
4105 // Don't emit a 1-byte object as a .fill.
4106 if (Bytes > 1)
4107 return AP.OutStreamer->emitFill(Bytes, Value);
4108 }
4109
4110 // If this can be emitted with .ascii/.asciz, emit it as such.
4111 if (CDS->isString())
4112 return AP.OutStreamer->emitBytes(CDS->getAsString());
4113
4114 // Otherwise, emit the values in successive locations.
4115 uint64_t ElementByteSize = CDS->getElementByteSize();
4116 if (isa<IntegerType>(CDS->getElementType()) ||
4117 isa<ByteType>(CDS->getElementType())) {
4118 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4119 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4120 if (AP.isVerbose())
4121 AP.OutStreamer->getCommentOS()
4122 << format("0x%" PRIx64 "\n", CDS->getElementAsInteger(I));
4123 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(I),
4124 ElementByteSize);
4125 }
4126 } else {
4127 Type *ET = CDS->getElementType();
4128 for (uint64_t I = 0, E = CDS->getNumElements(); I != E; ++I) {
4129 emitGlobalAliasInline(AP, ElementByteSize * I, AliasList);
4131 }
4132 }
4133
4134 unsigned Size = DL.getTypeAllocSize(CDS->getType());
4135 unsigned EmittedSize =
4136 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
4137 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
4138 if (unsigned Padding = Size - EmittedSize)
4139 AP.OutStreamer->emitZeros(Padding);
4140}
4141
4143 const ConstantArray *CA, AsmPrinter &AP,
4144 const Constant *BaseCV, uint64_t Offset,
4145 AsmPrinter::AliasMapTy *AliasList) {
4146 // See if we can aggregate some values. Make sure it can be
4147 // represented as a series of bytes of the constant value.
4148 int Value = isRepeatedByteSequence(CA, DL);
4149
4150 if (Value != -1) {
4151 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
4152 AP.OutStreamer->emitFill(Bytes, Value);
4153 } else {
4154 for (unsigned I = 0, E = CA->getNumOperands(); I != E; ++I) {
4155 emitGlobalConstantImpl(DL, CA->getOperand(I), AP, BaseCV, Offset,
4156 AliasList);
4157 Offset += DL.getTypeAllocSize(CA->getOperand(I)->getType());
4158 }
4159 }
4160}
4161
4162static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP);
4163
4164static void emitGlobalConstantVector(const DataLayout &DL, const Constant *CV,
4165 AsmPrinter &AP,
4166 AsmPrinter::AliasMapTy *AliasList) {
4167 auto *VTy = cast<FixedVectorType>(CV->getType());
4168 Type *ElementType = VTy->getElementType();
4169 uint64_t ElementSizeInBits = DL.getTypeSizeInBits(ElementType);
4170 uint64_t ElementAllocSizeInBits = DL.getTypeAllocSizeInBits(ElementType);
4171 uint64_t EmittedSize;
4172 if (ElementSizeInBits != ElementAllocSizeInBits) {
4173 // If the allocation size of an element is different from the size in bits,
4174 // printing each element separately will insert incorrect padding.
4175 //
4176 // The general algorithm here is complicated; instead of writing it out
4177 // here, just use the existing code in ConstantFolding.
4178 Type *IntT =
4179 IntegerType::get(CV->getContext(), DL.getTypeSizeInBits(CV->getType()));
4181 ConstantExpr::getBitCast(const_cast<Constant *>(CV), IntT), DL));
4182 if (!CI) {
4184 "Cannot lower vector global with unusual element type");
4185 }
4186 emitGlobalAliasInline(AP, 0, AliasList);
4188 EmittedSize = DL.getTypeStoreSize(CV->getType());
4189 } else {
4190 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
4191 emitGlobalAliasInline(AP, DL.getTypeAllocSize(CV->getType()) * I, AliasList);
4193 }
4194 EmittedSize = DL.getTypeAllocSize(ElementType) * VTy->getNumElements();
4195 }
4196
4197 unsigned Size = DL.getTypeAllocSize(CV->getType());
4198 if (unsigned Padding = Size - EmittedSize)
4199 AP.OutStreamer->emitZeros(Padding);
4200}
4201
4203 const ConstantStruct *CS, AsmPrinter &AP,
4204 const Constant *BaseCV, uint64_t Offset,
4205 AsmPrinter::AliasMapTy *AliasList) {
4206 // Print the fields in successive locations. Pad to align if needed!
4207 uint64_t Size = DL.getTypeAllocSize(CS->getType());
4208 const StructLayout *Layout = DL.getStructLayout(CS->getType());
4209 uint64_t SizeSoFar = 0;
4210 for (unsigned I = 0, E = CS->getNumOperands(); I != E; ++I) {
4211 const Constant *Field = CS->getOperand(I);
4212
4213 // Print the actual field value.
4214 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar,
4215 AliasList);
4216
4217 // Check if padding is needed and insert one or more 0s.
4218 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
4219 uint64_t PadSize = ((I == E - 1 ? Size : Layout->getElementOffset(I + 1)) -
4220 Layout->getElementOffset(I)) -
4221 FieldSize;
4222 SizeSoFar += FieldSize + PadSize;
4223
4224 // Insert padding - this may include padding to increase the size of the
4225 // current field up to the ABI size (if the struct is not packed) as well
4226 // as padding to ensure that the next field starts at the right offset.
4227 AP.OutStreamer->emitZeros(PadSize);
4228 }
4229 assert(SizeSoFar == Layout->getSizeInBytes() &&
4230 "Layout of constant struct may be incorrect!");
4231}
4232
4233static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
4234 assert(ET && "Unknown float type");
4235 APInt API = APF.bitcastToAPInt();
4236
4237 // First print a comment with what we think the original floating-point value
4238 // should have been.
4239 if (AP.isVerbose()) {
4240 SmallString<8> StrVal;
4241 APF.toString(StrVal);
4242 ET->print(AP.OutStreamer->getCommentOS());
4243 AP.OutStreamer->getCommentOS() << ' ' << StrVal << '\n';
4244 }
4245
4246 // Now iterate through the APInt chunks, emitting them in endian-correct
4247 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
4248 // floats).
4249 unsigned NumBytes = API.getBitWidth() / 8;
4250 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
4251 const uint64_t *p = API.getRawData();
4252
4253 // PPC's long double has odd notions of endianness compared to how LLVM
4254 // handles it: p[0] goes first for *big* endian on PPC.
4255 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
4256 int Chunk = API.getNumWords() - 1;
4257
4258 if (TrailingBytes)
4259 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
4260
4261 for (; Chunk >= 0; --Chunk)
4262 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4263 } else {
4264 unsigned Chunk;
4265 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
4266 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
4267
4268 if (TrailingBytes)
4269 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
4270 }
4271
4272 // Emit the tail padding for the long double.
4273 const DataLayout &DL = AP.getDataLayout();
4274 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
4275}
4276
4277static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
4278 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
4279}
4280
4282 uint64_t TypeStoreSize,
4283 AsmPrinter &AP) {
4284 const DataLayout &DL = AP.getDataLayout();
4285 unsigned BitWidth = Val.getBitWidth();
4286
4287 // Copy the value as we may massage the layout for constants whose bit width
4288 // is not a multiple of 64-bits.
4289 APInt Realigned(Val);
4290 uint64_t ExtraBits = 0;
4291 unsigned ExtraBitsSize = BitWidth & 63;
4292
4293 if (ExtraBitsSize) {
4294 // The bit width of the data is not a multiple of 64-bits.
4295 // The extra bits are expected to be at the end of the chunk of the memory.
4296 // Little endian:
4297 // * Nothing to be done, just record the extra bits to emit.
4298 // Big endian:
4299 // * Record the extra bits to emit.
4300 // * Realign the raw data to emit the chunks of 64-bits.
4301 if (DL.isBigEndian()) {
4302 // Basically the structure of the raw data is a chunk of 64-bits cells:
4303 // 0 1 BitWidth / 64
4304 // [chunk1][chunk2] ... [chunkN].
4305 // The most significant chunk is chunkN and it should be emitted first.
4306 // However, due to the alignment issue chunkN contains useless bits.
4307 // Realign the chunks so that they contain only useful information:
4308 // ExtraBits 0 1 (BitWidth / 64) - 1
4309 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
4310 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
4311 ExtraBits =
4312 Realigned.getRawData()[0] & (((uint64_t)-1) >> (64 - ExtraBitsSize));
4313 if (BitWidth >= 64)
4314 Realigned.lshrInPlace(ExtraBitsSize);
4315 } else
4316 ExtraBits = Realigned.getRawData()[BitWidth / 64];
4317 }
4318
4319 // We don't expect assemblers to support data directives
4320 // for more than 64 bits, so we emit the data in at most 64-bit
4321 // quantities at a time.
4322 const uint64_t *RawData = Realigned.getRawData();
4323 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
4324 uint64_t ChunkVal = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
4325 AP.OutStreamer->emitIntValue(ChunkVal, 8);
4326 }
4327
4328 if (ExtraBitsSize) {
4329 // Emit the extra bits after the 64-bits chunks.
4330
4331 // Emit a directive that fills the expected size.
4332 uint64_t Size = TypeStoreSize - (BitWidth / 64) * 8;
4333 assert(Size && Size * 8 >= ExtraBitsSize &&
4334 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) ==
4335 ExtraBits &&
4336 "Directive too small for extra bits.");
4337 AP.OutStreamer->emitIntValue(ExtraBits, Size);
4338 }
4339}
4340
4342 AsmPrinter &AP) {
4344 CB->getValue(), AP.getDataLayout().getTypeStoreSize(CB->getType()), AP);
4345}
4346
4351
4352/// Transform a not absolute MCExpr containing a reference to a GOT
4353/// equivalent global, by a target specific GOT pc relative access to the
4354/// final symbol.
4356 const Constant *BaseCst,
4357 uint64_t Offset) {
4358 // The global @foo below illustrates a global that uses a got equivalent.
4359 //
4360 // @bar = global i32 42
4361 // @gotequiv = private unnamed_addr constant i32* @bar
4362 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
4363 // i64 ptrtoint (i32* @foo to i64))
4364 // to i32)
4365 //
4366 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
4367 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
4368 // form:
4369 //
4370 // foo = cstexpr, where
4371 // cstexpr := <gotequiv> - "." + <cst>
4372 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
4373 //
4374 // After canonicalization by evaluateAsRelocatable `ME` turns into:
4375 //
4376 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
4377 // gotpcrelcst := <offset from @foo base> + <cst>
4378 MCValue MV;
4379 if (!(*ME)->evaluateAsRelocatable(MV, nullptr) || MV.isAbsolute())
4380 return;
4381 const MCSymbol *GOTEquivSym = MV.getAddSym();
4382 if (!GOTEquivSym)
4383 return;
4384
4385 // Check that GOT equivalent symbol is cached.
4386 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
4387 return;
4388
4389 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
4390 if (!BaseGV)
4391 return;
4392
4393 // Check for a valid base symbol
4394 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
4395 const MCSymbol *SymB = MV.getSubSym();
4396
4397 if (!SymB || BaseSym != SymB)
4398 return;
4399
4400 // Make sure to match:
4401 //
4402 // gotpcrelcst := <offset from @foo base> + <cst>
4403 //
4404 int64_t GOTPCRelCst = Offset + MV.getConstant();
4405 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
4406 return;
4407
4408 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
4409 //
4410 // bar:
4411 // .long 42
4412 // gotequiv:
4413 // .quad bar
4414 // foo:
4415 // .long gotequiv - "." + <cst>
4416 //
4417 // is replaced by the target specific equivalent to:
4418 //
4419 // bar:
4420 // .long 42
4421 // foo:
4422 // .long bar@GOTPCREL+<gotpcrelcst>
4423 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
4424 const GlobalVariable *GV = Result.first;
4425 int NumUses = (int)Result.second;
4426 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
4427 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
4429 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
4430
4431 // Update GOT equivalent usage information
4432 --NumUses;
4433 if (NumUses >= 0)
4434 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
4435}
4436
4437static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
4438 AsmPrinter &AP, const Constant *BaseCV,
4440 AsmPrinter::AliasMapTy *AliasList) {
4441 assert((!AliasList || AP.TM.getTargetTriple().isOSBinFormatXCOFF()) &&
4442 "AliasList only expected for XCOFF");
4443 emitGlobalAliasInline(AP, Offset, AliasList);
4444 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4445
4446 // Globals with sub-elements such as combinations of arrays and structs
4447 // are handled recursively by emitGlobalConstantImpl. Keep track of the
4448 // constant symbol base and the current position with BaseCV and Offset.
4449 if (!BaseCV && CV->hasOneUse())
4450 BaseCV = dyn_cast<Constant>(CV->user_back());
4451
4453 StructType *structType;
4454 if (AliasList && (structType = llvm::dyn_cast<StructType>(CV->getType()))) {
4455 unsigned numElements = {structType->getNumElements()};
4456 if (numElements != 0) {
4457 // Handle cases of aliases to direct struct elements
4458 const StructLayout *Layout = DL.getStructLayout(structType);
4459 uint64_t SizeSoFar = 0;
4460 for (unsigned int i = 0; i < numElements - 1; ++i) {
4461 uint64_t GapToNext = Layout->getElementOffset(i + 1) - SizeSoFar;
4462 AP.OutStreamer->emitZeros(GapToNext);
4463 SizeSoFar += GapToNext;
4464 emitGlobalAliasInline(AP, Offset + SizeSoFar, AliasList);
4465 }
4466 AP.OutStreamer->emitZeros(Size - SizeSoFar);
4467 return;
4468 }
4469 }
4470 return AP.OutStreamer->emitZeros(Size);
4471 }
4472
4473 if (isa<UndefValue>(CV))
4474 return AP.OutStreamer->emitZeros(Size);
4475
4476 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
4477 if (isa<VectorType>(CV->getType()))
4478 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4479
4480 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4481 if (StoreSize <= 8) {
4482 if (AP.isVerbose())
4483 AP.OutStreamer->getCommentOS()
4484 << format("0x%" PRIx64 "\n", CI->getZExtValue());
4485 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
4486 } else {
4488 }
4489
4490 // Emit tail padding if needed
4491 if (Size != StoreSize)
4492 AP.OutStreamer->emitZeros(Size - StoreSize);
4493
4494 return;
4495 }
4496
4497 if (const ConstantByte *CB = dyn_cast<ConstantByte>(CV)) {
4498 if (isa<VectorType>(CV->getType()))
4499 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4500
4501 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
4502 if (StoreSize <= 8) {
4503 if (AP.isVerbose())
4504 AP.OutStreamer->getCommentOS()
4505 << format("0x%" PRIx64 "\n", CB->getZExtValue());
4506 AP.OutStreamer->emitIntValue(CB->getZExtValue(), StoreSize);
4507 } else {
4509 }
4510
4511 // Emit tail padding if needed
4512 if (Size != StoreSize)
4513 AP.OutStreamer->emitZeros(Size - StoreSize);
4514
4515 return;
4516 }
4517
4518 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
4519 if (isa<VectorType>(CV->getType()))
4520 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4521 else
4522 return emitGlobalConstantFP(CFP, AP);
4523 }
4524
4525 if (isa<ConstantPointerNull>(CV)) {
4526 AP.OutStreamer->emitIntValue(0, Size);
4527 return;
4528 }
4529
4531 return emitGlobalConstantDataSequential(DL, CDS, AP, AliasList);
4532
4533 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
4534 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset, AliasList);
4535
4536 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
4537 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset, AliasList);
4538
4539 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
4540 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
4541 // vectors).
4542 if (CE->getOpcode() == Instruction::BitCast)
4543 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
4544
4545 if (Size > 8) {
4546 // If the constant expression's size is greater than 64-bits, then we have
4547 // to emit the value in chunks. Try to constant fold the value and emit it
4548 // that way.
4549 Constant *New = ConstantFoldConstant(CE, DL);
4550 if (New != CE)
4551 return emitGlobalConstantImpl(DL, New, AP);
4552 }
4553 }
4554
4555 if (isa<ConstantVector>(CV))
4556 return emitGlobalConstantVector(DL, CV, AP, AliasList);
4557
4558 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
4559 // thread the streamer with EmitValue.
4560 const MCExpr *ME = AP.lowerConstant(CV, BaseCV, Offset);
4561
4562 // Since lowerConstant already folded and got rid of all IR pointer and
4563 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
4564 // directly.
4566 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
4567
4568 AP.OutStreamer->emitValue(ME, Size);
4569}
4570
4571/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
4573 AliasMapTy *AliasList) {
4574 uint64_t Size = DL.getTypeAllocSize(CV->getType());
4575 if (Size)
4576 emitGlobalConstantImpl(DL, CV, *this, nullptr, 0, AliasList);
4577 else if (MAI->hasSubsectionsViaSymbols()) {
4578 // If the global has zero size, emit a single byte so that two labels don't
4579 // look like they are at the same location.
4580 OutStreamer->emitIntValue(0, 1);
4581 }
4582 if (!AliasList)
4583 return;
4584 // TODO: These remaining aliases are not emitted in the correct location. Need
4585 // to handle the case where the alias offset doesn't refer to any sub-element.
4586 for (auto &AliasPair : *AliasList) {
4587 for (const GlobalAlias *GA : AliasPair.second)
4588 OutStreamer->emitLabel(getSymbol(GA));
4589 }
4590}
4591
4593 // Target doesn't support this yet!
4594 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
4595}
4596
4598 if (Offset > 0)
4599 OS << '+' << Offset;
4600 else if (Offset < 0)
4601 OS << Offset;
4602}
4603
4604void AsmPrinter::emitNops(unsigned N) {
4605 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
4606 for (; N; --N)
4608}
4609
4610//===----------------------------------------------------------------------===//
4611// Symbol Lowering Routines.
4612//===----------------------------------------------------------------------===//
4613
4615 return OutContext.createTempSymbol(Name, true);
4616}
4617
4619 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(
4620 BA->getBasicBlock());
4621}
4622
4624 return const_cast<AsmPrinter *>(this)->getAddrLabelSymbol(BB);
4625}
4626
4630
4631/// GetCPISymbol - Return the symbol for the specified constant pool entry.
4632MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
4633 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment() ||
4634 getSubtargetInfo().getTargetTriple().isUEFI()) {
4635 const MachineConstantPoolEntry &CPE =
4636 MF->getConstantPool()->getConstants()[CPID];
4637 if (!CPE.isMachineConstantPoolEntry()) {
4638 const DataLayout &DL = MF->getDataLayout();
4639 SectionKind Kind = CPE.getSectionKind(&DL);
4640 const Constant *C = CPE.Val.ConstVal;
4641 Align Alignment = CPE.Alignment;
4643 DL, Kind, C, Alignment, &MF->getFunction());
4644 if (S && TM.getTargetTriple().isOSBinFormatCOFF()) {
4645 if (MCSymbol *Sym =
4646 static_cast<const MCSectionCOFF *>(S)->getCOMDATSymbol()) {
4647 if (Sym->isUndefined())
4648 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
4649 return Sym;
4650 }
4651 }
4652 }
4653 }
4654
4655 const DataLayout &DL = getDataLayout();
4656 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4657 "CPI" + Twine(getFunctionNumber()) + "_" +
4658 Twine(CPID));
4659}
4660
4661/// GetJTISymbol - Return the symbol for the specified jump table entry.
4662MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
4663 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
4664}
4665
4666/// GetJTSetSymbol - Return the symbol for the specified jump table .set
4667/// FIXME: privatize to AsmPrinter.
4668MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
4669 const DataLayout &DL = getDataLayout();
4670 return OutContext.getOrCreateSymbol(Twine(DL.getInternalSymbolPrefix()) +
4671 Twine(getFunctionNumber()) + "_" +
4672 Twine(UID) + "_set_" + Twine(MBBID));
4673}
4674
4679
4680/// Return the MCSymbol for the specified ExternalSymbol.
4682 SmallString<60> NameStr;
4684 return OutContext.getOrCreateSymbol(NameStr);
4685}
4686
4687/// PrintParentLoopComment - Print comments about parent loops of this one.
4689 unsigned FunctionNumber) {
4690 if (!Loop) return;
4691 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
4692 OS.indent(Loop->getLoopDepth()*2)
4693 << "Parent Loop BB" << FunctionNumber << "_"
4694 << Loop->getHeader()->getNumber()
4695 << " Depth=" << Loop->getLoopDepth() << '\n';
4696}
4697
4698/// PrintChildLoopComment - Print comments about child loops within
4699/// the loop for this basic block, with nesting.
4701 unsigned FunctionNumber) {
4702 // Add child loop information
4703 for (const MachineLoop *CL : *Loop) {
4704 OS.indent(CL->getLoopDepth()*2)
4705 << "Child Loop BB" << FunctionNumber << "_"
4706 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
4707 << '\n';
4708 PrintChildLoopComment(OS, CL, FunctionNumber);
4709 }
4710}
4711
4712/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
4714 const MachineLoopInfo *LI,
4715 const AsmPrinter &AP) {
4716 // Add loop depth information
4717 const MachineLoop *Loop = LI->getLoopFor(&MBB);
4718 if (!Loop) return;
4719
4720 MachineBasicBlock *Header = Loop->getHeader();
4721 assert(Header && "No header for loop");
4722
4723 // If this block is not a loop header, just print out what is the loop header
4724 // and return.
4725 if (Header != &MBB) {
4726 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
4727 Twine(AP.getFunctionNumber())+"_" +
4729 " Depth="+Twine(Loop->getLoopDepth()));
4730 return;
4731 }
4732
4733 // Otherwise, it is a loop header. Print out information about child and
4734 // parent loops.
4735 raw_ostream &OS = AP.OutStreamer->getCommentOS();
4736
4738
4739 OS << "=>";
4740 OS.indent(Loop->getLoopDepth()*2-2);
4741
4742 OS << "This ";
4743 if (Loop->isInnermost())
4744 OS << "Inner ";
4745 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
4746
4748}
4749
4750/// emitBasicBlockStart - This method prints the label for the specified
4751/// MachineBasicBlock, an alignment (if present) and a comment describing
4752/// it if appropriate.
4754 // End the previous funclet and start a new one.
4755 if (MBB.isEHFuncletEntry()) {
4756 for (auto &Handler : Handlers) {
4757 Handler->endFunclet();
4758 Handler->beginFunclet(MBB);
4759 }
4760 for (auto &Handler : EHHandlers) {
4761 Handler->endFunclet();
4762 Handler->beginFunclet(MBB);
4763 }
4764 }
4765
4766 // Switch to a new section if this basic block must begin a section. The
4767 // entry block is always placed in the function section and is handled
4768 // separately.
4769 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4770 OutStreamer->switchSection(
4771 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
4772 MBB, TM));
4773 CurrentSectionBeginSym = MBB.getSymbol();
4774 }
4775
4776 for (auto &Handler : Handlers)
4777 Handler->beginCodeAlignment(MBB);
4778
4779 // Emit an alignment directive for this block, if needed.
4780 const Align Alignment = MBB.getAlignment();
4781 if (Alignment != Align(1))
4782 emitAlignment(Alignment, nullptr, MBB.getMaxBytesForAlignment());
4783
4784 // If the block has its address taken, emit any labels that were used to
4785 // reference the block. It is possible that there is more than one label
4786 // here, because multiple LLVM BB's may have been RAUW'd to this block after
4787 // the references were generated.
4788 if (MBB.isIRBlockAddressTaken()) {
4789 if (isVerbose())
4790 OutStreamer->AddComment("Block address taken");
4791
4792 BasicBlock *BB = MBB.getAddressTakenIRBlock();
4793 assert(BB && BB->hasAddressTaken() && "Missing BB");
4794 for (MCSymbol *Sym : getAddrLabelSymbolToEmit(BB))
4795 OutStreamer->emitLabel(Sym);
4796 } else if (isVerbose() && MBB.isMachineBlockAddressTaken()) {
4797 OutStreamer->AddComment("Block address taken");
4798 } else if (isVerbose() && MBB.isInlineAsmBrIndirectTarget()) {
4799 OutStreamer->AddComment("Inline asm indirect target");
4800 }
4801
4802 // Print some verbose block comments.
4803 if (isVerbose()) {
4804 if (const BasicBlock *BB = MBB.getBasicBlock()) {
4805 if (BB->hasName()) {
4806 BB->printAsOperand(OutStreamer->getCommentOS(),
4807 /*PrintType=*/false, BB->getModule());
4808 OutStreamer->getCommentOS() << '\n';
4809 }
4810 }
4811
4812 assert(MLI != nullptr && "MachineLoopInfo should has been computed");
4814 }
4815
4816 // Print the main label for the block.
4817 if (shouldEmitLabelForBasicBlock(MBB)) {
4818 if (isVerbose() && MBB.hasLabelMustBeEmitted())
4819 OutStreamer->AddComment("Label of block must be emitted");
4820 OutStreamer->emitLabel(MBB.getSymbol());
4821 } else {
4822 if (isVerbose()) {
4823 // NOTE: Want this comment at start of line, don't emit with AddComment.
4824 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
4825 false);
4826 }
4827 }
4828
4829 if (MBB.isEHContTarget() &&
4830 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
4831 OutStreamer->emitLabel(MBB.getEHContSymbol());
4832 }
4833
4834 // With BB sections, each basic block must handle CFI information on its own
4835 // if it begins a section (Entry block call is handled separately, next to
4836 // beginFunction).
4837 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
4838 for (auto &Handler : Handlers)
4839 Handler->beginBasicBlockSection(MBB);
4840 for (auto &Handler : EHHandlers)
4841 Handler->beginBasicBlockSection(MBB);
4842 }
4843}
4844
4846 // Check if CFI information needs to be updated for this MBB with basic block
4847 // sections.
4848 if (MBB.isEndSection()) {
4849 for (auto &Handler : Handlers)
4850 Handler->endBasicBlockSection(MBB);
4851 for (auto &Handler : EHHandlers)
4852 Handler->endBasicBlockSection(MBB);
4853 }
4854}
4855
4856void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
4857 bool IsDefinition) const {
4859
4860 switch (Visibility) {
4861 default: break;
4863 if (IsDefinition)
4864 Attr = MAI->getHiddenVisibilityAttr();
4865 else
4866 Attr = MAI->getHiddenDeclarationVisibilityAttr();
4867 break;
4869 Attr = MAI->getProtectedVisibilityAttr();
4870 break;
4871 }
4872
4873 if (Attr != MCSA_Invalid)
4874 OutStreamer->emitSymbolAttribute(Sym, Attr);
4875}
4876
4877bool AsmPrinter::shouldEmitLabelForBasicBlock(
4878 const MachineBasicBlock &MBB) const {
4879 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
4880 // in the labels mode (option `=labels`) and every section beginning in the
4881 // sections mode (`=all` and `=list=`).
4882 if ((MF->getTarget().Options.BBAddrMap || MBB.isBeginSection()) &&
4883 !MBB.isEntryBlock())
4884 return true;
4885 // A label is needed for any block with at least one predecessor (when that
4886 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
4887 // entry, or if a label is forced).
4888 return !MBB.pred_empty() &&
4889 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
4890 MBB.hasLabelMustBeEmitted());
4891}
4892
4893/// isBlockOnlyReachableByFallthough - Return true if the basic block has
4894/// exactly one predecessor and the control transfer mechanism between
4895/// the predecessor and this block is a fall-through.
4898 // If this is a landing pad, it isn't a fall through. If it has no preds,
4899 // then nothing falls through to it.
4900 if (MBB->isEHPad() || MBB->pred_empty())
4901 return false;
4902
4903 // If there isn't exactly one predecessor, it can't be a fall through.
4904 if (MBB->pred_size() > 1)
4905 return false;
4906
4907 // The predecessor has to be immediately before this block.
4908 MachineBasicBlock *Pred = *MBB->pred_begin();
4909 if (!Pred->isLayoutSuccessor(MBB))
4910 return false;
4911
4912 // If the block is completely empty, then it definitely does fall through.
4913 if (Pred->empty())
4914 return true;
4915
4916 // Check the terminators in the previous blocks
4917 for (const auto &MI : Pred->terminators()) {
4918 // If it is not a simple branch, we are in a table somewhere.
4919 if (!MI.isBranch() || MI.isIndirectBranch())
4920 return false;
4921
4922 // If we are the operands of one of the branches, this is not a fall
4923 // through. Note that targets with delay slots will usually bundle
4924 // terminators with the delay slot instruction.
4925 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
4926 if (OP->isJTI())
4927 return false;
4928 if (OP->isMBB() && OP->getMBB() == MBB)
4929 return false;
4930 }
4931 }
4932
4933 return true;
4934}
4935
4936GCMetadataPrinter *AsmPrinter::getOrCreateGCPrinter(GCStrategy &S) {
4937 if (!S.usesMetadata())
4938 return nullptr;
4939
4940 auto [GCPI, Inserted] = GCMetadataPrinters.try_emplace(&S);
4941 if (!Inserted)
4942 return GCPI->second.get();
4943
4944 auto Name = S.getName();
4945
4946 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
4948 if (Name == GCMetaPrinter.getName()) {
4949 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
4950 GMP->S = &S;
4951 GCPI->second = std::move(GMP);
4952 return GCPI->second.get();
4953 }
4954
4955 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
4956}
4957
4959 std::unique_ptr<AsmPrinterHandler> Handler) {
4960 Handlers.insert(Handlers.begin(), std::move(Handler));
4962}
4963
4964/// Pin vtables to this file.
4966
4968
4969// In the binary's "xray_instr_map" section, an array of these function entries
4970// describes each instrumentation point. When XRay patches your code, the index
4971// into this table will be given to your handler as a patch point identifier.
4973 auto Kind8 = static_cast<uint8_t>(Kind);
4974 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
4975 Out->emitBinaryData(
4976 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
4977 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
4978 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
4979 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
4980 Out->emitZeros(Padding);
4981}
4982
4984 if (Sleds.empty())
4985 return;
4986
4987 auto PrevSection = OutStreamer->getCurrentSectionOnly();
4988 const Function &F = MF->getFunction();
4989 MCSection *InstMap = nullptr;
4990 MCSection *FnSledIndex = nullptr;
4991 const Triple &TT = TM.getTargetTriple();
4992 // Use PC-relative addresses on all targets.
4993 if (TT.isOSBinFormatELF()) {
4994 auto LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
4995 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
4996 StringRef GroupName;
4997 if (F.hasComdat()) {
4998 Flags |= ELF::SHF_GROUP;
4999 GroupName = F.getComdat()->getName();
5000 }
5001 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
5002 Flags, 0, GroupName, F.hasComdat(),
5003 MCSection::NonUniqueID, LinkedToSym);
5004
5005 if (TM.Options.XRayFunctionIndex)
5006 FnSledIndex = OutContext.getELFSection(
5007 "xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5008 MCSection::NonUniqueID, LinkedToSym);
5009 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
5010 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map",
5013 if (TM.Options.XRayFunctionIndex)
5014 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx",
5017 } else {
5018 llvm_unreachable("Unsupported target");
5019 }
5020
5021 auto WordSizeBytes = MAI->getCodePointerSize();
5022
5023 // Now we switch to the instrumentation map section. Because this is done
5024 // per-function, we are able to create an index entry that will represent the
5025 // range of sleds associated with a function.
5026 auto &Ctx = OutContext;
5027 MCSymbol *SledsStart =
5028 OutContext.createLinkerPrivateSymbol("xray_sleds_start");
5029 OutStreamer->switchSection(InstMap);
5030 OutStreamer->emitLabel(SledsStart);
5031 for (const auto &Sled : Sleds) {
5032 MCSymbol *Dot = Ctx.createTempSymbol();
5033 OutStreamer->emitLabel(Dot);
5034 OutStreamer->emitValueImpl(
5036 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5037 WordSizeBytes);
5038 OutStreamer->emitValueImpl(
5042 MCConstantExpr::create(WordSizeBytes, Ctx),
5043 Ctx),
5044 Ctx),
5045 WordSizeBytes);
5046 Sled.emit(WordSizeBytes, OutStreamer.get());
5047 }
5048 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
5049 OutStreamer->emitLabel(SledsEnd);
5050
5051 // We then emit a single entry in the index per function. We use the symbols
5052 // that bound the instrumentation map as the range for a specific function.
5053 // Each entry contains 2 words and needs to be word-aligned.
5054 if (FnSledIndex) {
5055 OutStreamer->switchSection(FnSledIndex);
5056 OutStreamer->emitValueToAlignment(Align(WordSizeBytes));
5057 // For Mach-O, use an "l" symbol as the atom of this subsection. The label
5058 // difference uses a SUBTRACTOR external relocation which references the
5059 // symbol.
5060 MCSymbol *Dot = Ctx.createLinkerPrivateSymbol("xray_fn_idx");
5061 OutStreamer->emitLabel(Dot);
5062 OutStreamer->emitValueImpl(
5064 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
5065 WordSizeBytes);
5066 OutStreamer->emitValueImpl(MCConstantExpr::create(Sleds.size(), Ctx),
5067 WordSizeBytes);
5068 OutStreamer->switchSection(PrevSection);
5069 }
5070 Sleds.clear();
5071}
5072
5074 SledKind Kind, uint8_t Version) {
5075 const Function &F = MI.getMF()->getFunction();
5076 auto Attr = F.getFnAttribute("function-instrument");
5077 bool LogArgs = F.hasFnAttribute("xray-log-args");
5078 bool AlwaysInstrument =
5079 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
5080 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
5082 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
5083 AlwaysInstrument, &F, Version});
5084}
5085
5087 const Function &F = MF->getFunction();
5088 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
5089 (void)F.getFnAttribute("patchable-function-prefix")
5090 .getValueAsString()
5091 .getAsInteger(10, PatchableFunctionPrefix);
5092 (void)F.getFnAttribute("patchable-function-entry")
5093 .getValueAsString()
5094 .getAsInteger(10, PatchableFunctionEntry);
5095 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
5096 return;
5097 const unsigned PointerSize = getPointerSize();
5098 if (TM.getTargetTriple().isOSBinFormatELF()) {
5099 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
5100 const MCSymbolELF *LinkedToSym = nullptr;
5101 StringRef GroupName, SectionName;
5102
5103 if (F.hasFnAttribute("patchable-function-entry-section"))
5104 SectionName = F.getFnAttribute("patchable-function-entry-section")
5105 .getValueAsString();
5106 if (SectionName.empty())
5107 SectionName = "__patchable_function_entries";
5108
5109 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
5110 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
5111 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
5112 Flags |= ELF::SHF_LINK_ORDER;
5113 if (F.hasComdat()) {
5114 Flags |= ELF::SHF_GROUP;
5115 GroupName = F.getComdat()->getName();
5116 }
5117 LinkedToSym = static_cast<const MCSymbolELF *>(CurrentFnSym);
5118 }
5119 OutStreamer->switchSection(OutContext.getELFSection(
5120 SectionName, ELF::SHT_PROGBITS, Flags, 0, GroupName, F.hasComdat(),
5121 MCSection::NonUniqueID, LinkedToSym));
5122 emitAlignment(Align(PointerSize));
5123 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
5124 }
5125}
5126
5128 return OutStreamer->getContext().getDwarfVersion();
5129}
5130
5132 OutStreamer->getContext().setDwarfVersion(Version);
5133}
5134
5136 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
5137}
5138
5141 OutStreamer->getContext().getDwarfFormat());
5142}
5143
5145 return {getDwarfVersion(), uint8_t(MAI->getCodePointerSize()),
5146 OutStreamer->getContext().getDwarfFormat(),
5148}
5149
5152 OutStreamer->getContext().getDwarfFormat());
5153}
5154
5155std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
5158 const MCSymbol *BranchLabel) const {
5159 const auto TLI = MF->getSubtarget().getTargetLowering();
5160 const auto BaseExpr =
5161 TLI->getPICJumpTableRelocBaseExpr(MF, JTI, MMI->getContext());
5162 const auto Base = &cast<MCSymbolRefExpr>(BaseExpr)->getSymbol();
5163
5164 // By default, for the architectures that support CodeView,
5165 // EK_LabelDifference32 is implemented as an Int32 from the base address.
5166 return std::make_tuple(Base, 0, BranchLabel,
5168}
5169
5171 const Triple &TT = TM.getTargetTriple();
5172 assert(TT.isOSBinFormatCOFF());
5173
5174 bool IsTargetArm64EC = TT.isWindowsArm64EC();
5176 SmallVector<MCSymbol *> FuncOverrideDefaultSymbols;
5177 bool SwitchedToDirectiveSection = false;
5178 for (const Function &F : M.functions()) {
5179 if (F.hasFnAttribute("loader-replaceable")) {
5180 if (!SwitchedToDirectiveSection) {
5181 OutStreamer->switchSection(
5182 OutContext.getObjectFileInfo()->getDrectveSection());
5183 SwitchedToDirectiveSection = true;
5184 }
5185
5186 StringRef Name = F.getName();
5187
5188 // For hybrid-patchable targets, strip the prefix so that we can mark
5189 // the real function as replaceable.
5190 if (IsTargetArm64EC && Name.ends_with(HybridPatchableTargetSuffix)) {
5191 Name = Name.drop_back(HybridPatchableTargetSuffix.size());
5192 }
5193
5194 MCSymbol *FuncOverrideSymbol =
5195 MMI->getContext().getOrCreateSymbol(Name + "_$fo$");
5196 OutStreamer->beginCOFFSymbolDef(FuncOverrideSymbol);
5197 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5198 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5199 OutStreamer->endCOFFSymbolDef();
5200
5201 MCSymbol *FuncOverrideDefaultSymbol =
5202 MMI->getContext().getOrCreateSymbol(Name + "_$fo_default$");
5203 OutStreamer->beginCOFFSymbolDef(FuncOverrideDefaultSymbol);
5204 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
5205 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5206 OutStreamer->endCOFFSymbolDef();
5207 FuncOverrideDefaultSymbols.push_back(FuncOverrideDefaultSymbol);
5208
5209 OutStreamer->emitBytes((Twine(" /ALTERNATENAME:") +
5210 FuncOverrideSymbol->getName() + "=" +
5211 FuncOverrideDefaultSymbol->getName())
5212 .toStringRef(Buf));
5213 Buf.clear();
5214 }
5215 }
5216
5217 if (SwitchedToDirectiveSection)
5218 OutStreamer->popSection();
5219
5220 if (FuncOverrideDefaultSymbols.empty())
5221 return;
5222
5223 // MSVC emits the symbols for the default variables pointing at the start of
5224 // the .data section, but doesn't actually allocate any space for them. LLVM
5225 // can't do this, so have all of the variables pointing at a single byte
5226 // instead.
5227 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getDataSection());
5228 for (MCSymbol *Symbol : FuncOverrideDefaultSymbols) {
5229 OutStreamer->emitLabel(Symbol);
5230 }
5231 OutStreamer->emitZeros(1);
5232 OutStreamer->popSection();
5233}
5234
5236 const Triple &TT = TM.getTargetTriple();
5237 assert(TT.isOSBinFormatCOFF());
5238
5239 // Emit an absolute @feat.00 symbol.
5240 MCSymbol *S = MMI->getContext().getOrCreateSymbol(StringRef("@feat.00"));
5241 OutStreamer->beginCOFFSymbolDef(S);
5242 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
5243 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
5244 OutStreamer->endCOFFSymbolDef();
5245 int64_t Feat00Value = 0;
5246
5247 if (TT.getArch() == Triple::x86) {
5248 // According to the PE-COFF spec, the LSB of this value marks the object
5249 // for "registered SEH". This means that all SEH handler entry points
5250 // must be registered in .sxdata. Use of any unregistered handlers will
5251 // cause the process to terminate immediately. LLVM does not know how to
5252 // register any SEH handlers, so its object files should be safe.
5253 Feat00Value |= COFF::Feat00Flags::SafeSEH;
5254 }
5255
5256 if (M.getControlFlowGuardMode() == ControlFlowGuardMode::Enabled) {
5257 // Object is CFG-aware. Only set if we actually inserted the checks.
5258 Feat00Value |= COFF::Feat00Flags::GuardCF;
5259 }
5260
5261 if (M.getModuleFlag("ehcontguard")) {
5262 // Object also has EHCont.
5263 Feat00Value |= COFF::Feat00Flags::GuardEHCont;
5264 }
5265
5266 if (M.getModuleFlag("ms-kernel")) {
5267 // Object is compiled with /kernel.
5268 Feat00Value |= COFF::Feat00Flags::Kernel;
5269 }
5270
5271 OutStreamer->emitSymbolAttribute(S, MCSA_Global);
5272 OutStreamer->emitAssignment(
5273 S, MCConstantExpr::create(Feat00Value, MMI->getContext()));
5274}
5275
5276namespace llvm {
5277namespace {
5279 MachineFunction &MF) {
5281 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
5284 MF.getFunction())
5285 .getManager();
5286 return MFAM;
5287}
5288} // anonymous namespace
5289
5292 MachineModuleInfo &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
5293 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5294 AsmPrinter.MMI = &MMI;
5295 AsmPrinter.GetORE = [&MAM, &M](MachineFunction &MF) {
5296 return &getMFAM(M, MAM, MF)
5298 };
5299 AsmPrinter.GetMDT = [&MAM, &M](MachineFunction &MF) {
5300 return &getMFAM(M, MAM, MF).getResult<MachineDominatorTreeAnalysis>(MF);
5301 };
5302 AsmPrinter.GetMLI = [&MAM, &M](MachineFunction &MF) {
5303 return &getMFAM(M, MAM, MF).getResult<MachineLoopAnalysis>(MF);
5304 };
5305 // TODO(boomanaiden154): Get GC working with the new pass manager.
5306 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5308 AsmPrinter.EmitStackMaps = [](Module &M) {};
5310}
5311
5313 MachineFunction &MF,
5315 const ModuleAnalysisManagerMachineFunctionProxy::Result &MAMProxy =
5317 MachineModuleInfo &MMI =
5318 MAMProxy
5319 .getCachedResult<MachineModuleAnalysis>(*MF.getFunction().getParent())
5320 ->getMMI();
5321 AsmPrinter.GetMMI = [&MMI]() { return &MMI; };
5322 AsmPrinter.MMI = &MMI;
5323 AsmPrinter.GetORE = [&MFAM](MachineFunction &MF) {
5325 };
5326 AsmPrinter.GetMDT = [&MFAM](MachineFunction &MF) {
5327 return &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
5328 };
5329 AsmPrinter.GetMLI = [&MFAM](MachineFunction &MF) {
5330 return &MFAM.getResult<MachineLoopAnalysis>(MF);
5331 };
5332 // TODO(boomanaiden154): Get GC working with the new pass manager.
5333 AsmPrinter.BeginGCAssembly = [](Module &M) {};
5335 AsmPrinter.EmitStackMaps = [](Module &M) {};
5337}
5338
5339} // 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 emitGlobalConstantLargeByte(const ConstantByte *CB, AsmPrinter &AP)
static void tagGlobalDefinition(Module &M, GlobalVariable *G)
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
static void emitGlobalConstantLargeAPInt(const APInt &Val, uint64_t TypeStoreSize, AsmPrinter &AP)
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, const Constant *BaseCst, uint64_t Offset)
Transform a not absolute MCExpr containing a reference to a GOT equivalent global,...
static llvm::object::BBAddrMap::Features getBBAddrMapFeature(const MachineFunction &MF, int NumMBBSectionRanges, bool HasCalls, const CFGProfile *FuncCFGProfile)
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
static void emitGlobalAliasInline(AsmPrinter &AP, uint64_t Offset, AsmPrinter::AliasMapTy *AliasList)
static bool needFuncLabels(const MachineFunction &MF, const AsmPrinter &Asm)
Returns true if function begin and end labels should be emitted.
static unsigned getNumGlobalVariableUses(const Constant *C, bool &HasNonGlobalUsers)
Compute the number of Global Variables that uses a Constant.
static 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:5890
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:5949
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition APFloat.h:1545
APInt bitcastToAPInt() const
Definition APFloat.h:1408
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:642
void emitDanglingPrefetchTargets()
Emit prefetch targets that were not mapped to any basic block.
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
MCSymbol * getSymbol(const GlobalValue *GV) const
void emitULEB128(uint64_t Value, const char *Desc=nullptr, unsigned PadTo=0) const
Emit the specified unsigned leb128 value.
SmallVector< XRayFunctionEntry, 4 > Sleds
Definition AsmPrinter.h: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:663
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:694
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:618
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:520
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition AsmPrinter.h:626
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:622
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:688
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:588
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:684
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
void emitPrefetchTargetSymbol(unsigned BaseID, unsigned CallsiteIndex)
Helper to emit a symbol for the prefetch target associated with the given BBID and callsite index.
virtual void emitFunctionDescriptor()
Definition AsmPrinter.h:651
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:659
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:630
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:675
The address of a basic block.
Definition Constants.h:1065
BasicBlock * getBasicBlock() const
Definition Constants.h:1100
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:576
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:595
Class for constant bytes.
Definition Constants.h:281
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:345
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:859
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:736
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:812
LLVM_ABI uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
LLVM_ABI bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers or bytes.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
LLVM_ABI Type * getElementType() const
Return the element type of the array/vector.
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1291
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A signed pointer, in the ptrauth sense.
Definition Constants.h:1198
StructType * getType() const
Specialization - reduce amount of casting.
Definition Constants.h:647
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:629
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:1118
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:216
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:572
A debug info location.
Definition DebugLoc.h:123
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool empty() const
Definition DenseMap.h:109
iterator end()
Definition DenseMap.h:81
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
Emits exception handling directives.
Definition EHStreamer.h:30
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h: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:603
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:354
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
size_t getFixedSize() const
Definition MCSection.h:209
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:1157
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:736
TypeSize getSizeInBytes() const
Definition DataLayout.h:745
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:767
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Information about stack frame layout on the target.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
@ AllowOverEstimate
Allow the reported instruction size to be larger than the actual size.
@ NoVerify
Do not verify instruction size.
Align getMinFunctionAlignment() const
Return the minimum function alignment.
virtual const MCExpr * lowerDSOLocalEquivalent(const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
virtual const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Get the target specific PC relative GOT entry relocation.
virtual 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 Function *F) const
Given a constant with the SectionKind, return a section that it should be placed in.
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset?
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol,...
virtual 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:826
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:803
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:314
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:328
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
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:158
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:275
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:440
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
iterator_range< user_iterator > users()
Definition Value.h:427
User * user_back()
Definition Value.h:413
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:713
bool use_empty() const
Definition Value.h:347
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
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:1247
@ SHF_LINK_ORDER
Definition ELF.h:1262
@ SHF_GROUP
Definition ELF.h:1269
@ SHF_WRITE
Definition ELF.h:1244
@ SHT_LLVM_JT_SIZES
Definition ELF.h:1187
@ SHT_PROGBITS
Definition ELF.h:1146
@ SHT_LLVM_SYMPART
Definition ELF.h:1179
@ 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:777
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:963
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 raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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:552
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.