Bug Summary

File:llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
Warning:line 280, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name AsmPrinter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/lib/CodeGen/AsmPrinter -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/lib/CodeGen/AsmPrinter -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-21-164211-33944-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
1//===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AsmPrinter class.
10//
11//===----------------------------------------------------------------------===//
12
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/IR/BasicBlock.h"
63#include "llvm/IR/Comdat.h"
64#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfoMetadata.h"
68#include "llvm/IR/DerivedTypes.h"
69#include "llvm/IR/Function.h"
70#include "llvm/IR/GCStrategy.h"
71#include "llvm/IR/GlobalAlias.h"
72#include "llvm/IR/GlobalIFunc.h"
73#include "llvm/IR/GlobalIndirectSymbol.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/Pass.h"
105#include "llvm/Remarks/Remark.h"
106#include "llvm/Remarks/RemarkFormat.h"
107#include "llvm/Remarks/RemarkStreamer.h"
108#include "llvm/Remarks/RemarkStringTable.h"
109#include "llvm/Support/Casting.h"
110#include "llvm/Support/CommandLine.h"
111#include "llvm/Support/Compiler.h"
112#include "llvm/Support/ErrorHandling.h"
113#include "llvm/Support/FileSystem.h"
114#include "llvm/Support/Format.h"
115#include "llvm/Support/MathExtras.h"
116#include "llvm/Support/Path.h"
117#include "llvm/Support/TargetRegistry.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"
123#include <algorithm>
124#include <cassert>
125#include <cinttypes>
126#include <cstdint>
127#include <iterator>
128#include <limits>
129#include <memory>
130#include <string>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135
136#define DEBUG_TYPE"asm-printer" "asm-printer"
137
138// FIXME: this option currently only applies to DWARF, and not CodeView, tables
139static cl::opt<bool>
140 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
141 cl::desc("Disable debug info printing"));
142
143const char DWARFGroupName[] = "dwarf";
144const char DWARFGroupDescription[] = "DWARF Emission";
145const char DbgTimerName[] = "emit";
146const char DbgTimerDescription[] = "Debug Info Emission";
147const char EHTimerName[] = "write_exception";
148const char EHTimerDescription[] = "DWARF Exception Writer";
149const char CFGuardName[] = "Control Flow Guard";
150const char CFGuardDescription[] = "Control Flow Guard";
151const char CodeViewLineTablesGroupName[] = "linetables";
152const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
153const char PPTimerName[] = "emit";
154const char PPTimerDescription[] = "Pseudo Probe Emission";
155const char PPGroupName[] = "pseudo probe";
156const char PPGroupDescription[] = "Pseudo Probe Emission";
157
158STATISTIC(EmittedInsts, "Number of machine instrs printed")static llvm::Statistic EmittedInsts = {"asm-printer", "EmittedInsts"
, "Number of machine instrs printed"}
;
159
160char AsmPrinter::ID = 0;
161
162using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>;
163
164static gcp_map_type &getGCMap(void *&P) {
165 if (!P)
166 P = new gcp_map_type();
167 return *(gcp_map_type*)P;
168}
169
170/// getGVAlignment - Return the alignment to use for the specified global
171/// value. This rounds up to the preferred alignment if possible and legal.
172Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL,
173 Align InAlign) {
174 Align Alignment;
175 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
176 Alignment = DL.getPreferredAlign(GVar);
177
178 // If InAlign is specified, round it to it.
179 if (InAlign > Alignment)
180 Alignment = InAlign;
181
182 // If the GV has a specified alignment, take it into account.
183 const MaybeAlign GVAlign(GV->getAlignment());
184 if (!GVAlign)
185 return Alignment;
186
187 assert(GVAlign && "GVAlign must be set")(static_cast <bool> (GVAlign && "GVAlign must be set"
) ? void (0) : __assert_fail ("GVAlign && \"GVAlign must be set\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 187, __extension__ __PRETTY_FUNCTION__))
;
188
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;
193 return Alignment;
194}
195
196AsmPrinter::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();
200}
201
202AsmPrinter::~AsmPrinter() {
203 assert(!DD && Handlers.size() == NumUserHandlers &&(static_cast <bool> (!DD && Handlers.size() == NumUserHandlers
&& "Debug/EH info didn't get finalized") ? void (0) :
__assert_fail ("!DD && Handlers.size() == NumUserHandlers && \"Debug/EH info didn't get finalized\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 204, __extension__ __PRETTY_FUNCTION__))
204 "Debug/EH info didn't get finalized")(static_cast <bool> (!DD && Handlers.size() == NumUserHandlers
&& "Debug/EH info didn't get finalized") ? void (0) :
__assert_fail ("!DD && Handlers.size() == NumUserHandlers && \"Debug/EH info didn't get finalized\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 204, __extension__ __PRETTY_FUNCTION__))
;
205
206 if (GCMetadataPrinters) {
207 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
208
209 delete &GCMap;
210 GCMetadataPrinters = nullptr;
211 }
212}
213
214bool AsmPrinter::isPositionIndependent() const {
215 return TM.isPositionIndependent();
216}
217
218/// getFunctionNumber - Return a unique ID for the current function.
219unsigned AsmPrinter::getFunctionNumber() const {
220 return MF->getFunctionNumber();
221}
222
223const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
224 return *TM.getObjFileLowering();
225}
226
227const DataLayout &AsmPrinter::getDataLayout() const {
228 return MMI->getModule()->getDataLayout();
229}
230
231// Do not use the cached DataLayout because some client use it without a Module
232// (dsymutil, llvm-dwarfdump).
233unsigned AsmPrinter::getPointerSize() const {
234 return TM.getPointerSize(0); // FIXME: Default address space
235}
236
237const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
238 assert(MF && "getSubtargetInfo requires a valid MachineFunction!")(static_cast <bool> (MF && "getSubtargetInfo requires a valid MachineFunction!"
) ? void (0) : __assert_fail ("MF && \"getSubtargetInfo requires a valid MachineFunction!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 238, __extension__ __PRETTY_FUNCTION__))
;
239 return MF->getSubtarget<MCSubtargetInfo>();
240}
241
242void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
243 S.emitInstruction(Inst, getSubtargetInfo());
244}
245
246void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
247 if (DD) {
248 assert(OutStreamer->hasRawTextSupport() &&(static_cast <bool> (OutStreamer->hasRawTextSupport(
) && "Expected assembly output mode.") ? void (0) : __assert_fail
("OutStreamer->hasRawTextSupport() && \"Expected assembly output mode.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 249, __extension__ __PRETTY_FUNCTION__))
249 "Expected assembly output mode.")(static_cast <bool> (OutStreamer->hasRawTextSupport(
) && "Expected assembly output mode.") ? void (0) : __assert_fail
("OutStreamer->hasRawTextSupport() && \"Expected assembly output mode.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 249, __extension__ __PRETTY_FUNCTION__))
;
250 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
251 }
252}
253
254/// getCurrentSection() - Return the current section we are emitting to.
255const MCSection *AsmPrinter::getCurrentSection() const {
256 return OutStreamer->getCurrentSectionOnly();
257}
258
259void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
260 AU.setPreservesAll();
261 MachineFunctionPass::getAnalysisUsage(AU);
262 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
263 AU.addRequired<GCModuleInfo>();
264}
265
266bool AsmPrinter::doInitialization(Module &M) {
267 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
268 MMI = MMIWP
0.1
'MMIWP' is null
? &MMIWP->getMMI() : nullptr
;
1
'?' condition is false
2
Null pointer value stored to field 'MMI'
269
270 // Initialize TargetLoweringObjectFile.
271 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
272 .Initialize(OutContext, TM);
273
274 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
275 .getModuleMetadata(M);
276
277 OutStreamer->InitSections(false);
278
279 if (DisableDebugInfoPrinting)
3
Assuming the condition is true
4
Taking true branch
280 MMI->setDebugInfoAvailability(false);
5
Called C++ object pointer is null
281
282 // Emit the version-min deployment target directive if needed.
283 //
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
289 // anyway.
290 const Triple &Target = TM.getTargetTriple();
291 OutStreamer->emitVersionForTarget(Target, M.getSDKVersion());
292
293 // Allow the target to emit any magic that it wants at the start of the file.
294 emitStartOfAsmFile(M);
295
296 // Very minimal debug info. It is ignored if we emit actual debug info. If we
297 // don't, this at least helps the user find where a global came from.
298 if (MAI->hasSingleParameterDotFile()) {
299 // .file "foo.c"
300 if (MAI->hasBasenameOnlyForFileDirective())
301 OutStreamer->emitFileDirective(
302 llvm::sys::path::filename(M.getSourceFileName()));
303 else
304 OutStreamer->emitFileDirective(M.getSourceFileName());
305 }
306
307 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
308 assert(MI && "AsmPrinter didn't require GCModuleInfo?")(static_cast <bool> (MI && "AsmPrinter didn't require GCModuleInfo?"
) ? void (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 308, __extension__ __PRETTY_FUNCTION__))
;
309 for (auto &I : *MI)
310 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
311 MP->beginAssembly(M, *MI, *this);
312
313 // Emit module-level inline asm if it exists.
314 if (!M.getModuleInlineAsm().empty()) {
315 // We're at the module level. Construct MCSubtarget from the default CPU
316 // and target triple.
317 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
318 TM.getTargetTriple().str(), TM.getTargetCPU(),
319 TM.getTargetFeatureString()));
320 assert(STI && "Unable to create subtarget info")(static_cast <bool> (STI && "Unable to create subtarget info"
) ? void (0) : __assert_fail ("STI && \"Unable to create subtarget info\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 320, __extension__ __PRETTY_FUNCTION__))
;
321 OutStreamer->AddComment("Start of file scope inline assembly");
322 OutStreamer->AddBlankLine();
323 emitInlineAsm(M.getModuleInlineAsm() + "\n",
324 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
325 OutStreamer->AddComment("End of file scope inline assembly");
326 OutStreamer->AddBlankLine();
327 }
328
329 if (MAI->doesSupportDebugInformation()) {
330 bool EmitCodeView = M.getCodeViewFlag();
331 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
332 Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
333 DbgTimerName, DbgTimerDescription,
334 CodeViewLineTablesGroupName,
335 CodeViewLineTablesGroupDescription);
336 }
337 if (!EmitCodeView || M.getDwarfVersion()) {
338 if (!DisableDebugInfoPrinting) {
339 DD = new DwarfDebug(this);
340 Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
341 DbgTimerDescription, DWARFGroupName,
342 DWARFGroupDescription);
343 }
344 }
345 }
346
347 if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
348 PP = new PseudoProbeHandler(this, &M);
349 Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
350 PPTimerDescription, PPGroupName, PPGroupDescription);
351 }
352
353 switch (MAI->getExceptionHandlingType()) {
354 case ExceptionHandling::None:
355 // We may want to emit CFI for debug.
356 LLVM_FALLTHROUGH[[gnu::fallthrough]];
357 case ExceptionHandling::SjLj:
358 case ExceptionHandling::DwarfCFI:
359 case ExceptionHandling::ARM:
360 for (auto &F : M.getFunctionList()) {
361 if (getFunctionCFISectionType(F) != CFISection::None)
362 ModuleCFISection = getFunctionCFISectionType(F);
363 // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
364 // the module needs .eh_frame. If we have found that case, we are done.
365 if (ModuleCFISection == CFISection::EH)
366 break;
367 }
368 assert(MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI ||(static_cast <bool> (MAI->getExceptionHandlingType()
== ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection
::EH) ? void (0) : __assert_fail ("MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection::EH"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 369, __extension__ __PRETTY_FUNCTION__))
369 ModuleCFISection != CFISection::EH)(static_cast <bool> (MAI->getExceptionHandlingType()
== ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection
::EH) ? void (0) : __assert_fail ("MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI || ModuleCFISection != CFISection::EH"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 369, __extension__ __PRETTY_FUNCTION__))
;
370 break;
371 default:
372 break;
373 }
374
375 EHStreamer *ES = nullptr;
376 switch (MAI->getExceptionHandlingType()) {
377 case ExceptionHandling::None:
378 if (!needsCFIForDebug())
379 break;
380 LLVM_FALLTHROUGH[[gnu::fallthrough]];
381 case ExceptionHandling::SjLj:
382 case ExceptionHandling::DwarfCFI:
383 ES = new DwarfCFIException(this);
384 break;
385 case ExceptionHandling::ARM:
386 ES = new ARMException(this);
387 break;
388 case ExceptionHandling::WinEH:
389 switch (MAI->getWinEHEncodingType()) {
390 default: llvm_unreachable("unsupported unwinding information encoding")::llvm::llvm_unreachable_internal("unsupported unwinding information encoding"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 390)
;
391 case WinEH::EncodingType::Invalid:
392 break;
393 case WinEH::EncodingType::X86:
394 case WinEH::EncodingType::Itanium:
395 ES = new WinException(this);
396 break;
397 }
398 break;
399 case ExceptionHandling::Wasm:
400 ES = new WasmException(this);
401 break;
402 case ExceptionHandling::AIX:
403 ES = new AIXException(this);
404 break;
405 }
406 if (ES)
407 Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
408 EHTimerDescription, DWARFGroupName,
409 DWARFGroupDescription);
410
411 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
412 if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
413 Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
414 CFGuardDescription, DWARFGroupName,
415 DWARFGroupDescription);
416
417 for (const HandlerInfo &HI : Handlers) {
418 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
419 HI.TimerGroupDescription, TimePassesIsEnabled);
420 HI.Handler->beginModule(&M);
421 }
422
423 return false;
424}
425
426static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
427 if (!MAI.hasWeakDefCanBeHiddenDirective())
428 return false;
429
430 return GV->canBeOmittedFromSymbolTable();
431}
432
433void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
434 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
435 switch (Linkage) {
436 case GlobalValue::CommonLinkage:
437 case GlobalValue::LinkOnceAnyLinkage:
438 case GlobalValue::LinkOnceODRLinkage:
439 case GlobalValue::WeakAnyLinkage:
440 case GlobalValue::WeakODRLinkage:
441 if (MAI->hasWeakDefDirective()) {
442 // .globl _foo
443 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
444
445 if (!canBeHidden(GV, *MAI))
446 // .weak_definition _foo
447 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
448 else
449 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
450 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
451 // .globl _foo
452 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
453 //NOTE: linkonce is handled by the section the symbol was assigned to.
454 } else {
455 // .weak _foo
456 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
457 }
458 return;
459 case GlobalValue::ExternalLinkage:
460 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
461 return;
462 case GlobalValue::PrivateLinkage:
463 case GlobalValue::InternalLinkage:
464 return;
465 case GlobalValue::ExternalWeakLinkage:
466 case GlobalValue::AvailableExternallyLinkage:
467 case GlobalValue::AppendingLinkage:
468 llvm_unreachable("Should never emit this")::llvm::llvm_unreachable_internal("Should never emit this", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 468)
;
469 }
470 llvm_unreachable("Unknown linkage type!")::llvm::llvm_unreachable_internal("Unknown linkage type!", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 470)
;
471}
472
473void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
474 const GlobalValue *GV) const {
475 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
476}
477
478MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
479 return TM.getSymbol(GV);
480}
481
482MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const {
483 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
484 // exact definion (intersection of GlobalValue::hasExactDefinition() and
485 // !isInterposable()). These linkages include: external, appending, internal,
486 // private. It may be profitable to use a local alias for external. The
487 // assembler would otherwise be conservative and assume a global default
488 // visibility symbol can be interposable, even if the code generator already
489 // assumed it.
490 if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) {
491 const Module &M = *GV.getParent();
492 if (TM.getRelocationModel() != Reloc::Static &&
493 M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
494 return getSymbolWithGlobalValueBase(&GV, "$local");
495 }
496 return TM.getSymbol(&GV);
497}
498
499/// EmitGlobalVariable - Emit the specified global variable to the .s file.
500void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
501 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
502 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&(static_cast <bool> (!(IsEmuTLSVar && GV->hasCommonLinkage
()) && "No emulated TLS variables in the common section"
) ? void (0) : __assert_fail ("!(IsEmuTLSVar && GV->hasCommonLinkage()) && \"No emulated TLS variables in the common section\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 503, __extension__ __PRETTY_FUNCTION__))
503 "No emulated TLS variables in the common section")(static_cast <bool> (!(IsEmuTLSVar && GV->hasCommonLinkage
()) && "No emulated TLS variables in the common section"
) ? void (0) : __assert_fail ("!(IsEmuTLSVar && GV->hasCommonLinkage()) && \"No emulated TLS variables in the common section\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 503, __extension__ __PRETTY_FUNCTION__))
;
504
505 // Never emit TLS variable xyz in emulated TLS model.
506 // The initialization value is in __emutls_t.xyz instead of xyz.
507 if (IsEmuTLSVar)
508 return;
509
510 if (GV->hasInitializer()) {
511 // Check to see if this is a special global used by LLVM, if so, emit it.
512 if (emitSpecialLLVMGlobal(GV))
513 return;
514
515 // Skip the emission of global equivalents. The symbol can be emitted later
516 // on by emitGlobalGOTEquivs in case it turns out to be needed.
517 if (GlobalGOTEquivs.count(getSymbol(GV)))
518 return;
519
520 if (isVerbose()) {
521 // When printing the control variable __emutls_v.*,
522 // we don't need to print the original TLS variable name.
523 GV->printAsOperand(OutStreamer->GetCommentOS(),
524 /*PrintType=*/false, GV->getParent());
525 OutStreamer->GetCommentOS() << '\n';
526 }
527 }
528
529 MCSymbol *GVSym = getSymbol(GV);
530 MCSymbol *EmittedSym = GVSym;
531
532 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
533 // attributes.
534 // GV's or GVSym's attributes will be used for the EmittedSym.
535 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
536
537 if (!GV->hasInitializer()) // External globals require no extra code.
538 return;
539
540 GVSym->redefineIfPossible();
541 if (GVSym->isDefined() || GVSym->isVariable())
542 OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
543 "' is already defined");
544
545 if (MAI->hasDotTypeDotSizeDirective())
546 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
547
548 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
549
550 const DataLayout &DL = GV->getParent()->getDataLayout();
551 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
552
553 // If the alignment is specified, we *must* obey it. Overaligning a global
554 // with a specified alignment is a prompt way to break globals emitted to
555 // sections and expected to be contiguous (e.g. ObjC metadata).
556 const Align Alignment = getGVAlignment(GV, DL);
557
558 for (const HandlerInfo &HI : Handlers) {
559 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
560 HI.TimerGroupName, HI.TimerGroupDescription,
561 TimePassesIsEnabled);
562 HI.Handler->setSymbolSize(GVSym, Size);
563 }
564
565 // Handle common symbols
566 if (GVKind.isCommon()) {
567 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
568 // .comm _foo, 42, 4
569 const bool SupportsAlignment =
570 getObjFileLowering().getCommDirectiveSupportsAlignment();
571 OutStreamer->emitCommonSymbol(GVSym, Size,
572 SupportsAlignment ? Alignment.value() : 0);
573 return;
574 }
575
576 // Determine to which section this global should be emitted.
577 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
578
579 // If we have a bss global going to a section that supports the
580 // zerofill directive, do so here.
581 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
582 TheSection->isVirtualSection()) {
583 if (Size == 0)
584 Size = 1; // zerofill of 0 bytes is undefined.
585 emitLinkage(GV, GVSym);
586 // .zerofill __DATA, __bss, _foo, 400, 5
587 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
588 return;
589 }
590
591 // If this is a BSS local symbol and we are emitting in the BSS
592 // section use .lcomm/.comm directive.
593 if (GVKind.isBSSLocal() &&
594 getObjFileLowering().getBSSSection() == TheSection) {
595 if (Size == 0)
596 Size = 1; // .comm Foo, 0 is undefined, avoid it.
597
598 // Use .lcomm only if it supports user-specified alignment.
599 // Otherwise, while it would still be correct to use .lcomm in some
600 // cases (e.g. when Align == 1), the external assembler might enfore
601 // some -unknown- default alignment behavior, which could cause
602 // spurious differences between external and integrated assembler.
603 // Prefer to simply fall back to .local / .comm in this case.
604 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
605 // .lcomm _foo, 42
606 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
607 return;
608 }
609
610 // .local _foo
611 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
612 // .comm _foo, 42, 4
613 const bool SupportsAlignment =
614 getObjFileLowering().getCommDirectiveSupportsAlignment();
615 OutStreamer->emitCommonSymbol(GVSym, Size,
616 SupportsAlignment ? Alignment.value() : 0);
617 return;
618 }
619
620 // Handle thread local data for mach-o which requires us to output an
621 // additional structure of data and mangle the original symbol so that we
622 // can reference it later.
623 //
624 // TODO: This should become an "emit thread local global" method on TLOF.
625 // All of this macho specific stuff should be sunk down into TLOFMachO and
626 // stuff like "TLSExtraDataSection" should no longer be part of the parent
627 // TLOF class. This will also make it more obvious that stuff like
628 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
629 // specific code.
630 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
631 // Emit the .tbss symbol
632 MCSymbol *MangSym =
633 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
634
635 if (GVKind.isThreadBSS()) {
636 TheSection = getObjFileLowering().getTLSBSSSection();
637 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
638 } else if (GVKind.isThreadData()) {
639 OutStreamer->SwitchSection(TheSection);
640
641 emitAlignment(Alignment, GV);
642 OutStreamer->emitLabel(MangSym);
643
644 emitGlobalConstant(GV->getParent()->getDataLayout(),
645 GV->getInitializer());
646 }
647
648 OutStreamer->AddBlankLine();
649
650 // Emit the variable struct for the runtime.
651 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
652
653 OutStreamer->SwitchSection(TLVSect);
654 // Emit the linkage here.
655 emitLinkage(GV, GVSym);
656 OutStreamer->emitLabel(GVSym);
657
658 // Three pointers in size:
659 // - __tlv_bootstrap - used to make sure support exists
660 // - spare pointer, used when mapped by the runtime
661 // - pointer to mangled symbol above with initializer
662 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
663 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
664 PtrSize);
665 OutStreamer->emitIntValue(0, PtrSize);
666 OutStreamer->emitSymbolValue(MangSym, PtrSize);
667
668 OutStreamer->AddBlankLine();
669 return;
670 }
671
672 MCSymbol *EmittedInitSym = GVSym;
673
674 OutStreamer->SwitchSection(TheSection);
675
676 emitLinkage(GV, EmittedInitSym);
677 emitAlignment(Alignment, GV);
678
679 OutStreamer->emitLabel(EmittedInitSym);
680 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
681 if (LocalAlias != EmittedInitSym)
682 OutStreamer->emitLabel(LocalAlias);
683
684 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
685
686 if (MAI->hasDotTypeDotSizeDirective())
687 // .size foo, 42
688 OutStreamer->emitELFSize(EmittedInitSym,
689 MCConstantExpr::create(Size, OutContext));
690
691 OutStreamer->AddBlankLine();
692}
693
694/// Emit the directive and value for debug thread local expression
695///
696/// \p Value - The value to emit.
697/// \p Size - The size of the integer (in bytes) to emit.
698void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
699 OutStreamer->emitValue(Value, Size);
700}
701
702void AsmPrinter::emitFunctionHeaderComment() {}
703
704/// EmitFunctionHeader - This method emits the header for the current
705/// function.
706void AsmPrinter::emitFunctionHeader() {
707 const Function &F = MF->getFunction();
708
709 if (isVerbose())
710 OutStreamer->GetCommentOS()
711 << "-- Begin function "
712 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
713
714 // Print out constants referenced by the function
715 emitConstantPool();
716
717 // Print the 'header' of function.
718 // If basic block sections are desired, explicitly request a unique section
719 // for this function's entry block.
720 if (MF->front().isBeginSection())
721 MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
722 else
723 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
724 OutStreamer->SwitchSection(MF->getSection());
725
726 if (!MAI->hasVisibilityOnlyWithLinkage())
727 emitVisibility(CurrentFnSym, F.getVisibility());
728
729 if (MAI->needsFunctionDescriptors())
730 emitLinkage(&F, CurrentFnDescSym);
731
732 emitLinkage(&F, CurrentFnSym);
733 if (MAI->hasFunctionAlignment())
734 emitAlignment(MF->getAlignment(), &F);
735
736 if (MAI->hasDotTypeDotSizeDirective())
737 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
738
739 if (F.hasFnAttribute(Attribute::Cold))
740 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
741
742 if (isVerbose()) {
743 F.printAsOperand(OutStreamer->GetCommentOS(),
744 /*PrintType=*/false, F.getParent());
745 emitFunctionHeaderComment();
746 OutStreamer->GetCommentOS() << '\n';
747 }
748
749 // Emit the prefix data.
750 if (F.hasPrefixData()) {
751 if (MAI->hasSubsectionsViaSymbols()) {
752 // Preserving prefix data on platforms which use subsections-via-symbols
753 // is a bit tricky. Here we introduce a symbol for the prefix data
754 // and use the .alt_entry attribute to mark the function's real entry point
755 // as an alternative entry point to the prefix-data symbol.
756 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
757 OutStreamer->emitLabel(PrefixSym);
758
759 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
760
761 // Emit an .alt_entry directive for the actual function symbol.
762 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
763 } else {
764 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
765 }
766 }
767
768 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
769 // place prefix data before NOPs.
770 unsigned PatchableFunctionPrefix = 0;
771 unsigned PatchableFunctionEntry = 0;
772 (void)F.getFnAttribute("patchable-function-prefix")
773 .getValueAsString()
774 .getAsInteger(10, PatchableFunctionPrefix);
775 (void)F.getFnAttribute("patchable-function-entry")
776 .getValueAsString()
777 .getAsInteger(10, PatchableFunctionEntry);
778 if (PatchableFunctionPrefix) {
779 CurrentPatchableFunctionEntrySym =
780 OutContext.createLinkerPrivateTempSymbol();
781 OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
782 emitNops(PatchableFunctionPrefix);
783 } else if (PatchableFunctionEntry) {
784 // May be reassigned when emitting the body, to reference the label after
785 // the initial BTI (AArch64) or endbr32/endbr64 (x86).
786 CurrentPatchableFunctionEntrySym = CurrentFnBegin;
787 }
788
789 // Emit the function descriptor. This is a virtual function to allow targets
790 // to emit their specific function descriptor. Right now it is only used by
791 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
792 // descriptors and should be converted to use this hook as well.
793 if (MAI->needsFunctionDescriptors())
794 emitFunctionDescriptor();
795
796 // Emit the CurrentFnSym. This is a virtual function to allow targets to do
797 // their wild and crazy things as required.
798 emitFunctionEntryLabel();
799
800 // If the function had address-taken blocks that got deleted, then we have
801 // references to the dangling symbols. Emit them at the start of the function
802 // so that we don't get references to undefined symbols.
803 std::vector<MCSymbol*> DeadBlockSyms;
804 MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
805 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
806 OutStreamer->AddComment("Address taken block that was later removed");
807 OutStreamer->emitLabel(DeadBlockSyms[i]);
808 }
809
810 if (CurrentFnBegin) {
811 if (MAI->useAssignmentForEHBegin()) {
812 MCSymbol *CurPos = OutContext.createTempSymbol();
813 OutStreamer->emitLabel(CurPos);
814 OutStreamer->emitAssignment(CurrentFnBegin,
815 MCSymbolRefExpr::create(CurPos, OutContext));
816 } else {
817 OutStreamer->emitLabel(CurrentFnBegin);
818 }
819 }
820
821 // Emit pre-function debug and/or EH information.
822 for (const HandlerInfo &HI : Handlers) {
823 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
824 HI.TimerGroupDescription, TimePassesIsEnabled);
825 HI.Handler->beginFunction(MF);
826 }
827
828 // Emit the prologue data.
829 if (F.hasPrologueData())
830 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
831}
832
833/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
834/// function. This can be overridden by targets as required to do custom stuff.
835void AsmPrinter::emitFunctionEntryLabel() {
836 CurrentFnSym->redefineIfPossible();
837
838 // The function label could have already been emitted if two symbols end up
839 // conflicting due to asm renaming. Detect this and emit an error.
840 if (CurrentFnSym->isVariable())
841 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
842 "' is a protected alias");
843
844 OutStreamer->emitLabel(CurrentFnSym);
845
846 if (TM.getTargetTriple().isOSBinFormatELF()) {
847 MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction());
848 if (Sym != CurrentFnSym)
849 OutStreamer->emitLabel(Sym);
850 }
851}
852
853/// emitComments - Pretty-print comments for instructions.
854static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
855 const MachineFunction *MF = MI.getMF();
856 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
857
858 // Check for spills and reloads
859
860 // We assume a single instruction only has a spill or reload, not
861 // both.
862 Optional<unsigned> Size;
863 if ((Size = MI.getRestoreSize(TII))) {
864 CommentOS << *Size << "-byte Reload\n";
865 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
866 if (*Size) {
867 if (*Size == unsigned(MemoryLocation::UnknownSize))
868 CommentOS << "Unknown-size Folded Reload\n";
869 else
870 CommentOS << *Size << "-byte Folded Reload\n";
871 }
872 } else if ((Size = MI.getSpillSize(TII))) {
873 CommentOS << *Size << "-byte Spill\n";
874 } else if ((Size = MI.getFoldedSpillSize(TII))) {
875 if (*Size) {
876 if (*Size == unsigned(MemoryLocation::UnknownSize))
877 CommentOS << "Unknown-size Folded Spill\n";
878 else
879 CommentOS << *Size << "-byte Folded Spill\n";
880 }
881 }
882
883 // Check for spill-induced copies
884 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
885 CommentOS << " Reload Reuse\n";
886}
887
888/// emitImplicitDef - This method emits the specified machine instruction
889/// that is an implicit def.
890void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
891 Register RegNo = MI->getOperand(0).getReg();
892
893 SmallString<128> Str;
894 raw_svector_ostream OS(Str);
895 OS << "implicit-def: "
896 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
897
898 OutStreamer->AddComment(OS.str());
899 OutStreamer->AddBlankLine();
900}
901
902static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
903 std::string Str;
904 raw_string_ostream OS(Str);
905 OS << "kill:";
906 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
907 const MachineOperand &Op = MI->getOperand(i);
908 assert(Op.isReg() && "KILL instruction must have only register operands")(static_cast <bool> (Op.isReg() && "KILL instruction must have only register operands"
) ? void (0) : __assert_fail ("Op.isReg() && \"KILL instruction must have only register operands\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 908, __extension__ __PRETTY_FUNCTION__))
;
909 OS << ' ' << (Op.isDef() ? "def " : "killed ")
910 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
911 }
912 AP.OutStreamer->AddComment(OS.str());
913 AP.OutStreamer->AddBlankLine();
914}
915
916/// emitDebugValueComment - This method handles the target-independent form
917/// of DBG_VALUE, returning true if it was able to do so. A false return
918/// means the target will need to handle MI in EmitInstruction.
919static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
920 // This code handles only the 4-operand target-independent form.
921 if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
922 return false;
923
924 SmallString<128> Str;
925 raw_svector_ostream OS(Str);
926 OS << "DEBUG_VALUE: ";
927
928 const DILocalVariable *V = MI->getDebugVariable();
929 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
930 StringRef Name = SP->getName();
931 if (!Name.empty())
932 OS << Name << ":";
933 }
934 OS << V->getName();
935 OS << " <- ";
936
937 const DIExpression *Expr = MI->getDebugExpression();
938 if (Expr->getNumElements()) {
939 OS << '[';
940 ListSeparator LS;
941 for (auto Op : Expr->expr_ops()) {
942 OS << LS << dwarf::OperationEncodingString(Op.getOp());
943 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
944 OS << ' ' << Op.getArg(I);
945 }
946 OS << "] ";
947 }
948
949 // Register or immediate value. Register 0 means undef.
950 for (const MachineOperand &Op : MI->debug_operands()) {
951 if (&Op != MI->debug_operands().begin())
952 OS << ", ";
953 switch (Op.getType()) {
954 case MachineOperand::MO_FPImmediate: {
955 APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
956 Type *ImmTy = Op.getFPImm()->getType();
957 if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
958 ImmTy->isDoubleTy()) {
959 OS << APF.convertToDouble();
960 } else {
961 // There is no good way to print long double. Convert a copy to
962 // double. Ah well, it's only a comment.
963 bool ignored;
964 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
965 &ignored);
966 OS << "(long double) " << APF.convertToDouble();
967 }
968 break;
969 }
970 case MachineOperand::MO_Immediate: {
971 OS << Op.getImm();
972 break;
973 }
974 case MachineOperand::MO_CImmediate: {
975 Op.getCImm()->getValue().print(OS, false /*isSigned*/);
976 break;
977 }
978 case MachineOperand::MO_TargetIndex: {
979 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
980 // NOTE: Want this comment at start of line, don't emit with AddComment.
981 AP.OutStreamer->emitRawComment(OS.str());
982 break;
983 }
984 case MachineOperand::MO_Register:
985 case MachineOperand::MO_FrameIndex: {
986 Register Reg;
987 Optional<StackOffset> Offset;
988 if (Op.isReg()) {
989 Reg = Op.getReg();
990 } else {
991 const TargetFrameLowering *TFI =
992 AP.MF->getSubtarget().getFrameLowering();
993 Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
994 }
995 if (!Reg) {
996 // Suppress offset, it is not meaningful here.
997 OS << "undef";
998 break;
999 }
1000 // The second operand is only an offset if it's an immediate.
1001 if (MI->isIndirectDebugValue())
1002 Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1003 if (Offset)
1004 OS << '[';
1005 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1006 if (Offset)
1007 OS << '+' << Offset->getFixed() << ']';
1008 break;
1009 }
1010 default:
1011 llvm_unreachable("Unknown operand type")::llvm::llvm_unreachable_internal("Unknown operand type", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1011)
;
1012 }
1013 }
1014
1015 // NOTE: Want this comment at start of line, don't emit with AddComment.
1016 AP.OutStreamer->emitRawComment(OS.str());
1017 return true;
1018}
1019
1020/// This method handles the target-independent form of DBG_LABEL, returning
1021/// true if it was able to do so. A false return means the target will need
1022/// to handle MI in EmitInstruction.
1023static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
1024 if (MI->getNumOperands() != 1)
1025 return false;
1026
1027 SmallString<128> Str;
1028 raw_svector_ostream OS(Str);
1029 OS << "DEBUG_LABEL: ";
1030
1031 const DILabel *V = MI->getDebugLabel();
1032 if (auto *SP = dyn_cast<DISubprogram>(
1033 V->getScope()->getNonLexicalBlockFileScope())) {
1034 StringRef Name = SP->getName();
1035 if (!Name.empty())
1036 OS << Name << ":";
1037 }
1038 OS << V->getName();
1039
1040 // NOTE: Want this comment at start of line, don't emit with AddComment.
1041 AP.OutStreamer->emitRawComment(OS.str());
1042 return true;
1043}
1044
1045AsmPrinter::CFISection
1046AsmPrinter::getFunctionCFISectionType(const Function &F) const {
1047 // Ignore functions that won't get emitted.
1048 if (F.isDeclarationForLinker())
1049 return CFISection::None;
1050
1051 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
1052 F.needsUnwindTableEntry())
1053 return CFISection::EH;
1054
1055 if (MMI->hasDebugInfo() || TM.Options.ForceDwarfFrameSection)
1056 return CFISection::Debug;
1057
1058 return CFISection::None;
1059}
1060
1061AsmPrinter::CFISection
1062AsmPrinter::getFunctionCFISectionType(const MachineFunction &MF) const {
1063 return getFunctionCFISectionType(MF.getFunction());
1064}
1065
1066bool AsmPrinter::needsSEHMoves() {
1067 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
1068}
1069
1070bool AsmPrinter::needsCFIForDebug() const {
1071 return MAI->getExceptionHandlingType() == ExceptionHandling::None &&
1072 MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
1073}
1074
1075void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
1076 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1077 if (!needsCFIForDebug() &&
1078 ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1079 ExceptionHandlingType != ExceptionHandling::ARM)
1080 return;
1081
1082 if (getFunctionCFISectionType(*MF) == CFISection::None)
1083 return;
1084
1085 // If there is no "real" instruction following this CFI instruction, skip
1086 // emitting it; it would be beyond the end of the function's FDE range.
1087 auto *MBB = MI.getParent();
1088 auto I = std::next(MI.getIterator());
1089 while (I != MBB->end() && I->isTransient())
1090 ++I;
1091 if (I == MBB->instr_end() &&
1092 MBB->getReverseIterator() == MBB->getParent()->rbegin())
1093 return;
1094
1095 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1096 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1097 const MCCFIInstruction &CFI = Instrs[CFIIndex];
1098 emitCFIInstruction(CFI);
1099}
1100
1101void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
1102 // The operands are the MCSymbol and the frame offset of the allocation.
1103 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1104 int FrameOffset = MI.getOperand(1).getImm();
1105
1106 // Emit a symbol assignment.
1107 OutStreamer->emitAssignment(FrameAllocSym,
1108 MCConstantExpr::create(FrameOffset, OutContext));
1109}
1110
1111/// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
1112/// given basic block. This can be used to capture more precise profile
1113/// information. We use the last 4 bits (LSBs) to encode the following
1114/// information:
1115/// * (1): set if return block (ret or tail call).
1116/// * (2): set if ends with a tail call.
1117/// * (3): set if exception handling (EH) landing pad.
1118/// * (4): set if the block can fall through to its next.
1119/// The remaining bits are zero.
1120static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1121 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
1122 return ((unsigned)MBB.isReturnBlock()) |
1123 ((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
1124 (MBB.isEHPad() << 2) |
1125 (const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
1126}
1127
1128void AsmPrinter::emitBBAddrMapSection(const MachineFunction &MF) {
1129 MCSection *BBAddrMapSection =
1130 getObjFileLowering().getBBAddrMapSection(*MF.getSection());
1131 assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.")(static_cast <bool> (BBAddrMapSection && ".llvm_bb_addr_map section is not initialized."
) ? void (0) : __assert_fail ("BBAddrMapSection && \".llvm_bb_addr_map section is not initialized.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1131, __extension__ __PRETTY_FUNCTION__))
;
1132
1133 const MCSymbol *FunctionSymbol = getFunctionBegin();
1134
1135 OutStreamer->PushSection();
1136 OutStreamer->SwitchSection(BBAddrMapSection);
1137 OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1138 // Emit the total number of basic blocks in this function.
1139 OutStreamer->emitULEB128IntValue(MF.size());
1140 // Emit BB Information for each basic block in the funciton.
1141 for (const MachineBasicBlock &MBB : MF) {
1142 const MCSymbol *MBBSymbol =
1143 MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1144 // Emit the basic block offset.
1145 emitLabelDifferenceAsULEB128(MBBSymbol, FunctionSymbol);
1146 // Emit the basic block size. When BBs have alignments, their size cannot
1147 // always be computed from their offsets.
1148 emitLabelDifferenceAsULEB128(MBB.getEndSymbol(), MBBSymbol);
1149 OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1150 }
1151 OutStreamer->PopSection();
1152}
1153
1154void AsmPrinter::emitPseudoProbe(const MachineInstr &MI) {
1155 auto GUID = MI.getOperand(0).getImm();
1156 auto Index = MI.getOperand(1).getImm();
1157 auto Type = MI.getOperand(2).getImm();
1158 auto Attr = MI.getOperand(3).getImm();
1159 DILocation *DebugLoc = MI.getDebugLoc();
1160 PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1161}
1162
1163void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
1164 if (!MF.getTarget().Options.EmitStackSizeSection)
1165 return;
1166
1167 MCSection *StackSizeSection =
1168 getObjFileLowering().getStackSizesSection(*getCurrentSection());
1169 if (!StackSizeSection)
1170 return;
1171
1172 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1173 // Don't emit functions with dynamic stack allocations.
1174 if (FrameInfo.hasVarSizedObjects())
1175 return;
1176
1177 OutStreamer->PushSection();
1178 OutStreamer->SwitchSection(StackSizeSection);
1179
1180 const MCSymbol *FunctionSymbol = getFunctionBegin();
1181 uint64_t StackSize = FrameInfo.getStackSize();
1182 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1183 OutStreamer->emitULEB128IntValue(StackSize);
1184
1185 OutStreamer->PopSection();
1186}
1187
1188void AsmPrinter::emitStackUsage(const MachineFunction &MF) {
1189 const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1190
1191 // OutputFilename empty implies -fstack-usage is not passed.
1192 if (OutputFilename.empty())
1193 return;
1194
1195 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1196 uint64_t StackSize = FrameInfo.getStackSize();
1197
1198 if (StackUsageStream == nullptr) {
1199 std::error_code EC;
1200 StackUsageStream =
1201 std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1202 if (EC) {
1203 errs() << "Could not open file: " << EC.message();
1204 return;
1205 }
1206 }
1207
1208 *StackUsageStream << MF.getFunction().getParent()->getName();
1209 if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1210 *StackUsageStream << ':' << DSP->getLine();
1211
1212 *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1213 if (FrameInfo.hasVarSizedObjects())
1214 *StackUsageStream << "dynamic\n";
1215 else
1216 *StackUsageStream << "static\n";
1217}
1218
1219static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF) {
1220 MachineModuleInfo &MMI = MF.getMMI();
1221 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo())
1222 return true;
1223
1224 // We might emit an EH table that uses function begin and end labels even if
1225 // we don't have any landingpads.
1226 if (!MF.getFunction().hasPersonalityFn())
1227 return false;
1228 return !isNoOpWithoutInvoke(
1229 classifyEHPersonality(MF.getFunction().getPersonalityFn()));
1230}
1231
1232/// EmitFunctionBody - This method emits the body and trailer for a
1233/// function.
1234void AsmPrinter::emitFunctionBody() {
1235 emitFunctionHeader();
1236
1237 // Emit target-specific gunk before the function body.
1238 emitFunctionBodyStart();
1239
1240 if (isVerbose()) {
1241 // Get MachineDominatorTree or compute it on the fly if it's unavailable
1242 MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1243 if (!MDT) {
1244 OwnedMDT = std::make_unique<MachineDominatorTree>();
1245 OwnedMDT->getBase().recalculate(*MF);
1246 MDT = OwnedMDT.get();
1247 }
1248
1249 // Get MachineLoopInfo or compute it on the fly if it's unavailable
1250 MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1251 if (!MLI) {
1252 OwnedMLI = std::make_unique<MachineLoopInfo>();
1253 OwnedMLI->getBase().analyze(MDT->getBase());
1254 MLI = OwnedMLI.get();
1255 }
1256 }
1257
1258 // Print out code for the function.
1259 bool HasAnyRealCode = false;
1260 int NumInstsInFunction = 0;
1261
1262 bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE"asm-printer");
1263 for (auto &MBB : *MF) {
1264 // Print a label for the basic block.
1265 emitBasicBlockStart(MBB);
1266 DenseMap<StringRef, unsigned> MnemonicCounts;
1267 for (auto &MI : MBB) {
1268 // Print the assembly for the instruction.
1269 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1270 !MI.isDebugInstr()) {
1271 HasAnyRealCode = true;
1272 ++NumInstsInFunction;
1273 }
1274
1275 // If there is a pre-instruction symbol, emit a label for it here.
1276 if (MCSymbol *S = MI.getPreInstrSymbol())
1277 OutStreamer->emitLabel(S);
1278
1279 for (const HandlerInfo &HI : Handlers) {
1280 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1281 HI.TimerGroupDescription, TimePassesIsEnabled);
1282 HI.Handler->beginInstruction(&MI);
1283 }
1284
1285 if (isVerbose())
1286 emitComments(MI, OutStreamer->GetCommentOS());
1287
1288 switch (MI.getOpcode()) {
1289 case TargetOpcode::CFI_INSTRUCTION:
1290 emitCFIInstruction(MI);
1291 break;
1292 case TargetOpcode::LOCAL_ESCAPE:
1293 emitFrameAlloc(MI);
1294 break;
1295 case TargetOpcode::ANNOTATION_LABEL:
1296 case TargetOpcode::EH_LABEL:
1297 case TargetOpcode::GC_LABEL:
1298 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1299 break;
1300 case TargetOpcode::INLINEASM:
1301 case TargetOpcode::INLINEASM_BR:
1302 emitInlineAsm(&MI);
1303 break;
1304 case TargetOpcode::DBG_VALUE:
1305 case TargetOpcode::DBG_VALUE_LIST:
1306 if (isVerbose()) {
1307 if (!emitDebugValueComment(&MI, *this))
1308 emitInstruction(&MI);
1309 }
1310 break;
1311 case TargetOpcode::DBG_INSTR_REF:
1312 // This instruction reference will have been resolved to a machine
1313 // location, and a nearby DBG_VALUE created. We can safely ignore
1314 // the instruction reference.
1315 break;
1316 case TargetOpcode::DBG_PHI:
1317 // This instruction is only used to label a program point, it's purely
1318 // meta information.
1319 break;
1320 case TargetOpcode::DBG_LABEL:
1321 if (isVerbose()) {
1322 if (!emitDebugLabelComment(&MI, *this))
1323 emitInstruction(&MI);
1324 }
1325 break;
1326 case TargetOpcode::IMPLICIT_DEF:
1327 if (isVerbose()) emitImplicitDef(&MI);
1328 break;
1329 case TargetOpcode::KILL:
1330 if (isVerbose()) emitKill(&MI, *this);
1331 break;
1332 case TargetOpcode::PSEUDO_PROBE:
1333 emitPseudoProbe(MI);
1334 break;
1335 default:
1336 emitInstruction(&MI);
1337 if (CanDoExtraAnalysis) {
1338 MCInst MCI;
1339 MCI.setOpcode(MI.getOpcode());
1340 auto Name = OutStreamer->getMnemonic(MCI);
1341 auto I = MnemonicCounts.insert({Name, 0u});
1342 I.first->second++;
1343 }
1344 break;
1345 }
1346
1347 // If there is a post-instruction symbol, emit a label for it here.
1348 if (MCSymbol *S = MI.getPostInstrSymbol())
1349 OutStreamer->emitLabel(S);
1350
1351 for (const HandlerInfo &HI : Handlers) {
1352 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1353 HI.TimerGroupDescription, TimePassesIsEnabled);
1354 HI.Handler->endInstruction();
1355 }
1356 }
1357
1358 // We must emit temporary symbol for the end of this basic block, if either
1359 // we have BBLabels enabled or if this basic blocks marks the end of a
1360 // section.
1361 if (MF->hasBBLabels() ||
1362 (MAI->hasDotTypeDotSizeDirective() && MBB.isEndSection()))
1363 OutStreamer->emitLabel(MBB.getEndSymbol());
1364
1365 if (MBB.isEndSection()) {
1366 // The size directive for the section containing the entry block is
1367 // handled separately by the function section.
1368 if (!MBB.sameSection(&MF->front())) {
1369 if (MAI->hasDotTypeDotSizeDirective()) {
1370 // Emit the size directive for the basic block section.
1371 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1372 MCSymbolRefExpr::create(MBB.getEndSymbol(), OutContext),
1373 MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
1374 OutContext);
1375 OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1376 }
1377 MBBSectionRanges[MBB.getSectionIDNum()] =
1378 MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
1379 }
1380 }
1381 emitBasicBlockEnd(MBB);
1382
1383 if (CanDoExtraAnalysis) {
1384 // Skip empty blocks.
1385 if (MBB.empty())
1386 continue;
1387
1388 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE"asm-printer", "InstructionMix",
1389 MBB.begin()->getDebugLoc(), &MBB);
1390
1391 // Generate instruction mix remark. First, sort counts in descending order
1392 // by count and name.
1393 SmallVector<std::pair<StringRef, unsigned>, 128> MnemonicVec;
1394 for (auto &KV : MnemonicCounts)
1395 MnemonicVec.emplace_back(KV.first, KV.second);
1396
1397 sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
1398 const std::pair<StringRef, unsigned> &B) {
1399 if (A.second > B.second)
1400 return true;
1401 if (A.second == B.second)
1402 return StringRef(A.first) < StringRef(B.first);
1403 return false;
1404 });
1405 R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
1406 for (auto &KV : MnemonicVec) {
1407 auto Name = (Twine("INST_") + KV.first.trim()).str();
1408 R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
1409 }
1410 ORE->emit(R);
1411 }
1412 }
1413
1414 EmittedInsts += NumInstsInFunction;
1415 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE"asm-printer", "InstructionCount",
1416 MF->getFunction().getSubprogram(),
1417 &MF->front());
1418 R << ore::NV("NumInstructions", NumInstsInFunction)
1419 << " instructions in function";
1420 ORE->emit(R);
1421
1422 // If the function is empty and the object file uses .subsections_via_symbols,
1423 // then we need to emit *something* to the function body to prevent the
1424 // labels from collapsing together. Just emit a noop.
1425 // Similarly, don't emit empty functions on Windows either. It can lead to
1426 // duplicate entries (two functions with the same RVA) in the Guard CF Table
1427 // after linking, causing the kernel not to load the binary:
1428 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1429 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1430 const Triple &TT = TM.getTargetTriple();
1431 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1432 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1433 MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
1434
1435 // Targets can opt-out of emitting the noop here by leaving the opcode
1436 // unspecified.
1437 if (Noop.getOpcode()) {
1438 OutStreamer->AddComment("avoids zero-length function");
1439 emitNops(1);
1440 }
1441 }
1442
1443 // Switch to the original section in case basic block sections was used.
1444 OutStreamer->SwitchSection(MF->getSection());
1445
1446 const Function &F = MF->getFunction();
1447 for (const auto &BB : F) {
1448 if (!BB.hasAddressTaken())
1449 continue;
1450 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
1451 if (Sym->isDefined())
1452 continue;
1453 OutStreamer->AddComment("Address of block that was removed by CodeGen");
1454 OutStreamer->emitLabel(Sym);
1455 }
1456
1457 // Emit target-specific gunk after the function body.
1458 emitFunctionBodyEnd();
1459
1460 if (needFuncLabelsForEHOrDebugInfo(*MF) ||
1461 MAI->hasDotTypeDotSizeDirective()) {
1462 // Create a symbol for the end of function.
1463 CurrentFnEnd = createTempSymbol("func_end");
1464 OutStreamer->emitLabel(CurrentFnEnd);
1465 }
1466
1467 // If the target wants a .size directive for the size of the function, emit
1468 // it.
1469 if (MAI->hasDotTypeDotSizeDirective()) {
1470 // We can get the size as difference between the function label and the
1471 // temp label.
1472 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1473 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1474 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
1475 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1476 }
1477
1478 for (const HandlerInfo &HI : Handlers) {
1479 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1480 HI.TimerGroupDescription, TimePassesIsEnabled);
1481 HI.Handler->markFunctionEnd();
1482 }
1483
1484 MBBSectionRanges[MF->front().getSectionIDNum()] =
1485 MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
1486
1487 // Print out jump tables referenced by the function.
1488 emitJumpTableInfo();
1489
1490 // Emit post-function debug and/or EH information.
1491 for (const HandlerInfo &HI : Handlers) {
1492 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1493 HI.TimerGroupDescription, TimePassesIsEnabled);
1494 HI.Handler->endFunction(MF);
1495 }
1496
1497 // Emit section containing BB address offsets and their metadata, when
1498 // BB labels are requested for this function. Skip empty functions.
1499 if (MF->hasBBLabels() && HasAnyRealCode)
1500 emitBBAddrMapSection(*MF);
1501
1502 // Emit section containing stack size metadata.
1503 emitStackSizeSection(*MF);
1504
1505 // Emit .su file containing function stack size information.
1506 emitStackUsage(*MF);
1507
1508 emitPatchableFunctionEntries();
1509
1510 if (isVerbose())
1511 OutStreamer->GetCommentOS() << "-- End function\n";
1512
1513 OutStreamer->AddBlankLine();
1514}
1515
1516/// Compute the number of Global Variables that uses a Constant.
1517static unsigned getNumGlobalVariableUses(const Constant *C) {
1518 if (!C)
1519 return 0;
1520
1521 if (isa<GlobalVariable>(C))
1522 return 1;
1523
1524 unsigned NumUses = 0;
1525 for (auto *CU : C->users())
1526 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1527
1528 return NumUses;
1529}
1530
1531/// Only consider global GOT equivalents if at least one user is a
1532/// cstexpr inside an initializer of another global variables. Also, don't
1533/// handle cstexpr inside instructions. During global variable emission,
1534/// candidates are skipped and are emitted later in case at least one cstexpr
1535/// isn't replaced by a PC relative GOT entry access.
1536static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1537 unsigned &NumGOTEquivUsers) {
1538 // Global GOT equivalents are unnamed private globals with a constant
1539 // pointer initializer to another global symbol. They must point to a
1540 // GlobalVariable or Function, i.e., as GlobalValue.
1541 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1542 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1543 !isa<GlobalValue>(GV->getOperand(0)))
1544 return false;
1545
1546 // To be a got equivalent, at least one of its users need to be a constant
1547 // expression used by another global variable.
1548 for (auto *U : GV->users())
1549 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1550
1551 return NumGOTEquivUsers > 0;
1552}
1553
1554/// Unnamed constant global variables solely contaning a pointer to
1555/// another globals variable is equivalent to a GOT table entry; it contains the
1556/// the address of another symbol. Optimize it and replace accesses to these
1557/// "GOT equivalents" by using the GOT entry for the final global instead.
1558/// Compute GOT equivalent candidates among all global variables to avoid
1559/// emitting them if possible later on, after it use is replaced by a GOT entry
1560/// access.
1561void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1562 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1563 return;
1564
1565 for (const auto &G : M.globals()) {
1566 unsigned NumGOTEquivUsers = 0;
1567 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1568 continue;
1569
1570 const MCSymbol *GOTEquivSym = getSymbol(&G);
1571 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1572 }
1573}
1574
1575/// Constant expressions using GOT equivalent globals may not be eligible
1576/// for PC relative GOT entry conversion, in such cases we need to emit such
1577/// globals we previously omitted in EmitGlobalVariable.
1578void AsmPrinter::emitGlobalGOTEquivs() {
1579 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1580 return;
1581
1582 SmallVector<const GlobalVariable *, 8> FailedCandidates;
1583 for (auto &I : GlobalGOTEquivs) {
1584 const GlobalVariable *GV = I.second.first;
1585 unsigned Cnt = I.second.second;
1586 if (Cnt)
1587 FailedCandidates.push_back(GV);
1588 }
1589 GlobalGOTEquivs.clear();
1590
1591 for (auto *GV : FailedCandidates)
1592 emitGlobalVariable(GV);
1593}
1594
1595void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1596 const GlobalIndirectSymbol& GIS) {
1597 MCSymbol *Name = getSymbol(&GIS);
1598 bool IsFunction = GIS.getValueType()->isFunctionTy();
1599 // Treat bitcasts of functions as functions also. This is important at least
1600 // on WebAssembly where object and function addresses can't alias each other.
1601 if (!IsFunction)
1602 if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol()))
1603 if (CE->getOpcode() == Instruction::BitCast)
1604 IsFunction =
1605 CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1606
1607 // AIX's assembly directive `.set` is not usable for aliasing purpose,
1608 // so AIX has to use the extra-label-at-definition strategy. At this
1609 // point, all the extra label is emitted, we just have to emit linkage for
1610 // those labels.
1611 if (TM.getTargetTriple().isOSBinFormatXCOFF()) {
1612 assert(!isa<GlobalIFunc>(GIS) && "IFunc is not supported on AIX.")(static_cast <bool> (!isa<GlobalIFunc>(GIS) &&
"IFunc is not supported on AIX.") ? void (0) : __assert_fail
("!isa<GlobalIFunc>(GIS) && \"IFunc is not supported on AIX.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1612, __extension__ __PRETTY_FUNCTION__))
;
1613 assert(MAI->hasVisibilityOnlyWithLinkage() &&(static_cast <bool> (MAI->hasVisibilityOnlyWithLinkage
() && "Visibility should be handled with emitLinkage() on AIX."
) ? void (0) : __assert_fail ("MAI->hasVisibilityOnlyWithLinkage() && \"Visibility should be handled with emitLinkage() on AIX.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
1614 "Visibility should be handled with emitLinkage() on AIX.")(static_cast <bool> (MAI->hasVisibilityOnlyWithLinkage
() && "Visibility should be handled with emitLinkage() on AIX."
) ? void (0) : __assert_fail ("MAI->hasVisibilityOnlyWithLinkage() && \"Visibility should be handled with emitLinkage() on AIX.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
;
1615 emitLinkage(&GIS, Name);
1616 // If it's a function, also emit linkage for aliases of function entry
1617 // point.
1618 if (IsFunction)
1619 emitLinkage(&GIS,
1620 getObjFileLowering().getFunctionEntryPointSymbol(&GIS, TM));
1621 return;
1622 }
1623
1624 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1625 OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1626 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1627 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1628 else
1629 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage")(static_cast <bool> (GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"
) ? void (0) : __assert_fail ("GIS.hasLocalLinkage() && \"Invalid alias or ifunc linkage\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1629, __extension__ __PRETTY_FUNCTION__))
;
1630
1631 // Set the symbol type to function if the alias has a function type.
1632 // This affects codegen when the aliasee is not a function.
1633 if (IsFunction)
1634 OutStreamer->emitSymbolAttribute(Name, isa<GlobalIFunc>(GIS)
1635 ? MCSA_ELF_TypeIndFunction
1636 : MCSA_ELF_TypeFunction);
1637
1638 emitVisibility(Name, GIS.getVisibility());
1639
1640 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1641
1642 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1643 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
1644
1645 // Emit the directives as assignments aka .set:
1646 OutStreamer->emitAssignment(Name, Expr);
1647 MCSymbol *LocalAlias = getSymbolPreferLocal(GIS);
1648 if (LocalAlias != Name)
1649 OutStreamer->emitAssignment(LocalAlias, Expr);
1650
1651 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1652 // If the aliasee does not correspond to a symbol in the output, i.e. the
1653 // alias is not of an object or the aliased object is private, then set the
1654 // size of the alias symbol from the type of the alias. We don't do this in
1655 // other situations as the alias and aliasee having differing types but same
1656 // size may be intentional.
1657 const GlobalObject *BaseObject = GA->getBaseObject();
1658 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1659 (!BaseObject || BaseObject->hasPrivateLinkage())) {
1660 const DataLayout &DL = M.getDataLayout();
1661 uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1662 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1663 }
1664 }
1665}
1666
1667void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) {
1668 if (!RS.needsSection())
1669 return;
1670
1671 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1672
1673 Optional<SmallString<128>> Filename;
1674 if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1675 Filename = *FilenameRef;
1676 sys::fs::make_absolute(*Filename);
1677 assert(!Filename->empty() && "The filename can't be empty.")(static_cast <bool> (!Filename->empty() && "The filename can't be empty."
) ? void (0) : __assert_fail ("!Filename->empty() && \"The filename can't be empty.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1677, __extension__ __PRETTY_FUNCTION__))
;
1678 }
1679
1680 std::string Buf;
1681 raw_string_ostream OS(Buf);
1682 std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1683 Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename))
1684 : RemarkSerializer.metaSerializer(OS);
1685 MetaSerializer->emit();
1686
1687 // Switch to the remarks section.
1688 MCSection *RemarksSection =
1689 OutContext.getObjectFileInfo()->getRemarksSection();
1690 OutStreamer->SwitchSection(RemarksSection);
1691
1692 OutStreamer->emitBinaryData(OS.str());
1693}
1694
1695bool AsmPrinter::doFinalization(Module &M) {
1696 // Set the MachineFunction to nullptr so that we can catch attempted
1697 // accesses to MF specific features at the module level and so that
1698 // we can conditionalize accesses based on whether or not it is nullptr.
1699 MF = nullptr;
1700
1701 // Gather all GOT equivalent globals in the module. We really need two
1702 // passes over the globals: one to compute and another to avoid its emission
1703 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1704 // where the got equivalent shows up before its use.
1705 computeGlobalGOTEquivs(M);
1706
1707 // Emit global variables.
1708 for (const auto &G : M.globals())
1709 emitGlobalVariable(&G);
1710
1711 // Emit remaining GOT equivalent globals.
1712 emitGlobalGOTEquivs();
1713
1714 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1715
1716 // Emit linkage(XCOFF) and visibility info for declarations
1717 for (const Function &F : M) {
1718 if (!F.isDeclarationForLinker())
1719 continue;
1720
1721 MCSymbol *Name = getSymbol(&F);
1722 // Function getSymbol gives us the function descriptor symbol for XCOFF.
1723
1724 if (!TM.getTargetTriple().isOSBinFormatXCOFF()) {
1725 GlobalValue::VisibilityTypes V = F.getVisibility();
1726 if (V == GlobalValue::DefaultVisibility)
1727 continue;
1728
1729 emitVisibility(Name, V, false);
1730 continue;
1731 }
1732
1733 if (F.isIntrinsic())
1734 continue;
1735
1736 // Handle the XCOFF case.
1737 // Variable `Name` is the function descriptor symbol (see above). Get the
1738 // function entry point symbol.
1739 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
1740 // Emit linkage for the function entry point.
1741 emitLinkage(&F, FnEntryPointSym);
1742
1743 // Emit linkage for the function descriptor.
1744 emitLinkage(&F, Name);
1745 }
1746
1747 // Emit the remarks section contents.
1748 // FIXME: Figure out when is the safest time to emit this section. It should
1749 // not come after debug info.
1750 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
1751 emitRemarksSection(*RS);
1752
1753 TLOF.emitModuleMetadata(*OutStreamer, M);
1754
1755 if (TM.getTargetTriple().isOSBinFormatELF()) {
1756 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1757
1758 // Output stubs for external and common global variables.
1759 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1760 if (!Stubs.empty()) {
1761 OutStreamer->SwitchSection(TLOF.getDataSection());
1762 const DataLayout &DL = M.getDataLayout();
1763
1764 emitAlignment(Align(DL.getPointerSize()));
1765 for (const auto &Stub : Stubs) {
1766 OutStreamer->emitLabel(Stub.first);
1767 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1768 DL.getPointerSize());
1769 }
1770 }
1771 }
1772
1773 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1774 MachineModuleInfoCOFF &MMICOFF =
1775 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
1776
1777 // Output stubs for external and common global variables.
1778 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
1779 if (!Stubs.empty()) {
1780 const DataLayout &DL = M.getDataLayout();
1781
1782 for (const auto &Stub : Stubs) {
1783 SmallString<256> SectionName = StringRef(".rdata$");
1784 SectionName += Stub.first->getName();
1785 OutStreamer->SwitchSection(OutContext.getCOFFSection(
1786 SectionName,
1787 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
1788 COFF::IMAGE_SCN_LNK_COMDAT,
1789 SectionKind::getReadOnly(), Stub.first->getName(),
1790 COFF::IMAGE_COMDAT_SELECT_ANY));
1791 emitAlignment(Align(DL.getPointerSize()));
1792 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
1793 OutStreamer->emitLabel(Stub.first);
1794 OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1795 DL.getPointerSize());
1796 }
1797 }
1798 }
1799
1800 // Finalize debug and EH information.
1801 for (const HandlerInfo &HI : Handlers) {
1802 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1803 HI.TimerGroupDescription, TimePassesIsEnabled);
1804 HI.Handler->endModule();
1805 }
1806
1807 // This deletes all the ephemeral handlers that AsmPrinter added, while
1808 // keeping all the user-added handlers alive until the AsmPrinter is
1809 // destroyed.
1810 Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
1811 DD = nullptr;
1812
1813 // If the target wants to know about weak references, print them all.
1814 if (MAI->getWeakRefDirective()) {
1815 // FIXME: This is not lazy, it would be nice to only print weak references
1816 // to stuff that is actually used. Note that doing so would require targets
1817 // to notice uses in operands (due to constant exprs etc). This should
1818 // happen with the MC stuff eventually.
1819
1820 // Print out module-level global objects here.
1821 for (const auto &GO : M.global_objects()) {
1822 if (!GO.hasExternalWeakLinkage())
1823 continue;
1824 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1825 }
1826 }
1827
1828 // Print aliases in topological order, that is, for each alias a = b,
1829 // b must be printed before a.
1830 // This is because on some targets (e.g. PowerPC) linker expects aliases in
1831 // such an order to generate correct TOC information.
1832 SmallVector<const GlobalAlias *, 16> AliasStack;
1833 SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
1834 for (const auto &Alias : M.aliases()) {
1835 for (const GlobalAlias *Cur = &Alias; Cur;
1836 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1837 if (!AliasVisited.insert(Cur).second)
1838 break;
1839 AliasStack.push_back(Cur);
1840 }
1841 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1842 emitGlobalIndirectSymbol(M, *AncestorAlias);
1843 AliasStack.clear();
1844 }
1845 for (const auto &IFunc : M.ifuncs())
1846 emitGlobalIndirectSymbol(M, IFunc);
1847
1848 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1849 assert(MI && "AsmPrinter didn't require GCModuleInfo?")(static_cast <bool> (MI && "AsmPrinter didn't require GCModuleInfo?"
) ? void (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1849, __extension__ __PRETTY_FUNCTION__))
;
1850 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1851 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1852 MP->finishAssembly(M, *MI, *this);
1853
1854 // Emit llvm.ident metadata in an '.ident' directive.
1855 emitModuleIdents(M);
1856
1857 // Emit bytes for llvm.commandline metadata.
1858 emitModuleCommandLines(M);
1859
1860 // Emit __morestack address if needed for indirect calls.
1861 if (MMI->usesMorestackAddr()) {
1862 Align Alignment(1);
1863 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1864 getDataLayout(), SectionKind::getReadOnly(),
1865 /*C=*/nullptr, Alignment);
1866 OutStreamer->SwitchSection(ReadOnlySection);
1867
1868 MCSymbol *AddrSymbol =
1869 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1870 OutStreamer->emitLabel(AddrSymbol);
1871
1872 unsigned PtrSize = MAI->getCodePointerSize();
1873 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1874 PtrSize);
1875 }
1876
1877 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1878 // split-stack is used.
1879 if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
1880 OutStreamer->SwitchSection(
1881 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1882 if (MMI->hasNosplitStack())
1883 OutStreamer->SwitchSection(
1884 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1885 }
1886
1887 // If we don't have any trampolines, then we don't require stack memory
1888 // to be executable. Some targets have a directive to declare this.
1889 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1890 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1891 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1892 OutStreamer->SwitchSection(S);
1893
1894 if (TM.Options.EmitAddrsig) {
1895 // Emit address-significance attributes for all globals.
1896 OutStreamer->emitAddrsig();
1897 for (const GlobalValue &GV : M.global_values()) {
1898 if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() &&
1899 !GV.isThreadLocal() && !GV.hasDLLImportStorageClass() &&
1900 !GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr())
1901 OutStreamer->emitAddrsigSym(getSymbol(&GV));
1902 }
1903 }
1904
1905 // Emit symbol partition specifications (ELF only).
1906 if (TM.getTargetTriple().isOSBinFormatELF()) {
1907 unsigned UniqueID = 0;
1908 for (const GlobalValue &GV : M.global_values()) {
1909 if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1910 GV.getVisibility() != GlobalValue::DefaultVisibility)
1911 continue;
1912
1913 OutStreamer->SwitchSection(
1914 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
1915 "", false, ++UniqueID, nullptr));
1916 OutStreamer->emitBytes(GV.getPartition());
1917 OutStreamer->emitZeros(1);
1918 OutStreamer->emitValue(
1919 MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
1920 MAI->getCodePointerSize());
1921 }
1922 }
1923
1924 // Allow the target to emit any magic that it wants at the end of the file,
1925 // after everything else has gone out.
1926 emitEndOfAsmFile(M);
1927
1928 MMI = nullptr;
1929
1930 OutStreamer->Finish();
1931 OutStreamer->reset();
1932 OwnedMLI.reset();
1933 OwnedMDT.reset();
1934
1935 return false;
1936}
1937
1938MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) {
1939 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
1940 if (Res.second)
1941 Res.first->second = createTempSymbol("exception");
1942 return Res.first->second;
1943}
1944
1945void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1946 this->MF = &MF;
1947 const Function &F = MF.getFunction();
1948
1949 // Get the function symbol.
1950 if (!MAI->needsFunctionDescriptors()) {
1951 CurrentFnSym = getSymbol(&MF.getFunction());
1952 } else {
1953 assert(TM.getTargetTriple().isOSAIX() &&(static_cast <bool> (TM.getTargetTriple().isOSAIX() &&
"Only AIX uses the function descriptor hooks.") ? void (0) :
__assert_fail ("TM.getTargetTriple().isOSAIX() && \"Only AIX uses the function descriptor hooks.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1954, __extension__ __PRETTY_FUNCTION__))
1954 "Only AIX uses the function descriptor hooks.")(static_cast <bool> (TM.getTargetTriple().isOSAIX() &&
"Only AIX uses the function descriptor hooks.") ? void (0) :
__assert_fail ("TM.getTargetTriple().isOSAIX() && \"Only AIX uses the function descriptor hooks.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1954, __extension__ __PRETTY_FUNCTION__))
;
1955 // AIX is unique here in that the name of the symbol emitted for the
1956 // function body does not have the same name as the source function's
1957 // C-linkage name.
1958 assert(CurrentFnDescSym && "The function descriptor symbol needs to be"(static_cast <bool> (CurrentFnDescSym && "The function descriptor symbol needs to be"
" initalized first.") ? void (0) : __assert_fail ("CurrentFnDescSym && \"The function descriptor symbol needs to be\" \" initalized first.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1959, __extension__ __PRETTY_FUNCTION__))
1959 " initalized first.")(static_cast <bool> (CurrentFnDescSym && "The function descriptor symbol needs to be"
" initalized first.") ? void (0) : __assert_fail ("CurrentFnDescSym && \"The function descriptor symbol needs to be\" \" initalized first.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1959, __extension__ __PRETTY_FUNCTION__))
;
1960
1961 // Get the function entry point symbol.
1962 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM);
1963 }
1964
1965 CurrentFnSymForSize = CurrentFnSym;
1966 CurrentFnBegin = nullptr;
1967 CurrentSectionBeginSym = nullptr;
1968 MBBSectionRanges.clear();
1969 MBBSectionExceptionSyms.clear();
1970 bool NeedsLocalForSize = MAI->needsLocalForSize();
1971 if (F.hasFnAttribute("patchable-function-entry") ||
1972 F.hasFnAttribute("function-instrument") ||
1973 F.hasFnAttribute("xray-instruction-threshold") ||
1974 needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize ||
1975 MF.getTarget().Options.EmitStackSizeSection || MF.hasBBLabels()) {
1976 CurrentFnBegin = createTempSymbol("func_begin");
1977 if (NeedsLocalForSize)
1978 CurrentFnSymForSize = CurrentFnBegin;
1979 }
1980
1981 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1982}
1983
1984namespace {
1985
1986// Keep track the alignment, constpool entries per Section.
1987 struct SectionCPs {
1988 MCSection *S;
1989 Align Alignment;
1990 SmallVector<unsigned, 4> CPEs;
1991
1992 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
1993 };
1994
1995} // end anonymous namespace
1996
1997/// EmitConstantPool - Print to the current output stream assembly
1998/// representations of the constants in the constant pool MCP. This is
1999/// used to print out constants which have been "spilled to memory" by
2000/// the code generator.
2001void AsmPrinter::emitConstantPool() {
2002 const MachineConstantPool *MCP = MF->getConstantPool();
2003 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2004 if (CP.empty()) return;
2005
2006 // Calculate sections for constant pool entries. We collect entries to go into
2007 // the same section together to reduce amount of section switch statements.
2008 SmallVector<SectionCPs, 4> CPSections;
2009 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2010 const MachineConstantPoolEntry &CPE = CP[i];
2011 Align Alignment = CPE.getAlign();
2012
2013 SectionKind Kind = CPE.getSectionKind(&getDataLayout());
2014
2015 const Constant *C = nullptr;
2016 if (!CPE.isMachineConstantPoolEntry())
2017 C = CPE.Val.ConstVal;
2018
2019 MCSection *S = getObjFileLowering().getSectionForConstant(
2020 getDataLayout(), Kind, C, Alignment);
2021
2022 // The number of sections are small, just do a linear search from the
2023 // last section to the first.
2024 bool Found = false;
2025 unsigned SecIdx = CPSections.size();
2026 while (SecIdx != 0) {
2027 if (CPSections[--SecIdx].S == S) {
2028 Found = true;
2029 break;
2030 }
2031 }
2032 if (!Found) {
2033 SecIdx = CPSections.size();
2034 CPSections.push_back(SectionCPs(S, Alignment));
2035 }
2036
2037 if (Alignment > CPSections[SecIdx].Alignment)
2038 CPSections[SecIdx].Alignment = Alignment;
2039 CPSections[SecIdx].CPEs.push_back(i);
2040 }
2041
2042 // Now print stuff into the calculated sections.
2043 const MCSection *CurSection = nullptr;
2044 unsigned Offset = 0;
2045 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2046 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2047 unsigned CPI = CPSections[i].CPEs[j];
2048 MCSymbol *Sym = GetCPISymbol(CPI);
2049 if (!Sym->isUndefined())
2050 continue;
2051
2052 if (CurSection != CPSections[i].S) {
2053 OutStreamer->SwitchSection(CPSections[i].S);
2054 emitAlignment(Align(CPSections[i].Alignment));
2055 CurSection = CPSections[i].S;
2056 Offset = 0;
2057 }
2058
2059 MachineConstantPoolEntry CPE = CP[CPI];
2060
2061 // Emit inter-object padding for alignment.
2062 unsigned NewOffset = alignTo(Offset, CPE.getAlign());
2063 OutStreamer->emitZeros(NewOffset - Offset);
2064
2065 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
2066
2067 OutStreamer->emitLabel(Sym);
2068 if (CPE.isMachineConstantPoolEntry())
2069 emitMachineConstantPoolValue(CPE.Val.MachineCPVal);
2070 else
2071 emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
2072 }
2073 }
2074}
2075
2076// Print assembly representations of the jump tables used by the current
2077// function.
2078void AsmPrinter::emitJumpTableInfo() {
2079 const DataLayout &DL = MF->getDataLayout();
2080 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2081 if (!MJTI) return;
2082 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2083 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2084 if (JT.empty()) return;
2085
2086 // Pick the directive to use to print the jump table entries, and switch to
2087 // the appropriate section.
2088 const Function &F = MF->getFunction();
2089 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
2090 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2091 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
2092 F);
2093 if (JTInDiffSection) {
2094 // Drop it in the readonly section.
2095 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2096 OutStreamer->SwitchSection(ReadOnlySection);
2097 }
2098
2099 emitAlignment(Align(MJTI->getEntryAlignment(DL)));
2100
2101 // Jump tables in code sections are marked with a data_region directive
2102 // where that's supported.
2103 if (!JTInDiffSection)
2104 OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2105
2106 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2107 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2108
2109 // If this jump table was deleted, ignore it.
2110 if (JTBBs.empty()) continue;
2111
2112 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2113 /// emit a .set directive for each unique entry.
2114 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
2115 MAI->doesSetDirectiveSuppressReloc()) {
2116 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
2117 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2118 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
2119 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
2120 const MachineBasicBlock *MBB = JTBBs[ii];
2121 if (!EmittedSets.insert(MBB).second)
2122 continue;
2123
2124 // .set LJTSet, LBB32-base
2125 const MCExpr *LHS =
2126 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2127 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2128 MCBinaryExpr::createSub(LHS, Base,
2129 OutContext));
2130 }
2131 }
2132
2133 // On some targets (e.g. Darwin) we want to emit two consecutive labels
2134 // before each jump table. The first label is never referenced, but tells
2135 // the assembler and linker the extents of the jump table object. The
2136 // second label is actually referenced by the code.
2137 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2138 // FIXME: This doesn't have to have any specific name, just any randomly
2139 // named and numbered local label started with 'l' would work. Simplify
2140 // GetJTISymbol.
2141 OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2142
2143 MCSymbol* JTISymbol = GetJTISymbol(JTI);
2144 OutStreamer->emitLabel(JTISymbol);
2145
2146 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
2147 emitJumpTableEntry(MJTI, JTBBs[ii], JTI);
2148 }
2149 if (!JTInDiffSection)
2150 OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2151}
2152
2153/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2154/// current stream.
2155void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2156 const MachineBasicBlock *MBB,
2157 unsigned UID) const {
2158 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block")(static_cast <bool> (MBB && MBB->getNumber()
>= 0 && "Invalid basic block") ? void (0) : __assert_fail
("MBB && MBB->getNumber() >= 0 && \"Invalid basic block\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2158, __extension__ __PRETTY_FUNCTION__))
;
2159 const MCExpr *Value = nullptr;
2160 switch (MJTI->getEntryKind()) {
2161 case MachineJumpTableInfo::EK_Inline:
2162 llvm_unreachable("Cannot emit EK_Inline jump table entry")::llvm::llvm_unreachable_internal("Cannot emit EK_Inline jump table entry"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2162)
;
2163 case MachineJumpTableInfo::EK_Custom32:
2164 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
2165 MJTI, MBB, UID, OutContext);
2166 break;
2167 case MachineJumpTableInfo::EK_BlockAddress:
2168 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2169 // .word LBB123
2170 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2171 break;
2172 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
2173 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2174 // with a relocation as gp-relative, e.g.:
2175 // .gprel32 LBB123
2176 MCSymbol *MBBSym = MBB->getSymbol();
2177 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2178 return;
2179 }
2180
2181 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
2182 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2183 // with a relocation as gp-relative, e.g.:
2184 // .gpdword LBB123
2185 MCSymbol *MBBSym = MBB->getSymbol();
2186 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2187 return;
2188 }
2189
2190 case MachineJumpTableInfo::EK_LabelDifference32: {
2191 // Each entry is the address of the block minus the address of the jump
2192 // table. This is used for PIC jump tables where gprel32 is not supported.
2193 // e.g.:
2194 // .word LBB123 - LJTI1_2
2195 // If the .set directive avoids relocations, this is emitted as:
2196 // .set L4_5_set_123, LBB123 - LJTI1_2
2197 // .word L4_5_set_123
2198 if (MAI->doesSetDirectiveSuppressReloc()) {
2199 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
2200 OutContext);
2201 break;
2202 }
2203 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
2204 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2205 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
2206 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
2207 break;
2208 }
2209 }
2210
2211 assert(Value && "Unknown entry kind!")(static_cast <bool> (Value && "Unknown entry kind!"
) ? void (0) : __assert_fail ("Value && \"Unknown entry kind!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2211, __extension__ __PRETTY_FUNCTION__))
;
2212
2213 unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
2214 OutStreamer->emitValue(Value, EntrySize);
2215}
2216
2217/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2218/// special global used by LLVM. If so, emit it and return true, otherwise
2219/// do nothing and return false.
2220bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
2221 if (GV->getName() == "llvm.used") {
2222 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
2223 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
2224 return true;
2225 }
2226
2227 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2228 if (GV->getSection() == "llvm.metadata" ||
2229 GV->hasAvailableExternallyLinkage())
2230 return true;
2231
2232 if (!GV->hasAppendingLinkage()) return false;
2233
2234 assert(GV->hasInitializer() && "Not a special LLVM global!")(static_cast <bool> (GV->hasInitializer() &&
"Not a special LLVM global!") ? void (0) : __assert_fail ("GV->hasInitializer() && \"Not a special LLVM global!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2234, __extension__ __PRETTY_FUNCTION__))
;
2235
2236 if (GV->getName() == "llvm.global_ctors") {
2237 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2238 /* isCtor */ true);
2239
2240 return true;
2241 }
2242
2243 if (GV->getName() == "llvm.global_dtors") {
2244 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2245 /* isCtor */ false);
2246
2247 return true;
2248 }
2249
2250 report_fatal_error("unknown special variable");
2251}
2252
2253/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2254/// global in the specified llvm.used list.
2255void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2256 // Should be an array of 'i8*'.
2257 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2258 const GlobalValue *GV =
2259 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2260 if (GV)
2261 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2262 }
2263}
2264
2265void AsmPrinter::preprocessXXStructorList(const DataLayout &DL,
2266 const Constant *List,
2267 SmallVector<Structor, 8> &Structors) {
2268 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2269 // the init priority.
2270 if (!isa<ConstantArray>(List))
2271 return;
2272
2273 // Gather the structors in a form that's convenient for sorting by priority.
2274 for (Value *O : cast<ConstantArray>(List)->operands()) {
2275 auto *CS = cast<ConstantStruct>(O);
2276 if (CS->getOperand(1)->isNullValue())
2277 break; // Found a null terminator, skip the rest.
2278 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2279 if (!Priority)
2280 continue; // Malformed.
2281 Structors.push_back(Structor());
2282 Structor &S = Structors.back();
2283 S.Priority = Priority->getLimitedValue(65535);
2284 S.Func = CS->getOperand(1);
2285 if (!CS->getOperand(2)->isNullValue()) {
2286 if (TM.getTargetTriple().isOSAIX())
2287 llvm::report_fatal_error(
2288 "associated data of XXStructor list is not yet supported on AIX");
2289 S.ComdatKey =
2290 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2291 }
2292 }
2293
2294 // Emit the function pointers in the target-specific order
2295 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2296 return L.Priority < R.Priority;
2297 });
2298}
2299
2300/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2301/// priority.
2302void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List,
2303 bool IsCtor) {
2304 SmallVector<Structor, 8> Structors;
2305 preprocessXXStructorList(DL, List, Structors);
2306 if (Structors.empty())
2307 return;
2308
2309 // Emit the structors in reverse order if we are using the .ctor/.dtor
2310 // initialization scheme.
2311 if (!TM.Options.UseInitArray)
2312 std::reverse(Structors.begin(), Structors.end());
2313
2314 const Align Align = DL.getPointerPrefAlignment();
2315 for (Structor &S : Structors) {
2316 const TargetLoweringObjectFile &Obj = getObjFileLowering();
2317 const MCSymbol *KeySym = nullptr;
2318 if (GlobalValue *GV = S.ComdatKey) {
2319 if (GV->isDeclarationForLinker())
2320 // If the associated variable is not defined in this module
2321 // (it might be available_externally, or have been an
2322 // available_externally definition that was dropped by the
2323 // EliminateAvailableExternally pass), some other TU
2324 // will provide its dynamic initializer.
2325 continue;
2326
2327 KeySym = getSymbol(GV);
2328 }
2329
2330 MCSection *OutputSection =
2331 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2332 : Obj.getStaticDtorSection(S.Priority, KeySym));
2333 OutStreamer->SwitchSection(OutputSection);
2334 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2335 emitAlignment(Align);
2336 emitXXStructor(DL, S.Func);
2337 }
2338}
2339
2340void AsmPrinter::emitModuleIdents(Module &M) {
2341 if (!MAI->hasIdentDirective())
2342 return;
2343
2344 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2345 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2346 const MDNode *N = NMD->getOperand(i);
2347 assert(N->getNumOperands() == 1 &&(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.ident metadata entry can have only one operand") ? void
(0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.ident metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2348, __extension__ __PRETTY_FUNCTION__))
2348 "llvm.ident metadata entry can have only one operand")(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.ident metadata entry can have only one operand") ? void
(0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.ident metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2348, __extension__ __PRETTY_FUNCTION__))
;
2349 const MDString *S = cast<MDString>(N->getOperand(0));
2350 OutStreamer->emitIdent(S->getString());
2351 }
2352 }
2353}
2354
2355void AsmPrinter::emitModuleCommandLines(Module &M) {
2356 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
2357 if (!CommandLine)
2358 return;
2359
2360 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2361 if (!NMD || !NMD->getNumOperands())
2362 return;
2363
2364 OutStreamer->PushSection();
2365 OutStreamer->SwitchSection(CommandLine);
2366 OutStreamer->emitZeros(1);
2367 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2368 const MDNode *N = NMD->getOperand(i);
2369 assert(N->getNumOperands() == 1 &&(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.commandline metadata entry can have only one operand")
? void (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.commandline metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2370, __extension__ __PRETTY_FUNCTION__))
2370 "llvm.commandline metadata entry can have only one operand")(static_cast <bool> (N->getNumOperands() == 1 &&
"llvm.commandline metadata entry can have only one operand")
? void (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.commandline metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2370, __extension__ __PRETTY_FUNCTION__))
;
2371 const MDString *S = cast<MDString>(N->getOperand(0));
2372 OutStreamer->emitBytes(S->getString());
2373 OutStreamer->emitZeros(1);
2374 }
2375 OutStreamer->PopSection();
2376}
2377
2378//===--------------------------------------------------------------------===//
2379// Emission and print routines
2380//
2381
2382/// Emit a byte directive and value.
2383///
2384void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2385
2386/// Emit a short directive and value.
2387void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2388
2389/// Emit a long directive and value.
2390void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2391
2392/// Emit a long long directive and value.
2393void AsmPrinter::emitInt64(uint64_t Value) const {
2394 OutStreamer->emitInt64(Value);
2395}
2396
2397/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2398/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2399/// .set if it avoids relocations.
2400void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
2401 unsigned Size) const {
2402 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2403}
2404
2405/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2406/// where the size in bytes of the directive is specified by Size and Label
2407/// specifies the label. This implicitly uses .set if it is available.
2408void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
2409 unsigned Size,
2410 bool IsSectionRelative) const {
2411 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2412 OutStreamer->EmitCOFFSecRel32(Label, Offset);
2413 if (Size > 4)
2414 OutStreamer->emitZeros(Size - 4);
2415 return;
2416 }
2417
2418 // Emit Label+Offset (or just Label if Offset is zero)
2419 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2420 if (Offset)
2421 Expr = MCBinaryExpr::createAdd(
2422 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2423
2424 OutStreamer->emitValue(Expr, Size);
2425}
2426
2427//===----------------------------------------------------------------------===//
2428
2429// EmitAlignment - Emit an alignment directive to the specified power of
2430// two boundary. If a global value is specified, and if that global has
2431// an explicit alignment requested, it will override the alignment request
2432// if required for correctness.
2433void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const {
2434 if (GV)
2435 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2436
2437 if (Alignment == Align(1))
2438 return; // 1-byte aligned: no need to emit alignment.
2439
2440 if (getCurrentSection()->getKind().isText())
2441 OutStreamer->emitCodeAlignment(Alignment.value());
2442 else
2443 OutStreamer->emitValueToAlignment(Alignment.value());
2444}
2445
2446//===----------------------------------------------------------------------===//
2447// Constant emission.
2448//===----------------------------------------------------------------------===//
2449
2450const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
2451 MCContext &Ctx = OutContext;
2452
2453 if (CV->isNullValue() || isa<UndefValue>(CV))
2454 return MCConstantExpr::create(0, Ctx);
2455
2456 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2457 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2458
2459 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2460 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2461
2462 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2463 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
2464
2465 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
2466 return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM);
2467
2468 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2469 if (!CE) {
2470 llvm_unreachable("Unknown constant value to lower!")::llvm::llvm_unreachable_internal("Unknown constant value to lower!"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2470)
;
2471 }
2472
2473 switch (CE->getOpcode()) {
2474 case Instruction::AddrSpaceCast: {
2475 const Constant *Op = CE->getOperand(0);
2476 unsigned DstAS = CE->getType()->getPointerAddressSpace();
2477 unsigned SrcAS = Op->getType()->getPointerAddressSpace();
2478 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
2479 return lowerConstant(Op);
2480
2481 // Fallthrough to error.
2482 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2483 }
2484 default: {
2485 // If the code isn't optimized, there may be outstanding folding
2486 // opportunities. Attempt to fold the expression using DataLayout as a
2487 // last resort before giving up.
2488 Constant *C = ConstantFoldConstant(CE, getDataLayout());
2489 if (C != CE)
2490 return lowerConstant(C);
2491
2492 // Otherwise report the problem to the user.
2493 std::string S;
2494 raw_string_ostream OS(S);
2495 OS << "Unsupported expression in static initializer: ";
2496 CE->printAsOperand(OS, /*PrintType=*/false,
2497 !MF ? nullptr : MF->getFunction().getParent());
2498 report_fatal_error(OS.str());
2499 }
2500 case Instruction::GetElementPtr: {
2501 // Generate a symbolic expression for the byte address
2502 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2503 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2504
2505 const MCExpr *Base = lowerConstant(CE->getOperand(0));
2506 if (!OffsetAI)
2507 return Base;
2508
2509 int64_t Offset = OffsetAI.getSExtValue();
2510 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2511 Ctx);
2512 }
2513
2514 case Instruction::Trunc:
2515 // We emit the value and depend on the assembler to truncate the generated
2516 // expression properly. This is important for differences between
2517 // blockaddress labels. Since the two labels are in the same function, it
2518 // is reasonable to treat their delta as a 32-bit value.
2519 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2520 case Instruction::BitCast:
2521 return lowerConstant(CE->getOperand(0));
2522
2523 case Instruction::IntToPtr: {
2524 const DataLayout &DL = getDataLayout();
2525
2526 // Handle casts to pointers by changing them into casts to the appropriate
2527 // integer type. This promotes constant folding and simplifies this code.
2528 Constant *Op = CE->getOperand(0);
2529 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2530 false/*ZExt*/);
2531 return lowerConstant(Op);
2532 }
2533
2534 case Instruction::PtrToInt: {
2535 const DataLayout &DL = getDataLayout();
2536
2537 // Support only foldable casts to/from pointers that can be eliminated by
2538 // changing the pointer to the appropriately sized integer type.
2539 Constant *Op = CE->getOperand(0);
2540 Type *Ty = CE->getType();
2541
2542 const MCExpr *OpExpr = lowerConstant(Op);
2543
2544 // We can emit the pointer value into this slot if the slot is an
2545 // integer slot equal to the size of the pointer.
2546 //
2547 // If the pointer is larger than the resultant integer, then
2548 // as with Trunc just depend on the assembler to truncate it.
2549 if (DL.getTypeAllocSize(Ty).getFixedSize() <=
2550 DL.getTypeAllocSize(Op->getType()).getFixedSize())
2551 return OpExpr;
2552
2553 // Otherwise the pointer is smaller than the resultant integer, mask off
2554 // the high bits so we are sure to get a proper truncation if the input is
2555 // a constant expr.
2556 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2557 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2558 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2559 }
2560
2561 case Instruction::Sub: {
2562 GlobalValue *LHSGV;
2563 APInt LHSOffset;
2564 DSOLocalEquivalent *DSOEquiv;
2565 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2566 getDataLayout(), &DSOEquiv)) {
2567 GlobalValue *RHSGV;
2568 APInt RHSOffset;
2569 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2570 getDataLayout())) {
2571 const MCExpr *RelocExpr =
2572 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2573 if (!RelocExpr) {
2574 const MCExpr *LHSExpr =
2575 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
2576 if (DSOEquiv &&
2577 getObjFileLowering().supportDSOLocalEquivalentLowering())
2578 LHSExpr =
2579 getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM);
2580 RelocExpr = MCBinaryExpr::createSub(
2581 LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2582 }
2583 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2584 if (Addend != 0)
2585 RelocExpr = MCBinaryExpr::createAdd(
2586 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2587 return RelocExpr;
2588 }
2589 }
2590 }
2591 // else fallthrough
2592 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2593
2594 // The MC library also has a right-shift operator, but it isn't consistently
2595 // signed or unsigned between different targets.
2596 case Instruction::Add:
2597 case Instruction::Mul:
2598 case Instruction::SDiv:
2599 case Instruction::SRem:
2600 case Instruction::Shl:
2601 case Instruction::And:
2602 case Instruction::Or:
2603 case Instruction::Xor: {
2604 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2605 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2606 switch (CE->getOpcode()) {
2607 default: llvm_unreachable("Unknown binary operator constant cast expr")::llvm::llvm_unreachable_internal("Unknown binary operator constant cast expr"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2607)
;
2608 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2609 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2610 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2611 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2612 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2613 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2614 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2615 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2616 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2617 }
2618 }
2619 }
2620}
2621
2622static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2623 AsmPrinter &AP,
2624 const Constant *BaseCV = nullptr,
2625 uint64_t Offset = 0);
2626
2627static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2628static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2629
2630/// isRepeatedByteSequence - Determine whether the given value is
2631/// composed of a repeated sequence of identical bytes and return the
2632/// byte value. If it is not a repeated sequence, return -1.
2633static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2634 StringRef Data = V->getRawDataValues();
2635 assert(!Data.empty() && "Empty aggregates should be CAZ node")(static_cast <bool> (!Data.empty() && "Empty aggregates should be CAZ node"
) ? void (0) : __assert_fail ("!Data.empty() && \"Empty aggregates should be CAZ node\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2635, __extension__ __PRETTY_FUNCTION__))
;
2636 char C = Data[0];
2637 for (unsigned i = 1, e = Data.size(); i != e; ++i)
2638 if (Data[i] != C) return -1;
2639 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2640}
2641
2642/// isRepeatedByteSequence - Determine whether the given value is
2643/// composed of a repeated sequence of identical bytes and return the
2644/// byte value. If it is not a repeated sequence, return -1.
2645static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2646 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2647 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2648 assert(Size % 8 == 0)(static_cast <bool> (Size % 8 == 0) ? void (0) : __assert_fail
("Size % 8 == 0", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2648, __extension__ __PRETTY_FUNCTION__))
;
2649
2650 // Extend the element to take zero padding into account.
2651 APInt Value = CI->getValue().zextOrSelf(Size);
2652 if (!Value.isSplat(8))
2653 return -1;
2654
2655 return Value.zextOrTrunc(8).getZExtValue();
2656 }
2657 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2658 // Make sure all array elements are sequences of the same repeated
2659 // byte.
2660 assert(CA->getNumOperands() != 0 && "Should be a CAZ")(static_cast <bool> (CA->getNumOperands() != 0 &&
"Should be a CAZ") ? void (0) : __assert_fail ("CA->getNumOperands() != 0 && \"Should be a CAZ\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2660, __extension__ __PRETTY_FUNCTION__))
;
2661 Constant *Op0 = CA->getOperand(0);
2662 int Byte = isRepeatedByteSequence(Op0, DL);
2663 if (Byte == -1)
2664 return -1;
2665
2666 // All array elements must be equal.
2667 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2668 if (CA->getOperand(i) != Op0)
2669 return -1;
2670 return Byte;
2671 }
2672
2673 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2674 return isRepeatedByteSequence(CDS);
2675
2676 return -1;
2677}
2678
2679static void emitGlobalConstantDataSequential(const DataLayout &DL,
2680 const ConstantDataSequential *CDS,
2681 AsmPrinter &AP) {
2682 // See if we can aggregate this into a .fill, if so, emit it as such.
2683 int Value = isRepeatedByteSequence(CDS, DL);
2684 if (Value != -1) {
2685 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2686 // Don't emit a 1-byte object as a .fill.
2687 if (Bytes > 1)
2688 return AP.OutStreamer->emitFill(Bytes, Value);
2689 }
2690
2691 // If this can be emitted with .ascii/.asciz, emit it as such.
2692 if (CDS->isString())
2693 return AP.OutStreamer->emitBytes(CDS->getAsString());
2694
2695 // Otherwise, emit the values in successive locations.
2696 unsigned ElementByteSize = CDS->getElementByteSize();
2697 if (isa<IntegerType>(CDS->getElementType())) {
2698 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2699 if (AP.isVerbose())
2700 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64"l" "x" "\n",
2701 CDS->getElementAsInteger(i));
2702 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i),
2703 ElementByteSize);
2704 }
2705 } else {
2706 Type *ET = CDS->getElementType();
2707 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2708 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
2709 }
2710
2711 unsigned Size = DL.getTypeAllocSize(CDS->getType());
2712 unsigned EmittedSize =
2713 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
2714 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!")(static_cast <bool> (EmittedSize <= Size && "Size cannot be less than EmittedSize!"
) ? void (0) : __assert_fail ("EmittedSize <= Size && \"Size cannot be less than EmittedSize!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2714, __extension__ __PRETTY_FUNCTION__))
;
2715 if (unsigned Padding = Size - EmittedSize)
2716 AP.OutStreamer->emitZeros(Padding);
2717}
2718
2719static void emitGlobalConstantArray(const DataLayout &DL,
2720 const ConstantArray *CA, AsmPrinter &AP,
2721 const Constant *BaseCV, uint64_t Offset) {
2722 // See if we can aggregate some values. Make sure it can be
2723 // represented as a series of bytes of the constant value.
2724 int Value = isRepeatedByteSequence(CA, DL);
2725
2726 if (Value != -1) {
2727 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2728 AP.OutStreamer->emitFill(Bytes, Value);
2729 }
2730 else {
2731 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2732 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2733 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2734 }
2735 }
2736}
2737
2738static void emitGlobalConstantVector(const DataLayout &DL,
2739 const ConstantVector *CV, AsmPrinter &AP) {
2740 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2741 emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2742
2743 unsigned Size = DL.getTypeAllocSize(CV->getType());
2744 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2745 CV->getType()->getNumElements();
2746 if (unsigned Padding = Size - EmittedSize)
2747 AP.OutStreamer->emitZeros(Padding);
2748}
2749
2750static void emitGlobalConstantStruct(const DataLayout &DL,
2751 const ConstantStruct *CS, AsmPrinter &AP,
2752 const Constant *BaseCV, uint64_t Offset) {
2753 // Print the fields in successive locations. Pad to align if needed!
2754 unsigned Size = DL.getTypeAllocSize(CS->getType());
2755 const StructLayout *Layout = DL.getStructLayout(CS->getType());
2756 uint64_t SizeSoFar = 0;
2757 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2758 const Constant *Field = CS->getOperand(i);
2759
2760 // Print the actual field value.
2761 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2762
2763 // Check if padding is needed and insert one or more 0s.
2764 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2765 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2766 - Layout->getElementOffset(i)) - FieldSize;
2767 SizeSoFar += FieldSize + PadSize;
2768
2769 // Insert padding - this may include padding to increase the size of the
2770 // current field up to the ABI size (if the struct is not packed) as well
2771 // as padding to ensure that the next field starts at the right offset.
2772 AP.OutStreamer->emitZeros(PadSize);
2773 }
2774 assert(SizeSoFar == Layout->getSizeInBytes() &&(static_cast <bool> (SizeSoFar == Layout->getSizeInBytes
() && "Layout of constant struct may be incorrect!") ?
void (0) : __assert_fail ("SizeSoFar == Layout->getSizeInBytes() && \"Layout of constant struct may be incorrect!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2775, __extension__ __PRETTY_FUNCTION__))
2775 "Layout of constant struct may be incorrect!")(static_cast <bool> (SizeSoFar == Layout->getSizeInBytes
() && "Layout of constant struct may be incorrect!") ?
void (0) : __assert_fail ("SizeSoFar == Layout->getSizeInBytes() && \"Layout of constant struct may be incorrect!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2775, __extension__ __PRETTY_FUNCTION__))
;
2776}
2777
2778static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2779 assert(ET && "Unknown float type")(static_cast <bool> (ET && "Unknown float type"
) ? void (0) : __assert_fail ("ET && \"Unknown float type\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2779, __extension__ __PRETTY_FUNCTION__))
;
2780 APInt API = APF.bitcastToAPInt();
2781
2782 // First print a comment with what we think the original floating-point value
2783 // should have been.
2784 if (AP.isVerbose()) {
2785 SmallString<8> StrVal;
2786 APF.toString(StrVal);
2787 ET->print(AP.OutStreamer->GetCommentOS());
2788 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2789 }
2790
2791 // Now iterate through the APInt chunks, emitting them in endian-correct
2792 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2793 // floats).
2794 unsigned NumBytes = API.getBitWidth() / 8;
2795 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2796 const uint64_t *p = API.getRawData();
2797
2798 // PPC's long double has odd notions of endianness compared to how LLVM
2799 // handles it: p[0] goes first for *big* endian on PPC.
2800 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2801 int Chunk = API.getNumWords() - 1;
2802
2803 if (TrailingBytes)
2804 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2805
2806 for (; Chunk >= 0; --Chunk)
2807 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2808 } else {
2809 unsigned Chunk;
2810 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2811 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2812
2813 if (TrailingBytes)
2814 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2815 }
2816
2817 // Emit the tail padding for the long double.
2818 const DataLayout &DL = AP.getDataLayout();
2819 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2820}
2821
2822static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2823 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2824}
2825
2826static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2827 const DataLayout &DL = AP.getDataLayout();
2828 unsigned BitWidth = CI->getBitWidth();
2829
2830 // Copy the value as we may massage the layout for constants whose bit width
2831 // is not a multiple of 64-bits.
2832 APInt Realigned(CI->getValue());
2833 uint64_t ExtraBits = 0;
2834 unsigned ExtraBitsSize = BitWidth & 63;
2835
2836 if (ExtraBitsSize) {
2837 // The bit width of the data is not a multiple of 64-bits.
2838 // The extra bits are expected to be at the end of the chunk of the memory.
2839 // Little endian:
2840 // * Nothing to be done, just record the extra bits to emit.
2841 // Big endian:
2842 // * Record the extra bits to emit.
2843 // * Realign the raw data to emit the chunks of 64-bits.
2844 if (DL.isBigEndian()) {
2845 // Basically the structure of the raw data is a chunk of 64-bits cells:
2846 // 0 1 BitWidth / 64
2847 // [chunk1][chunk2] ... [chunkN].
2848 // The most significant chunk is chunkN and it should be emitted first.
2849 // However, due to the alignment issue chunkN contains useless bits.
2850 // Realign the chunks so that they contain only useful information:
2851 // ExtraBits 0 1 (BitWidth / 64) - 1
2852 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2853 ExtraBitsSize = alignTo(ExtraBitsSize, 8);
2854 ExtraBits = Realigned.getRawData()[0] &
2855 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2856 Realigned.lshrInPlace(ExtraBitsSize);
2857 } else
2858 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2859 }
2860
2861 // We don't expect assemblers to support integer data directives
2862 // for more than 64 bits, so we emit the data in at most 64-bit
2863 // quantities at a time.
2864 const uint64_t *RawData = Realigned.getRawData();
2865 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2866 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2867 AP.OutStreamer->emitIntValue(Val, 8);
2868 }
2869
2870 if (ExtraBitsSize) {
2871 // Emit the extra bits after the 64-bits chunks.
2872
2873 // Emit a directive that fills the expected size.
2874 uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType());
2875 Size -= (BitWidth / 64) * 8;
2876 assert(Size && Size * 8 >= ExtraBitsSize &&(static_cast <bool> (Size && Size * 8 >= ExtraBitsSize
&& (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize
))) == ExtraBits && "Directive too small for extra bits."
) ? void (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2878, __extension__ __PRETTY_FUNCTION__))
2877 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))(static_cast <bool> (Size && Size * 8 >= ExtraBitsSize
&& (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize
))) == ExtraBits && "Directive too small for extra bits."
) ? void (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2878, __extension__ __PRETTY_FUNCTION__))
2878 == ExtraBits && "Directive too small for extra bits.")(static_cast <bool> (Size && Size * 8 >= ExtraBitsSize
&& (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize
))) == ExtraBits && "Directive too small for extra bits."
) ? void (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2878, __extension__ __PRETTY_FUNCTION__))
;
2879 AP.OutStreamer->emitIntValue(ExtraBits, Size);
2880 }
2881}
2882
2883/// Transform a not absolute MCExpr containing a reference to a GOT
2884/// equivalent global, by a target specific GOT pc relative access to the
2885/// final symbol.
2886static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2887 const Constant *BaseCst,
2888 uint64_t Offset) {
2889 // The global @foo below illustrates a global that uses a got equivalent.
2890 //
2891 // @bar = global i32 42
2892 // @gotequiv = private unnamed_addr constant i32* @bar
2893 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2894 // i64 ptrtoint (i32* @foo to i64))
2895 // to i32)
2896 //
2897 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2898 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2899 // form:
2900 //
2901 // foo = cstexpr, where
2902 // cstexpr := <gotequiv> - "." + <cst>
2903 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2904 //
2905 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2906 //
2907 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2908 // gotpcrelcst := <offset from @foo base> + <cst>
2909 MCValue MV;
2910 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2911 return;
2912 const MCSymbolRefExpr *SymA = MV.getSymA();
2913 if (!SymA)
2914 return;
2915
2916 // Check that GOT equivalent symbol is cached.
2917 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2918 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2919 return;
2920
2921 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2922 if (!BaseGV)
2923 return;
2924
2925 // Check for a valid base symbol
2926 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2927 const MCSymbolRefExpr *SymB = MV.getSymB();
2928
2929 if (!SymB || BaseSym != &SymB->getSymbol())
2930 return;
2931
2932 // Make sure to match:
2933 //
2934 // gotpcrelcst := <offset from @foo base> + <cst>
2935 //
2936 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2937 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2938 // if the target knows how to encode it.
2939 int64_t GOTPCRelCst = Offset + MV.getConstant();
2940 if (GOTPCRelCst < 0)
2941 return;
2942 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2943 return;
2944
2945 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2946 //
2947 // bar:
2948 // .long 42
2949 // gotequiv:
2950 // .quad bar
2951 // foo:
2952 // .long gotequiv - "." + <cst>
2953 //
2954 // is replaced by the target specific equivalent to:
2955 //
2956 // bar:
2957 // .long 42
2958 // foo:
2959 // .long bar@GOTPCREL+<gotpcrelcst>
2960 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2961 const GlobalVariable *GV = Result.first;
2962 int NumUses = (int)Result.second;
2963 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2964 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2965 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2966 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2967
2968 // Update GOT equivalent usage information
2969 --NumUses;
2970 if (NumUses >= 0)
2971 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2972}
2973
2974static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2975 AsmPrinter &AP, const Constant *BaseCV,
2976 uint64_t Offset) {
2977 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2978
2979 // Globals with sub-elements such as combinations of arrays and structs
2980 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2981 // constant symbol base and the current position with BaseCV and Offset.
2982 if (!BaseCV && CV->hasOneUse())
2983 BaseCV = dyn_cast<Constant>(CV->user_back());
2984
2985 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2986 return AP.OutStreamer->emitZeros(Size);
2987
2988 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2989 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
2990
2991 if (StoreSize <= 8) {
2992 if (AP.isVerbose())
2993 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64"l" "x" "\n",
2994 CI->getZExtValue());
2995 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
2996 } else {
2997 emitGlobalConstantLargeInt(CI, AP);
2998 }
2999
3000 // Emit tail padding if needed
3001 if (Size != StoreSize)
3002 AP.OutStreamer->emitZeros(Size - StoreSize);
3003
3004 return;
3005 }
3006
3007 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
3008 return emitGlobalConstantFP(CFP, AP);
3009
3010 if (isa<ConstantPointerNull>(CV)) {
3011 AP.OutStreamer->emitIntValue(0, Size);
3012 return;
3013 }
3014
3015 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
3016 return emitGlobalConstantDataSequential(DL, CDS, AP);
3017
3018 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
3019 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
3020
3021 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
3022 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
3023
3024 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3025 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3026 // vectors).
3027 if (CE->getOpcode() == Instruction::BitCast)
3028 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
3029
3030 if (Size > 8) {
3031 // If the constant expression's size is greater than 64-bits, then we have
3032 // to emit the value in chunks. Try to constant fold the value and emit it
3033 // that way.
3034 Constant *New = ConstantFoldConstant(CE, DL);
3035 if (New != CE)
3036 return emitGlobalConstantImpl(DL, New, AP);
3037 }
3038 }
3039
3040 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
3041 return emitGlobalConstantVector(DL, V, AP);
3042
3043 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3044 // thread the streamer with EmitValue.
3045 const MCExpr *ME = AP.lowerConstant(CV);
3046
3047 // Since lowerConstant already folded and got rid of all IR pointer and
3048 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3049 // directly.
3050 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
3051 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
3052
3053 AP.OutStreamer->emitValue(ME, Size);
3054}
3055
3056/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3057void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) {
3058 uint64_t Size = DL.getTypeAllocSize(CV->getType());
3059 if (Size)
3060 emitGlobalConstantImpl(DL, CV, *this);
3061 else if (MAI->hasSubsectionsViaSymbols()) {
3062 // If the global has zero size, emit a single byte so that two labels don't
3063 // look like they are at the same location.
3064 OutStreamer->emitIntValue(0, 1);
3065 }
3066}
3067
3068void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
3069 // Target doesn't support this yet!
3070 llvm_unreachable("Target does not support EmitMachineConstantPoolValue")::llvm::llvm_unreachable_internal("Target does not support EmitMachineConstantPoolValue"
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3070)
;
3071}
3072
3073void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
3074 if (Offset > 0)
3075 OS << '+' << Offset;
3076 else if (Offset < 0)
3077 OS << Offset;
3078}
3079
3080void AsmPrinter::emitNops(unsigned N) {
3081 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop();
3082 for (; N; --N)
3083 EmitToStreamer(*OutStreamer, Nop);
3084}
3085
3086//===----------------------------------------------------------------------===//
3087// Symbol Lowering Routines.
3088//===----------------------------------------------------------------------===//
3089
3090MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
3091 return OutContext.createTempSymbol(Name, true);
3092}
3093
3094MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
3095 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
3096}
3097
3098MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
3099 return MMI->getAddrLabelSymbol(BB);
3100}
3101
3102/// GetCPISymbol - Return the symbol for the specified constant pool entry.
3103MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3104 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3105 const MachineConstantPoolEntry &CPE =
3106 MF->getConstantPool()->getConstants()[CPID];
3107 if (!CPE.isMachineConstantPoolEntry()) {
3108 const DataLayout &DL = MF->getDataLayout();
3109 SectionKind Kind = CPE.getSectionKind(&DL);
3110 const Constant *C = CPE.Val.ConstVal;
3111 Align Alignment = CPE.Alignment;
3112 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3113 getObjFileLowering().getSectionForConstant(DL, Kind, C,
3114 Alignment))) {
3115 if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3116 if (Sym->isUndefined())
3117 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
3118 return Sym;
3119 }
3120 }
3121 }
3122 }
3123
3124 const DataLayout &DL = getDataLayout();
3125 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3126 "CPI" + Twine(getFunctionNumber()) + "_" +
3127 Twine(CPID));
3128}
3129
3130/// GetJTISymbol - Return the symbol for the specified jump table entry.
3131MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3132 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
3133}
3134
3135/// GetJTSetSymbol - Return the symbol for the specified jump table .set
3136/// FIXME: privatize to AsmPrinter.
3137MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3138 const DataLayout &DL = getDataLayout();
3139 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3140 Twine(getFunctionNumber()) + "_" +
3141 Twine(UID) + "_set_" + Twine(MBBID));
3142}
3143
3144MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
3145 StringRef Suffix) const {
3146 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3147}
3148
3149/// Return the MCSymbol for the specified ExternalSymbol.
3150MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
3151 SmallString<60> NameStr;
3152 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
3153 return OutContext.getOrCreateSymbol(NameStr);
3154}
3155
3156/// PrintParentLoopComment - Print comments about parent loops of this one.
3157static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3158 unsigned FunctionNumber) {
3159 if (!Loop) return;
3160 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
3161 OS.indent(Loop->getLoopDepth()*2)
3162 << "Parent Loop BB" << FunctionNumber << "_"
3163 << Loop->getHeader()->getNumber()
3164 << " Depth=" << Loop->getLoopDepth() << '\n';
3165}
3166
3167/// PrintChildLoopComment - Print comments about child loops within
3168/// the loop for this basic block, with nesting.
3169static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
3170 unsigned FunctionNumber) {
3171 // Add child loop information
3172 for (const MachineLoop *CL : *Loop) {
3173 OS.indent(CL->getLoopDepth()*2)
3174 << "Child Loop BB" << FunctionNumber << "_"
3175 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3176 << '\n';
3177 PrintChildLoopComment(OS, CL, FunctionNumber);
3178 }
3179}
3180
3181/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3182static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
3183 const MachineLoopInfo *LI,
3184 const AsmPrinter &AP) {
3185 // Add loop depth information
3186 const MachineLoop *Loop = LI->getLoopFor(&MBB);
3187 if (!Loop) return;
3188
3189 MachineBasicBlock *Header = Loop->getHeader();
3190 assert(Header && "No header for loop")(static_cast <bool> (Header && "No header for loop"
) ? void (0) : __assert_fail ("Header && \"No header for loop\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3190, __extension__ __PRETTY_FUNCTION__))
;
3191
3192 // If this block is not a loop header, just print out what is the loop header
3193 // and return.
3194 if (Header != &MBB) {
3195 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
3196 Twine(AP.getFunctionNumber())+"_" +
3197 Twine(Loop->getHeader()->getNumber())+
3198 " Depth="+Twine(Loop->getLoopDepth()));
3199 return;
3200 }
3201
3202 // Otherwise, it is a loop header. Print out information about child and
3203 // parent loops.
3204 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
3205
3206 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
3207
3208 OS << "=>";
3209 OS.indent(Loop->getLoopDepth()*2-2);
3210
3211 OS << "This ";
3212 if (Loop->isInnermost())
3213 OS << "Inner ";
3214 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3215
3216 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
3217}
3218
3219/// emitBasicBlockStart - This method prints the label for the specified
3220/// MachineBasicBlock, an alignment (if present) and a comment describing
3221/// it if appropriate.
3222void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
3223 // End the previous funclet and start a new one.
3224 if (MBB.isEHFuncletEntry()) {
3225 for (const HandlerInfo &HI : Handlers) {
3226 HI.Handler->endFunclet();
3227 HI.Handler->beginFunclet(MBB);
3228 }
3229 }
3230
3231 // Emit an alignment directive for this block, if needed.
3232 const Align Alignment = MBB.getAlignment();
3233 if (Alignment != Align(1))
3234 emitAlignment(Alignment);
3235
3236 // Switch to a new section if this basic block must begin a section. The
3237 // entry block is always placed in the function section and is handled
3238 // separately.
3239 if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3240 OutStreamer->SwitchSection(
3241 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3242 MBB, TM));
3243 CurrentSectionBeginSym = MBB.getSymbol();
3244 }
3245
3246 // If the block has its address taken, emit any labels that were used to
3247 // reference the block. It is possible that there is more than one label
3248 // here, because multiple LLVM BB's may have been RAUW'd to this block after
3249 // the references were generated.
3250 if (MBB.hasAddressTaken()) {
3251 const BasicBlock *BB = MBB.getBasicBlock();
3252 if (isVerbose())
3253 OutStreamer->AddComment("Block address taken");
3254
3255 // MBBs can have their address taken as part of CodeGen without having
3256 // their corresponding BB's address taken in IR
3257 if (BB->hasAddressTaken())
3258 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3259 OutStreamer->emitLabel(Sym);
3260 }
3261
3262 // Print some verbose block comments.
3263 if (isVerbose()) {
3264 if (const BasicBlock *BB = MBB.getBasicBlock()) {
3265 if (BB->hasName()) {
3266 BB->printAsOperand(OutStreamer->GetCommentOS(),
3267 /*PrintType=*/false, BB->getModule());
3268 OutStreamer->GetCommentOS() << '\n';
3269 }
3270 }
3271
3272 assert(MLI != nullptr && "MachineLoopInfo should has been computed")(static_cast <bool> (MLI != nullptr && "MachineLoopInfo should has been computed"
) ? void (0) : __assert_fail ("MLI != nullptr && \"MachineLoopInfo should has been computed\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3272, __extension__ __PRETTY_FUNCTION__))
;
3273 emitBasicBlockLoopComments(MBB, MLI, *this);
3274 }
3275
3276 // Print the main label for the block.
3277 if (shouldEmitLabelForBasicBlock(MBB)) {
3278 if (isVerbose() && MBB.hasLabelMustBeEmitted())
3279 OutStreamer->AddComment("Label of block must be emitted");
3280 OutStreamer->emitLabel(MBB.getSymbol());
3281 } else {
3282 if (isVerbose()) {
3283 // NOTE: Want this comment at start of line, don't emit with AddComment.
3284 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3285 false);
3286 }
3287 }
3288
3289 if (MBB.isEHCatchretTarget() &&
3290 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) {
3291 OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
3292 }
3293
3294 // With BB sections, each basic block must handle CFI information on its own
3295 // if it begins a section (Entry block is handled separately by
3296 // AsmPrinterHandler::beginFunction).
3297 if (MBB.isBeginSection() && !MBB.isEntryBlock())
3298 for (const HandlerInfo &HI : Handlers)
3299 HI.Handler->beginBasicBlock(MBB);
3300}
3301
3302void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
3303 // Check if CFI information needs to be updated for this MBB with basic block
3304 // sections.
3305 if (MBB.isEndSection())
3306 for (const HandlerInfo &HI : Handlers)
3307 HI.Handler->endBasicBlock(MBB);
3308}
3309
3310void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3311 bool IsDefinition) const {
3312 MCSymbolAttr Attr = MCSA_Invalid;
3313
3314 switch (Visibility) {
3315 default: break;
3316 case GlobalValue::HiddenVisibility:
3317 if (IsDefinition)
3318 Attr = MAI->getHiddenVisibilityAttr();
3319 else
3320 Attr = MAI->getHiddenDeclarationVisibilityAttr();
3321 break;
3322 case GlobalValue::ProtectedVisibility:
3323 Attr = MAI->getProtectedVisibilityAttr();
3324 break;
3325 }
3326
3327 if (Attr != MCSA_Invalid)
3328 OutStreamer->emitSymbolAttribute(Sym, Attr);
3329}
3330
3331bool AsmPrinter::shouldEmitLabelForBasicBlock(
3332 const MachineBasicBlock &MBB) const {
3333 // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3334 // in the labels mode (option `=labels`) and every section beginning in the
3335 // sections mode (`=all` and `=list=`).
3336 if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
3337 return true;
3338 // A label is needed for any block with at least one predecessor (when that
3339 // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3340 // entry, or if a label is forced).
3341 return !MBB.pred_empty() &&
3342 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() ||
3343 MBB.hasLabelMustBeEmitted());
3344}
3345
3346/// isBlockOnlyReachableByFallthough - Return true if the basic block has
3347/// exactly one predecessor and the control transfer mechanism between
3348/// the predecessor and this block is a fall-through.
3349bool AsmPrinter::
3350isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
3351 // If this is a landing pad, it isn't a fall through. If it has no preds,
3352 // then nothing falls through to it.
3353 if (MBB->isEHPad() || MBB->pred_empty())
3354 return false;
3355
3356 // If there isn't exactly one predecessor, it can't be a fall through.
3357 if (MBB->pred_size() > 1)
3358 return false;
3359
3360 // The predecessor has to be immediately before this block.
3361 MachineBasicBlock *Pred = *MBB->pred_begin();
3362 if (!Pred->isLayoutSuccessor(MBB))
3363 return false;
3364
3365 // If the block is completely empty, then it definitely does fall through.
3366 if (Pred->empty())
3367 return true;
3368
3369 // Check the terminators in the previous blocks
3370 for (const auto &MI : Pred->terminators()) {
3371 // If it is not a simple branch, we are in a table somewhere.
3372 if (!MI.isBranch() || MI.isIndirectBranch())
3373 return false;
3374
3375 // If we are the operands of one of the branches, this is not a fall
3376 // through. Note that targets with delay slots will usually bundle
3377 // terminators with the delay slot instruction.
3378 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3379 if (OP->isJTI())
3380 return false;
3381 if (OP->isMBB() && OP->getMBB() == MBB)
3382 return false;
3383 }
3384 }
3385
3386 return true;
3387}
3388
3389GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3390 if (!S.usesMetadata())
3391 return nullptr;
3392
3393 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3394 gcp_map_type::iterator GCPI = GCMap.find(&S);
3395 if (GCPI != GCMap.end())
3396 return GCPI->second.get();
3397
3398 auto Name = S.getName();
3399
3400 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
3401 GCMetadataPrinterRegistry::entries())
3402 if (Name == GCMetaPrinter.getName()) {
3403 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
3404 GMP->S = &S;
3405 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3406 return IterBool.first->second.get();
3407 }
3408
3409 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3410}
3411
3412void AsmPrinter::emitStackMaps(StackMaps &SM) {
3413 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3414 assert(MI && "AsmPrinter didn't require GCModuleInfo?")(static_cast <bool> (MI && "AsmPrinter didn't require GCModuleInfo?"
) ? void (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3414, __extension__ __PRETTY_FUNCTION__))
;
3415 bool NeedsDefault = false;
3416 if (MI->begin() == MI->end())
3417 // No GC strategy, use the default format.
3418 NeedsDefault = true;
3419 else
3420 for (auto &I : *MI) {
3421 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3422 if (MP->emitStackMaps(SM, *this))
3423 continue;
3424 // The strategy doesn't have printer or doesn't emit custom stack maps.
3425 // Use the default format.
3426 NeedsDefault = true;
3427 }
3428
3429 if (NeedsDefault)
3430 SM.serializeToStackMapSection();
3431}
3432
3433/// Pin vtable to this file.
3434AsmPrinterHandler::~AsmPrinterHandler() = default;
3435
3436void AsmPrinterHandler::markFunctionEnd() {}
3437
3438// In the binary's "xray_instr_map" section, an array of these function entries
3439// describes each instrumentation point. When XRay patches your code, the index
3440// into this table will be given to your handler as a patch point identifier.
3441void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const {
3442 auto Kind8 = static_cast<uint8_t>(Kind);
3443 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3444 Out->emitBinaryData(
3445 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3446 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3447 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3448 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size")(static_cast <bool> (Padding >= 0 && "Instrumentation map entry > 4 * Word Size"
) ? void (0) : __assert_fail ("Padding >= 0 && \"Instrumentation map entry > 4 * Word Size\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3448, __extension__ __PRETTY_FUNCTION__))
;
3449 Out->emitZeros(Padding);
3450}
3451
3452void AsmPrinter::emitXRayTable() {
3453 if (Sleds.empty())
3454 return;
3455
3456 auto PrevSection = OutStreamer->getCurrentSectionOnly();
3457 const Function &F = MF->getFunction();
3458 MCSection *InstMap = nullptr;
3459 MCSection *FnSledIndex = nullptr;
3460 const Triple &TT = TM.getTargetTriple();
3461 // Use PC-relative addresses on all targets.
3462 if (TT.isOSBinFormatELF()) {
3463 auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3464 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3465 StringRef GroupName;
3466 if (F.hasComdat()) {
3467 Flags |= ELF::SHF_GROUP;
3468 GroupName = F.getComdat()->getName();
3469 }
3470 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3471 Flags, 0, GroupName, F.hasComdat(),
3472 MCSection::NonUniqueID, LinkedToSym);
3473
3474 if (!TM.Options.XRayOmitFunctionIndex)
3475 FnSledIndex = OutContext.getELFSection(
3476 "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
3477 GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
3478 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3479 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3480 SectionKind::getReadOnlyWithRel());
3481 if (!TM.Options.XRayOmitFunctionIndex)
3482 FnSledIndex = OutContext.getMachOSection(
3483 "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3484 } else {
3485 llvm_unreachable("Unsupported target")::llvm::llvm_unreachable_internal("Unsupported target", "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3485)
;
3486 }
3487
3488 auto WordSizeBytes = MAI->getCodePointerSize();
3489
3490 // Now we switch to the instrumentation map section. Because this is done
3491 // per-function, we are able to create an index entry that will represent the
3492 // range of sleds associated with a function.
3493 auto &Ctx = OutContext;
3494 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3495 OutStreamer->SwitchSection(InstMap);
3496 OutStreamer->emitLabel(SledsStart);
3497 for (const auto &Sled : Sleds) {
3498 MCSymbol *Dot = Ctx.createTempSymbol();
3499 OutStreamer->emitLabel(Dot);
3500 OutStreamer->emitValueImpl(
3501 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx),
3502 MCSymbolRefExpr::create(Dot, Ctx), Ctx),
3503 WordSizeBytes);
3504 OutStreamer->emitValueImpl(
3505 MCBinaryExpr::createSub(
3506 MCSymbolRefExpr::create(CurrentFnBegin, Ctx),
3507 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx),
3508 MCConstantExpr::create(WordSizeBytes, Ctx),
3509 Ctx),
3510 Ctx),
3511 WordSizeBytes);
3512 Sled.emit(WordSizeBytes, OutStreamer.get());
3513 }
3514 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3515 OutStreamer->emitLabel(SledsEnd);
3516
3517 // We then emit a single entry in the index per function. We use the symbols
3518 // that bound the instrumentation map as the range for a specific function.
3519 // Each entry here will be 2 * word size aligned, as we're writing down two
3520 // pointers. This should work for both 32-bit and 64-bit platforms.
3521 if (FnSledIndex) {
3522 OutStreamer->SwitchSection(FnSledIndex);
3523 OutStreamer->emitCodeAlignment(2 * WordSizeBytes);
3524 OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3525 OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3526 OutStreamer->SwitchSection(PrevSection);
3527 }
3528 Sleds.clear();
3529}
3530
3531void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
3532 SledKind Kind, uint8_t Version) {
3533 const Function &F = MI.getMF()->getFunction();
3534 auto Attr = F.getFnAttribute("function-instrument");
3535 bool LogArgs = F.hasFnAttribute("xray-log-args");
3536 bool AlwaysInstrument =
3537 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3538 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3539 Kind = SledKind::LOG_ARGS_ENTER;
3540 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3541 AlwaysInstrument, &F, Version});
3542}
3543
3544void AsmPrinter::emitPatchableFunctionEntries() {
3545 const Function &F = MF->getFunction();
3546 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3547 (void)F.getFnAttribute("patchable-function-prefix")
3548 .getValueAsString()
3549 .getAsInteger(10, PatchableFunctionPrefix);
3550 (void)F.getFnAttribute("patchable-function-entry")
3551 .getValueAsString()
3552 .getAsInteger(10, PatchableFunctionEntry);
3553 if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3554 return;
3555 const unsigned PointerSize = getPointerSize();
3556 if (TM.getTargetTriple().isOSBinFormatELF()) {
3557 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3558 const MCSymbolELF *LinkedToSym = nullptr;
3559 StringRef GroupName;
3560
3561 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
3562 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
3563 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
3564 Flags |= ELF::SHF_LINK_ORDER;
3565 if (F.hasComdat()) {
3566 Flags |= ELF::SHF_GROUP;
3567 GroupName = F.getComdat()->getName();
3568 }
3569 LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3570 }
3571 OutStreamer->SwitchSection(OutContext.getELFSection(
3572 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
3573 F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
3574 emitAlignment(Align(PointerSize));
3575 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
3576 }
3577}
3578
3579uint16_t AsmPrinter::getDwarfVersion() const {
3580 return OutStreamer->getContext().getDwarfVersion();
3581}
3582
3583void AsmPrinter::setDwarfVersion(uint16_t Version) {
3584 OutStreamer->getContext().setDwarfVersion(Version);
3585}
3586
3587bool AsmPrinter::isDwarf64() const {
3588 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
3589}
3590
3591unsigned int AsmPrinter::getDwarfOffsetByteSize() const {
3592 return dwarf::getDwarfOffsetByteSize(
3593 OutStreamer->getContext().getDwarfFormat());
3594}
3595
3596unsigned int AsmPrinter::getUnitLengthFieldByteSize() const {
3597 return dwarf::getUnitLengthFieldByteSize(
3598 OutStreamer->getContext().getDwarfFormat());
3599}