Bug Summary

File:lib/CodeGen/AsmPrinter/AsmPrinter.cpp
Warning:line 2503, column 44
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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