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