1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the AsmPrinter class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/AsmPrinter.h"
14 #include "CodeViewDebug.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "PseudoProbePrinter.h"
18 #include "WasmException.h"
19 #include "WinCFGuard.h"
20 #include "WinException.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
36 #include "llvm/BinaryFormat/COFF.h"
37 #include "llvm/BinaryFormat/Dwarf.h"
38 #include "llvm/BinaryFormat/ELF.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/GCMetadataPrinter.h"
41 #include "llvm/CodeGen/MachineBasicBlock.h"
42 #include "llvm/CodeGen/MachineConstantPool.h"
43 #include "llvm/CodeGen/MachineDominators.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBundle.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineLoopInfo.h"
51 #include "llvm/CodeGen/MachineMemOperand.h"
52 #include "llvm/CodeGen/MachineModuleInfo.h"
53 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
54 #include "llvm/CodeGen/MachineOperand.h"
55 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/Config/config.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/Comdat.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GCStrategy.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalIFunc.h"
74 #include "llvm/IR/GlobalObject.h"
75 #include "llvm/IR/GlobalValue.h"
76 #include "llvm/IR/GlobalVariable.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Mangler.h"
79 #include "llvm/IR/Metadata.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/Operator.h"
82 #include "llvm/IR/PseudoProbe.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/MC/MCAsmInfo.h"
86 #include "llvm/MC/MCContext.h"
87 #include "llvm/MC/MCDirectives.h"
88 #include "llvm/MC/MCDwarf.h"
89 #include "llvm/MC/MCExpr.h"
90 #include "llvm/MC/MCInst.h"
91 #include "llvm/MC/MCSection.h"
92 #include "llvm/MC/MCSectionCOFF.h"
93 #include "llvm/MC/MCSectionELF.h"
94 #include "llvm/MC/MCSectionMachO.h"
95 #include "llvm/MC/MCSectionXCOFF.h"
96 #include "llvm/MC/MCStreamer.h"
97 #include "llvm/MC/MCSubtargetInfo.h"
98 #include "llvm/MC/MCSymbol.h"
99 #include "llvm/MC/MCSymbolELF.h"
100 #include "llvm/MC/MCSymbolXCOFF.h"
101 #include "llvm/MC/MCTargetOptions.h"
102 #include "llvm/MC/MCValue.h"
103 #include "llvm/MC/SectionKind.h"
104 #include "llvm/MC/TargetRegistry.h"
105 #include "llvm/Pass.h"
106 #include "llvm/Remarks/Remark.h"
107 #include "llvm/Remarks/RemarkFormat.h"
108 #include "llvm/Remarks/RemarkStreamer.h"
109 #include "llvm/Remarks/RemarkStringTable.h"
110 #include "llvm/Support/Casting.h"
111 #include "llvm/Support/CommandLine.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/ErrorHandling.h"
114 #include "llvm/Support/FileSystem.h"
115 #include "llvm/Support/Format.h"
116 #include "llvm/Support/MathExtras.h"
117 #include "llvm/Support/Path.h"
118 #include "llvm/Support/Timer.h"
119 #include "llvm/Support/raw_ostream.h"
120 #include "llvm/Target/TargetLoweringObjectFile.h"
121 #include "llvm/Target/TargetMachine.h"
122 #include "llvm/Target/TargetOptions.h"
134 using namespace llvm
;
136 #define DEBUG_TYPE "asm-printer"
138 // FIXME: this option currently only applies to DWARF, and not CodeView, tables
140 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden
,
141 cl::desc("Disable debug info printing"));
143 const char DWARFGroupName
[] = "dwarf";
144 const char DWARFGroupDescription
[] = "DWARF Emission";
145 const char DbgTimerName
[] = "emit";
146 const char DbgTimerDescription
[] = "Debug Info Emission";
147 const char EHTimerName
[] = "write_exception";
148 const char EHTimerDescription
[] = "DWARF Exception Writer";
149 const char CFGuardName
[] = "Control Flow Guard";
150 const char CFGuardDescription
[] = "Control Flow Guard";
151 const char CodeViewLineTablesGroupName
[] = "linetables";
152 const char CodeViewLineTablesGroupDescription
[] = "CodeView Line Tables";
153 const char PPTimerName
[] = "emit";
154 const char PPTimerDescription
[] = "Pseudo Probe Emission";
155 const char PPGroupName
[] = "pseudo probe";
156 const char PPGroupDescription
[] = "Pseudo Probe Emission";
158 STATISTIC(EmittedInsts
, "Number of machine instrs printed");
160 char AsmPrinter::ID
= 0;
162 using gcp_map_type
= DenseMap
<GCStrategy
*, std::unique_ptr
<GCMetadataPrinter
>>;
164 static gcp_map_type
&getGCMap(void *&P
) {
166 P
= new gcp_map_type();
167 return *(gcp_map_type
*)P
;
170 /// getGVAlignment - Return the alignment to use for the specified global
171 /// value. This rounds up to the preferred alignment if possible and legal.
172 Align
AsmPrinter::getGVAlignment(const GlobalObject
*GV
, const DataLayout
&DL
,
175 if (const GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(GV
))
176 Alignment
= DL
.getPreferredAlign(GVar
);
178 // If InAlign is specified, round it to it.
179 if (InAlign
> Alignment
)
182 // If the GV has a specified alignment, take it into account.
183 const MaybeAlign
GVAlign(GV
->getAlign());
187 assert(GVAlign
&& "GVAlign must be set");
189 // If the GVAlign is larger than NumBits, or if we are required to obey
190 // NumBits because the GV has an assigned section, obey it.
191 if (*GVAlign
> Alignment
|| GV
->hasSection())
192 Alignment
= *GVAlign
;
196 AsmPrinter::AsmPrinter(TargetMachine
&tm
, std::unique_ptr
<MCStreamer
> Streamer
)
197 : MachineFunctionPass(ID
), TM(tm
), MAI(tm
.getMCAsmInfo()),
198 OutContext(Streamer
->getContext()), OutStreamer(std::move(Streamer
)) {
199 VerboseAsm
= OutStreamer
->isVerboseAsm();
202 AsmPrinter::~AsmPrinter() {
203 assert(!DD
&& Handlers
.size() == NumUserHandlers
&&
204 "Debug/EH info didn't get finalized");
206 if (GCMetadataPrinters
) {
207 gcp_map_type
&GCMap
= getGCMap(GCMetadataPrinters
);
210 GCMetadataPrinters
= nullptr;
214 bool AsmPrinter::isPositionIndependent() const {
215 return TM
.isPositionIndependent();
218 /// getFunctionNumber - Return a unique ID for the current function.
219 unsigned AsmPrinter::getFunctionNumber() const {
220 return MF
->getFunctionNumber();
223 const TargetLoweringObjectFile
&AsmPrinter::getObjFileLowering() const {
224 return *TM
.getObjFileLowering();
227 const DataLayout
&AsmPrinter::getDataLayout() const {
228 return MMI
->getModule()->getDataLayout();
231 // Do not use the cached DataLayout because some client use it without a Module
232 // (dsymutil, llvm-dwarfdump).
233 unsigned AsmPrinter::getPointerSize() const {
234 return TM
.getPointerSize(0); // FIXME: Default address space
237 const MCSubtargetInfo
&AsmPrinter::getSubtargetInfo() const {
238 assert(MF
&& "getSubtargetInfo requires a valid MachineFunction!");
239 return MF
->getSubtarget
<MCSubtargetInfo
>();
242 void AsmPrinter::EmitToStreamer(MCStreamer
&S
, const MCInst
&Inst
) {
243 S
.emitInstruction(Inst
, getSubtargetInfo());
246 void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction
&MF
) {
248 assert(OutStreamer
->hasRawTextSupport() &&
249 "Expected assembly output mode.");
250 (void)DD
->emitInitialLocDirective(MF
, /*CUID=*/0);
254 /// getCurrentSection() - Return the current section we are emitting to.
255 const MCSection
*AsmPrinter::getCurrentSection() const {
256 return OutStreamer
->getCurrentSectionOnly();
259 void AsmPrinter::getAnalysisUsage(AnalysisUsage
&AU
) const {
260 AU
.setPreservesAll();
261 MachineFunctionPass::getAnalysisUsage(AU
);
262 AU
.addRequired
<MachineOptimizationRemarkEmitterPass
>();
263 AU
.addRequired
<GCModuleInfo
>();
266 bool AsmPrinter::doInitialization(Module
&M
) {
267 auto *MMIWP
= getAnalysisIfAvailable
<MachineModuleInfoWrapperPass
>();
268 MMI
= MMIWP
? &MMIWP
->getMMI() : nullptr;
270 // Initialize TargetLoweringObjectFile.
271 const_cast<TargetLoweringObjectFile
&>(getObjFileLowering())
272 .Initialize(OutContext
, TM
);
274 const_cast<TargetLoweringObjectFile
&>(getObjFileLowering())
275 .getModuleMetadata(M
);
277 OutStreamer
->initSections(false, *TM
.getMCSubtargetInfo());
279 if (DisableDebugInfoPrinting
)
280 MMI
->setDebugInfoAvailability(false);
282 // Emit the version-min deployment target directive if needed.
284 // FIXME: If we end up with a collection of these sorts of Darwin-specific
285 // or ELF-specific things, it may make sense to have a platform helper class
286 // that will work with the target helper class. For now keep it here, as the
287 // alternative is duplicated code in each of the target asm printers that
288 // use the directive, where it would need the same conditionalization
290 const Triple
&Target
= TM
.getTargetTriple();
291 Triple
TVT(M
.getDarwinTargetVariantTriple());
292 OutStreamer
->emitVersionForTarget(
293 Target
, M
.getSDKVersion(),
294 M
.getDarwinTargetVariantTriple().empty() ? nullptr : &TVT
,
295 M
.getDarwinTargetVariantSDKVersion());
297 // Allow the target to emit any magic that it wants at the start of the file.
298 emitStartOfAsmFile(M
);
300 // Very minimal debug info. It is ignored if we emit actual debug info. If we
301 // don't, this at least helps the user find where a global came from.
302 if (MAI
->hasSingleParameterDotFile()) {
305 SmallString
<128> FileName
;
306 if (MAI
->hasBasenameOnlyForFileDirective())
307 FileName
= llvm::sys::path::filename(M
.getSourceFileName());
309 FileName
= M
.getSourceFileName();
310 if (MAI
->hasFourStringsDotFile()) {
311 #ifdef PACKAGE_VENDOR
312 const char VerStr
[] =
313 PACKAGE_VENDOR
" " PACKAGE_NAME
" version " PACKAGE_VERSION
;
315 const char VerStr
[] = PACKAGE_NAME
" version " PACKAGE_VERSION
;
317 // TODO: Add timestamp and description.
318 OutStreamer
->emitFileDirective(FileName
, VerStr
, "", "");
320 OutStreamer
->emitFileDirective(FileName
);
324 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
325 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
327 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*I
))
328 MP
->beginAssembly(M
, *MI
, *this);
330 // Emit module-level inline asm if it exists.
331 if (!M
.getModuleInlineAsm().empty()) {
332 OutStreamer
->AddComment("Start of file scope inline assembly");
333 OutStreamer
->AddBlankLine();
334 emitInlineAsm(M
.getModuleInlineAsm() + "\n", *TM
.getMCSubtargetInfo(),
335 TM
.Options
.MCOptions
);
336 OutStreamer
->AddComment("End of file scope inline assembly");
337 OutStreamer
->AddBlankLine();
340 if (MAI
->doesSupportDebugInformation()) {
341 bool EmitCodeView
= M
.getCodeViewFlag();
342 if (EmitCodeView
&& TM
.getTargetTriple().isOSWindows()) {
343 Handlers
.emplace_back(std::make_unique
<CodeViewDebug
>(this),
344 DbgTimerName
, DbgTimerDescription
,
345 CodeViewLineTablesGroupName
,
346 CodeViewLineTablesGroupDescription
);
348 if (!EmitCodeView
|| M
.getDwarfVersion()) {
349 if (!DisableDebugInfoPrinting
) {
350 DD
= new DwarfDebug(this);
351 Handlers
.emplace_back(std::unique_ptr
<DwarfDebug
>(DD
), DbgTimerName
,
352 DbgTimerDescription
, DWARFGroupName
,
353 DWARFGroupDescription
);
358 if (M
.getNamedMetadata(PseudoProbeDescMetadataName
)) {
359 PP
= new PseudoProbeHandler(this);
360 Handlers
.emplace_back(std::unique_ptr
<PseudoProbeHandler
>(PP
), PPTimerName
,
361 PPTimerDescription
, PPGroupName
, PPGroupDescription
);
364 switch (MAI
->getExceptionHandlingType()) {
365 case ExceptionHandling::None
:
366 // We may want to emit CFI for debug.
368 case ExceptionHandling::SjLj
:
369 case ExceptionHandling::DwarfCFI
:
370 case ExceptionHandling::ARM
:
371 for (auto &F
: M
.getFunctionList()) {
372 if (getFunctionCFISectionType(F
) != CFISection::None
)
373 ModuleCFISection
= getFunctionCFISectionType(F
);
374 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
375 // the module needs .eh_frame. If we have found that case, we are done.
376 if (ModuleCFISection
== CFISection::EH
)
379 assert(MAI
->getExceptionHandlingType() == ExceptionHandling::DwarfCFI
||
380 ModuleCFISection
!= CFISection::EH
);
386 EHStreamer
*ES
= nullptr;
387 switch (MAI
->getExceptionHandlingType()) {
388 case ExceptionHandling::None
:
389 if (!needsCFIForDebug())
392 case ExceptionHandling::SjLj
:
393 case ExceptionHandling::DwarfCFI
:
394 ES
= new DwarfCFIException(this);
396 case ExceptionHandling::ARM
:
397 ES
= new ARMException(this);
399 case ExceptionHandling::WinEH
:
400 switch (MAI
->getWinEHEncodingType()) {
401 default: llvm_unreachable("unsupported unwinding information encoding");
402 case WinEH::EncodingType::Invalid
:
404 case WinEH::EncodingType::X86
:
405 case WinEH::EncodingType::Itanium
:
406 ES
= new WinException(this);
410 case ExceptionHandling::Wasm
:
411 ES
= new WasmException(this);
413 case ExceptionHandling::AIX
:
414 ES
= new AIXException(this);
418 Handlers
.emplace_back(std::unique_ptr
<EHStreamer
>(ES
), EHTimerName
,
419 EHTimerDescription
, DWARFGroupName
,
420 DWARFGroupDescription
);
422 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
423 if (mdconst::extract_or_null
<ConstantInt
>(M
.getModuleFlag("cfguard")))
424 Handlers
.emplace_back(std::make_unique
<WinCFGuard
>(this), CFGuardName
,
425 CFGuardDescription
, DWARFGroupName
,
426 DWARFGroupDescription
);
428 for (const HandlerInfo
&HI
: Handlers
) {
429 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
430 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
431 HI
.Handler
->beginModule(&M
);
437 static bool canBeHidden(const GlobalValue
*GV
, const MCAsmInfo
&MAI
) {
438 if (!MAI
.hasWeakDefCanBeHiddenDirective())
441 return GV
->canBeOmittedFromSymbolTable();
444 void AsmPrinter::emitLinkage(const GlobalValue
*GV
, MCSymbol
*GVSym
) const {
445 GlobalValue::LinkageTypes Linkage
= GV
->getLinkage();
447 case GlobalValue::CommonLinkage
:
448 case GlobalValue::LinkOnceAnyLinkage
:
449 case GlobalValue::LinkOnceODRLinkage
:
450 case GlobalValue::WeakAnyLinkage
:
451 case GlobalValue::WeakODRLinkage
:
452 if (MAI
->hasWeakDefDirective()) {
454 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_Global
);
456 if (!canBeHidden(GV
, *MAI
))
457 // .weak_definition _foo
458 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_WeakDefinition
);
460 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_WeakDefAutoPrivate
);
461 } else if (MAI
->avoidWeakIfComdat() && GV
->hasComdat()) {
463 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_Global
);
464 //NOTE: linkonce is handled by the section the symbol was assigned to.
467 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_Weak
);
470 case GlobalValue::ExternalLinkage
:
471 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_Global
);
473 case GlobalValue::PrivateLinkage
:
474 case GlobalValue::InternalLinkage
:
476 case GlobalValue::ExternalWeakLinkage
:
477 case GlobalValue::AvailableExternallyLinkage
:
478 case GlobalValue::AppendingLinkage
:
479 llvm_unreachable("Should never emit this");
481 llvm_unreachable("Unknown linkage type!");
484 void AsmPrinter::getNameWithPrefix(SmallVectorImpl
<char> &Name
,
485 const GlobalValue
*GV
) const {
486 TM
.getNameWithPrefix(Name
, GV
, getObjFileLowering().getMangler());
489 MCSymbol
*AsmPrinter::getSymbol(const GlobalValue
*GV
) const {
490 return TM
.getSymbol(GV
);
493 MCSymbol
*AsmPrinter::getSymbolPreferLocal(const GlobalValue
&GV
) const {
494 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
495 // exact definion (intersection of GlobalValue::hasExactDefinition() and
496 // !isInterposable()). These linkages include: external, appending, internal,
497 // private. It may be profitable to use a local alias for external. The
498 // assembler would otherwise be conservative and assume a global default
499 // visibility symbol can be interposable, even if the code generator already
501 if (TM
.getTargetTriple().isOSBinFormatELF() && GV
.canBenefitFromLocalAlias()) {
502 const Module
&M
= *GV
.getParent();
503 if (TM
.getRelocationModel() != Reloc::Static
&&
504 M
.getPIELevel() == PIELevel::Default
&& GV
.isDSOLocal())
505 return getSymbolWithGlobalValueBase(&GV
, "$local");
507 return TM
.getSymbol(&GV
);
510 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
511 void AsmPrinter::emitGlobalVariable(const GlobalVariable
*GV
) {
512 bool IsEmuTLSVar
= TM
.useEmulatedTLS() && GV
->isThreadLocal();
513 assert(!(IsEmuTLSVar
&& GV
->hasCommonLinkage()) &&
514 "No emulated TLS variables in the common section");
516 // Never emit TLS variable xyz in emulated TLS model.
517 // The initialization value is in __emutls_t.xyz instead of xyz.
521 if (GV
->hasInitializer()) {
522 // Check to see if this is a special global used by LLVM, if so, emit it.
523 if (emitSpecialLLVMGlobal(GV
))
526 // Skip the emission of global equivalents. The symbol can be emitted later
527 // on by emitGlobalGOTEquivs in case it turns out to be needed.
528 if (GlobalGOTEquivs
.count(getSymbol(GV
)))
532 // When printing the control variable __emutls_v.*,
533 // we don't need to print the original TLS variable name.
534 GV
->printAsOperand(OutStreamer
->GetCommentOS(),
535 /*PrintType=*/false, GV
->getParent());
536 OutStreamer
->GetCommentOS() << '\n';
540 MCSymbol
*GVSym
= getSymbol(GV
);
541 MCSymbol
*EmittedSym
= GVSym
;
543 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
545 // GV's or GVSym's attributes will be used for the EmittedSym.
546 emitVisibility(EmittedSym
, GV
->getVisibility(), !GV
->isDeclaration());
548 if (!GV
->hasInitializer()) // External globals require no extra code.
551 GVSym
->redefineIfPossible();
552 if (GVSym
->isDefined() || GVSym
->isVariable())
553 OutContext
.reportError(SMLoc(), "symbol '" + Twine(GVSym
->getName()) +
554 "' is already defined");
556 if (MAI
->hasDotTypeDotSizeDirective())
557 OutStreamer
->emitSymbolAttribute(EmittedSym
, MCSA_ELF_TypeObject
);
559 SectionKind GVKind
= TargetLoweringObjectFile::getKindForGlobal(GV
, TM
);
561 const DataLayout
&DL
= GV
->getParent()->getDataLayout();
562 uint64_t Size
= DL
.getTypeAllocSize(GV
->getValueType());
564 // If the alignment is specified, we *must* obey it. Overaligning a global
565 // with a specified alignment is a prompt way to break globals emitted to
566 // sections and expected to be contiguous (e.g. ObjC metadata).
567 const Align Alignment
= getGVAlignment(GV
, DL
);
569 for (const HandlerInfo
&HI
: Handlers
) {
570 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
,
571 HI
.TimerGroupName
, HI
.TimerGroupDescription
,
572 TimePassesIsEnabled
);
573 HI
.Handler
->setSymbolSize(GVSym
, Size
);
576 // Handle common symbols
577 if (GVKind
.isCommon()) {
578 if (Size
== 0) Size
= 1; // .comm Foo, 0 is undefined, avoid it.
580 const bool SupportsAlignment
=
581 getObjFileLowering().getCommDirectiveSupportsAlignment();
582 OutStreamer
->emitCommonSymbol(GVSym
, Size
,
583 SupportsAlignment
? Alignment
.value() : 0);
587 // Determine to which section this global should be emitted.
588 MCSection
*TheSection
= getObjFileLowering().SectionForGlobal(GV
, GVKind
, TM
);
590 // If we have a bss global going to a section that supports the
591 // zerofill directive, do so here.
592 if (GVKind
.isBSS() && MAI
->hasMachoZeroFillDirective() &&
593 TheSection
->isVirtualSection()) {
595 Size
= 1; // zerofill of 0 bytes is undefined.
596 emitLinkage(GV
, GVSym
);
597 // .zerofill __DATA, __bss, _foo, 400, 5
598 OutStreamer
->emitZerofill(TheSection
, GVSym
, Size
, Alignment
.value());
602 // If this is a BSS local symbol and we are emitting in the BSS
603 // section use .lcomm/.comm directive.
604 if (GVKind
.isBSSLocal() &&
605 getObjFileLowering().getBSSSection() == TheSection
) {
607 Size
= 1; // .comm Foo, 0 is undefined, avoid it.
609 // Use .lcomm only if it supports user-specified alignment.
610 // Otherwise, while it would still be correct to use .lcomm in some
611 // cases (e.g. when Align == 1), the external assembler might enfore
612 // some -unknown- default alignment behavior, which could cause
613 // spurious differences between external and integrated assembler.
614 // Prefer to simply fall back to .local / .comm in this case.
615 if (MAI
->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment
) {
617 OutStreamer
->emitLocalCommonSymbol(GVSym
, Size
, Alignment
.value());
622 OutStreamer
->emitSymbolAttribute(GVSym
, MCSA_Local
);
624 const bool SupportsAlignment
=
625 getObjFileLowering().getCommDirectiveSupportsAlignment();
626 OutStreamer
->emitCommonSymbol(GVSym
, Size
,
627 SupportsAlignment
? Alignment
.value() : 0);
631 // Handle thread local data for mach-o which requires us to output an
632 // additional structure of data and mangle the original symbol so that we
633 // can reference it later.
635 // TODO: This should become an "emit thread local global" method on TLOF.
636 // All of this macho specific stuff should be sunk down into TLOFMachO and
637 // stuff like "TLSExtraDataSection" should no longer be part of the parent
638 // TLOF class. This will also make it more obvious that stuff like
639 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
641 if (GVKind
.isThreadLocal() && MAI
->hasMachoTBSSDirective()) {
642 // Emit the .tbss symbol
644 OutContext
.getOrCreateSymbol(GVSym
->getName() + Twine("$tlv$init"));
646 if (GVKind
.isThreadBSS()) {
647 TheSection
= getObjFileLowering().getTLSBSSSection();
648 OutStreamer
->emitTBSSSymbol(TheSection
, MangSym
, Size
, Alignment
.value());
649 } else if (GVKind
.isThreadData()) {
650 OutStreamer
->SwitchSection(TheSection
);
652 emitAlignment(Alignment
, GV
);
653 OutStreamer
->emitLabel(MangSym
);
655 emitGlobalConstant(GV
->getParent()->getDataLayout(),
656 GV
->getInitializer());
659 OutStreamer
->AddBlankLine();
661 // Emit the variable struct for the runtime.
662 MCSection
*TLVSect
= getObjFileLowering().getTLSExtraDataSection();
664 OutStreamer
->SwitchSection(TLVSect
);
665 // Emit the linkage here.
666 emitLinkage(GV
, GVSym
);
667 OutStreamer
->emitLabel(GVSym
);
669 // Three pointers in size:
670 // - __tlv_bootstrap - used to make sure support exists
671 // - spare pointer, used when mapped by the runtime
672 // - pointer to mangled symbol above with initializer
673 unsigned PtrSize
= DL
.getPointerTypeSize(GV
->getType());
674 OutStreamer
->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
676 OutStreamer
->emitIntValue(0, PtrSize
);
677 OutStreamer
->emitSymbolValue(MangSym
, PtrSize
);
679 OutStreamer
->AddBlankLine();
683 MCSymbol
*EmittedInitSym
= GVSym
;
685 OutStreamer
->SwitchSection(TheSection
);
687 emitLinkage(GV
, EmittedInitSym
);
688 emitAlignment(Alignment
, GV
);
690 OutStreamer
->emitLabel(EmittedInitSym
);
691 MCSymbol
*LocalAlias
= getSymbolPreferLocal(*GV
);
692 if (LocalAlias
!= EmittedInitSym
)
693 OutStreamer
->emitLabel(LocalAlias
);
695 emitGlobalConstant(GV
->getParent()->getDataLayout(), GV
->getInitializer());
697 if (MAI
->hasDotTypeDotSizeDirective())
699 OutStreamer
->emitELFSize(EmittedInitSym
,
700 MCConstantExpr::create(Size
, OutContext
));
702 OutStreamer
->AddBlankLine();
705 /// Emit the directive and value for debug thread local expression
707 /// \p Value - The value to emit.
708 /// \p Size - The size of the integer (in bytes) to emit.
709 void AsmPrinter::emitDebugValue(const MCExpr
*Value
, unsigned Size
) const {
710 OutStreamer
->emitValue(Value
, Size
);
713 void AsmPrinter::emitFunctionHeaderComment() {}
715 /// EmitFunctionHeader - This method emits the header for the current
717 void AsmPrinter::emitFunctionHeader() {
718 const Function
&F
= MF
->getFunction();
721 OutStreamer
->GetCommentOS()
722 << "-- Begin function "
723 << GlobalValue::dropLLVMManglingEscape(F
.getName()) << '\n';
725 // Print out constants referenced by the function
728 // Print the 'header' of function.
729 // If basic block sections are desired, explicitly request a unique section
730 // for this function's entry block.
731 if (MF
->front().isBeginSection())
732 MF
->setSection(getObjFileLowering().getUniqueSectionForFunction(F
, TM
));
734 MF
->setSection(getObjFileLowering().SectionForGlobal(&F
, TM
));
735 OutStreamer
->SwitchSection(MF
->getSection());
737 if (!MAI
->hasVisibilityOnlyWithLinkage())
738 emitVisibility(CurrentFnSym
, F
.getVisibility());
740 if (MAI
->needsFunctionDescriptors())
741 emitLinkage(&F
, CurrentFnDescSym
);
743 emitLinkage(&F
, CurrentFnSym
);
744 if (MAI
->hasFunctionAlignment())
745 emitAlignment(MF
->getAlignment(), &F
);
747 if (MAI
->hasDotTypeDotSizeDirective())
748 OutStreamer
->emitSymbolAttribute(CurrentFnSym
, MCSA_ELF_TypeFunction
);
750 if (F
.hasFnAttribute(Attribute::Cold
))
751 OutStreamer
->emitSymbolAttribute(CurrentFnSym
, MCSA_Cold
);
754 F
.printAsOperand(OutStreamer
->GetCommentOS(),
755 /*PrintType=*/false, F
.getParent());
756 emitFunctionHeaderComment();
757 OutStreamer
->GetCommentOS() << '\n';
760 // Emit the prefix data.
761 if (F
.hasPrefixData()) {
762 if (MAI
->hasSubsectionsViaSymbols()) {
763 // Preserving prefix data on platforms which use subsections-via-symbols
764 // is a bit tricky. Here we introduce a symbol for the prefix data
765 // and use the .alt_entry attribute to mark the function's real entry point
766 // as an alternative entry point to the prefix-data symbol.
767 MCSymbol
*PrefixSym
= OutContext
.createLinkerPrivateTempSymbol();
768 OutStreamer
->emitLabel(PrefixSym
);
770 emitGlobalConstant(F
.getParent()->getDataLayout(), F
.getPrefixData());
772 // Emit an .alt_entry directive for the actual function symbol.
773 OutStreamer
->emitSymbolAttribute(CurrentFnSym
, MCSA_AltEntry
);
775 emitGlobalConstant(F
.getParent()->getDataLayout(), F
.getPrefixData());
779 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
780 // place prefix data before NOPs.
781 unsigned PatchableFunctionPrefix
= 0;
782 unsigned PatchableFunctionEntry
= 0;
783 (void)F
.getFnAttribute("patchable-function-prefix")
785 .getAsInteger(10, PatchableFunctionPrefix
);
786 (void)F
.getFnAttribute("patchable-function-entry")
788 .getAsInteger(10, PatchableFunctionEntry
);
789 if (PatchableFunctionPrefix
) {
790 CurrentPatchableFunctionEntrySym
=
791 OutContext
.createLinkerPrivateTempSymbol();
792 OutStreamer
->emitLabel(CurrentPatchableFunctionEntrySym
);
793 emitNops(PatchableFunctionPrefix
);
794 } else if (PatchableFunctionEntry
) {
795 // May be reassigned when emitting the body, to reference the label after
796 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
797 CurrentPatchableFunctionEntrySym
= CurrentFnBegin
;
800 // Emit the function descriptor. This is a virtual function to allow targets
801 // to emit their specific function descriptor. Right now it is only used by
802 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
803 // descriptors and should be converted to use this hook as well.
804 if (MAI
->needsFunctionDescriptors())
805 emitFunctionDescriptor();
807 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
808 // their wild and crazy things as required.
809 emitFunctionEntryLabel();
811 // If the function had address-taken blocks that got deleted, then we have
812 // references to the dangling symbols. Emit them at the start of the function
813 // so that we don't get references to undefined symbols.
814 std::vector
<MCSymbol
*> DeadBlockSyms
;
815 MMI
->takeDeletedSymbolsForFunction(&F
, DeadBlockSyms
);
816 for (MCSymbol
*DeadBlockSym
: DeadBlockSyms
) {
817 OutStreamer
->AddComment("Address taken block that was later removed");
818 OutStreamer
->emitLabel(DeadBlockSym
);
821 if (CurrentFnBegin
) {
822 if (MAI
->useAssignmentForEHBegin()) {
823 MCSymbol
*CurPos
= OutContext
.createTempSymbol();
824 OutStreamer
->emitLabel(CurPos
);
825 OutStreamer
->emitAssignment(CurrentFnBegin
,
826 MCSymbolRefExpr::create(CurPos
, OutContext
));
828 OutStreamer
->emitLabel(CurrentFnBegin
);
832 // Emit pre-function debug and/or EH information.
833 for (const HandlerInfo
&HI
: Handlers
) {
834 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
835 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
836 HI
.Handler
->beginFunction(MF
);
839 // Emit the prologue data.
840 if (F
.hasPrologueData())
841 emitGlobalConstant(F
.getParent()->getDataLayout(), F
.getPrologueData());
844 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
845 /// function. This can be overridden by targets as required to do custom stuff.
846 void AsmPrinter::emitFunctionEntryLabel() {
847 CurrentFnSym
->redefineIfPossible();
849 // The function label could have already been emitted if two symbols end up
850 // conflicting due to asm renaming. Detect this and emit an error.
851 if (CurrentFnSym
->isVariable())
852 report_fatal_error("'" + Twine(CurrentFnSym
->getName()) +
853 "' is a protected alias");
855 OutStreamer
->emitLabel(CurrentFnSym
);
857 if (TM
.getTargetTriple().isOSBinFormatELF()) {
858 MCSymbol
*Sym
= getSymbolPreferLocal(MF
->getFunction());
859 if (Sym
!= CurrentFnSym
)
860 OutStreamer
->emitLabel(Sym
);
864 /// emitComments - Pretty-print comments for instructions.
865 static void emitComments(const MachineInstr
&MI
, raw_ostream
&CommentOS
) {
866 const MachineFunction
*MF
= MI
.getMF();
867 const TargetInstrInfo
*TII
= MF
->getSubtarget().getInstrInfo();
869 // Check for spills and reloads
871 // We assume a single instruction only has a spill or reload, not
873 Optional
<unsigned> Size
;
874 if ((Size
= MI
.getRestoreSize(TII
))) {
875 CommentOS
<< *Size
<< "-byte Reload\n";
876 } else if ((Size
= MI
.getFoldedRestoreSize(TII
))) {
878 if (*Size
== unsigned(MemoryLocation::UnknownSize
))
879 CommentOS
<< "Unknown-size Folded Reload\n";
881 CommentOS
<< *Size
<< "-byte Folded Reload\n";
883 } else if ((Size
= MI
.getSpillSize(TII
))) {
884 CommentOS
<< *Size
<< "-byte Spill\n";
885 } else if ((Size
= MI
.getFoldedSpillSize(TII
))) {
887 if (*Size
== unsigned(MemoryLocation::UnknownSize
))
888 CommentOS
<< "Unknown-size Folded Spill\n";
890 CommentOS
<< *Size
<< "-byte Folded Spill\n";
894 // Check for spill-induced copies
895 if (MI
.getAsmPrinterFlag(MachineInstr::ReloadReuse
))
896 CommentOS
<< " Reload Reuse\n";
899 /// emitImplicitDef - This method emits the specified machine instruction
900 /// that is an implicit def.
901 void AsmPrinter::emitImplicitDef(const MachineInstr
*MI
) const {
902 Register RegNo
= MI
->getOperand(0).getReg();
904 SmallString
<128> Str
;
905 raw_svector_ostream
OS(Str
);
906 OS
<< "implicit-def: "
907 << printReg(RegNo
, MF
->getSubtarget().getRegisterInfo());
909 OutStreamer
->AddComment(OS
.str());
910 OutStreamer
->AddBlankLine();
913 static void emitKill(const MachineInstr
*MI
, AsmPrinter
&AP
) {
915 raw_string_ostream
OS(Str
);
917 for (const MachineOperand
&Op
: MI
->operands()) {
918 assert(Op
.isReg() && "KILL instruction must have only register operands");
919 OS
<< ' ' << (Op
.isDef() ? "def " : "killed ")
920 << printReg(Op
.getReg(), AP
.MF
->getSubtarget().getRegisterInfo());
922 AP
.OutStreamer
->AddComment(OS
.str());
923 AP
.OutStreamer
->AddBlankLine();
926 /// emitDebugValueComment - This method handles the target-independent form
927 /// of DBG_VALUE, returning true if it was able to do so. A false return
928 /// means the target will need to handle MI in EmitInstruction.
929 static bool emitDebugValueComment(const MachineInstr
*MI
, AsmPrinter
&AP
) {
930 // This code handles only the 4-operand target-independent form.
931 if (MI
->isNonListDebugValue() && MI
->getNumOperands() != 4)
934 SmallString
<128> Str
;
935 raw_svector_ostream
OS(Str
);
936 OS
<< "DEBUG_VALUE: ";
938 const DILocalVariable
*V
= MI
->getDebugVariable();
939 if (auto *SP
= dyn_cast
<DISubprogram
>(V
->getScope())) {
940 StringRef Name
= SP
->getName();
947 const DIExpression
*Expr
= MI
->getDebugExpression();
948 if (Expr
->getNumElements()) {
951 for (auto Op
: Expr
->expr_ops()) {
952 OS
<< LS
<< dwarf::OperationEncodingString(Op
.getOp());
953 for (unsigned I
= 0; I
< Op
.getNumArgs(); ++I
)
954 OS
<< ' ' << Op
.getArg(I
);
959 // Register or immediate value. Register 0 means undef.
960 for (const MachineOperand
&Op
: MI
->debug_operands()) {
961 if (&Op
!= MI
->debug_operands().begin())
963 switch (Op
.getType()) {
964 case MachineOperand::MO_FPImmediate
: {
965 APFloat APF
= APFloat(Op
.getFPImm()->getValueAPF());
966 Type
*ImmTy
= Op
.getFPImm()->getType();
967 if (ImmTy
->isBFloatTy() || ImmTy
->isHalfTy() || ImmTy
->isFloatTy() ||
968 ImmTy
->isDoubleTy()) {
969 OS
<< APF
.convertToDouble();
971 // There is no good way to print long double. Convert a copy to
972 // double. Ah well, it's only a comment.
974 APF
.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven
,
976 OS
<< "(long double) " << APF
.convertToDouble();
980 case MachineOperand::MO_Immediate
: {
984 case MachineOperand::MO_CImmediate
: {
985 Op
.getCImm()->getValue().print(OS
, false /*isSigned*/);
988 case MachineOperand::MO_TargetIndex
: {
989 OS
<< "!target-index(" << Op
.getIndex() << "," << Op
.getOffset() << ")";
990 // NOTE: Want this comment at start of line, don't emit with AddComment.
991 AP
.OutStreamer
->emitRawComment(OS
.str());
994 case MachineOperand::MO_Register
:
995 case MachineOperand::MO_FrameIndex
: {
997 Optional
<StackOffset
> Offset
;
1001 const TargetFrameLowering
*TFI
=
1002 AP
.MF
->getSubtarget().getFrameLowering();
1003 Offset
= TFI
->getFrameIndexReference(*AP
.MF
, Op
.getIndex(), Reg
);
1006 // Suppress offset, it is not meaningful here.
1010 // The second operand is only an offset if it's an immediate.
1011 if (MI
->isIndirectDebugValue())
1012 Offset
= StackOffset::getFixed(MI
->getDebugOffset().getImm());
1015 OS
<< printReg(Reg
, AP
.MF
->getSubtarget().getRegisterInfo());
1017 OS
<< '+' << Offset
->getFixed() << ']';
1021 llvm_unreachable("Unknown operand type");
1025 // NOTE: Want this comment at start of line, don't emit with AddComment.
1026 AP
.OutStreamer
->emitRawComment(OS
.str());
1030 /// This method handles the target-independent form of DBG_LABEL, returning
1031 /// true if it was able to do so. A false return means the target will need
1032 /// to handle MI in EmitInstruction.
1033 static bool emitDebugLabelComment(const MachineInstr
*MI
, AsmPrinter
&AP
) {
1034 if (MI
->getNumOperands() != 1)
1037 SmallString
<128> Str
;
1038 raw_svector_ostream
OS(Str
);
1039 OS
<< "DEBUG_LABEL: ";
1041 const DILabel
*V
= MI
->getDebugLabel();
1042 if (auto *SP
= dyn_cast
<DISubprogram
>(
1043 V
->getScope()->getNonLexicalBlockFileScope())) {
1044 StringRef Name
= SP
->getName();
1050 // NOTE: Want this comment at start of line, don't emit with AddComment.
1051 AP
.OutStreamer
->emitRawComment(OS
.str());
1055 AsmPrinter::CFISection
1056 AsmPrinter::getFunctionCFISectionType(const Function
&F
) const {
1057 // Ignore functions that won't get emitted.
1058 if (F
.isDeclarationForLinker())
1059 return CFISection::None
;
1061 if (MAI
->getExceptionHandlingType() == ExceptionHandling::DwarfCFI
&&
1062 F
.needsUnwindTableEntry())
1063 return CFISection::EH
;
1065 if (MMI
->hasDebugInfo() || TM
.Options
.ForceDwarfFrameSection
)
1066 return CFISection::Debug
;
1068 return CFISection::None
;
1071 AsmPrinter::CFISection
1072 AsmPrinter::getFunctionCFISectionType(const MachineFunction
&MF
) const {
1073 return getFunctionCFISectionType(MF
.getFunction());
1076 bool AsmPrinter::needsSEHMoves() {
1077 return MAI
->usesWindowsCFI() && MF
->getFunction().needsUnwindTableEntry();
1080 bool AsmPrinter::needsCFIForDebug() const {
1081 return MAI
->getExceptionHandlingType() == ExceptionHandling::None
&&
1082 MAI
->doesUseCFIForDebug() && ModuleCFISection
== CFISection::Debug
;
1085 void AsmPrinter::emitCFIInstruction(const MachineInstr
&MI
) {
1086 ExceptionHandling ExceptionHandlingType
= MAI
->getExceptionHandlingType();
1087 if (!needsCFIForDebug() &&
1088 ExceptionHandlingType
!= ExceptionHandling::DwarfCFI
&&
1089 ExceptionHandlingType
!= ExceptionHandling::ARM
)
1092 if (getFunctionCFISectionType(*MF
) == CFISection::None
)
1095 // If there is no "real" instruction following this CFI instruction, skip
1096 // emitting it; it would be beyond the end of the function's FDE range.
1097 auto *MBB
= MI
.getParent();
1098 auto I
= std::next(MI
.getIterator());
1099 while (I
!= MBB
->end() && I
->isTransient())
1101 if (I
== MBB
->instr_end() &&
1102 MBB
->getReverseIterator() == MBB
->getParent()->rbegin())
1105 const std::vector
<MCCFIInstruction
> &Instrs
= MF
->getFrameInstructions();
1106 unsigned CFIIndex
= MI
.getOperand(0).getCFIIndex();
1107 const MCCFIInstruction
&CFI
= Instrs
[CFIIndex
];
1108 emitCFIInstruction(CFI
);
1111 void AsmPrinter::emitFrameAlloc(const MachineInstr
&MI
) {
1112 // The operands are the MCSymbol and the frame offset of the allocation.
1113 MCSymbol
*FrameAllocSym
= MI
.getOperand(0).getMCSymbol();
1114 int FrameOffset
= MI
.getOperand(1).getImm();
1116 // Emit a symbol assignment.
1117 OutStreamer
->emitAssignment(FrameAllocSym
,
1118 MCConstantExpr::create(FrameOffset
, OutContext
));
1121 /// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
1122 /// given basic block. This can be used to capture more precise profile
1123 /// information. We use the last 4 bits (LSBs) to encode the following
1125 /// * (1): set if return block (ret or tail call).
1126 /// * (2): set if ends with a tail call.
1127 /// * (3): set if exception handling (EH) landing pad.
1128 /// * (4): set if the block can fall through to its next.
1129 /// The remaining bits are zero.
1130 static unsigned getBBAddrMapMetadata(const MachineBasicBlock
&MBB
) {
1131 const TargetInstrInfo
*TII
= MBB
.getParent()->getSubtarget().getInstrInfo();
1132 return ((unsigned)MBB
.isReturnBlock()) |
1133 ((!MBB
.empty() && TII
->isTailCall(MBB
.back())) << 1) |
1134 (MBB
.isEHPad() << 2) |
1135 (const_cast<MachineBasicBlock
&>(MBB
).canFallThrough() << 3);
1138 void AsmPrinter::emitBBAddrMapSection(const MachineFunction
&MF
) {
1139 MCSection
*BBAddrMapSection
=
1140 getObjFileLowering().getBBAddrMapSection(*MF
.getSection());
1141 assert(BBAddrMapSection
&& ".llvm_bb_addr_map section is not initialized.");
1143 const MCSymbol
*FunctionSymbol
= getFunctionBegin();
1145 OutStreamer
->PushSection();
1146 OutStreamer
->SwitchSection(BBAddrMapSection
);
1147 OutStreamer
->emitSymbolValue(FunctionSymbol
, getPointerSize());
1148 // Emit the total number of basic blocks in this function.
1149 OutStreamer
->emitULEB128IntValue(MF
.size());
1150 // Emit BB Information for each basic block in the funciton.
1151 for (const MachineBasicBlock
&MBB
: MF
) {
1152 const MCSymbol
*MBBSymbol
=
1153 MBB
.isEntryBlock() ? FunctionSymbol
: MBB
.getSymbol();
1154 // Emit the basic block offset.
1155 emitLabelDifferenceAsULEB128(MBBSymbol
, FunctionSymbol
);
1156 // Emit the basic block size. When BBs have alignments, their size cannot
1157 // always be computed from their offsets.
1158 emitLabelDifferenceAsULEB128(MBB
.getEndSymbol(), MBBSymbol
);
1159 OutStreamer
->emitULEB128IntValue(getBBAddrMapMetadata(MBB
));
1161 OutStreamer
->PopSection();
1164 void AsmPrinter::emitPseudoProbe(const MachineInstr
&MI
) {
1165 auto GUID
= MI
.getOperand(0).getImm();
1166 auto Index
= MI
.getOperand(1).getImm();
1167 auto Type
= MI
.getOperand(2).getImm();
1168 auto Attr
= MI
.getOperand(3).getImm();
1169 DILocation
*DebugLoc
= MI
.getDebugLoc();
1170 PP
->emitPseudoProbe(GUID
, Index
, Type
, Attr
, DebugLoc
);
1173 void AsmPrinter::emitStackSizeSection(const MachineFunction
&MF
) {
1174 if (!MF
.getTarget().Options
.EmitStackSizeSection
)
1177 MCSection
*StackSizeSection
=
1178 getObjFileLowering().getStackSizesSection(*getCurrentSection());
1179 if (!StackSizeSection
)
1182 const MachineFrameInfo
&FrameInfo
= MF
.getFrameInfo();
1183 // Don't emit functions with dynamic stack allocations.
1184 if (FrameInfo
.hasVarSizedObjects())
1187 OutStreamer
->PushSection();
1188 OutStreamer
->SwitchSection(StackSizeSection
);
1190 const MCSymbol
*FunctionSymbol
= getFunctionBegin();
1191 uint64_t StackSize
= FrameInfo
.getStackSize();
1192 OutStreamer
->emitSymbolValue(FunctionSymbol
, TM
.getProgramPointerSize());
1193 OutStreamer
->emitULEB128IntValue(StackSize
);
1195 OutStreamer
->PopSection();
1198 void AsmPrinter::emitStackUsage(const MachineFunction
&MF
) {
1199 const std::string
&OutputFilename
= MF
.getTarget().Options
.StackUsageOutput
;
1201 // OutputFilename empty implies -fstack-usage is not passed.
1202 if (OutputFilename
.empty())
1205 const MachineFrameInfo
&FrameInfo
= MF
.getFrameInfo();
1206 uint64_t StackSize
= FrameInfo
.getStackSize();
1208 if (StackUsageStream
== nullptr) {
1211 std::make_unique
<raw_fd_ostream
>(OutputFilename
, EC
, sys::fs::OF_Text
);
1213 errs() << "Could not open file: " << EC
.message();
1218 *StackUsageStream
<< MF
.getFunction().getParent()->getName();
1219 if (const DISubprogram
*DSP
= MF
.getFunction().getSubprogram())
1220 *StackUsageStream
<< ':' << DSP
->getLine();
1222 *StackUsageStream
<< ':' << MF
.getName() << '\t' << StackSize
<< '\t';
1223 if (FrameInfo
.hasVarSizedObjects())
1224 *StackUsageStream
<< "dynamic\n";
1226 *StackUsageStream
<< "static\n";
1229 static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction
&MF
) {
1230 MachineModuleInfo
&MMI
= MF
.getMMI();
1231 if (!MF
.getLandingPads().empty() || MF
.hasEHFunclets() || MMI
.hasDebugInfo())
1234 // We might emit an EH table that uses function begin and end labels even if
1235 // we don't have any landingpads.
1236 if (!MF
.getFunction().hasPersonalityFn())
1238 return !isNoOpWithoutInvoke(
1239 classifyEHPersonality(MF
.getFunction().getPersonalityFn()));
1242 /// EmitFunctionBody - This method emits the body and trailer for a
1244 void AsmPrinter::emitFunctionBody() {
1245 emitFunctionHeader();
1247 // Emit target-specific gunk before the function body.
1248 emitFunctionBodyStart();
1251 // Get MachineDominatorTree or compute it on the fly if it's unavailable
1252 MDT
= getAnalysisIfAvailable
<MachineDominatorTree
>();
1254 OwnedMDT
= std::make_unique
<MachineDominatorTree
>();
1255 OwnedMDT
->getBase().recalculate(*MF
);
1256 MDT
= OwnedMDT
.get();
1259 // Get MachineLoopInfo or compute it on the fly if it's unavailable
1260 MLI
= getAnalysisIfAvailable
<MachineLoopInfo
>();
1262 OwnedMLI
= std::make_unique
<MachineLoopInfo
>();
1263 OwnedMLI
->getBase().analyze(MDT
->getBase());
1264 MLI
= OwnedMLI
.get();
1268 // Print out code for the function.
1269 bool HasAnyRealCode
= false;
1270 int NumInstsInFunction
= 0;
1272 bool CanDoExtraAnalysis
= ORE
->allowExtraAnalysis(DEBUG_TYPE
);
1273 for (auto &MBB
: *MF
) {
1274 // Print a label for the basic block.
1275 emitBasicBlockStart(MBB
);
1276 DenseMap
<StringRef
, unsigned> MnemonicCounts
;
1277 for (auto &MI
: MBB
) {
1278 // Print the assembly for the instruction.
1279 if (!MI
.isPosition() && !MI
.isImplicitDef() && !MI
.isKill() &&
1280 !MI
.isDebugInstr()) {
1281 HasAnyRealCode
= true;
1282 ++NumInstsInFunction
;
1285 // If there is a pre-instruction symbol, emit a label for it here.
1286 if (MCSymbol
*S
= MI
.getPreInstrSymbol())
1287 OutStreamer
->emitLabel(S
);
1289 for (const HandlerInfo
&HI
: Handlers
) {
1290 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
1291 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
1292 HI
.Handler
->beginInstruction(&MI
);
1296 emitComments(MI
, OutStreamer
->GetCommentOS());
1298 switch (MI
.getOpcode()) {
1299 case TargetOpcode::CFI_INSTRUCTION
:
1300 emitCFIInstruction(MI
);
1302 case TargetOpcode::LOCAL_ESCAPE
:
1305 case TargetOpcode::ANNOTATION_LABEL
:
1306 case TargetOpcode::EH_LABEL
:
1307 case TargetOpcode::GC_LABEL
:
1308 OutStreamer
->emitLabel(MI
.getOperand(0).getMCSymbol());
1310 case TargetOpcode::INLINEASM
:
1311 case TargetOpcode::INLINEASM_BR
:
1314 case TargetOpcode::DBG_VALUE
:
1315 case TargetOpcode::DBG_VALUE_LIST
:
1317 if (!emitDebugValueComment(&MI
, *this))
1318 emitInstruction(&MI
);
1321 case TargetOpcode::DBG_INSTR_REF
:
1322 // This instruction reference will have been resolved to a machine
1323 // location, and a nearby DBG_VALUE created. We can safely ignore
1324 // the instruction reference.
1326 case TargetOpcode::DBG_PHI
:
1327 // This instruction is only used to label a program point, it's purely
1328 // meta information.
1330 case TargetOpcode::DBG_LABEL
:
1332 if (!emitDebugLabelComment(&MI
, *this))
1333 emitInstruction(&MI
);
1336 case TargetOpcode::IMPLICIT_DEF
:
1337 if (isVerbose()) emitImplicitDef(&MI
);
1339 case TargetOpcode::KILL
:
1340 if (isVerbose()) emitKill(&MI
, *this);
1342 case TargetOpcode::PSEUDO_PROBE
:
1343 emitPseudoProbe(MI
);
1345 case TargetOpcode::ARITH_FENCE
:
1347 OutStreamer
->emitRawComment("ARITH_FENCE");
1350 emitInstruction(&MI
);
1351 if (CanDoExtraAnalysis
) {
1353 MCI
.setOpcode(MI
.getOpcode());
1354 auto Name
= OutStreamer
->getMnemonic(MCI
);
1355 auto I
= MnemonicCounts
.insert({Name
, 0u});
1361 // If there is a post-instruction symbol, emit a label for it here.
1362 if (MCSymbol
*S
= MI
.getPostInstrSymbol())
1363 OutStreamer
->emitLabel(S
);
1365 for (const HandlerInfo
&HI
: Handlers
) {
1366 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
1367 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
1368 HI
.Handler
->endInstruction();
1372 // We must emit temporary symbol for the end of this basic block, if either
1373 // we have BBLabels enabled or if this basic blocks marks the end of a
1375 if (MF
->hasBBLabels() ||
1376 (MAI
->hasDotTypeDotSizeDirective() && MBB
.isEndSection()))
1377 OutStreamer
->emitLabel(MBB
.getEndSymbol());
1379 if (MBB
.isEndSection()) {
1380 // The size directive for the section containing the entry block is
1381 // handled separately by the function section.
1382 if (!MBB
.sameSection(&MF
->front())) {
1383 if (MAI
->hasDotTypeDotSizeDirective()) {
1384 // Emit the size directive for the basic block section.
1385 const MCExpr
*SizeExp
= MCBinaryExpr::createSub(
1386 MCSymbolRefExpr::create(MBB
.getEndSymbol(), OutContext
),
1387 MCSymbolRefExpr::create(CurrentSectionBeginSym
, OutContext
),
1389 OutStreamer
->emitELFSize(CurrentSectionBeginSym
, SizeExp
);
1391 MBBSectionRanges
[MBB
.getSectionIDNum()] =
1392 MBBSectionRange
{CurrentSectionBeginSym
, MBB
.getEndSymbol()};
1395 emitBasicBlockEnd(MBB
);
1397 if (CanDoExtraAnalysis
) {
1398 // Skip empty blocks.
1402 MachineOptimizationRemarkAnalysis
R(DEBUG_TYPE
, "InstructionMix",
1403 MBB
.begin()->getDebugLoc(), &MBB
);
1405 // Generate instruction mix remark. First, sort counts in descending order
1406 // by count and name.
1407 SmallVector
<std::pair
<StringRef
, unsigned>, 128> MnemonicVec
;
1408 for (auto &KV
: MnemonicCounts
)
1409 MnemonicVec
.emplace_back(KV
.first
, KV
.second
);
1411 sort(MnemonicVec
, [](const std::pair
<StringRef
, unsigned> &A
,
1412 const std::pair
<StringRef
, unsigned> &B
) {
1413 if (A
.second
> B
.second
)
1415 if (A
.second
== B
.second
)
1416 return StringRef(A
.first
) < StringRef(B
.first
);
1419 R
<< "BasicBlock: " << ore::NV("BasicBlock", MBB
.getName()) << "\n";
1420 for (auto &KV
: MnemonicVec
) {
1421 auto Name
= (Twine("INST_") + getToken(KV
.first
.trim()).first
).str();
1422 R
<< KV
.first
<< ": " << ore::NV(Name
, KV
.second
) << "\n";
1428 EmittedInsts
+= NumInstsInFunction
;
1429 MachineOptimizationRemarkAnalysis
R(DEBUG_TYPE
, "InstructionCount",
1430 MF
->getFunction().getSubprogram(),
1432 R
<< ore::NV("NumInstructions", NumInstsInFunction
)
1433 << " instructions in function";
1436 // If the function is empty and the object file uses .subsections_via_symbols,
1437 // then we need to emit *something* to the function body to prevent the
1438 // labels from collapsing together. Just emit a noop.
1439 // Similarly, don't emit empty functions on Windows either. It can lead to
1440 // duplicate entries (two functions with the same RVA) in the Guard CF Table
1441 // after linking, causing the kernel not to load the binary:
1442 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1443 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1444 const Triple
&TT
= TM
.getTargetTriple();
1445 if (!HasAnyRealCode
&& (MAI
->hasSubsectionsViaSymbols() ||
1446 (TT
.isOSWindows() && TT
.isOSBinFormatCOFF()))) {
1447 MCInst Noop
= MF
->getSubtarget().getInstrInfo()->getNop();
1449 // Targets can opt-out of emitting the noop here by leaving the opcode
1451 if (Noop
.getOpcode()) {
1452 OutStreamer
->AddComment("avoids zero-length function");
1457 // Switch to the original section in case basic block sections was used.
1458 OutStreamer
->SwitchSection(MF
->getSection());
1460 const Function
&F
= MF
->getFunction();
1461 for (const auto &BB
: F
) {
1462 if (!BB
.hasAddressTaken())
1464 MCSymbol
*Sym
= GetBlockAddressSymbol(&BB
);
1465 if (Sym
->isDefined())
1467 OutStreamer
->AddComment("Address of block that was removed by CodeGen");
1468 OutStreamer
->emitLabel(Sym
);
1471 // Emit target-specific gunk after the function body.
1472 emitFunctionBodyEnd();
1474 if (needFuncLabelsForEHOrDebugInfo(*MF
) ||
1475 MAI
->hasDotTypeDotSizeDirective()) {
1476 // Create a symbol for the end of function.
1477 CurrentFnEnd
= createTempSymbol("func_end");
1478 OutStreamer
->emitLabel(CurrentFnEnd
);
1481 // If the target wants a .size directive for the size of the function, emit
1483 if (MAI
->hasDotTypeDotSizeDirective()) {
1484 // We can get the size as difference between the function label and the
1486 const MCExpr
*SizeExp
= MCBinaryExpr::createSub(
1487 MCSymbolRefExpr::create(CurrentFnEnd
, OutContext
),
1488 MCSymbolRefExpr::create(CurrentFnSymForSize
, OutContext
), OutContext
);
1489 OutStreamer
->emitELFSize(CurrentFnSym
, SizeExp
);
1492 for (const HandlerInfo
&HI
: Handlers
) {
1493 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
1494 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
1495 HI
.Handler
->markFunctionEnd();
1498 MBBSectionRanges
[MF
->front().getSectionIDNum()] =
1499 MBBSectionRange
{CurrentFnBegin
, CurrentFnEnd
};
1501 // Print out jump tables referenced by the function.
1502 emitJumpTableInfo();
1504 // Emit post-function debug and/or EH information.
1505 for (const HandlerInfo
&HI
: Handlers
) {
1506 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
1507 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
1508 HI
.Handler
->endFunction(MF
);
1511 // Emit section containing BB address offsets and their metadata, when
1512 // BB labels are requested for this function. Skip empty functions.
1513 if (MF
->hasBBLabels() && HasAnyRealCode
)
1514 emitBBAddrMapSection(*MF
);
1516 // Emit section containing stack size metadata.
1517 emitStackSizeSection(*MF
);
1519 // Emit .su file containing function stack size information.
1520 emitStackUsage(*MF
);
1522 emitPatchableFunctionEntries();
1525 OutStreamer
->GetCommentOS() << "-- End function\n";
1527 OutStreamer
->AddBlankLine();
1530 /// Compute the number of Global Variables that uses a Constant.
1531 static unsigned getNumGlobalVariableUses(const Constant
*C
) {
1535 if (isa
<GlobalVariable
>(C
))
1538 unsigned NumUses
= 0;
1539 for (auto *CU
: C
->users())
1540 NumUses
+= getNumGlobalVariableUses(dyn_cast
<Constant
>(CU
));
1545 /// Only consider global GOT equivalents if at least one user is a
1546 /// cstexpr inside an initializer of another global variables. Also, don't
1547 /// handle cstexpr inside instructions. During global variable emission,
1548 /// candidates are skipped and are emitted later in case at least one cstexpr
1549 /// isn't replaced by a PC relative GOT entry access.
1550 static bool isGOTEquivalentCandidate(const GlobalVariable
*GV
,
1551 unsigned &NumGOTEquivUsers
) {
1552 // Global GOT equivalents are unnamed private globals with a constant
1553 // pointer initializer to another global symbol. They must point to a
1554 // GlobalVariable or Function, i.e., as GlobalValue.
1555 if (!GV
->hasGlobalUnnamedAddr() || !GV
->hasInitializer() ||
1556 !GV
->isConstant() || !GV
->isDiscardableIfUnused() ||
1557 !isa
<GlobalValue
>(GV
->getOperand(0)))
1560 // To be a got equivalent, at least one of its users need to be a constant
1561 // expression used by another global variable.
1562 for (auto *U
: GV
->users())
1563 NumGOTEquivUsers
+= getNumGlobalVariableUses(dyn_cast
<Constant
>(U
));
1565 return NumGOTEquivUsers
> 0;
1568 /// Unnamed constant global variables solely contaning a pointer to
1569 /// another globals variable is equivalent to a GOT table entry; it contains the
1570 /// the address of another symbol. Optimize it and replace accesses to these
1571 /// "GOT equivalents" by using the GOT entry for the final global instead.
1572 /// Compute GOT equivalent candidates among all global variables to avoid
1573 /// emitting them if possible later on, after it use is replaced by a GOT entry
1575 void AsmPrinter::computeGlobalGOTEquivs(Module
&M
) {
1576 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1579 for (const auto &G
: M
.globals()) {
1580 unsigned NumGOTEquivUsers
= 0;
1581 if (!isGOTEquivalentCandidate(&G
, NumGOTEquivUsers
))
1584 const MCSymbol
*GOTEquivSym
= getSymbol(&G
);
1585 GlobalGOTEquivs
[GOTEquivSym
] = std::make_pair(&G
, NumGOTEquivUsers
);
1589 /// Constant expressions using GOT equivalent globals may not be eligible
1590 /// for PC relative GOT entry conversion, in such cases we need to emit such
1591 /// globals we previously omitted in EmitGlobalVariable.
1592 void AsmPrinter::emitGlobalGOTEquivs() {
1593 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1596 SmallVector
<const GlobalVariable
*, 8> FailedCandidates
;
1597 for (auto &I
: GlobalGOTEquivs
) {
1598 const GlobalVariable
*GV
= I
.second
.first
;
1599 unsigned Cnt
= I
.second
.second
;
1601 FailedCandidates
.push_back(GV
);
1603 GlobalGOTEquivs
.clear();
1605 for (auto *GV
: FailedCandidates
)
1606 emitGlobalVariable(GV
);
1609 void AsmPrinter::emitGlobalAlias(Module
&M
, const GlobalAlias
&GA
) {
1610 MCSymbol
*Name
= getSymbol(&GA
);
1611 bool IsFunction
= GA
.getValueType()->isFunctionTy();
1612 // Treat bitcasts of functions as functions also. This is important at least
1613 // on WebAssembly where object and function addresses can't alias each other.
1615 if (auto *CE
= dyn_cast
<ConstantExpr
>(GA
.getAliasee()))
1616 if (CE
->getOpcode() == Instruction::BitCast
)
1618 CE
->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1620 // AIX's assembly directive `.set` is not usable for aliasing purpose,
1621 // so AIX has to use the extra-label-at-definition strategy. At this
1622 // point, all the extra label is emitted, we just have to emit linkage for
1624 if (TM
.getTargetTriple().isOSBinFormatXCOFF()) {
1625 assert(MAI
->hasVisibilityOnlyWithLinkage() &&
1626 "Visibility should be handled with emitLinkage() on AIX.");
1627 emitLinkage(&GA
, Name
);
1628 // If it's a function, also emit linkage for aliases of function entry
1632 getObjFileLowering().getFunctionEntryPointSymbol(&GA
, TM
));
1636 if (GA
.hasExternalLinkage() || !MAI
->getWeakRefDirective())
1637 OutStreamer
->emitSymbolAttribute(Name
, MCSA_Global
);
1638 else if (GA
.hasWeakLinkage() || GA
.hasLinkOnceLinkage())
1639 OutStreamer
->emitSymbolAttribute(Name
, MCSA_WeakReference
);
1641 assert(GA
.hasLocalLinkage() && "Invalid alias linkage");
1643 // Set the symbol type to function if the alias has a function type.
1644 // This affects codegen when the aliasee is not a function.
1646 OutStreamer
->emitSymbolAttribute(Name
, MCSA_ELF_TypeFunction
);
1648 emitVisibility(Name
, GA
.getVisibility());
1650 const MCExpr
*Expr
= lowerConstant(GA
.getAliasee());
1652 if (MAI
->hasAltEntry() && isa
<MCBinaryExpr
>(Expr
))
1653 OutStreamer
->emitSymbolAttribute(Name
, MCSA_AltEntry
);
1655 // Emit the directives as assignments aka .set:
1656 OutStreamer
->emitAssignment(Name
, Expr
);
1657 MCSymbol
*LocalAlias
= getSymbolPreferLocal(GA
);
1658 if (LocalAlias
!= Name
)
1659 OutStreamer
->emitAssignment(LocalAlias
, Expr
);
1661 // If the aliasee does not correspond to a symbol in the output, i.e. the
1662 // alias is not of an object or the aliased object is private, then set the
1663 // size of the alias symbol from the type of the alias. We don't do this in
1664 // other situations as the alias and aliasee having differing types but same
1665 // size may be intentional.
1666 const GlobalObject
*BaseObject
= GA
.getAliaseeObject();
1667 if (MAI
->hasDotTypeDotSizeDirective() && GA
.getValueType()->isSized() &&
1668 (!BaseObject
|| BaseObject
->hasPrivateLinkage())) {
1669 const DataLayout
&DL
= M
.getDataLayout();
1670 uint64_t Size
= DL
.getTypeAllocSize(GA
.getValueType());
1671 OutStreamer
->emitELFSize(Name
, MCConstantExpr::create(Size
, OutContext
));
1675 void AsmPrinter::emitGlobalIFunc(Module
&M
, const GlobalIFunc
&GI
) {
1676 assert(!TM
.getTargetTriple().isOSBinFormatXCOFF() &&
1677 "IFunc is not supported on AIX.");
1679 MCSymbol
*Name
= getSymbol(&GI
);
1681 if (GI
.hasExternalLinkage() || !MAI
->getWeakRefDirective())
1682 OutStreamer
->emitSymbolAttribute(Name
, MCSA_Global
);
1683 else if (GI
.hasWeakLinkage() || GI
.hasLinkOnceLinkage())
1684 OutStreamer
->emitSymbolAttribute(Name
, MCSA_WeakReference
);
1686 assert(GI
.hasLocalLinkage() && "Invalid ifunc linkage");
1688 OutStreamer
->emitSymbolAttribute(Name
, MCSA_ELF_TypeIndFunction
);
1689 emitVisibility(Name
, GI
.getVisibility());
1691 // Emit the directives as assignments aka .set:
1692 const MCExpr
*Expr
= lowerConstant(GI
.getResolver());
1693 OutStreamer
->emitAssignment(Name
, Expr
);
1694 MCSymbol
*LocalAlias
= getSymbolPreferLocal(GI
);
1695 if (LocalAlias
!= Name
)
1696 OutStreamer
->emitAssignment(LocalAlias
, Expr
);
1699 void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer
&RS
) {
1700 if (!RS
.needsSection())
1703 remarks::RemarkSerializer
&RemarkSerializer
= RS
.getSerializer();
1705 Optional
<SmallString
<128>> Filename
;
1706 if (Optional
<StringRef
> FilenameRef
= RS
.getFilename()) {
1707 Filename
= *FilenameRef
;
1708 sys::fs::make_absolute(*Filename
);
1709 assert(!Filename
->empty() && "The filename can't be empty.");
1713 raw_string_ostream
OS(Buf
);
1714 std::unique_ptr
<remarks::MetaSerializer
> MetaSerializer
=
1715 Filename
? RemarkSerializer
.metaSerializer(OS
, Filename
->str())
1716 : RemarkSerializer
.metaSerializer(OS
);
1717 MetaSerializer
->emit();
1719 // Switch to the remarks section.
1720 MCSection
*RemarksSection
=
1721 OutContext
.getObjectFileInfo()->getRemarksSection();
1722 OutStreamer
->SwitchSection(RemarksSection
);
1724 OutStreamer
->emitBinaryData(OS
.str());
1727 bool AsmPrinter::doFinalization(Module
&M
) {
1728 // Set the MachineFunction to nullptr so that we can catch attempted
1729 // accesses to MF specific features at the module level and so that
1730 // we can conditionalize accesses based on whether or not it is nullptr.
1733 // Gather all GOT equivalent globals in the module. We really need two
1734 // passes over the globals: one to compute and another to avoid its emission
1735 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1736 // where the got equivalent shows up before its use.
1737 computeGlobalGOTEquivs(M
);
1739 // Emit global variables.
1740 for (const auto &G
: M
.globals())
1741 emitGlobalVariable(&G
);
1743 // Emit remaining GOT equivalent globals.
1744 emitGlobalGOTEquivs();
1746 const TargetLoweringObjectFile
&TLOF
= getObjFileLowering();
1748 // Emit linkage(XCOFF) and visibility info for declarations
1749 for (const Function
&F
: M
) {
1750 if (!F
.isDeclarationForLinker())
1753 MCSymbol
*Name
= getSymbol(&F
);
1754 // Function getSymbol gives us the function descriptor symbol for XCOFF.
1756 if (!TM
.getTargetTriple().isOSBinFormatXCOFF()) {
1757 GlobalValue::VisibilityTypes V
= F
.getVisibility();
1758 if (V
== GlobalValue::DefaultVisibility
)
1761 emitVisibility(Name
, V
, false);
1765 if (F
.isIntrinsic())
1768 // Handle the XCOFF case.
1769 // Variable `Name` is the function descriptor symbol (see above). Get the
1770 // function entry point symbol.
1771 MCSymbol
*FnEntryPointSym
= TLOF
.getFunctionEntryPointSymbol(&F
, TM
);
1772 // Emit linkage for the function entry point.
1773 emitLinkage(&F
, FnEntryPointSym
);
1775 // Emit linkage for the function descriptor.
1776 emitLinkage(&F
, Name
);
1779 // Emit the remarks section contents.
1780 // FIXME: Figure out when is the safest time to emit this section. It should
1781 // not come after debug info.
1782 if (remarks::RemarkStreamer
*RS
= M
.getContext().getMainRemarkStreamer())
1783 emitRemarksSection(*RS
);
1785 TLOF
.emitModuleMetadata(*OutStreamer
, M
);
1787 if (TM
.getTargetTriple().isOSBinFormatELF()) {
1788 MachineModuleInfoELF
&MMIELF
= MMI
->getObjFileInfo
<MachineModuleInfoELF
>();
1790 // Output stubs for external and common global variables.
1791 MachineModuleInfoELF::SymbolListTy Stubs
= MMIELF
.GetGVStubList();
1792 if (!Stubs
.empty()) {
1793 OutStreamer
->SwitchSection(TLOF
.getDataSection());
1794 const DataLayout
&DL
= M
.getDataLayout();
1796 emitAlignment(Align(DL
.getPointerSize()));
1797 for (const auto &Stub
: Stubs
) {
1798 OutStreamer
->emitLabel(Stub
.first
);
1799 OutStreamer
->emitSymbolValue(Stub
.second
.getPointer(),
1800 DL
.getPointerSize());
1805 if (TM
.getTargetTriple().isOSBinFormatCOFF()) {
1806 MachineModuleInfoCOFF
&MMICOFF
=
1807 MMI
->getObjFileInfo
<MachineModuleInfoCOFF
>();
1809 // Output stubs for external and common global variables.
1810 MachineModuleInfoCOFF::SymbolListTy Stubs
= MMICOFF
.GetGVStubList();
1811 if (!Stubs
.empty()) {
1812 const DataLayout
&DL
= M
.getDataLayout();
1814 for (const auto &Stub
: Stubs
) {
1815 SmallString
<256> SectionName
= StringRef(".rdata$");
1816 SectionName
+= Stub
.first
->getName();
1817 OutStreamer
->SwitchSection(OutContext
.getCOFFSection(
1819 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ
|
1820 COFF::IMAGE_SCN_LNK_COMDAT
,
1821 SectionKind::getReadOnly(), Stub
.first
->getName(),
1822 COFF::IMAGE_COMDAT_SELECT_ANY
));
1823 emitAlignment(Align(DL
.getPointerSize()));
1824 OutStreamer
->emitSymbolAttribute(Stub
.first
, MCSA_Global
);
1825 OutStreamer
->emitLabel(Stub
.first
);
1826 OutStreamer
->emitSymbolValue(Stub
.second
.getPointer(),
1827 DL
.getPointerSize());
1832 // This needs to happen before emitting debug information since that can end
1833 // arbitrary sections.
1834 if (auto *TS
= OutStreamer
->getTargetStreamer())
1835 TS
->emitConstantPools();
1837 // Finalize debug and EH information.
1838 for (const HandlerInfo
&HI
: Handlers
) {
1839 NamedRegionTimer
T(HI
.TimerName
, HI
.TimerDescription
, HI
.TimerGroupName
,
1840 HI
.TimerGroupDescription
, TimePassesIsEnabled
);
1841 HI
.Handler
->endModule();
1844 // This deletes all the ephemeral handlers that AsmPrinter added, while
1845 // keeping all the user-added handlers alive until the AsmPrinter is
1847 Handlers
.erase(Handlers
.begin() + NumUserHandlers
, Handlers
.end());
1850 // If the target wants to know about weak references, print them all.
1851 if (MAI
->getWeakRefDirective()) {
1852 // FIXME: This is not lazy, it would be nice to only print weak references
1853 // to stuff that is actually used. Note that doing so would require targets
1854 // to notice uses in operands (due to constant exprs etc). This should
1855 // happen with the MC stuff eventually.
1857 // Print out module-level global objects here.
1858 for (const auto &GO
: M
.global_objects()) {
1859 if (!GO
.hasExternalWeakLinkage())
1861 OutStreamer
->emitSymbolAttribute(getSymbol(&GO
), MCSA_WeakReference
);
1863 if (shouldEmitWeakSwiftAsyncExtendedFramePointerFlags()) {
1864 auto SymbolName
= "swift_async_extendedFramePointerFlags";
1865 auto Global
= M
.getGlobalVariable(SymbolName
);
1867 auto Int8PtrTy
= Type::getInt8PtrTy(M
.getContext());
1868 Global
= new GlobalVariable(M
, Int8PtrTy
, false,
1869 GlobalValue::ExternalWeakLinkage
, nullptr,
1871 OutStreamer
->emitSymbolAttribute(getSymbol(Global
), MCSA_WeakReference
);
1876 // Print aliases in topological order, that is, for each alias a = b,
1877 // b must be printed before a.
1878 // This is because on some targets (e.g. PowerPC) linker expects aliases in
1879 // such an order to generate correct TOC information.
1880 SmallVector
<const GlobalAlias
*, 16> AliasStack
;
1881 SmallPtrSet
<const GlobalAlias
*, 16> AliasVisited
;
1882 for (const auto &Alias
: M
.aliases()) {
1883 for (const GlobalAlias
*Cur
= &Alias
; Cur
;
1884 Cur
= dyn_cast
<GlobalAlias
>(Cur
->getAliasee())) {
1885 if (!AliasVisited
.insert(Cur
).second
)
1887 AliasStack
.push_back(Cur
);
1889 for (const GlobalAlias
*AncestorAlias
: llvm::reverse(AliasStack
))
1890 emitGlobalAlias(M
, *AncestorAlias
);
1893 for (const auto &IFunc
: M
.ifuncs())
1894 emitGlobalIFunc(M
, IFunc
);
1896 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
1897 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
1898 for (GCModuleInfo::iterator I
= MI
->end(), E
= MI
->begin(); I
!= E
; )
1899 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(**--I
))
1900 MP
->finishAssembly(M
, *MI
, *this);
1902 // Emit llvm.ident metadata in an '.ident' directive.
1903 emitModuleIdents(M
);
1905 // Emit bytes for llvm.commandline metadata.
1906 emitModuleCommandLines(M
);
1908 // Emit __morestack address if needed for indirect calls.
1909 if (MMI
->usesMorestackAddr()) {
1911 MCSection
*ReadOnlySection
= getObjFileLowering().getSectionForConstant(
1912 getDataLayout(), SectionKind::getReadOnly(),
1913 /*C=*/nullptr, Alignment
);
1914 OutStreamer
->SwitchSection(ReadOnlySection
);
1916 MCSymbol
*AddrSymbol
=
1917 OutContext
.getOrCreateSymbol(StringRef("__morestack_addr"));
1918 OutStreamer
->emitLabel(AddrSymbol
);
1920 unsigned PtrSize
= MAI
->getCodePointerSize();
1921 OutStreamer
->emitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1925 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1926 // split-stack is used.
1927 if (TM
.getTargetTriple().isOSBinFormatELF() && MMI
->hasSplitStack()) {
1928 OutStreamer
->SwitchSection(
1929 OutContext
.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS
, 0));
1930 if (MMI
->hasNosplitStack())
1931 OutStreamer
->SwitchSection(
1932 OutContext
.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS
, 0));
1935 // If we don't have any trampolines, then we don't require stack memory
1936 // to be executable. Some targets have a directive to declare this.
1937 Function
*InitTrampolineIntrinsic
= M
.getFunction("llvm.init.trampoline");
1938 if (!InitTrampolineIntrinsic
|| InitTrampolineIntrinsic
->use_empty())
1939 if (MCSection
*S
= MAI
->getNonexecutableStackSection(OutContext
))
1940 OutStreamer
->SwitchSection(S
);
1942 if (TM
.Options
.EmitAddrsig
) {
1943 // Emit address-significance attributes for all globals.
1944 OutStreamer
->emitAddrsig();
1945 for (const GlobalValue
&GV
: M
.global_values()) {
1946 if (!GV
.use_empty() && !GV
.isTransitiveUsedByMetadataOnly() &&
1947 !GV
.isThreadLocal() && !GV
.hasDLLImportStorageClass() &&
1948 !GV
.getName().startswith("llvm.") && !GV
.hasAtLeastLocalUnnamedAddr())
1949 OutStreamer
->emitAddrsigSym(getSymbol(&GV
));
1953 // Emit symbol partition specifications (ELF only).
1954 if (TM
.getTargetTriple().isOSBinFormatELF()) {
1955 unsigned UniqueID
= 0;
1956 for (const GlobalValue
&GV
: M
.global_values()) {
1957 if (!GV
.hasPartition() || GV
.isDeclarationForLinker() ||
1958 GV
.getVisibility() != GlobalValue::DefaultVisibility
)
1961 OutStreamer
->SwitchSection(
1962 OutContext
.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART
, 0, 0,
1963 "", false, ++UniqueID
, nullptr));
1964 OutStreamer
->emitBytes(GV
.getPartition());
1965 OutStreamer
->emitZeros(1);
1966 OutStreamer
->emitValue(
1967 MCSymbolRefExpr::create(getSymbol(&GV
), OutContext
),
1968 MAI
->getCodePointerSize());
1972 // Allow the target to emit any magic that it wants at the end of the file,
1973 // after everything else has gone out.
1974 emitEndOfAsmFile(M
);
1978 OutStreamer
->Finish();
1979 OutStreamer
->reset();
1986 MCSymbol
*AsmPrinter::getMBBExceptionSym(const MachineBasicBlock
&MBB
) {
1987 auto Res
= MBBSectionExceptionSyms
.try_emplace(MBB
.getSectionIDNum());
1989 Res
.first
->second
= createTempSymbol("exception");
1990 return Res
.first
->second
;
1993 void AsmPrinter::SetupMachineFunction(MachineFunction
&MF
) {
1995 const Function
&F
= MF
.getFunction();
1997 // Get the function symbol.
1998 if (!MAI
->needsFunctionDescriptors()) {
1999 CurrentFnSym
= getSymbol(&MF
.getFunction());
2001 assert(TM
.getTargetTriple().isOSAIX() &&
2002 "Only AIX uses the function descriptor hooks.");
2003 // AIX is unique here in that the name of the symbol emitted for the
2004 // function body does not have the same name as the source function's
2006 assert(CurrentFnDescSym
&& "The function descriptor symbol needs to be"
2007 " initalized first.");
2009 // Get the function entry point symbol.
2010 CurrentFnSym
= getObjFileLowering().getFunctionEntryPointSymbol(&F
, TM
);
2013 CurrentFnSymForSize
= CurrentFnSym
;
2014 CurrentFnBegin
= nullptr;
2015 CurrentSectionBeginSym
= nullptr;
2016 MBBSectionRanges
.clear();
2017 MBBSectionExceptionSyms
.clear();
2018 bool NeedsLocalForSize
= MAI
->needsLocalForSize();
2019 if (F
.hasFnAttribute("patchable-function-entry") ||
2020 F
.hasFnAttribute("function-instrument") ||
2021 F
.hasFnAttribute("xray-instruction-threshold") ||
2022 needFuncLabelsForEHOrDebugInfo(MF
) || NeedsLocalForSize
||
2023 MF
.getTarget().Options
.EmitStackSizeSection
|| MF
.hasBBLabels()) {
2024 CurrentFnBegin
= createTempSymbol("func_begin");
2025 if (NeedsLocalForSize
)
2026 CurrentFnSymForSize
= CurrentFnBegin
;
2029 ORE
= &getAnalysis
<MachineOptimizationRemarkEmitterPass
>().getORE();
2034 // Keep track the alignment, constpool entries per Section.
2038 SmallVector
<unsigned, 4> CPEs
;
2040 SectionCPs(MCSection
*s
, Align a
) : S(s
), Alignment(a
) {}
2043 } // end anonymous namespace
2045 /// EmitConstantPool - Print to the current output stream assembly
2046 /// representations of the constants in the constant pool MCP. This is
2047 /// used to print out constants which have been "spilled to memory" by
2048 /// the code generator.
2049 void AsmPrinter::emitConstantPool() {
2050 const MachineConstantPool
*MCP
= MF
->getConstantPool();
2051 const std::vector
<MachineConstantPoolEntry
> &CP
= MCP
->getConstants();
2052 if (CP
.empty()) return;
2054 // Calculate sections for constant pool entries. We collect entries to go into
2055 // the same section together to reduce amount of section switch statements.
2056 SmallVector
<SectionCPs
, 4> CPSections
;
2057 for (unsigned i
= 0, e
= CP
.size(); i
!= e
; ++i
) {
2058 const MachineConstantPoolEntry
&CPE
= CP
[i
];
2059 Align Alignment
= CPE
.getAlign();
2061 SectionKind Kind
= CPE
.getSectionKind(&getDataLayout());
2063 const Constant
*C
= nullptr;
2064 if (!CPE
.isMachineConstantPoolEntry())
2065 C
= CPE
.Val
.ConstVal
;
2067 MCSection
*S
= getObjFileLowering().getSectionForConstant(
2068 getDataLayout(), Kind
, C
, Alignment
);
2070 // The number of sections are small, just do a linear search from the
2071 // last section to the first.
2073 unsigned SecIdx
= CPSections
.size();
2074 while (SecIdx
!= 0) {
2075 if (CPSections
[--SecIdx
].S
== S
) {
2081 SecIdx
= CPSections
.size();
2082 CPSections
.push_back(SectionCPs(S
, Alignment
));
2085 if (Alignment
> CPSections
[SecIdx
].Alignment
)
2086 CPSections
[SecIdx
].Alignment
= Alignment
;
2087 CPSections
[SecIdx
].CPEs
.push_back(i
);
2090 // Now print stuff into the calculated sections.
2091 const MCSection
*CurSection
= nullptr;
2092 unsigned Offset
= 0;
2093 for (unsigned i
= 0, e
= CPSections
.size(); i
!= e
; ++i
) {
2094 for (unsigned j
= 0, ee
= CPSections
[i
].CPEs
.size(); j
!= ee
; ++j
) {
2095 unsigned CPI
= CPSections
[i
].CPEs
[j
];
2096 MCSymbol
*Sym
= GetCPISymbol(CPI
);
2097 if (!Sym
->isUndefined())
2100 if (CurSection
!= CPSections
[i
].S
) {
2101 OutStreamer
->SwitchSection(CPSections
[i
].S
);
2102 emitAlignment(Align(CPSections
[i
].Alignment
));
2103 CurSection
= CPSections
[i
].S
;
2107 MachineConstantPoolEntry CPE
= CP
[CPI
];
2109 // Emit inter-object padding for alignment.
2110 unsigned NewOffset
= alignTo(Offset
, CPE
.getAlign());
2111 OutStreamer
->emitZeros(NewOffset
- Offset
);
2113 Offset
= NewOffset
+ CPE
.getSizeInBytes(getDataLayout());
2115 OutStreamer
->emitLabel(Sym
);
2116 if (CPE
.isMachineConstantPoolEntry())
2117 emitMachineConstantPoolValue(CPE
.Val
.MachineCPVal
);
2119 emitGlobalConstant(getDataLayout(), CPE
.Val
.ConstVal
);
2124 // Print assembly representations of the jump tables used by the current
2126 void AsmPrinter::emitJumpTableInfo() {
2127 const DataLayout
&DL
= MF
->getDataLayout();
2128 const MachineJumpTableInfo
*MJTI
= MF
->getJumpTableInfo();
2130 if (MJTI
->getEntryKind() == MachineJumpTableInfo::EK_Inline
) return;
2131 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
2132 if (JT
.empty()) return;
2134 // Pick the directive to use to print the jump table entries, and switch to
2135 // the appropriate section.
2136 const Function
&F
= MF
->getFunction();
2137 const TargetLoweringObjectFile
&TLOF
= getObjFileLowering();
2138 bool JTInDiffSection
= !TLOF
.shouldPutJumpTableInFunctionSection(
2139 MJTI
->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32
,
2141 if (JTInDiffSection
) {
2142 // Drop it in the readonly section.
2143 MCSection
*ReadOnlySection
= TLOF
.getSectionForJumpTable(F
, TM
);
2144 OutStreamer
->SwitchSection(ReadOnlySection
);
2147 emitAlignment(Align(MJTI
->getEntryAlignment(DL
)));
2149 // Jump tables in code sections are marked with a data_region directive
2150 // where that's supported.
2151 if (!JTInDiffSection
)
2152 OutStreamer
->emitDataRegion(MCDR_DataRegionJT32
);
2154 for (unsigned JTI
= 0, e
= JT
.size(); JTI
!= e
; ++JTI
) {
2155 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[JTI
].MBBs
;
2157 // If this jump table was deleted, ignore it.
2158 if (JTBBs
.empty()) continue;
2160 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2161 /// emit a .set directive for each unique entry.
2162 if (MJTI
->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32
&&
2163 MAI
->doesSetDirectiveSuppressReloc()) {
2164 SmallPtrSet
<const MachineBasicBlock
*, 16> EmittedSets
;
2165 const TargetLowering
*TLI
= MF
->getSubtarget().getTargetLowering();
2166 const MCExpr
*Base
= TLI
->getPICJumpTableRelocBaseExpr(MF
,JTI
,OutContext
);
2167 for (const MachineBasicBlock
*MBB
: JTBBs
) {
2168 if (!EmittedSets
.insert(MBB
).second
)
2171 // .set LJTSet, LBB32-base
2173 MCSymbolRefExpr::create(MBB
->getSymbol(), OutContext
);
2174 OutStreamer
->emitAssignment(GetJTSetSymbol(JTI
, MBB
->getNumber()),
2175 MCBinaryExpr::createSub(LHS
, Base
,
2180 // On some targets (e.g. Darwin) we want to emit two consecutive labels
2181 // before each jump table. The first label is never referenced, but tells
2182 // the assembler and linker the extents of the jump table object. The
2183 // second label is actually referenced by the code.
2184 if (JTInDiffSection
&& DL
.hasLinkerPrivateGlobalPrefix())
2185 // FIXME: This doesn't have to have any specific name, just any randomly
2186 // named and numbered local label started with 'l' would work. Simplify
2188 OutStreamer
->emitLabel(GetJTISymbol(JTI
, true));
2190 MCSymbol
* JTISymbol
= GetJTISymbol(JTI
);
2191 OutStreamer
->emitLabel(JTISymbol
);
2193 for (const MachineBasicBlock
*MBB
: JTBBs
)
2194 emitJumpTableEntry(MJTI
, MBB
, JTI
);
2196 if (!JTInDiffSection
)
2197 OutStreamer
->emitDataRegion(MCDR_DataRegionEnd
);
2200 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2202 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
2203 const MachineBasicBlock
*MBB
,
2204 unsigned UID
) const {
2205 assert(MBB
&& MBB
->getNumber() >= 0 && "Invalid basic block");
2206 const MCExpr
*Value
= nullptr;
2207 switch (MJTI
->getEntryKind()) {
2208 case MachineJumpTableInfo::EK_Inline
:
2209 llvm_unreachable("Cannot emit EK_Inline jump table entry");
2210 case MachineJumpTableInfo::EK_Custom32
:
2211 Value
= MF
->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
2212 MJTI
, MBB
, UID
, OutContext
);
2214 case MachineJumpTableInfo::EK_BlockAddress
:
2215 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2217 Value
= MCSymbolRefExpr::create(MBB
->getSymbol(), OutContext
);
2219 case MachineJumpTableInfo::EK_GPRel32BlockAddress
: {
2220 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2221 // with a relocation as gp-relative, e.g.:
2223 MCSymbol
*MBBSym
= MBB
->getSymbol();
2224 OutStreamer
->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym
, OutContext
));
2228 case MachineJumpTableInfo::EK_GPRel64BlockAddress
: {
2229 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2230 // with a relocation as gp-relative, e.g.:
2232 MCSymbol
*MBBSym
= MBB
->getSymbol();
2233 OutStreamer
->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym
, OutContext
));
2237 case MachineJumpTableInfo::EK_LabelDifference32
: {
2238 // Each entry is the address of the block minus the address of the jump
2239 // table. This is used for PIC jump tables where gprel32 is not supported.
2241 // .word LBB123 - LJTI1_2
2242 // If the .set directive avoids relocations, this is emitted as:
2243 // .set L4_5_set_123, LBB123 - LJTI1_2
2244 // .word L4_5_set_123
2245 if (MAI
->doesSetDirectiveSuppressReloc()) {
2246 Value
= MCSymbolRefExpr::create(GetJTSetSymbol(UID
, MBB
->getNumber()),
2250 Value
= MCSymbolRefExpr::create(MBB
->getSymbol(), OutContext
);
2251 const TargetLowering
*TLI
= MF
->getSubtarget().getTargetLowering();
2252 const MCExpr
*Base
= TLI
->getPICJumpTableRelocBaseExpr(MF
, UID
, OutContext
);
2253 Value
= MCBinaryExpr::createSub(Value
, Base
, OutContext
);
2258 assert(Value
&& "Unknown entry kind!");
2260 unsigned EntrySize
= MJTI
->getEntrySize(getDataLayout());
2261 OutStreamer
->emitValue(Value
, EntrySize
);
2264 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2265 /// special global used by LLVM. If so, emit it and return true, otherwise
2266 /// do nothing and return false.
2267 bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable
*GV
) {
2268 if (GV
->getName() == "llvm.used") {
2269 if (MAI
->hasNoDeadStrip()) // No need to emit this at all.
2270 emitLLVMUsedList(cast
<ConstantArray
>(GV
->getInitializer()));
2274 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2275 if (GV
->getSection() == "llvm.metadata" ||
2276 GV
->hasAvailableExternallyLinkage())
2279 if (!GV
->hasAppendingLinkage()) return false;
2281 assert(GV
->hasInitializer() && "Not a special LLVM global!");
2283 if (GV
->getName() == "llvm.global_ctors") {
2284 emitXXStructorList(GV
->getParent()->getDataLayout(), GV
->getInitializer(),
2290 if (GV
->getName() == "llvm.global_dtors") {
2291 emitXXStructorList(GV
->getParent()->getDataLayout(), GV
->getInitializer(),
2292 /* isCtor */ false);
2297 report_fatal_error("unknown special variable");
2300 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2301 /// global in the specified llvm.used list.
2302 void AsmPrinter::emitLLVMUsedList(const ConstantArray
*InitList
) {
2303 // Should be an array of 'i8*'.
2304 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
2305 const GlobalValue
*GV
=
2306 dyn_cast
<GlobalValue
>(InitList
->getOperand(i
)->stripPointerCasts());
2308 OutStreamer
->emitSymbolAttribute(getSymbol(GV
), MCSA_NoDeadStrip
);
2312 void AsmPrinter::preprocessXXStructorList(const DataLayout
&DL
,
2313 const Constant
*List
,
2314 SmallVector
<Structor
, 8> &Structors
) {
2315 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2316 // the init priority.
2317 if (!isa
<ConstantArray
>(List
))
2320 // Gather the structors in a form that's convenient for sorting by priority.
2321 for (Value
*O
: cast
<ConstantArray
>(List
)->operands()) {
2322 auto *CS
= cast
<ConstantStruct
>(O
);
2323 if (CS
->getOperand(1)->isNullValue())
2324 break; // Found a null terminator, skip the rest.
2325 ConstantInt
*Priority
= dyn_cast
<ConstantInt
>(CS
->getOperand(0));
2327 continue; // Malformed.
2328 Structors
.push_back(Structor());
2329 Structor
&S
= Structors
.back();
2330 S
.Priority
= Priority
->getLimitedValue(65535);
2331 S
.Func
= CS
->getOperand(1);
2332 if (!CS
->getOperand(2)->isNullValue()) {
2333 if (TM
.getTargetTriple().isOSAIX())
2334 llvm::report_fatal_error(
2335 "associated data of XXStructor list is not yet supported on AIX");
2337 dyn_cast
<GlobalValue
>(CS
->getOperand(2)->stripPointerCasts());
2341 // Emit the function pointers in the target-specific order
2342 llvm::stable_sort(Structors
, [](const Structor
&L
, const Structor
&R
) {
2343 return L
.Priority
< R
.Priority
;
2347 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2349 void AsmPrinter::emitXXStructorList(const DataLayout
&DL
, const Constant
*List
,
2351 SmallVector
<Structor
, 8> Structors
;
2352 preprocessXXStructorList(DL
, List
, Structors
);
2353 if (Structors
.empty())
2356 // Emit the structors in reverse order if we are using the .ctor/.dtor
2357 // initialization scheme.
2358 if (!TM
.Options
.UseInitArray
)
2359 std::reverse(Structors
.begin(), Structors
.end());
2361 const Align Align
= DL
.getPointerPrefAlignment();
2362 for (Structor
&S
: Structors
) {
2363 const TargetLoweringObjectFile
&Obj
= getObjFileLowering();
2364 const MCSymbol
*KeySym
= nullptr;
2365 if (GlobalValue
*GV
= S
.ComdatKey
) {
2366 if (GV
->isDeclarationForLinker())
2367 // If the associated variable is not defined in this module
2368 // (it might be available_externally, or have been an
2369 // available_externally definition that was dropped by the
2370 // EliminateAvailableExternally pass), some other TU
2371 // will provide its dynamic initializer.
2374 KeySym
= getSymbol(GV
);
2377 MCSection
*OutputSection
=
2378 (IsCtor
? Obj
.getStaticCtorSection(S
.Priority
, KeySym
)
2379 : Obj
.getStaticDtorSection(S
.Priority
, KeySym
));
2380 OutStreamer
->SwitchSection(OutputSection
);
2381 if (OutStreamer
->getCurrentSection() != OutStreamer
->getPreviousSection())
2382 emitAlignment(Align
);
2383 emitXXStructor(DL
, S
.Func
);
2387 void AsmPrinter::emitModuleIdents(Module
&M
) {
2388 if (!MAI
->hasIdentDirective())
2391 if (const NamedMDNode
*NMD
= M
.getNamedMetadata("llvm.ident")) {
2392 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
2393 const MDNode
*N
= NMD
->getOperand(i
);
2394 assert(N
->getNumOperands() == 1 &&
2395 "llvm.ident metadata entry can have only one operand");
2396 const MDString
*S
= cast
<MDString
>(N
->getOperand(0));
2397 OutStreamer
->emitIdent(S
->getString());
2402 void AsmPrinter::emitModuleCommandLines(Module
&M
) {
2403 MCSection
*CommandLine
= getObjFileLowering().getSectionForCommandLines();
2407 const NamedMDNode
*NMD
= M
.getNamedMetadata("llvm.commandline");
2408 if (!NMD
|| !NMD
->getNumOperands())
2411 OutStreamer
->PushSection();
2412 OutStreamer
->SwitchSection(CommandLine
);
2413 OutStreamer
->emitZeros(1);
2414 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
2415 const MDNode
*N
= NMD
->getOperand(i
);
2416 assert(N
->getNumOperands() == 1 &&
2417 "llvm.commandline metadata entry can have only one operand");
2418 const MDString
*S
= cast
<MDString
>(N
->getOperand(0));
2419 OutStreamer
->emitBytes(S
->getString());
2420 OutStreamer
->emitZeros(1);
2422 OutStreamer
->PopSection();
2425 //===--------------------------------------------------------------------===//
2426 // Emission and print routines
2429 /// Emit a byte directive and value.
2431 void AsmPrinter::emitInt8(int Value
) const { OutStreamer
->emitInt8(Value
); }
2433 /// Emit a short directive and value.
2434 void AsmPrinter::emitInt16(int Value
) const { OutStreamer
->emitInt16(Value
); }
2436 /// Emit a long directive and value.
2437 void AsmPrinter::emitInt32(int Value
) const { OutStreamer
->emitInt32(Value
); }
2439 /// Emit a long long directive and value.
2440 void AsmPrinter::emitInt64(uint64_t Value
) const {
2441 OutStreamer
->emitInt64(Value
);
2444 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2445 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2446 /// .set if it avoids relocations.
2447 void AsmPrinter::emitLabelDifference(const MCSymbol
*Hi
, const MCSymbol
*Lo
,
2448 unsigned Size
) const {
2449 OutStreamer
->emitAbsoluteSymbolDiff(Hi
, Lo
, Size
);
2452 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2453 /// where the size in bytes of the directive is specified by Size and Label
2454 /// specifies the label. This implicitly uses .set if it is available.
2455 void AsmPrinter::emitLabelPlusOffset(const MCSymbol
*Label
, uint64_t Offset
,
2457 bool IsSectionRelative
) const {
2458 if (MAI
->needsDwarfSectionOffsetDirective() && IsSectionRelative
) {
2459 OutStreamer
->EmitCOFFSecRel32(Label
, Offset
);
2461 OutStreamer
->emitZeros(Size
- 4);
2465 // Emit Label+Offset (or just Label if Offset is zero)
2466 const MCExpr
*Expr
= MCSymbolRefExpr::create(Label
, OutContext
);
2468 Expr
= MCBinaryExpr::createAdd(
2469 Expr
, MCConstantExpr::create(Offset
, OutContext
), OutContext
);
2471 OutStreamer
->emitValue(Expr
, Size
);
2474 //===----------------------------------------------------------------------===//
2476 // EmitAlignment - Emit an alignment directive to the specified power of
2477 // two boundary. If a global value is specified, and if that global has
2478 // an explicit alignment requested, it will override the alignment request
2479 // if required for correctness.
2480 void AsmPrinter::emitAlignment(Align Alignment
, const GlobalObject
*GV
,
2481 unsigned MaxBytesToEmit
) const {
2483 Alignment
= getGVAlignment(GV
, GV
->getParent()->getDataLayout(), Alignment
);
2485 if (Alignment
== Align(1))
2486 return; // 1-byte aligned: no need to emit alignment.
2488 if (getCurrentSection()->getKind().isText()) {
2489 const MCSubtargetInfo
*STI
= nullptr;
2491 STI
= &getSubtargetInfo();
2493 STI
= TM
.getMCSubtargetInfo();
2494 OutStreamer
->emitCodeAlignment(Alignment
.value(), STI
, MaxBytesToEmit
);
2496 OutStreamer
->emitValueToAlignment(Alignment
.value(), 0, 1, MaxBytesToEmit
);
2499 //===----------------------------------------------------------------------===//
2500 // Constant emission.
2501 //===----------------------------------------------------------------------===//
2503 const MCExpr
*AsmPrinter::lowerConstant(const Constant
*CV
) {
2504 MCContext
&Ctx
= OutContext
;
2506 if (CV
->isNullValue() || isa
<UndefValue
>(CV
))
2507 return MCConstantExpr::create(0, Ctx
);
2509 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
))
2510 return MCConstantExpr::create(CI
->getZExtValue(), Ctx
);
2512 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CV
))
2513 return MCSymbolRefExpr::create(getSymbol(GV
), Ctx
);
2515 if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(CV
))
2516 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA
), Ctx
);
2518 if (const auto *Equiv
= dyn_cast
<DSOLocalEquivalent
>(CV
))
2519 return getObjFileLowering().lowerDSOLocalEquivalent(Equiv
, TM
);
2521 if (const NoCFIValue
*NC
= dyn_cast
<NoCFIValue
>(CV
))
2522 return MCSymbolRefExpr::create(getSymbol(NC
->getGlobalValue()), Ctx
);
2524 const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
);
2526 llvm_unreachable("Unknown constant value to lower!");
2529 switch (CE
->getOpcode()) {
2530 case Instruction::AddrSpaceCast
: {
2531 const Constant
*Op
= CE
->getOperand(0);
2532 unsigned DstAS
= CE
->getType()->getPointerAddressSpace();
2533 unsigned SrcAS
= Op
->getType()->getPointerAddressSpace();
2534 if (TM
.isNoopAddrSpaceCast(SrcAS
, DstAS
))
2535 return lowerConstant(Op
);
2537 // Fallthrough to error.
2541 // If the code isn't optimized, there may be outstanding folding
2542 // opportunities. Attempt to fold the expression using DataLayout as a
2543 // last resort before giving up.
2544 Constant
*C
= ConstantFoldConstant(CE
, getDataLayout());
2546 return lowerConstant(C
);
2548 // Otherwise report the problem to the user.
2550 raw_string_ostream
OS(S
);
2551 OS
<< "Unsupported expression in static initializer: ";
2552 CE
->printAsOperand(OS
, /*PrintType=*/false,
2553 !MF
? nullptr : MF
->getFunction().getParent());
2554 report_fatal_error(Twine(OS
.str()));
2556 case Instruction::GetElementPtr
: {
2557 // Generate a symbolic expression for the byte address
2558 APInt
OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE
->getType()), 0);
2559 cast
<GEPOperator
>(CE
)->accumulateConstantOffset(getDataLayout(), OffsetAI
);
2561 const MCExpr
*Base
= lowerConstant(CE
->getOperand(0));
2565 int64_t Offset
= OffsetAI
.getSExtValue();
2566 return MCBinaryExpr::createAdd(Base
, MCConstantExpr::create(Offset
, Ctx
),
2570 case Instruction::Trunc
:
2571 // We emit the value and depend on the assembler to truncate the generated
2572 // expression properly. This is important for differences between
2573 // blockaddress labels. Since the two labels are in the same function, it
2574 // is reasonable to treat their delta as a 32-bit value.
2576 case Instruction::BitCast
:
2577 return lowerConstant(CE
->getOperand(0));
2579 case Instruction::IntToPtr
: {
2580 const DataLayout
&DL
= getDataLayout();
2582 // Handle casts to pointers by changing them into casts to the appropriate
2583 // integer type. This promotes constant folding and simplifies this code.
2584 Constant
*Op
= CE
->getOperand(0);
2585 Op
= ConstantExpr::getIntegerCast(Op
, DL
.getIntPtrType(CV
->getType()),
2587 return lowerConstant(Op
);
2590 case Instruction::PtrToInt
: {
2591 const DataLayout
&DL
= getDataLayout();
2593 // Support only foldable casts to/from pointers that can be eliminated by
2594 // changing the pointer to the appropriately sized integer type.
2595 Constant
*Op
= CE
->getOperand(0);
2596 Type
*Ty
= CE
->getType();
2598 const MCExpr
*OpExpr
= lowerConstant(Op
);
2600 // We can emit the pointer value into this slot if the slot is an
2601 // integer slot equal to the size of the pointer.
2603 // If the pointer is larger than the resultant integer, then
2604 // as with Trunc just depend on the assembler to truncate it.
2605 if (DL
.getTypeAllocSize(Ty
).getFixedSize() <=
2606 DL
.getTypeAllocSize(Op
->getType()).getFixedSize())
2609 // Otherwise the pointer is smaller than the resultant integer, mask off
2610 // the high bits so we are sure to get a proper truncation if the input is
2612 unsigned InBits
= DL
.getTypeAllocSizeInBits(Op
->getType());
2613 const MCExpr
*MaskExpr
= MCConstantExpr::create(~0ULL >> (64-InBits
), Ctx
);
2614 return MCBinaryExpr::createAnd(OpExpr
, MaskExpr
, Ctx
);
2617 case Instruction::Sub
: {
2620 DSOLocalEquivalent
*DSOEquiv
;
2621 if (IsConstantOffsetFromGlobal(CE
->getOperand(0), LHSGV
, LHSOffset
,
2622 getDataLayout(), &DSOEquiv
)) {
2625 if (IsConstantOffsetFromGlobal(CE
->getOperand(1), RHSGV
, RHSOffset
,
2627 const MCExpr
*RelocExpr
=
2628 getObjFileLowering().lowerRelativeReference(LHSGV
, RHSGV
, TM
);
2630 const MCExpr
*LHSExpr
=
2631 MCSymbolRefExpr::create(getSymbol(LHSGV
), Ctx
);
2633 getObjFileLowering().supportDSOLocalEquivalentLowering())
2635 getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv
, TM
);
2636 RelocExpr
= MCBinaryExpr::createSub(
2637 LHSExpr
, MCSymbolRefExpr::create(getSymbol(RHSGV
), Ctx
), Ctx
);
2639 int64_t Addend
= (LHSOffset
- RHSOffset
).getSExtValue();
2641 RelocExpr
= MCBinaryExpr::createAdd(
2642 RelocExpr
, MCConstantExpr::create(Addend
, Ctx
), Ctx
);
2650 // The MC library also has a right-shift operator, but it isn't consistently
2651 // signed or unsigned between different targets.
2652 case Instruction::Add
:
2653 case Instruction::Mul
:
2654 case Instruction::SDiv
:
2655 case Instruction::SRem
:
2656 case Instruction::Shl
:
2657 case Instruction::And
:
2658 case Instruction::Or
:
2659 case Instruction::Xor
: {
2660 const MCExpr
*LHS
= lowerConstant(CE
->getOperand(0));
2661 const MCExpr
*RHS
= lowerConstant(CE
->getOperand(1));
2662 switch (CE
->getOpcode()) {
2663 default: llvm_unreachable("Unknown binary operator constant cast expr");
2664 case Instruction::Add
: return MCBinaryExpr::createAdd(LHS
, RHS
, Ctx
);
2665 case Instruction::Sub
: return MCBinaryExpr::createSub(LHS
, RHS
, Ctx
);
2666 case Instruction::Mul
: return MCBinaryExpr::createMul(LHS
, RHS
, Ctx
);
2667 case Instruction::SDiv
: return MCBinaryExpr::createDiv(LHS
, RHS
, Ctx
);
2668 case Instruction::SRem
: return MCBinaryExpr::createMod(LHS
, RHS
, Ctx
);
2669 case Instruction::Shl
: return MCBinaryExpr::createShl(LHS
, RHS
, Ctx
);
2670 case Instruction::And
: return MCBinaryExpr::createAnd(LHS
, RHS
, Ctx
);
2671 case Instruction::Or
: return MCBinaryExpr::createOr (LHS
, RHS
, Ctx
);
2672 case Instruction::Xor
: return MCBinaryExpr::createXor(LHS
, RHS
, Ctx
);
2678 static void emitGlobalConstantImpl(const DataLayout
&DL
, const Constant
*C
,
2680 const Constant
*BaseCV
= nullptr,
2681 uint64_t Offset
= 0);
2683 static void emitGlobalConstantFP(const ConstantFP
*CFP
, AsmPrinter
&AP
);
2684 static void emitGlobalConstantFP(APFloat APF
, Type
*ET
, AsmPrinter
&AP
);
2686 /// isRepeatedByteSequence - Determine whether the given value is
2687 /// composed of a repeated sequence of identical bytes and return the
2688 /// byte value. If it is not a repeated sequence, return -1.
2689 static int isRepeatedByteSequence(const ConstantDataSequential
*V
) {
2690 StringRef Data
= V
->getRawDataValues();
2691 assert(!Data
.empty() && "Empty aggregates should be CAZ node");
2693 for (unsigned i
= 1, e
= Data
.size(); i
!= e
; ++i
)
2694 if (Data
[i
] != C
) return -1;
2695 return static_cast<uint8_t>(C
); // Ensure 255 is not returned as -1.
2698 /// isRepeatedByteSequence - Determine whether the given value is
2699 /// composed of a repeated sequence of identical bytes and return the
2700 /// byte value. If it is not a repeated sequence, return -1.
2701 static int isRepeatedByteSequence(const Value
*V
, const DataLayout
&DL
) {
2702 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
2703 uint64_t Size
= DL
.getTypeAllocSizeInBits(V
->getType());
2704 assert(Size
% 8 == 0);
2706 // Extend the element to take zero padding into account.
2707 APInt Value
= CI
->getValue().zextOrSelf(Size
);
2708 if (!Value
.isSplat(8))
2711 return Value
.zextOrTrunc(8).getZExtValue();
2713 if (const ConstantArray
*CA
= dyn_cast
<ConstantArray
>(V
)) {
2714 // Make sure all array elements are sequences of the same repeated
2716 assert(CA
->getNumOperands() != 0 && "Should be a CAZ");
2717 Constant
*Op0
= CA
->getOperand(0);
2718 int Byte
= isRepeatedByteSequence(Op0
, DL
);
2722 // All array elements must be equal.
2723 for (unsigned i
= 1, e
= CA
->getNumOperands(); i
!= e
; ++i
)
2724 if (CA
->getOperand(i
) != Op0
)
2729 if (const ConstantDataSequential
*CDS
= dyn_cast
<ConstantDataSequential
>(V
))
2730 return isRepeatedByteSequence(CDS
);
2735 static void emitGlobalConstantDataSequential(const DataLayout
&DL
,
2736 const ConstantDataSequential
*CDS
,
2738 // See if we can aggregate this into a .fill, if so, emit it as such.
2739 int Value
= isRepeatedByteSequence(CDS
, DL
);
2741 uint64_t Bytes
= DL
.getTypeAllocSize(CDS
->getType());
2742 // Don't emit a 1-byte object as a .fill.
2744 return AP
.OutStreamer
->emitFill(Bytes
, Value
);
2747 // If this can be emitted with .ascii/.asciz, emit it as such.
2748 if (CDS
->isString())
2749 return AP
.OutStreamer
->emitBytes(CDS
->getAsString());
2751 // Otherwise, emit the values in successive locations.
2752 unsigned ElementByteSize
= CDS
->getElementByteSize();
2753 if (isa
<IntegerType
>(CDS
->getElementType())) {
2754 for (unsigned i
= 0, e
= CDS
->getNumElements(); i
!= e
; ++i
) {
2756 AP
.OutStreamer
->GetCommentOS() << format("0x%" PRIx64
"\n",
2757 CDS
->getElementAsInteger(i
));
2758 AP
.OutStreamer
->emitIntValue(CDS
->getElementAsInteger(i
),
2762 Type
*ET
= CDS
->getElementType();
2763 for (unsigned I
= 0, E
= CDS
->getNumElements(); I
!= E
; ++I
)
2764 emitGlobalConstantFP(CDS
->getElementAsAPFloat(I
), ET
, AP
);
2767 unsigned Size
= DL
.getTypeAllocSize(CDS
->getType());
2768 unsigned EmittedSize
=
2769 DL
.getTypeAllocSize(CDS
->getElementType()) * CDS
->getNumElements();
2770 assert(EmittedSize
<= Size
&& "Size cannot be less than EmittedSize!");
2771 if (unsigned Padding
= Size
- EmittedSize
)
2772 AP
.OutStreamer
->emitZeros(Padding
);
2775 static void emitGlobalConstantArray(const DataLayout
&DL
,
2776 const ConstantArray
*CA
, AsmPrinter
&AP
,
2777 const Constant
*BaseCV
, uint64_t Offset
) {
2778 // See if we can aggregate some values. Make sure it can be
2779 // represented as a series of bytes of the constant value.
2780 int Value
= isRepeatedByteSequence(CA
, DL
);
2783 uint64_t Bytes
= DL
.getTypeAllocSize(CA
->getType());
2784 AP
.OutStreamer
->emitFill(Bytes
, Value
);
2787 for (unsigned i
= 0, e
= CA
->getNumOperands(); i
!= e
; ++i
) {
2788 emitGlobalConstantImpl(DL
, CA
->getOperand(i
), AP
, BaseCV
, Offset
);
2789 Offset
+= DL
.getTypeAllocSize(CA
->getOperand(i
)->getType());
2794 static void emitGlobalConstantVector(const DataLayout
&DL
,
2795 const ConstantVector
*CV
, AsmPrinter
&AP
) {
2796 for (unsigned i
= 0, e
= CV
->getType()->getNumElements(); i
!= e
; ++i
)
2797 emitGlobalConstantImpl(DL
, CV
->getOperand(i
), AP
);
2799 unsigned Size
= DL
.getTypeAllocSize(CV
->getType());
2800 unsigned EmittedSize
= DL
.getTypeAllocSize(CV
->getType()->getElementType()) *
2801 CV
->getType()->getNumElements();
2802 if (unsigned Padding
= Size
- EmittedSize
)
2803 AP
.OutStreamer
->emitZeros(Padding
);
2806 static void emitGlobalConstantStruct(const DataLayout
&DL
,
2807 const ConstantStruct
*CS
, AsmPrinter
&AP
,
2808 const Constant
*BaseCV
, uint64_t Offset
) {
2809 // Print the fields in successive locations. Pad to align if needed!
2810 unsigned Size
= DL
.getTypeAllocSize(CS
->getType());
2811 const StructLayout
*Layout
= DL
.getStructLayout(CS
->getType());
2812 uint64_t SizeSoFar
= 0;
2813 for (unsigned i
= 0, e
= CS
->getNumOperands(); i
!= e
; ++i
) {
2814 const Constant
*Field
= CS
->getOperand(i
);
2816 // Print the actual field value.
2817 emitGlobalConstantImpl(DL
, Field
, AP
, BaseCV
, Offset
+ SizeSoFar
);
2819 // Check if padding is needed and insert one or more 0s.
2820 uint64_t FieldSize
= DL
.getTypeAllocSize(Field
->getType());
2821 uint64_t PadSize
= ((i
== e
-1 ? Size
: Layout
->getElementOffset(i
+1))
2822 - Layout
->getElementOffset(i
)) - FieldSize
;
2823 SizeSoFar
+= FieldSize
+ PadSize
;
2825 // Insert padding - this may include padding to increase the size of the
2826 // current field up to the ABI size (if the struct is not packed) as well
2827 // as padding to ensure that the next field starts at the right offset.
2828 AP
.OutStreamer
->emitZeros(PadSize
);
2830 assert(SizeSoFar
== Layout
->getSizeInBytes() &&
2831 "Layout of constant struct may be incorrect!");
2834 static void emitGlobalConstantFP(APFloat APF
, Type
*ET
, AsmPrinter
&AP
) {
2835 assert(ET
&& "Unknown float type");
2836 APInt API
= APF
.bitcastToAPInt();
2838 // First print a comment with what we think the original floating-point value
2839 // should have been.
2840 if (AP
.isVerbose()) {
2841 SmallString
<8> StrVal
;
2842 APF
.toString(StrVal
);
2843 ET
->print(AP
.OutStreamer
->GetCommentOS());
2844 AP
.OutStreamer
->GetCommentOS() << ' ' << StrVal
<< '\n';
2847 // Now iterate through the APInt chunks, emitting them in endian-correct
2848 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2850 unsigned NumBytes
= API
.getBitWidth() / 8;
2851 unsigned TrailingBytes
= NumBytes
% sizeof(uint64_t);
2852 const uint64_t *p
= API
.getRawData();
2854 // PPC's long double has odd notions of endianness compared to how LLVM
2855 // handles it: p[0] goes first for *big* endian on PPC.
2856 if (AP
.getDataLayout().isBigEndian() && !ET
->isPPC_FP128Ty()) {
2857 int Chunk
= API
.getNumWords() - 1;
2860 AP
.OutStreamer
->emitIntValueInHexWithPadding(p
[Chunk
--], TrailingBytes
);
2862 for (; Chunk
>= 0; --Chunk
)
2863 AP
.OutStreamer
->emitIntValueInHexWithPadding(p
[Chunk
], sizeof(uint64_t));
2866 for (Chunk
= 0; Chunk
< NumBytes
/ sizeof(uint64_t); ++Chunk
)
2867 AP
.OutStreamer
->emitIntValueInHexWithPadding(p
[Chunk
], sizeof(uint64_t));
2870 AP
.OutStreamer
->emitIntValueInHexWithPadding(p
[Chunk
], TrailingBytes
);
2873 // Emit the tail padding for the long double.
2874 const DataLayout
&DL
= AP
.getDataLayout();
2875 AP
.OutStreamer
->emitZeros(DL
.getTypeAllocSize(ET
) - DL
.getTypeStoreSize(ET
));
2878 static void emitGlobalConstantFP(const ConstantFP
*CFP
, AsmPrinter
&AP
) {
2879 emitGlobalConstantFP(CFP
->getValueAPF(), CFP
->getType(), AP
);
2882 static void emitGlobalConstantLargeInt(const ConstantInt
*CI
, AsmPrinter
&AP
) {
2883 const DataLayout
&DL
= AP
.getDataLayout();
2884 unsigned BitWidth
= CI
->getBitWidth();
2886 // Copy the value as we may massage the layout for constants whose bit width
2887 // is not a multiple of 64-bits.
2888 APInt
Realigned(CI
->getValue());
2889 uint64_t ExtraBits
= 0;
2890 unsigned ExtraBitsSize
= BitWidth
& 63;
2892 if (ExtraBitsSize
) {
2893 // The bit width of the data is not a multiple of 64-bits.
2894 // The extra bits are expected to be at the end of the chunk of the memory.
2896 // * Nothing to be done, just record the extra bits to emit.
2898 // * Record the extra bits to emit.
2899 // * Realign the raw data to emit the chunks of 64-bits.
2900 if (DL
.isBigEndian()) {
2901 // Basically the structure of the raw data is a chunk of 64-bits cells:
2902 // 0 1 BitWidth / 64
2903 // [chunk1][chunk2] ... [chunkN].
2904 // The most significant chunk is chunkN and it should be emitted first.
2905 // However, due to the alignment issue chunkN contains useless bits.
2906 // Realign the chunks so that they contain only useful information:
2907 // ExtraBits 0 1 (BitWidth / 64) - 1
2908 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2909 ExtraBitsSize
= alignTo(ExtraBitsSize
, 8);
2910 ExtraBits
= Realigned
.getRawData()[0] &
2911 (((uint64_t)-1) >> (64 - ExtraBitsSize
));
2912 Realigned
.lshrInPlace(ExtraBitsSize
);
2914 ExtraBits
= Realigned
.getRawData()[BitWidth
/ 64];
2917 // We don't expect assemblers to support integer data directives
2918 // for more than 64 bits, so we emit the data in at most 64-bit
2919 // quantities at a time.
2920 const uint64_t *RawData
= Realigned
.getRawData();
2921 for (unsigned i
= 0, e
= BitWidth
/ 64; i
!= e
; ++i
) {
2922 uint64_t Val
= DL
.isBigEndian() ? RawData
[e
- i
- 1] : RawData
[i
];
2923 AP
.OutStreamer
->emitIntValue(Val
, 8);
2926 if (ExtraBitsSize
) {
2927 // Emit the extra bits after the 64-bits chunks.
2929 // Emit a directive that fills the expected size.
2930 uint64_t Size
= AP
.getDataLayout().getTypeStoreSize(CI
->getType());
2931 Size
-= (BitWidth
/ 64) * 8;
2932 assert(Size
&& Size
* 8 >= ExtraBitsSize
&&
2933 (ExtraBits
& (((uint64_t)-1) >> (64 - ExtraBitsSize
)))
2934 == ExtraBits
&& "Directive too small for extra bits.");
2935 AP
.OutStreamer
->emitIntValue(ExtraBits
, Size
);
2939 /// Transform a not absolute MCExpr containing a reference to a GOT
2940 /// equivalent global, by a target specific GOT pc relative access to the
2942 static void handleIndirectSymViaGOTPCRel(AsmPrinter
&AP
, const MCExpr
**ME
,
2943 const Constant
*BaseCst
,
2945 // The global @foo below illustrates a global that uses a got equivalent.
2947 // @bar = global i32 42
2948 // @gotequiv = private unnamed_addr constant i32* @bar
2949 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2950 // i64 ptrtoint (i32* @foo to i64))
2953 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2954 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2957 // foo = cstexpr, where
2958 // cstexpr := <gotequiv> - "." + <cst>
2959 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2961 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2963 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2964 // gotpcrelcst := <offset from @foo base> + <cst>
2966 if (!(*ME
)->evaluateAsRelocatable(MV
, nullptr, nullptr) || MV
.isAbsolute())
2968 const MCSymbolRefExpr
*SymA
= MV
.getSymA();
2972 // Check that GOT equivalent symbol is cached.
2973 const MCSymbol
*GOTEquivSym
= &SymA
->getSymbol();
2974 if (!AP
.GlobalGOTEquivs
.count(GOTEquivSym
))
2977 const GlobalValue
*BaseGV
= dyn_cast_or_null
<GlobalValue
>(BaseCst
);
2981 // Check for a valid base symbol
2982 const MCSymbol
*BaseSym
= AP
.getSymbol(BaseGV
);
2983 const MCSymbolRefExpr
*SymB
= MV
.getSymB();
2985 if (!SymB
|| BaseSym
!= &SymB
->getSymbol())
2988 // Make sure to match:
2990 // gotpcrelcst := <offset from @foo base> + <cst>
2992 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2993 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2994 // if the target knows how to encode it.
2995 int64_t GOTPCRelCst
= Offset
+ MV
.getConstant();
2996 if (GOTPCRelCst
< 0)
2998 if (!AP
.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst
!= 0)
3001 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
3008 // .long gotequiv - "." + <cst>
3010 // is replaced by the target specific equivalent to:
3015 // .long bar@GOTPCREL+<gotpcrelcst>
3016 AsmPrinter::GOTEquivUsePair Result
= AP
.GlobalGOTEquivs
[GOTEquivSym
];
3017 const GlobalVariable
*GV
= Result
.first
;
3018 int NumUses
= (int)Result
.second
;
3019 const GlobalValue
*FinalGV
= dyn_cast
<GlobalValue
>(GV
->getOperand(0));
3020 const MCSymbol
*FinalSym
= AP
.getSymbol(FinalGV
);
3021 *ME
= AP
.getObjFileLowering().getIndirectSymViaGOTPCRel(
3022 FinalGV
, FinalSym
, MV
, Offset
, AP
.MMI
, *AP
.OutStreamer
);
3024 // Update GOT equivalent usage information
3027 AP
.GlobalGOTEquivs
[GOTEquivSym
] = std::make_pair(GV
, NumUses
);
3030 static void emitGlobalConstantImpl(const DataLayout
&DL
, const Constant
*CV
,
3031 AsmPrinter
&AP
, const Constant
*BaseCV
,
3033 uint64_t Size
= DL
.getTypeAllocSize(CV
->getType());
3035 // Globals with sub-elements such as combinations of arrays and structs
3036 // are handled recursively by emitGlobalConstantImpl. Keep track of the
3037 // constant symbol base and the current position with BaseCV and Offset.
3038 if (!BaseCV
&& CV
->hasOneUse())
3039 BaseCV
= dyn_cast
<Constant
>(CV
->user_back());
3041 if (isa
<ConstantAggregateZero
>(CV
) || isa
<UndefValue
>(CV
))
3042 return AP
.OutStreamer
->emitZeros(Size
);
3044 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
3045 const uint64_t StoreSize
= DL
.getTypeStoreSize(CV
->getType());
3047 if (StoreSize
<= 8) {
3049 AP
.OutStreamer
->GetCommentOS() << format("0x%" PRIx64
"\n",
3050 CI
->getZExtValue());
3051 AP
.OutStreamer
->emitIntValue(CI
->getZExtValue(), StoreSize
);
3053 emitGlobalConstantLargeInt(CI
, AP
);
3056 // Emit tail padding if needed
3057 if (Size
!= StoreSize
)
3058 AP
.OutStreamer
->emitZeros(Size
- StoreSize
);
3063 if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
))
3064 return emitGlobalConstantFP(CFP
, AP
);
3066 if (isa
<ConstantPointerNull
>(CV
)) {
3067 AP
.OutStreamer
->emitIntValue(0, Size
);
3071 if (const ConstantDataSequential
*CDS
= dyn_cast
<ConstantDataSequential
>(CV
))
3072 return emitGlobalConstantDataSequential(DL
, CDS
, AP
);
3074 if (const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(CV
))
3075 return emitGlobalConstantArray(DL
, CVA
, AP
, BaseCV
, Offset
);
3077 if (const ConstantStruct
*CVS
= dyn_cast
<ConstantStruct
>(CV
))
3078 return emitGlobalConstantStruct(DL
, CVS
, AP
, BaseCV
, Offset
);
3080 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
3081 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3083 if (CE
->getOpcode() == Instruction::BitCast
)
3084 return emitGlobalConstantImpl(DL
, CE
->getOperand(0), AP
);
3087 // If the constant expression's size is greater than 64-bits, then we have
3088 // to emit the value in chunks. Try to constant fold the value and emit it
3090 Constant
*New
= ConstantFoldConstant(CE
, DL
);
3092 return emitGlobalConstantImpl(DL
, New
, AP
);
3096 if (const ConstantVector
*V
= dyn_cast
<ConstantVector
>(CV
))
3097 return emitGlobalConstantVector(DL
, V
, AP
);
3099 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3100 // thread the streamer with EmitValue.
3101 const MCExpr
*ME
= AP
.lowerConstant(CV
);
3103 // Since lowerConstant already folded and got rid of all IR pointer and
3104 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3106 if (AP
.getObjFileLowering().supportIndirectSymViaGOTPCRel())
3107 handleIndirectSymViaGOTPCRel(AP
, &ME
, BaseCV
, Offset
);
3109 AP
.OutStreamer
->emitValue(ME
, Size
);
3112 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3113 void AsmPrinter::emitGlobalConstant(const DataLayout
&DL
, const Constant
*CV
) {
3114 uint64_t Size
= DL
.getTypeAllocSize(CV
->getType());
3116 emitGlobalConstantImpl(DL
, CV
, *this);
3117 else if (MAI
->hasSubsectionsViaSymbols()) {
3118 // If the global has zero size, emit a single byte so that two labels don't
3119 // look like they are at the same location.
3120 OutStreamer
->emitIntValue(0, 1);
3124 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue
*MCPV
) {
3125 // Target doesn't support this yet!
3126 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
3129 void AsmPrinter::printOffset(int64_t Offset
, raw_ostream
&OS
) const {
3131 OS
<< '+' << Offset
;
3132 else if (Offset
< 0)
3136 void AsmPrinter::emitNops(unsigned N
) {
3137 MCInst Nop
= MF
->getSubtarget().getInstrInfo()->getNop();
3139 EmitToStreamer(*OutStreamer
, Nop
);
3142 //===----------------------------------------------------------------------===//
3143 // Symbol Lowering Routines.
3144 //===----------------------------------------------------------------------===//
3146 MCSymbol
*AsmPrinter::createTempSymbol(const Twine
&Name
) const {
3147 return OutContext
.createTempSymbol(Name
, true);
3150 MCSymbol
*AsmPrinter::GetBlockAddressSymbol(const BlockAddress
*BA
) const {
3151 return MMI
->getAddrLabelSymbol(BA
->getBasicBlock());
3154 MCSymbol
*AsmPrinter::GetBlockAddressSymbol(const BasicBlock
*BB
) const {
3155 return MMI
->getAddrLabelSymbol(BB
);
3158 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
3159 MCSymbol
*AsmPrinter::GetCPISymbol(unsigned CPID
) const {
3160 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3161 const MachineConstantPoolEntry
&CPE
=
3162 MF
->getConstantPool()->getConstants()[CPID
];
3163 if (!CPE
.isMachineConstantPoolEntry()) {
3164 const DataLayout
&DL
= MF
->getDataLayout();
3165 SectionKind Kind
= CPE
.getSectionKind(&DL
);
3166 const Constant
*C
= CPE
.Val
.ConstVal
;
3167 Align Alignment
= CPE
.Alignment
;
3168 if (const MCSectionCOFF
*S
= dyn_cast
<MCSectionCOFF
>(
3169 getObjFileLowering().getSectionForConstant(DL
, Kind
, C
,
3171 if (MCSymbol
*Sym
= S
->getCOMDATSymbol()) {
3172 if (Sym
->isUndefined())
3173 OutStreamer
->emitSymbolAttribute(Sym
, MCSA_Global
);
3180 const DataLayout
&DL
= getDataLayout();
3181 return OutContext
.getOrCreateSymbol(Twine(DL
.getPrivateGlobalPrefix()) +
3182 "CPI" + Twine(getFunctionNumber()) + "_" +
3186 /// GetJTISymbol - Return the symbol for the specified jump table entry.
3187 MCSymbol
*AsmPrinter::GetJTISymbol(unsigned JTID
, bool isLinkerPrivate
) const {
3188 return MF
->getJTISymbol(JTID
, OutContext
, isLinkerPrivate
);
3191 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
3192 /// FIXME: privatize to AsmPrinter.
3193 MCSymbol
*AsmPrinter::GetJTSetSymbol(unsigned UID
, unsigned MBBID
) const {
3194 const DataLayout
&DL
= getDataLayout();
3195 return OutContext
.getOrCreateSymbol(Twine(DL
.getPrivateGlobalPrefix()) +
3196 Twine(getFunctionNumber()) + "_" +
3197 Twine(UID
) + "_set_" + Twine(MBBID
));
3200 MCSymbol
*AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue
*GV
,
3201 StringRef Suffix
) const {
3202 return getObjFileLowering().getSymbolWithGlobalValueBase(GV
, Suffix
, TM
);
3205 /// Return the MCSymbol for the specified ExternalSymbol.
3206 MCSymbol
*AsmPrinter::GetExternalSymbolSymbol(StringRef Sym
) const {
3207 SmallString
<60> NameStr
;
3208 Mangler::getNameWithPrefix(NameStr
, Sym
, getDataLayout());
3209 return OutContext
.getOrCreateSymbol(NameStr
);
3212 /// PrintParentLoopComment - Print comments about parent loops of this one.
3213 static void PrintParentLoopComment(raw_ostream
&OS
, const MachineLoop
*Loop
,
3214 unsigned FunctionNumber
) {
3216 PrintParentLoopComment(OS
, Loop
->getParentLoop(), FunctionNumber
);
3217 OS
.indent(Loop
->getLoopDepth()*2)
3218 << "Parent Loop BB" << FunctionNumber
<< "_"
3219 << Loop
->getHeader()->getNumber()
3220 << " Depth=" << Loop
->getLoopDepth() << '\n';
3223 /// PrintChildLoopComment - Print comments about child loops within
3224 /// the loop for this basic block, with nesting.
3225 static void PrintChildLoopComment(raw_ostream
&OS
, const MachineLoop
*Loop
,
3226 unsigned FunctionNumber
) {
3227 // Add child loop information
3228 for (const MachineLoop
*CL
: *Loop
) {
3229 OS
.indent(CL
->getLoopDepth()*2)
3230 << "Child Loop BB" << FunctionNumber
<< "_"
3231 << CL
->getHeader()->getNumber() << " Depth " << CL
->getLoopDepth()
3233 PrintChildLoopComment(OS
, CL
, FunctionNumber
);
3237 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3238 static void emitBasicBlockLoopComments(const MachineBasicBlock
&MBB
,
3239 const MachineLoopInfo
*LI
,
3240 const AsmPrinter
&AP
) {
3241 // Add loop depth information
3242 const MachineLoop
*Loop
= LI
->getLoopFor(&MBB
);
3245 MachineBasicBlock
*Header
= Loop
->getHeader();
3246 assert(Header
&& "No header for loop");
3248 // If this block is not a loop header, just print out what is the loop header
3250 if (Header
!= &MBB
) {
3251 AP
.OutStreamer
->AddComment(" in Loop: Header=BB" +
3252 Twine(AP
.getFunctionNumber())+"_" +
3253 Twine(Loop
->getHeader()->getNumber())+
3254 " Depth="+Twine(Loop
->getLoopDepth()));
3258 // Otherwise, it is a loop header. Print out information about child and
3260 raw_ostream
&OS
= AP
.OutStreamer
->GetCommentOS();
3262 PrintParentLoopComment(OS
, Loop
->getParentLoop(), AP
.getFunctionNumber());
3265 OS
.indent(Loop
->getLoopDepth()*2-2);
3268 if (Loop
->isInnermost())
3270 OS
<< "Loop Header: Depth=" + Twine(Loop
->getLoopDepth()) << '\n';
3272 PrintChildLoopComment(OS
, Loop
, AP
.getFunctionNumber());
3275 /// emitBasicBlockStart - This method prints the label for the specified
3276 /// MachineBasicBlock, an alignment (if present) and a comment describing
3277 /// it if appropriate.
3278 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock
&MBB
) {
3279 // End the previous funclet and start a new one.
3280 if (MBB
.isEHFuncletEntry()) {
3281 for (const HandlerInfo
&HI
: Handlers
) {
3282 HI
.Handler
->endFunclet();
3283 HI
.Handler
->beginFunclet(MBB
);
3287 // Emit an alignment directive for this block, if needed.
3288 const Align Alignment
= MBB
.getAlignment();
3289 if (Alignment
!= Align(1))
3290 emitAlignment(Alignment
, nullptr, MBB
.getMaxBytesForAlignment());
3292 // Switch to a new section if this basic block must begin a section. The
3293 // entry block is always placed in the function section and is handled
3295 if (MBB
.isBeginSection() && !MBB
.isEntryBlock()) {
3296 OutStreamer
->SwitchSection(
3297 getObjFileLowering().getSectionForMachineBasicBlock(MF
->getFunction(),
3299 CurrentSectionBeginSym
= MBB
.getSymbol();
3302 // If the block has its address taken, emit any labels that were used to
3303 // reference the block. It is possible that there is more than one label
3304 // here, because multiple LLVM BB's may have been RAUW'd to this block after
3305 // the references were generated.
3306 const BasicBlock
*BB
= MBB
.getBasicBlock();
3307 if (MBB
.hasAddressTaken()) {
3309 OutStreamer
->AddComment("Block address taken");
3311 // MBBs can have their address taken as part of CodeGen without having
3312 // their corresponding BB's address taken in IR
3313 if (BB
&& BB
->hasAddressTaken())
3314 for (MCSymbol
*Sym
: MMI
->getAddrLabelSymbolToEmit(BB
))
3315 OutStreamer
->emitLabel(Sym
);
3318 // Print some verbose block comments.
3321 if (BB
->hasName()) {
3322 BB
->printAsOperand(OutStreamer
->GetCommentOS(),
3323 /*PrintType=*/false, BB
->getModule());
3324 OutStreamer
->GetCommentOS() << '\n';
3328 assert(MLI
!= nullptr && "MachineLoopInfo should has been computed");
3329 emitBasicBlockLoopComments(MBB
, MLI
, *this);
3332 // Print the main label for the block.
3333 if (shouldEmitLabelForBasicBlock(MBB
)) {
3334 if (isVerbose() && MBB
.hasLabelMustBeEmitted())
3335 OutStreamer
->AddComment("Label of block must be emitted");
3336 OutStreamer
->emitLabel(MBB
.getSymbol());
3339 // NOTE: Want this comment at start of line, don't emit with AddComment.
3340 OutStreamer
->emitRawComment(" %bb." + Twine(MBB
.getNumber()) + ":",
3345 if (MBB
.isEHCatchretTarget() &&
3346 MAI
->getExceptionHandlingType() == ExceptionHandling::WinEH
) {
3347 OutStreamer
->emitLabel(MBB
.getEHCatchretSymbol());
3350 // With BB sections, each basic block must handle CFI information on its own
3351 // if it begins a section (Entry block is handled separately by
3352 // AsmPrinterHandler::beginFunction).
3353 if (MBB
.isBeginSection() && !MBB
.isEntryBlock())
3354 for (const HandlerInfo
&HI
: Handlers
)
3355 HI
.Handler
->beginBasicBlock(MBB
);
3358 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock
&MBB
) {
3359 // Check if CFI information needs to be updated for this MBB with basic block
3361 if (MBB
.isEndSection())
3362 for (const HandlerInfo
&HI
: Handlers
)
3363 HI
.Handler
->endBasicBlock(MBB
);
3366 void AsmPrinter::emitVisibility(MCSymbol
*Sym
, unsigned Visibility
,
3367 bool IsDefinition
) const {
3368 MCSymbolAttr Attr
= MCSA_Invalid
;
3370 switch (Visibility
) {
3372 case GlobalValue::HiddenVisibility
:
3374 Attr
= MAI
->getHiddenVisibilityAttr();
3376 Attr
= MAI
->getHiddenDeclarationVisibilityAttr();
3378 case GlobalValue::ProtectedVisibility
:
3379 Attr
= MAI
->getProtectedVisibilityAttr();
3383 if (Attr
!= MCSA_Invalid
)
3384 OutStreamer
->emitSymbolAttribute(Sym
, Attr
);
3387 bool AsmPrinter::shouldEmitLabelForBasicBlock(
3388 const MachineBasicBlock
&MBB
) const {
3389 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3390 // in the labels mode (option `=labels`) and every section beginning in the
3391 // sections mode (`=all` and `=list=`).
3392 if ((MF
->hasBBLabels() || MBB
.isBeginSection()) && !MBB
.isEntryBlock())
3394 // A label is needed for any block with at least one predecessor (when that
3395 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3396 // entry, or if a label is forced).
3397 return !MBB
.pred_empty() &&
3398 (!isBlockOnlyReachableByFallthrough(&MBB
) || MBB
.isEHFuncletEntry() ||
3399 MBB
.hasLabelMustBeEmitted());
3402 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3403 /// exactly one predecessor and the control transfer mechanism between
3404 /// the predecessor and this block is a fall-through.
3406 isBlockOnlyReachableByFallthrough(const MachineBasicBlock
*MBB
) const {
3407 // If this is a landing pad, it isn't a fall through. If it has no preds,
3408 // then nothing falls through to it.
3409 if (MBB
->isEHPad() || MBB
->pred_empty())
3412 // If there isn't exactly one predecessor, it can't be a fall through.
3413 if (MBB
->pred_size() > 1)
3416 // The predecessor has to be immediately before this block.
3417 MachineBasicBlock
*Pred
= *MBB
->pred_begin();
3418 if (!Pred
->isLayoutSuccessor(MBB
))
3421 // If the block is completely empty, then it definitely does fall through.
3425 // Check the terminators in the previous blocks
3426 for (const auto &MI
: Pred
->terminators()) {
3427 // If it is not a simple branch, we are in a table somewhere.
3428 if (!MI
.isBranch() || MI
.isIndirectBranch())
3431 // If we are the operands of one of the branches, this is not a fall
3432 // through. Note that targets with delay slots will usually bundle
3433 // terminators with the delay slot instruction.
3434 for (ConstMIBundleOperands
OP(MI
); OP
.isValid(); ++OP
) {
3437 if (OP
->isMBB() && OP
->getMBB() == MBB
)
3445 GCMetadataPrinter
*AsmPrinter::GetOrCreateGCPrinter(GCStrategy
&S
) {
3446 if (!S
.usesMetadata())
3449 gcp_map_type
&GCMap
= getGCMap(GCMetadataPrinters
);
3450 gcp_map_type::iterator GCPI
= GCMap
.find(&S
);
3451 if (GCPI
!= GCMap
.end())
3452 return GCPI
->second
.get();
3454 auto Name
= S
.getName();
3456 for (const GCMetadataPrinterRegistry::entry
&GCMetaPrinter
:
3457 GCMetadataPrinterRegistry::entries())
3458 if (Name
== GCMetaPrinter
.getName()) {
3459 std::unique_ptr
<GCMetadataPrinter
> GMP
= GCMetaPrinter
.instantiate();
3461 auto IterBool
= GCMap
.insert(std::make_pair(&S
, std::move(GMP
)));
3462 return IterBool
.first
->second
.get();
3465 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name
));
3468 void AsmPrinter::emitStackMaps(StackMaps
&SM
) {
3469 GCModuleInfo
*MI
= getAnalysisIfAvailable
<GCModuleInfo
>();
3470 assert(MI
&& "AsmPrinter didn't require GCModuleInfo?");
3471 bool NeedsDefault
= false;
3472 if (MI
->begin() == MI
->end())
3473 // No GC strategy, use the default format.
3474 NeedsDefault
= true;
3476 for (auto &I
: *MI
) {
3477 if (GCMetadataPrinter
*MP
= GetOrCreateGCPrinter(*I
))
3478 if (MP
->emitStackMaps(SM
, *this))
3480 // The strategy doesn't have printer or doesn't emit custom stack maps.
3481 // Use the default format.
3482 NeedsDefault
= true;
3486 SM
.serializeToStackMapSection();
3489 /// Pin vtable to this file.
3490 AsmPrinterHandler::~AsmPrinterHandler() = default;
3492 void AsmPrinterHandler::markFunctionEnd() {}
3494 // In the binary's "xray_instr_map" section, an array of these function entries
3495 // describes each instrumentation point. When XRay patches your code, the index
3496 // into this table will be given to your handler as a patch point identifier.
3497 void AsmPrinter::XRayFunctionEntry::emit(int Bytes
, MCStreamer
*Out
) const {
3498 auto Kind8
= static_cast<uint8_t>(Kind
);
3499 Out
->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8
), 1));
3500 Out
->emitBinaryData(
3501 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument
), 1));
3502 Out
->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version
), 1));
3503 auto Padding
= (4 * Bytes
) - ((2 * Bytes
) + 3);
3504 assert(Padding
>= 0 && "Instrumentation map entry > 4 * Word Size");
3505 Out
->emitZeros(Padding
);
3508 void AsmPrinter::emitXRayTable() {
3512 auto PrevSection
= OutStreamer
->getCurrentSectionOnly();
3513 const Function
&F
= MF
->getFunction();
3514 MCSection
*InstMap
= nullptr;
3515 MCSection
*FnSledIndex
= nullptr;
3516 const Triple
&TT
= TM
.getTargetTriple();
3517 // Use PC-relative addresses on all targets.
3518 if (TT
.isOSBinFormatELF()) {
3519 auto LinkedToSym
= cast
<MCSymbolELF
>(CurrentFnSym
);
3520 auto Flags
= ELF::SHF_ALLOC
| ELF::SHF_LINK_ORDER
;
3521 StringRef GroupName
;
3522 if (F
.hasComdat()) {
3523 Flags
|= ELF::SHF_GROUP
;
3524 GroupName
= F
.getComdat()->getName();
3526 InstMap
= OutContext
.getELFSection("xray_instr_map", ELF::SHT_PROGBITS
,
3527 Flags
, 0, GroupName
, F
.hasComdat(),
3528 MCSection::NonUniqueID
, LinkedToSym
);
3530 if (!TM
.Options
.XRayOmitFunctionIndex
)
3531 FnSledIndex
= OutContext
.getELFSection(
3532 "xray_fn_idx", ELF::SHT_PROGBITS
, Flags
| ELF::SHF_WRITE
, 0,
3533 GroupName
, F
.hasComdat(), MCSection::NonUniqueID
, LinkedToSym
);
3534 } else if (MF
->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3535 InstMap
= OutContext
.getMachOSection("__DATA", "xray_instr_map", 0,
3536 SectionKind::getReadOnlyWithRel());
3537 if (!TM
.Options
.XRayOmitFunctionIndex
)
3538 FnSledIndex
= OutContext
.getMachOSection(
3539 "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3541 llvm_unreachable("Unsupported target");
3544 auto WordSizeBytes
= MAI
->getCodePointerSize();
3546 // Now we switch to the instrumentation map section. Because this is done
3547 // per-function, we are able to create an index entry that will represent the
3548 // range of sleds associated with a function.
3549 auto &Ctx
= OutContext
;
3550 MCSymbol
*SledsStart
= OutContext
.createTempSymbol("xray_sleds_start", true);
3551 OutStreamer
->SwitchSection(InstMap
);
3552 OutStreamer
->emitLabel(SledsStart
);
3553 for (const auto &Sled
: Sleds
) {
3554 MCSymbol
*Dot
= Ctx
.createTempSymbol();
3555 OutStreamer
->emitLabel(Dot
);
3556 OutStreamer
->emitValueImpl(
3557 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled
.Sled
, Ctx
),
3558 MCSymbolRefExpr::create(Dot
, Ctx
), Ctx
),
3560 OutStreamer
->emitValueImpl(
3561 MCBinaryExpr::createSub(
3562 MCSymbolRefExpr::create(CurrentFnBegin
, Ctx
),
3563 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot
, Ctx
),
3564 MCConstantExpr::create(WordSizeBytes
, Ctx
),
3568 Sled
.emit(WordSizeBytes
, OutStreamer
.get());
3570 MCSymbol
*SledsEnd
= OutContext
.createTempSymbol("xray_sleds_end", true);
3571 OutStreamer
->emitLabel(SledsEnd
);
3573 // We then emit a single entry in the index per function. We use the symbols
3574 // that bound the instrumentation map as the range for a specific function.
3575 // Each entry here will be 2 * word size aligned, as we're writing down two
3576 // pointers. This should work for both 32-bit and 64-bit platforms.
3578 OutStreamer
->SwitchSection(FnSledIndex
);
3579 OutStreamer
->emitCodeAlignment(2 * WordSizeBytes
, &getSubtargetInfo());
3580 OutStreamer
->emitSymbolValue(SledsStart
, WordSizeBytes
, false);
3581 OutStreamer
->emitSymbolValue(SledsEnd
, WordSizeBytes
, false);
3582 OutStreamer
->SwitchSection(PrevSection
);
3587 void AsmPrinter::recordSled(MCSymbol
*Sled
, const MachineInstr
&MI
,
3588 SledKind Kind
, uint8_t Version
) {
3589 const Function
&F
= MI
.getMF()->getFunction();
3590 auto Attr
= F
.getFnAttribute("function-instrument");
3591 bool LogArgs
= F
.hasFnAttribute("xray-log-args");
3592 bool AlwaysInstrument
=
3593 Attr
.isStringAttribute() && Attr
.getValueAsString() == "xray-always";
3594 if (Kind
== SledKind::FUNCTION_ENTER
&& LogArgs
)
3595 Kind
= SledKind::LOG_ARGS_ENTER
;
3596 Sleds
.emplace_back(XRayFunctionEntry
{Sled
, CurrentFnSym
, Kind
,
3597 AlwaysInstrument
, &F
, Version
});
3600 void AsmPrinter::emitPatchableFunctionEntries() {
3601 const Function
&F
= MF
->getFunction();
3602 unsigned PatchableFunctionPrefix
= 0, PatchableFunctionEntry
= 0;
3603 (void)F
.getFnAttribute("patchable-function-prefix")
3605 .getAsInteger(10, PatchableFunctionPrefix
);
3606 (void)F
.getFnAttribute("patchable-function-entry")
3608 .getAsInteger(10, PatchableFunctionEntry
);
3609 if (!PatchableFunctionPrefix
&& !PatchableFunctionEntry
)
3611 const unsigned PointerSize
= getPointerSize();
3612 if (TM
.getTargetTriple().isOSBinFormatELF()) {
3613 auto Flags
= ELF::SHF_WRITE
| ELF::SHF_ALLOC
;
3614 const MCSymbolELF
*LinkedToSym
= nullptr;
3615 StringRef GroupName
;
3617 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
3618 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
3619 if (MAI
->useIntegratedAssembler() || MAI
->binutilsIsAtLeast(2, 36)) {
3620 Flags
|= ELF::SHF_LINK_ORDER
;
3621 if (F
.hasComdat()) {
3622 Flags
|= ELF::SHF_GROUP
;
3623 GroupName
= F
.getComdat()->getName();
3625 LinkedToSym
= cast
<MCSymbolELF
>(CurrentFnSym
);
3627 OutStreamer
->SwitchSection(OutContext
.getELFSection(
3628 "__patchable_function_entries", ELF::SHT_PROGBITS
, Flags
, 0, GroupName
,
3629 F
.hasComdat(), MCSection::NonUniqueID
, LinkedToSym
));
3630 emitAlignment(Align(PointerSize
));
3631 OutStreamer
->emitSymbolValue(CurrentPatchableFunctionEntrySym
, PointerSize
);
3635 uint16_t AsmPrinter::getDwarfVersion() const {
3636 return OutStreamer
->getContext().getDwarfVersion();
3639 void AsmPrinter::setDwarfVersion(uint16_t Version
) {
3640 OutStreamer
->getContext().setDwarfVersion(Version
);
3643 bool AsmPrinter::isDwarf64() const {
3644 return OutStreamer
->getContext().getDwarfFormat() == dwarf::DWARF64
;
3647 unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
3648 return dwarf::getDwarfOffsetByteSize(
3649 OutStreamer
->getContext().getDwarfFormat());
3652 dwarf::FormParams
AsmPrinter::getDwarfFormParams() const {
3653 return {getDwarfVersion(), uint8_t(getPointerSize()),
3654 OutStreamer
->getContext().getDwarfFormat(),
3655 MAI
->doesDwarfUseRelocationsAcrossSections()};
3658 unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
3659 return dwarf::getUnitLengthFieldByteSize(
3660 OutStreamer
->getContext().getDwarfFormat());