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