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