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