Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name DwarfCompileUnit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/CodeGen/AsmPrinter -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
1//===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
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 contains support for constructing a dwarf compile unit.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfCompileUnit.h"
14#include "AddressPool.h"
15#include "DwarfExpression.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/BinaryFormat/Dwarf.h"
20#include "llvm/CodeGen/AsmPrinter.h"
21#include "llvm/CodeGen/DIE.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/MachineOperand.h"
25#include "llvm/CodeGen/TargetFrameLowering.h"
26#include "llvm/CodeGen/TargetRegisterInfo.h"
27#include "llvm/CodeGen/TargetSubtargetInfo.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DebugInfo.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/MC/MCSection.h"
32#include "llvm/MC/MCStreamer.h"
33#include "llvm/MC/MCSymbol.h"
34#include "llvm/MC/MCSymbolWasm.h"
35#include "llvm/MC/MachineLocation.h"
36#include "llvm/Target/TargetLoweringObjectFile.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Target/TargetOptions.h"
39#include <iterator>
40#include <string>
41#include <utility>
42
43using namespace llvm;
44
45static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
46
47 // According to DWARF Debugging Information Format Version 5,
48 // 3.1.2 Skeleton Compilation Unit Entries:
49 // "When generating a split DWARF object file (see Section 7.3.2
50 // on page 187), the compilation unit in the .debug_info section
51 // is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
52 if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
53 return dwarf::DW_TAG_skeleton_unit;
54
55 return dwarf::DW_TAG_compile_unit;
56}
57
58DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
59 AsmPrinter *A, DwarfDebug *DW,
60 DwarfFile *DWU, UnitKind Kind)
61 : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
62 insertDIE(Node, &getUnitDie());
63 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
64}
65
66/// addLabelAddress - Add a dwarf label attribute data and value using
67/// DW_FORM_addr or DW_FORM_GNU_addr_index.
68void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
69 const MCSymbol *Label) {
70 // Don't use the address pool in non-fission or in the skeleton unit itself.
71 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
14
Assuming the condition is false
15
Assuming field 'Skeleton' is non-null
72 return addLocalLabelAddress(Die, Attribute, Label);
73
74 if (Label)
16
Assuming 'Label' is null
75 DD->addArangeLabel(SymbolCU(this, Label));
76
77 bool UseAddrOffsetFormOrExpressions =
78 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
79
80 const MCSymbol *Base = nullptr;
81 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
17
Called C++ object pointer is null
82 Base = DD->getSectionLabel(&Label->getSection());
83
84 if (!Base || Base == Label) {
85 unsigned idx = DD->getAddressPool().getIndex(Label);
86 addAttribute(Die, Attribute,
87 DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
88 : dwarf::DW_FORM_GNU_addr_index,
89 DIEInteger(idx));
90 return;
91 }
92
93 // Could be extended to work with DWARFv4 Split DWARF if that's important for
94 // someone. In that case DW_FORM_data would be used.
95 assert(DD->getDwarfVersion() >= 5 &&(static_cast <bool> (DD->getDwarfVersion() >= 5 &&
"Addr+offset expressions are only valuable when using debug_addr (to "
"reduce relocations) available in DWARFv5 or higher") ? void
(0) : __assert_fail ("DD->getDwarfVersion() >= 5 && \"Addr+offset expressions are only valuable when using debug_addr (to \" \"reduce relocations) available in DWARFv5 or higher\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 97, __extension__
__PRETTY_FUNCTION__))
96 "Addr+offset expressions are only valuable when using debug_addr (to "(static_cast <bool> (DD->getDwarfVersion() >= 5 &&
"Addr+offset expressions are only valuable when using debug_addr (to "
"reduce relocations) available in DWARFv5 or higher") ? void
(0) : __assert_fail ("DD->getDwarfVersion() >= 5 && \"Addr+offset expressions are only valuable when using debug_addr (to \" \"reduce relocations) available in DWARFv5 or higher\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 97, __extension__
__PRETTY_FUNCTION__))
97 "reduce relocations) available in DWARFv5 or higher")(static_cast <bool> (DD->getDwarfVersion() >= 5 &&
"Addr+offset expressions are only valuable when using debug_addr (to "
"reduce relocations) available in DWARFv5 or higher") ? void
(0) : __assert_fail ("DD->getDwarfVersion() >= 5 && \"Addr+offset expressions are only valuable when using debug_addr (to \" \"reduce relocations) available in DWARFv5 or higher\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 97, __extension__
__PRETTY_FUNCTION__))
;
98 if (DD->useAddrOffsetExpressions()) {
99 auto *Loc = new (DIEValueAllocator) DIEBlock();
100 addPoolOpAddress(*Loc, Label);
101 addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
102 } else
103 addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
104 new (DIEValueAllocator) DIEAddrOffset(
105 DD->getAddressPool().getIndex(Base), Label, Base));
106}
107
108void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
109 dwarf::Attribute Attribute,
110 const MCSymbol *Label) {
111 if (Label)
112 DD->addArangeLabel(SymbolCU(this, Label));
113
114 if (Label)
115 addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
116 else
117 addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
118}
119
120unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
121 // If we print assembly, we can't separate .file entries according to
122 // compile units. Thus all files will belong to the default compile unit.
123
124 // FIXME: add a better feature test than hasRawTextSupport. Even better,
125 // extend .file to support this.
126 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
127 if (!File)
128 return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
129 CUID);
130 return Asm->OutStreamer->emitDwarfFileDirective(
131 0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
132 File->getSource(), CUID);
133}
134
135DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
136 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
137 // Check for pre-existence.
138 if (DIE *Die = getDIE(GV))
139 return Die;
140
141 assert(GV)(static_cast <bool> (GV) ? void (0) : __assert_fail ("GV"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 141, __extension__
__PRETTY_FUNCTION__))
;
142
143 auto *GVContext = GV->getScope();
144 const DIType *GTy = GV->getType();
145
146 auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
147 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
148 : getOrCreateContextDIE(GVContext);
149
150 // Add to map.
151 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
152 DIScope *DeclContext;
153 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
154 DeclContext = SDMDecl->getScope();
155 assert(SDMDecl->isStaticMember() && "Expected static member decl")(static_cast <bool> (SDMDecl->isStaticMember() &&
"Expected static member decl") ? void (0) : __assert_fail ("SDMDecl->isStaticMember() && \"Expected static member decl\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 155, __extension__
__PRETTY_FUNCTION__))
;
156 assert(GV->isDefinition())(static_cast <bool> (GV->isDefinition()) ? void (0) :
__assert_fail ("GV->isDefinition()", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 156, __extension__ __PRETTY_FUNCTION__))
;
157 // We need the declaration DIE that is in the static member's class.
158 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
159 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
160 // If the global variable's type is different from the one in the class
161 // member type, assume that it's more specific and also emit it.
162 if (GTy != SDMDecl->getBaseType())
163 addType(*VariableDIE, GTy);
164 } else {
165 DeclContext = GV->getScope();
166 // Add name and type.
167 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
168 if (GTy)
169 addType(*VariableDIE, GTy);
170
171 // Add scoping info.
172 if (!GV->isLocalToUnit())
173 addFlag(*VariableDIE, dwarf::DW_AT_external);
174
175 // Add line number info.
176 addSourceLine(*VariableDIE, GV);
177 }
178
179 if (!GV->isDefinition())
180 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
181 else
182 addGlobalName(GV->getName(), *VariableDIE, DeclContext);
183
184 addAnnotation(*VariableDIE, GV->getAnnotations());
185
186 if (uint32_t AlignInBytes = GV->getAlignInBytes())
187 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
188 AlignInBytes);
189
190 if (MDTuple *TP = GV->getTemplateParams())
191 addTemplateParams(*VariableDIE, DINodeArray(TP));
192
193 // Add location.
194 addLocationAttribute(VariableDIE, GV, GlobalExprs);
195
196 return VariableDIE;
197}
198
199void DwarfCompileUnit::addLocationAttribute(
200 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
201 bool addToAccelTable = false;
202 DIELoc *Loc = nullptr;
203 Optional<unsigned> NVPTXAddressSpace;
204 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
205 for (const auto &GE : GlobalExprs) {
206 const GlobalVariable *Global = GE.Var;
207 const DIExpression *Expr = GE.Expr;
208
209 // For compatibility with DWARF 3 and earlier,
210 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
211 // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
212 // DW_AT_const_value(X).
213 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
214 addToAccelTable = true;
215 addConstantValue(
216 *VariableDIE,
217 DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
218 *Expr->isConstant(),
219 Expr->getElement(1));
220 break;
221 }
222
223 // We cannot describe the location of dllimport'd variables: the
224 // computation of their address requires loads from the IAT.
225 if (Global && Global->hasDLLImportStorageClass())
226 continue;
227
228 // Nothing to describe without address or constant.
229 if (!Global && (!Expr || !Expr->isConstant()))
230 continue;
231
232 if (Global && Global->isThreadLocal() &&
233 !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
234 continue;
235
236 if (!Loc) {
237 addToAccelTable = true;
238 Loc = new (DIEValueAllocator) DIELoc;
239 DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
240 }
241
242 if (Expr) {
243 // According to
244 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
245 // cuda-gdb requires DW_AT_address_class for all variables to be able to
246 // correctly interpret address space of the variable address.
247 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
248 // sequence for the NVPTX + gdb target.
249 unsigned LocalNVPTXAddressSpace;
250 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
251 const DIExpression *NewExpr =
252 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
253 if (NewExpr != Expr) {
254 Expr = NewExpr;
255 NVPTXAddressSpace = LocalNVPTXAddressSpace;
256 }
257 }
258 DwarfExpr->addFragmentOffset(Expr);
259 }
260
261 if (Global) {
262 const MCSymbol *Sym = Asm->getSymbol(Global);
263 // 16-bit platforms like MSP430 and AVR take this path, so sink this
264 // assert to platforms that use it.
265 auto GetPointerSizedFormAndOp = [this]() {
266 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
267 assert((PointerSize == 4 || PointerSize == 8) &&(static_cast <bool> ((PointerSize == 4 || PointerSize ==
8) && "Add support for other sizes if necessary") ? void
(0) : __assert_fail ("(PointerSize == 4 || PointerSize == 8) && \"Add support for other sizes if necessary\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 268, __extension__
__PRETTY_FUNCTION__))
268 "Add support for other sizes if necessary")(static_cast <bool> ((PointerSize == 4 || PointerSize ==
8) && "Add support for other sizes if necessary") ? void
(0) : __assert_fail ("(PointerSize == 4 || PointerSize == 8) && \"Add support for other sizes if necessary\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 268, __extension__
__PRETTY_FUNCTION__))
;
269 struct FormAndOp {
270 dwarf::Form Form;
271 dwarf::LocationAtom Op;
272 };
273 return PointerSize == 4
274 ? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
275 : FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
276 };
277 if (Global->isThreadLocal()) {
278 if (Asm->TM.useEmulatedTLS()) {
279 // TODO: add debug info for emulated thread local mode.
280 } else {
281 // FIXME: Make this work with -gsplit-dwarf.
282 // Based on GCC's support for TLS:
283 if (!DD->useSplitDwarf()) {
284 auto FormAndOp = GetPointerSizedFormAndOp();
285 // 1) Start with a constNu of the appropriate pointer size
286 addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
287 // 2) containing the (relocated) offset of the TLS variable
288 // within the module's TLS block.
289 addExpr(*Loc, FormAndOp.Form,
290 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
291 } else {
292 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
293 addUInt(*Loc, dwarf::DW_FORM_udata,
294 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
295 }
296 // 3) followed by an OP to make the debugger do a TLS lookup.
297 addUInt(*Loc, dwarf::DW_FORM_data1,
298 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
299 : dwarf::DW_OP_form_tls_address);
300 }
301 } else if (Asm->TM.getRelocationModel() == Reloc::RWPI ||
302 Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) {
303 auto FormAndOp = GetPointerSizedFormAndOp();
304 // Constant
305 addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
306 // Relocation offset
307 addExpr(*Loc, FormAndOp.Form,
308 Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
309 // Base register
310 Register BaseReg = Asm->getObjFileLowering().getStaticBase();
311 BaseReg = Asm->TM.getMCRegisterInfo()->getDwarfRegNum(BaseReg, false);
312 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + BaseReg);
313 // Offset from base register
314 addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
315 // Operation
316 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
317 } else {
318 DD->addArangeLabel(SymbolCU(this, Sym));
319 addOpAddress(*Loc, Sym);
320 }
321 }
322 // Global variables attached to symbols are memory locations.
323 // It would be better if this were unconditional, but malformed input that
324 // mixes non-fragments and fragments for the same variable is too expensive
325 // to detect in the verifier.
326 if (DwarfExpr->isUnknownLocation())
327 DwarfExpr->setMemoryLocationKind();
328 DwarfExpr->addExpression(Expr);
329 }
330 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
331 // According to
332 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
333 // cuda-gdb requires DW_AT_address_class for all variables to be able to
334 // correctly interpret address space of the variable address.
335 const unsigned NVPTX_ADDR_global_space = 5;
336 addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
337 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
338 }
339 if (Loc)
340 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
341
342 if (DD->useAllLinkageNames())
343 addLinkageName(*VariableDIE, GV->getLinkageName());
344
345 if (addToAccelTable) {
346 DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
347
348 // If the linkage name is different than the name, go ahead and output
349 // that as well into the name table.
350 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
351 DD->useAllLinkageNames())
352 DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
353 }
354}
355
356DIE *DwarfCompileUnit::getOrCreateCommonBlock(
357 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
358 // Check for pre-existence.
359 if (DIE *NDie = getDIE(CB))
360 return NDie;
361 DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
362 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
363 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
364 addString(NDie, dwarf::DW_AT_name, Name);
365 addGlobalName(Name, NDie, CB->getScope());
366 if (CB->getFile())
367 addSourceLine(NDie, CB->getLineNo(), CB->getFile());
368 if (DIGlobalVariable *V = CB->getDecl())
369 getCU().addLocationAttribute(&NDie, V, GlobalExprs);
370 return &NDie;
371}
372
373void DwarfCompileUnit::addRange(RangeSpan Range) {
374 DD->insertSectionLabel(Range.Begin);
375
376 auto *PrevCU = DD->getPrevCU();
377 bool SameAsPrevCU = this == PrevCU;
378 DD->setPrevCU(this);
379 // If we have no current ranges just add the range and return, otherwise,
380 // check the current section and CU against the previous section and CU we
381 // emitted into and the subprogram was contained within. If these are the
382 // same then extend our current range, otherwise add this as a new range.
383 if (CURanges.empty() || !SameAsPrevCU ||
384 (&CURanges.back().End->getSection() !=
385 &Range.End->getSection())) {
386 // Before a new range is added, always terminate the prior line table.
387 if (PrevCU)
388 DD->terminateLineTable(PrevCU);
389 CURanges.push_back(Range);
390 return;
391 }
392
393 CURanges.back().End = Range.End;
394}
395
396void DwarfCompileUnit::initStmtList() {
397 if (CUNode->isDebugDirectivesOnly())
398 return;
399
400 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
401 if (DD->useSectionsAsReferences()) {
402 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
403 } else {
404 LineTableStartSym =
405 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
406 }
407
408 // DW_AT_stmt_list is a offset of line number information for this
409 // compile unit in debug_line section. For split dwarf this is
410 // left in the skeleton CU and so not included.
411 // The line table entries are not always emitted in assembly, so it
412 // is not okay to use line_table_start here.
413 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
414 TLOF.getDwarfLineSection()->getBeginSymbol());
415}
416
417void DwarfCompileUnit::applyStmtList(DIE &D) {
418 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
419 addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
420 TLOF.getDwarfLineSection()->getBeginSymbol());
421}
422
423void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
424 const MCSymbol *End) {
425 assert(Begin && "Begin label should not be null!")(static_cast <bool> (Begin && "Begin label should not be null!"
) ? void (0) : __assert_fail ("Begin && \"Begin label should not be null!\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 425, __extension__
__PRETTY_FUNCTION__))
;
426 assert(End && "End label should not be null!")(static_cast <bool> (End && "End label should not be null!"
) ? void (0) : __assert_fail ("End && \"End label should not be null!\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 426, __extension__
__PRETTY_FUNCTION__))
;
427 assert(Begin->isDefined() && "Invalid starting label")(static_cast <bool> (Begin->isDefined() && "Invalid starting label"
) ? void (0) : __assert_fail ("Begin->isDefined() && \"Invalid starting label\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 427, __extension__
__PRETTY_FUNCTION__))
;
428 assert(End->isDefined() && "Invalid end label")(static_cast <bool> (End->isDefined() && "Invalid end label"
) ? void (0) : __assert_fail ("End->isDefined() && \"Invalid end label\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 428, __extension__
__PRETTY_FUNCTION__))
;
429
430 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
431 if (DD->getDwarfVersion() < 4)
432 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
433 else
434 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
435}
436
437// Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
438// and DW_AT_high_pc attributes. If there are global variables in this
439// scope then create and insert DIEs for these variables.
440DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
441 DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
442
443 SmallVector<RangeSpan, 2> BB_List;
444 // If basic block sections are on, ranges for each basic block section has
445 // to be emitted separately.
446 for (const auto &R : Asm->MBBSectionRanges)
447 BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
448
449 attachRangesOrLowHighPC(*SPDie, BB_List);
450
451 if (DD->useAppleExtensionAttributes() &&
452 !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
453 *DD->getCurrentFunction()))
454 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
455
456 // Only include DW_AT_frame_base in full debug info
457 if (!includeMinimalInlineScopes()) {
458 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
459 TargetFrameLowering::DwarfFrameBase FrameBase =
460 TFI->getDwarfFrameBase(*Asm->MF);
461 switch (FrameBase.Kind) {
462 case TargetFrameLowering::DwarfFrameBase::Register: {
463 if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
464 MachineLocation Location(FrameBase.Location.Reg);
465 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
466 }
467 break;
468 }
469 case TargetFrameLowering::DwarfFrameBase::CFA: {
470 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
471 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
472 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
473 break;
474 }
475 case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
476 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
477 // don't want to depend on target specific headers in this code?
478 const unsigned TI_GLOBAL_RELOC = 3;
479 if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
480 // These need to be relocatable.
481 assert(FrameBase.Location.WasmLoc.Index == 0)(static_cast <bool> (FrameBase.Location.WasmLoc.Index ==
0) ? void (0) : __assert_fail ("FrameBase.Location.WasmLoc.Index == 0"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 481, __extension__
__PRETTY_FUNCTION__))
; // Only SP so far.
482 auto SPSym = cast<MCSymbolWasm>(
483 Asm->GetExternalSymbolSymbol("__stack_pointer"));
484 // FIXME: this repeats what WebAssemblyMCInstLower::
485 // GetExternalSymbolSymbol does, since if there's no code that
486 // refers to this symbol, we have to set it here.
487 SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
488 SPSym->setGlobalType(wasm::WasmGlobalType{
489 uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
490 Triple::wasm64
491 ? wasm::WASM_TYPE_I64
492 : wasm::WASM_TYPE_I32),
493 true});
494 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
495 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
496 addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
497 if (!isDwoUnit()) {
498 addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
499 } else {
500 // FIXME: when writing dwo, we need to avoid relocations. Probably
501 // the "right" solution is to treat globals the way func and data
502 // symbols are (with entries in .debug_addr).
503 // For now, since we only ever use index 0, this should work as-is.
504 addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
505 }
506 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
507 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
508 } else {
509 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
510 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
511 DIExpressionCursor Cursor({});
512 DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
513 FrameBase.Location.WasmLoc.Index);
514 DwarfExpr.addExpression(std::move(Cursor));
515 addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
516 }
517 break;
518 }
519 }
520 }
521
522 // Add name to the name table, we do this here because we're guaranteed
523 // to have concrete versions of our DW_TAG_subprogram nodes.
524 DD->addSubprogramNames(*CUNode, SP, *SPDie);
525
526 return *SPDie;
527}
528
529// Construct a DIE for this scope.
530void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
531 DIE &ParentScopeDIE) {
532 if (!Scope || !Scope->getScopeNode())
533 return;
534
535 auto *DS = Scope->getScopeNode();
536
537 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&(static_cast <bool> ((Scope->getInlinedAt() || !isa<
DISubprogram>(DS)) && "Only handle inlined subprograms here, use "
"constructSubprogramScopeDIE for non-inlined " "subprograms"
) ? void (0) : __assert_fail ("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 540, __extension__
__PRETTY_FUNCTION__))
538 "Only handle inlined subprograms here, use "(static_cast <bool> ((Scope->getInlinedAt() || !isa<
DISubprogram>(DS)) && "Only handle inlined subprograms here, use "
"constructSubprogramScopeDIE for non-inlined " "subprograms"
) ? void (0) : __assert_fail ("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 540, __extension__
__PRETTY_FUNCTION__))
539 "constructSubprogramScopeDIE for non-inlined "(static_cast <bool> ((Scope->getInlinedAt() || !isa<
DISubprogram>(DS)) && "Only handle inlined subprograms here, use "
"constructSubprogramScopeDIE for non-inlined " "subprograms"
) ? void (0) : __assert_fail ("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 540, __extension__
__PRETTY_FUNCTION__))
540 "subprograms")(static_cast <bool> ((Scope->getInlinedAt() || !isa<
DISubprogram>(DS)) && "Only handle inlined subprograms here, use "
"constructSubprogramScopeDIE for non-inlined " "subprograms"
) ? void (0) : __assert_fail ("(Scope->getInlinedAt() || !isa<DISubprogram>(DS)) && \"Only handle inlined subprograms here, use \" \"constructSubprogramScopeDIE for non-inlined \" \"subprograms\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 540, __extension__
__PRETTY_FUNCTION__))
;
541
542 // Emit inlined subprograms.
543 if (Scope->getParent() && isa<DISubprogram>(DS)) {
544 DIE *ScopeDIE = constructInlinedScopeDIE(Scope);
545 if (!ScopeDIE)
546 return;
547
548 ParentScopeDIE.addChild(ScopeDIE);
549 createAndAddScopeChildren(Scope, *ScopeDIE);
550 return;
551 }
552
553 // Early exit when we know the scope DIE is going to be null.
554 if (DD->isLexicalScopeDIENull(Scope))
555 return;
556
557 // Emit lexical blocks.
558 DIE *ScopeDIE = constructLexicalScopeDIE(Scope);
559 assert(ScopeDIE && "Scope DIE should not be null.")(static_cast <bool> (ScopeDIE && "Scope DIE should not be null."
) ? void (0) : __assert_fail ("ScopeDIE && \"Scope DIE should not be null.\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 559, __extension__
__PRETTY_FUNCTION__))
;
560
561 ParentScopeDIE.addChild(ScopeDIE);
562 createAndAddScopeChildren(Scope, *ScopeDIE);
563}
564
565void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
566 SmallVector<RangeSpan, 2> Range) {
567
568 HasRangeLists = true;
569
570 // Add the range list to the set of ranges to be emitted.
571 auto IndexAndList =
572 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
573 ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
574
575 uint32_t Index = IndexAndList.first;
576 auto &List = *IndexAndList.second;
577
578 // Under fission, ranges are specified by constant offsets relative to the
579 // CU's DW_AT_GNU_ranges_base.
580 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
581 // fission until we support the forms using the .debug_addr section
582 // (DW_RLE_startx_endx etc.).
583 if (DD->getDwarfVersion() >= 5)
584 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
585 else {
586 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
587 const MCSymbol *RangeSectionSym =
588 TLOF.getDwarfRangesSection()->getBeginSymbol();
589 if (isDwoUnit())
590 addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
591 RangeSectionSym);
592 else
593 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
594 RangeSectionSym);
595 }
596}
597
598void DwarfCompileUnit::attachRangesOrLowHighPC(
599 DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
600 assert(!Ranges.empty())(static_cast <bool> (!Ranges.empty()) ? void (0) : __assert_fail
("!Ranges.empty()", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 600, __extension__ __PRETTY_FUNCTION__))
;
601 if (!DD->useRangesSection() ||
602 (Ranges.size() == 1 &&
603 (!DD->alwaysUseRanges() ||
604 DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
605 Ranges.front().Begin))) {
606 const RangeSpan &Front = Ranges.front();
607 const RangeSpan &Back = Ranges.back();
608 attachLowHighPC(Die, Front.Begin, Back.End);
609 } else
610 addScopeRangeList(Die, std::move(Ranges));
611}
612
613void DwarfCompileUnit::attachRangesOrLowHighPC(
614 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
615 SmallVector<RangeSpan, 2> List;
616 List.reserve(Ranges.size());
617 for (const InsnRange &R : Ranges) {
618 auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
619 auto *EndLabel = DD->getLabelAfterInsn(R.second);
620
621 const auto *BeginMBB = R.first->getParent();
622 const auto *EndMBB = R.second->getParent();
623
624 const auto *MBB = BeginMBB;
625 // Basic block sections allows basic block subsets to be placed in unique
626 // sections. For each section, the begin and end label must be added to the
627 // list. If there is more than one range, debug ranges must be used.
628 // Otherwise, low/high PC can be used.
629 // FIXME: Debug Info Emission depends on block order and this assumes that
630 // the order of blocks will be frozen beyond this point.
631 do {
632 if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
633 auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
634 List.push_back(
635 {MBB->sameSection(BeginMBB) ? BeginLabel
636 : MBBSectionRange.BeginLabel,
637 MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
638 }
639 if (MBB->sameSection(EndMBB))
640 break;
641 MBB = MBB->getNextNode();
642 } while (true);
643 }
644 attachRangesOrLowHighPC(Die, std::move(List));
645}
646
647// This scope represents inlined body of a function. Construct DIE to
648// represent this concrete inlined copy of the function.
649DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
650 assert(Scope->getScopeNode())(static_cast <bool> (Scope->getScopeNode()) ? void (
0) : __assert_fail ("Scope->getScopeNode()", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 650, __extension__ __PRETTY_FUNCTION__))
;
651 auto *DS = Scope->getScopeNode();
652 auto *InlinedSP = getDISubprogram(DS);
653 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
654 // was inlined from another compile unit.
655 DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
656 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.")(static_cast <bool> (OriginDIE && "Unable to find original DIE for an inlined subprogram."
) ? void (0) : __assert_fail ("OriginDIE && \"Unable to find original DIE for an inlined subprogram.\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 656, __extension__
__PRETTY_FUNCTION__))
;
657
658 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
659 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
660
661 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
662
663 // Add the call site information to the DIE.
664 const DILocation *IA = Scope->getInlinedAt();
665 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
666 getOrCreateSourceID(IA->getFile()));
667 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
668 if (IA->getColumn())
669 addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
670 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
671 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
672 IA->getDiscriminator());
673
674 // Add name to the name table, we do this here because we're guaranteed
675 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
676 DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
677
678 return ScopeDIE;
679}
680
681// Construct new DW_TAG_lexical_block for this scope and attach
682// DW_AT_low_pc/DW_AT_high_pc labels.
683DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
684 if (DD->isLexicalScopeDIENull(Scope))
685 return nullptr;
686
687 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
688 if (Scope->isAbstractScope())
689 return ScopeDIE;
690
691 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
692
693 return ScopeDIE;
694}
695
696/// constructVariableDIE - Construct a DIE for the given DbgVariable.
697DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
698 auto D = constructVariableDIEImpl(DV, Abstract);
699 DV.setDIE(*D);
700 return D;
701}
702
703DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
704 const LexicalScope &Scope) {
705 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
706 insertDIE(DL.getLabel(), LabelDie);
707 DL.setDIE(*LabelDie);
708
709 if (Scope.isAbstractScope())
710 applyLabelAttributes(DL, *LabelDie);
711
712 return LabelDie;
713}
714
715DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
716 bool Abstract) {
717 // Define variable debug information entry.
718 auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
719 insertDIE(DV.getVariable(), VariableDie);
720
721 if (Abstract) {
722 applyVariableAttributes(DV, *VariableDie);
723 return VariableDie;
724 }
725
726 // Add variable address.
727
728 unsigned Index = DV.getDebugLocListIndex();
729 if (Index != ~0U) {
730 addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
731 auto TagOffset = DV.getDebugLocListTagOffset();
732 if (TagOffset)
733 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
734 *TagOffset);
735 return VariableDie;
736 }
737
738 // Check if variable has a single location description.
739 if (auto *DVal = DV.getValueLoc()) {
740 if (!DVal->isVariadic()) {
741 const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
742 if (Entry->isLocation()) {
743 addVariableAddress(DV, *VariableDie, Entry->getLoc());
744 } else if (Entry->isInt()) {
745 auto *Expr = DV.getSingleExpression();
746 if (Expr && Expr->getNumElements()) {
747 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
748 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
749 // If there is an expression, emit raw unsigned bytes.
750 DwarfExpr.addFragmentOffset(Expr);
751 DwarfExpr.addUnsignedConstant(Entry->getInt());
752 DwarfExpr.addExpression(Expr);
753 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
754 if (DwarfExpr.TagOffset)
755 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
756 dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
757 } else
758 addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
759 } else if (Entry->isConstantFP()) {
760 addConstantFPValue(*VariableDie, Entry->getConstantFP());
761 } else if (Entry->isConstantInt()) {
762 addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
763 } else if (Entry->isTargetIndexLocation()) {
764 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
765 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
766 const DIBasicType *BT = dyn_cast<DIBasicType>(
767 static_cast<const Metadata *>(DV.getVariable()->getType()));
768 DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
769 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
770 }
771 return VariableDie;
772 }
773 // If any of the location entries are registers with the value 0, then the
774 // location is undefined.
775 if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
776 return Entry.isLocation() && !Entry.getLoc().getReg();
777 }))
778 return VariableDie;
779 const DIExpression *Expr = DV.getSingleExpression();
780 assert(Expr && "Variadic Debug Value must have an Expression.")(static_cast <bool> (Expr && "Variadic Debug Value must have an Expression."
) ? void (0) : __assert_fail ("Expr && \"Variadic Debug Value must have an Expression.\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 780, __extension__
__PRETTY_FUNCTION__))
;
781 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
782 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
783 DwarfExpr.addFragmentOffset(Expr);
784 DIExpressionCursor Cursor(Expr);
785 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
786
787 auto AddEntry = [&](const DbgValueLocEntry &Entry,
788 DIExpressionCursor &Cursor) {
789 if (Entry.isLocation()) {
790 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
791 Entry.getLoc().getReg()))
792 return false;
793 } else if (Entry.isInt()) {
794 // If there is an expression, emit raw unsigned bytes.
795 DwarfExpr.addUnsignedConstant(Entry.getInt());
796 } else if (Entry.isConstantFP()) {
797 // DwarfExpression does not support arguments wider than 64 bits
798 // (see PR52584).
799 // TODO: Consider chunking expressions containing overly wide
800 // arguments into separate pointer-sized fragment expressions.
801 APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
802 if (RawBytes.getBitWidth() > 64)
803 return false;
804 DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
805 } else if (Entry.isConstantInt()) {
806 APInt RawBytes = Entry.getConstantInt()->getValue();
807 if (RawBytes.getBitWidth() > 64)
808 return false;
809 DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
810 } else if (Entry.isTargetIndexLocation()) {
811 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
812 // TODO TargetIndexLocation is a target-independent. Currently only the
813 // WebAssembly-specific encoding is supported.
814 assert(Asm->TM.getTargetTriple().isWasm())(static_cast <bool> (Asm->TM.getTargetTriple().isWasm
()) ? void (0) : __assert_fail ("Asm->TM.getTargetTriple().isWasm()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 814, __extension__
__PRETTY_FUNCTION__))
;
815 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
816 } else {
817 llvm_unreachable("Unsupported Entry type.")::llvm::llvm_unreachable_internal("Unsupported Entry type.", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 817)
;
818 }
819 return true;
820 };
821
822 if (!DwarfExpr.addExpression(
823 std::move(Cursor),
824 [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
825 return AddEntry(DVal->getLocEntries()[Idx], Cursor);
826 }))
827 return VariableDie;
828
829 // Now attach the location information to the DIE.
830 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
831 if (DwarfExpr.TagOffset)
832 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
833 *DwarfExpr.TagOffset);
834
835 return VariableDie;
836 }
837
838 // .. else use frame index.
839 if (!DV.hasFrameIndexExprs())
840 return VariableDie;
841
842 Optional<unsigned> NVPTXAddressSpace;
843 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
844 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
845 for (auto &Fragment : DV.getFrameIndexExprs()) {
846 Register FrameReg;
847 const DIExpression *Expr = Fragment.Expr;
848 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
849 StackOffset Offset =
850 TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
851 DwarfExpr.addFragmentOffset(Expr);
852
853 auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
854 SmallVector<uint64_t, 8> Ops;
855 TRI->getOffsetOpcodes(Offset, Ops);
856
857 // According to
858 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
859 // cuda-gdb requires DW_AT_address_class for all variables to be able to
860 // correctly interpret address space of the variable address.
861 // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
862 // sequence for the NVPTX + gdb target.
863 unsigned LocalNVPTXAddressSpace;
864 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
865 const DIExpression *NewExpr =
866 DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
867 if (NewExpr != Expr) {
868 Expr = NewExpr;
869 NVPTXAddressSpace = LocalNVPTXAddressSpace;
870 }
871 }
872 if (Expr)
873 Ops.append(Expr->elements_begin(), Expr->elements_end());
874 DIExpressionCursor Cursor(Ops);
875 DwarfExpr.setMemoryLocationKind();
876 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
877 addOpAddress(*Loc, FrameSymbol);
878 else
879 DwarfExpr.addMachineRegExpression(
880 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
881 DwarfExpr.addExpression(std::move(Cursor));
882 }
883 if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
884 // According to
885 // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
886 // cuda-gdb requires DW_AT_address_class for all variables to be able to
887 // correctly interpret address space of the variable address.
888 const unsigned NVPTX_ADDR_local_space = 6;
889 addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
890 NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
891 }
892 addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
893 if (DwarfExpr.TagOffset)
894 addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
895 *DwarfExpr.TagOffset);
896
897 return VariableDie;
898}
899
900DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
901 const LexicalScope &Scope,
902 DIE *&ObjectPointer) {
903 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
904 if (DV.isObjectPointer())
905 ObjectPointer = Var;
906 return Var;
907}
908
909/// Return all DIVariables that appear in count: expressions.
910static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
911 SmallVector<const DIVariable *, 2> Result;
912 auto *Array = dyn_cast<DICompositeType>(Var->getType());
913 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
914 return Result;
915 if (auto *DLVar = Array->getDataLocation())
916 Result.push_back(DLVar);
917 if (auto *AsVar = Array->getAssociated())
918 Result.push_back(AsVar);
919 if (auto *AlVar = Array->getAllocated())
920 Result.push_back(AlVar);
921 for (auto *El : Array->getElements()) {
922 if (auto *Subrange = dyn_cast<DISubrange>(El)) {
923 if (auto Count = Subrange->getCount())
924 if (auto *Dependency = Count.dyn_cast<DIVariable *>())
925 Result.push_back(Dependency);
926 if (auto LB = Subrange->getLowerBound())
927 if (auto *Dependency = LB.dyn_cast<DIVariable *>())
928 Result.push_back(Dependency);
929 if (auto UB = Subrange->getUpperBound())
930 if (auto *Dependency = UB.dyn_cast<DIVariable *>())
931 Result.push_back(Dependency);
932 if (auto ST = Subrange->getStride())
933 if (auto *Dependency = ST.dyn_cast<DIVariable *>())
934 Result.push_back(Dependency);
935 } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
936 if (auto Count = GenericSubrange->getCount())
937 if (auto *Dependency = Count.dyn_cast<DIVariable *>())
938 Result.push_back(Dependency);
939 if (auto LB = GenericSubrange->getLowerBound())
940 if (auto *Dependency = LB.dyn_cast<DIVariable *>())
941 Result.push_back(Dependency);
942 if (auto UB = GenericSubrange->getUpperBound())
943 if (auto *Dependency = UB.dyn_cast<DIVariable *>())
944 Result.push_back(Dependency);
945 if (auto ST = GenericSubrange->getStride())
946 if (auto *Dependency = ST.dyn_cast<DIVariable *>())
947 Result.push_back(Dependency);
948 }
949 }
950 return Result;
951}
952
953/// Sort local variables so that variables appearing inside of helper
954/// expressions come first.
955static SmallVector<DbgVariable *, 8>
956sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
957 SmallVector<DbgVariable *, 8> Result;
958 SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
959 // Map back from a DIVariable to its containing DbgVariable.
960 SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
961 // Set of DbgVariables in Result.
962 SmallDenseSet<DbgVariable *, 8> Visited;
963 // For cycle detection.
964 SmallDenseSet<DbgVariable *, 8> Visiting;
965
966 // Initialize the worklist and the DIVariable lookup table.
967 for (auto Var : reverse(Input)) {
968 DbgVar.insert({Var->getVariable(), Var});
969 WorkList.push_back({Var, 0});
970 }
971
972 // Perform a stable topological sort by doing a DFS.
973 while (!WorkList.empty()) {
974 auto Item = WorkList.back();
975 DbgVariable *Var = Item.getPointer();
976 bool visitedAllDependencies = Item.getInt();
977 WorkList.pop_back();
978
979 assert(Var)(static_cast <bool> (Var) ? void (0) : __assert_fail ("Var"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 979, __extension__
__PRETTY_FUNCTION__))
;
980
981 // Already handled.
982 if (Visited.count(Var))
983 continue;
984
985 // Add to Result if all dependencies are visited.
986 if (visitedAllDependencies) {
987 Visited.insert(Var);
988 Result.push_back(Var);
989 continue;
990 }
991
992 // Detect cycles.
993 auto Res = Visiting.insert(Var);
994 if (!Res.second) {
995 assert(false && "dependency cycle in local variables")(static_cast <bool> (false && "dependency cycle in local variables"
) ? void (0) : __assert_fail ("false && \"dependency cycle in local variables\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 995, __extension__
__PRETTY_FUNCTION__))
;
996 return Result;
997 }
998
999 // Push dependencies and this node onto the worklist, so that this node is
1000 // visited again after all of its dependencies are handled.
1001 WorkList.push_back({Var, 1});
1002 for (auto *Dependency : dependencies(Var)) {
1003 // Don't add dependency if it is in a different lexical scope or a global.
1004 if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
1005 if (DbgVariable *Var = DbgVar.lookup(Dep))
1006 WorkList.push_back({Var, 0});
1007 }
1008 }
1009 return Result;
1010}
1011
1012DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1013 LexicalScope *Scope) {
1014 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
1015
1016 if (Scope) {
1017 assert(!Scope->getInlinedAt())(static_cast <bool> (!Scope->getInlinedAt()) ? void (
0) : __assert_fail ("!Scope->getInlinedAt()", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018 assert(!Scope->isAbstractScope())(static_cast <bool> (!Scope->isAbstractScope()) ? void
(0) : __assert_fail ("!Scope->isAbstractScope()", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1018, __extension__ __PRETTY_FUNCTION__))
;
1019 // Collect lexical scope children first.
1020 // ObjectPointer might be a local (non-argument) local variable if it's a
1021 // block's synthetic this pointer.
1022 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1023 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1024 }
1025
1026 // If this is a variadic function, add an unspecified parameter.
1027 DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
1028
1029 // If we have a single element of null, it is a function that returns void.
1030 // If we have more than one elements and the last one is null, it is a
1031 // variadic function.
1032 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1033 !includeMinimalInlineScopes())
1034 ScopeDIE.addChild(
1035 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1036
1037 return ScopeDIE;
1038}
1039
1040DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1041 DIE &ScopeDIE) {
1042 DIE *ObjectPointer = nullptr;
1043
1044 // Emit function arguments (order is significant).
1045 auto Vars = DU->getScopeVariables().lookup(Scope);
1046 for (auto &DV : Vars.Args)
1047 ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1048
1049 // Emit local variables.
1050 auto Locals = sortLocalVars(Vars.Locals);
1051 for (DbgVariable *DV : Locals)
1052 ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
1053
1054 // Emit imported entities (skipped in gmlt-like data).
1055 if (!includeMinimalInlineScopes()) {
1056 for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
1057 ScopeDIE.addChild(constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
1058 }
1059
1060 // Emit labels.
1061 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1062 ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
1063
1064 // Emit inner lexical scopes.
1065 auto needToEmitLexicalScope = [this](LexicalScope *LS) {
1066 if (isa<DISubprogram>(LS->getScopeNode()))
1067 return true;
1068 auto Vars = DU->getScopeVariables().lookup(LS);
1069 if (!Vars.Args.empty() || !Vars.Locals.empty())
1070 return true;
1071 if (!includeMinimalInlineScopes() &&
1072 !ImportedEntities[LS->getScopeNode()].empty())
1073 return true;
1074 return false;
1075 };
1076 for (LexicalScope *LS : Scope->getChildren()) {
1077 // If the lexical block doesn't have non-scope children, skip
1078 // its emission and put its children directly to the parent scope.
1079 if (needToEmitLexicalScope(LS))
1080 constructScopeDIE(LS, ScopeDIE);
1081 else
1082 createAndAddScopeChildren(LS, ScopeDIE);
1083 }
1084
1085 return ObjectPointer;
1086}
1087
1088void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
1089 LexicalScope *Scope) {
1090 DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
1091 if (AbsDef)
1092 return;
1093
1094 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
1095
1096 DIE *ContextDIE;
1097 DwarfCompileUnit *ContextCU = this;
1098
1099 if (includeMinimalInlineScopes())
1100 ContextDIE = &getUnitDie();
1101 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
1102 // the important distinction that the debug node is not associated with the
1103 // DIE (since the debug node will be associated with the concrete DIE, if
1104 // any). It could be refactored to some common utility function.
1105 else if (auto *SPDecl = SP->getDeclaration()) {
1106 ContextDIE = &getUnitDie();
1107 getOrCreateSubprogramDIE(SPDecl);
1108 } else {
1109 ContextDIE = getOrCreateContextDIE(SP->getScope());
1110 // The scope may be shared with a subprogram that has already been
1111 // constructed in another CU, in which case we need to construct this
1112 // subprogram in the same CU.
1113 ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
1114 }
1115
1116 // Passing null as the associated node because the abstract definition
1117 // shouldn't be found by lookup.
1118 AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
1119 ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
1120 ContextCU->addSInt(*AbsDef, dwarf::DW_AT_inline,
1121 DD->getDwarfVersion() <= 4 ? Optional<dwarf::Form>()
1122 : dwarf::DW_FORM_implicit_const,
1123 dwarf::DW_INL_inlined);
1124 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1125 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
1126}
1127
1128bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1129 return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
8
Assuming the condition is false
9
Returning zero, which participates in a condition later
1130}
1131
1132dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1133 if (!useGNUAnalogForDwarf5Feature())
1134 return Tag;
1135 switch (Tag) {
1136 case dwarf::DW_TAG_call_site:
1137 return dwarf::DW_TAG_GNU_call_site;
1138 case dwarf::DW_TAG_call_site_parameter:
1139 return dwarf::DW_TAG_GNU_call_site_parameter;
1140 default:
1141 llvm_unreachable("DWARF5 tag with no GNU analog")::llvm::llvm_unreachable_internal("DWARF5 tag with no GNU analog"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1141)
;
1142 }
1143}
1144
1145dwarf::Attribute
1146DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1147 if (!useGNUAnalogForDwarf5Feature())
1148 return Attr;
1149 switch (Attr) {
1150 case dwarf::DW_AT_call_all_calls:
1151 return dwarf::DW_AT_GNU_all_call_sites;
1152 case dwarf::DW_AT_call_target:
1153 return dwarf::DW_AT_GNU_call_site_target;
1154 case dwarf::DW_AT_call_origin:
1155 return dwarf::DW_AT_abstract_origin;
1156 case dwarf::DW_AT_call_return_pc:
1157 return dwarf::DW_AT_low_pc;
1158 case dwarf::DW_AT_call_value:
1159 return dwarf::DW_AT_GNU_call_site_value;
1160 case dwarf::DW_AT_call_tail_call:
1161 return dwarf::DW_AT_GNU_tail_call;
1162 default:
1163 llvm_unreachable("DWARF5 attribute with no GNU analog")::llvm::llvm_unreachable_internal("DWARF5 attribute with no GNU analog"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1163)
;
1164 }
1165}
1166
1167dwarf::LocationAtom
1168DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1169 if (!useGNUAnalogForDwarf5Feature())
1170 return Loc;
1171 switch (Loc) {
1172 case dwarf::DW_OP_entry_value:
1173 return dwarf::DW_OP_GNU_entry_value;
1174 default:
1175 llvm_unreachable("DWARF5 location atom with no GNU analog")::llvm::llvm_unreachable_internal("DWARF5 location atom with no GNU analog"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1175)
;
1176 }
1177}
1178
1179DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1180 const DISubprogram *CalleeSP,
1181 bool IsTail,
1182 const MCSymbol *PCAddr,
1183 const MCSymbol *CallAddr,
1184 unsigned CallReg) {
1185 // Insert a call site entry DIE within ScopeDIE.
1186 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1187 ScopeDIE, nullptr);
1188
1189 if (CallReg) {
1
Assuming 'CallReg' is 0
2
Taking false branch
1190 // Indirect call.
1191 addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
1192 MachineLocation(CallReg));
1193 } else {
1194 DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
1195 assert(CalleeDIE && "Could not create DIE for call site entry origin")(static_cast <bool> (CalleeDIE && "Could not create DIE for call site entry origin"
) ? void (0) : __assert_fail ("CalleeDIE && \"Could not create DIE for call site entry origin\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1195, __extension__
__PRETTY_FUNCTION__))
;
3
Assuming 'CalleeDIE' is non-null
4
'?' condition is true
1196 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1197 *CalleeDIE);
1198 }
1199
1200 if (IsTail) {
5
Assuming 'IsTail' is true
6
Taking true branch
1201 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1202 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1203
1204 // Attach the address of the branch instruction to allow the debugger to
1205 // show where the tail call occurred. This attribute has no GNU analog.
1206 //
1207 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1208 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1209 // site entries to figure out the PC of tail-calling branch instructions.
1210 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1211 // don't emit it here.
1212 //
1213 // There's no need to tie non-GDB debuggers to this non-standardness, as it
1214 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1215 // the standard DW_AT_call_pc info.
1216 if (!useGNUAnalogForDwarf5Feature())
7
Calling 'DwarfCompileUnit::useGNUAnalogForDwarf5Feature'
10
Returning from 'DwarfCompileUnit::useGNUAnalogForDwarf5Feature'
11
Taking true branch
1217 addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
12
Passing value via 3rd parameter 'Label'
13
Calling 'DwarfCompileUnit::addLabelAddress'
1218 }
1219
1220 // Attach the return PC to allow the debugger to disambiguate call paths
1221 // from one function to another.
1222 //
1223 // The return PC is only really needed when the call /isn't/ a tail call, but
1224 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1225 // the DW_AT_call_pc emission logic for an explanation).
1226 if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1227 assert(PCAddr && "Missing return PC information for a call")(static_cast <bool> (PCAddr && "Missing return PC information for a call"
) ? void (0) : __assert_fail ("PCAddr && \"Missing return PC information for a call\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1227, __extension__
__PRETTY_FUNCTION__))
;
1228 addLabelAddress(CallSiteDIE,
1229 getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1230 }
1231
1232 return CallSiteDIE;
1233}
1234
1235void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1236 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1237 for (const auto &Param : Params) {
1238 unsigned Register = Param.getRegister();
1239 auto CallSiteDieParam =
1240 DIE::get(DIEValueAllocator,
1241 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1242 insertDIE(CallSiteDieParam);
1243 addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1244 MachineLocation(Register));
1245
1246 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1247 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1248 DwarfExpr.setCallSiteParamValueFlag();
1249
1250 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1251
1252 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1253 DwarfExpr.finalize());
1254
1255 CallSiteDIE.addChild(CallSiteDieParam);
1256 }
1257}
1258
1259DIE *DwarfCompileUnit::constructImportedEntityDIE(
1260 const DIImportedEntity *Module) {
1261 DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1262 insertDIE(Module, IMDie);
1263 DIE *EntityDie;
1264 auto *Entity = Module->getEntity();
1265 if (auto *NS = dyn_cast<DINamespace>(Entity))
1266 EntityDie = getOrCreateNameSpace(NS);
1267 else if (auto *M = dyn_cast<DIModule>(Entity))
1268 EntityDie = getOrCreateModule(M);
1269 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1270 EntityDie = getOrCreateSubprogramDIE(SP);
1271 else if (auto *T = dyn_cast<DIType>(Entity))
1272 EntityDie = getOrCreateTypeDIE(T);
1273 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1274 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1275 else
1276 EntityDie = getDIE(Entity);
1277 assert(EntityDie)(static_cast <bool> (EntityDie) ? void (0) : __assert_fail
("EntityDie", "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp"
, 1277, __extension__ __PRETTY_FUNCTION__))
;
1278 addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1279 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1280 StringRef Name = Module->getName();
1281 if (!Name.empty())
1282 addString(*IMDie, dwarf::DW_AT_name, Name);
1283
1284 // This is for imported module with renamed entities (such as variables and
1285 // subprograms).
1286 DINodeArray Elements = Module->getElements();
1287 for (const auto *Element : Elements) {
1288 if (!Element)
1289 continue;
1290 IMDie->addChild(
1291 constructImportedEntityDIE(cast<DIImportedEntity>(Element)));
1292 }
1293
1294 return IMDie;
1295}
1296
1297void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1298 DIE *D = getDIE(SP);
1299 if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1300 if (D)
1301 // If this subprogram has an abstract definition, reference that
1302 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1303 } else {
1304 assert(D || includeMinimalInlineScopes())(static_cast <bool> (D || includeMinimalInlineScopes())
? void (0) : __assert_fail ("D || includeMinimalInlineScopes()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1304, __extension__
__PRETTY_FUNCTION__))
;
1305 if (D)
1306 // And attach the attributes
1307 applySubprogramAttributesToDefinition(SP, *D);
1308 }
1309}
1310
1311void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1312 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1313
1314 auto *Die = Entity->getDIE();
1315 /// Label may be used to generate DW_AT_low_pc, so put it outside
1316 /// if/else block.
1317 const DbgLabel *Label = nullptr;
1318 if (AbsEntity && AbsEntity->getDIE()) {
1319 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1320 Label = dyn_cast<const DbgLabel>(Entity);
1321 } else {
1322 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1323 applyVariableAttributes(*Var, *Die);
1324 else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1325 applyLabelAttributes(*Label, *Die);
1326 else
1327 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.")::llvm::llvm_unreachable_internal("DbgEntity must be DbgVariable or DbgLabel."
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1327)
;
1328 }
1329
1330 if (Label)
1331 if (const auto *Sym = Label->getSymbol())
1332 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1333}
1334
1335DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1336 auto &AbstractEntities = getAbstractEntities();
1337 auto I = AbstractEntities.find(Node);
1338 if (I != AbstractEntities.end())
1339 return I->second.get();
1340 return nullptr;
1341}
1342
1343void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1344 LexicalScope *Scope) {
1345 assert(Scope && Scope->isAbstractScope())(static_cast <bool> (Scope && Scope->isAbstractScope
()) ? void (0) : __assert_fail ("Scope && Scope->isAbstractScope()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1345, __extension__
__PRETTY_FUNCTION__))
;
1346 auto &Entity = getAbstractEntities()[Node];
1347 if (isa<const DILocalVariable>(Node)) {
1348 Entity = std::make_unique<DbgVariable>(
1349 cast<const DILocalVariable>(Node), nullptr /* IA */);;
1350 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1351 } else if (isa<const DILabel>(Node)) {
1352 Entity = std::make_unique<DbgLabel>(
1353 cast<const DILabel>(Node), nullptr /* IA */);
1354 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1355 }
1356}
1357
1358void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1359 // Don't bother labeling the .dwo unit, as its offset isn't used.
1360 if (!Skeleton && !DD->useSectionsAsReferences()) {
1361 LabelBegin = Asm->createTempSymbol("cu_begin");
1362 Asm->OutStreamer->emitLabel(LabelBegin);
1363 }
1364
1365 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1366 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1367 : dwarf::DW_UT_compile;
1368 DwarfUnit::emitCommonHeader(UseOffsets, UT);
1369 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1370 Asm->emitInt64(getDWOId());
1371}
1372
1373bool DwarfCompileUnit::hasDwarfPubSections() const {
1374 switch (CUNode->getNameTableKind()) {
1375 case DICompileUnit::DebugNameTableKind::None:
1376 return false;
1377 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1378 // generated for things like Gold's gdb_index generation.
1379 case DICompileUnit::DebugNameTableKind::GNU:
1380 return true;
1381 case DICompileUnit::DebugNameTableKind::Default:
1382 return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1383 !CUNode->isDebugDirectivesOnly() &&
1384 DD->getAccelTableKind() != AccelTableKind::Apple &&
1385 DD->getDwarfVersion() < 5;
1386 }
1387 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum")::llvm::llvm_unreachable_internal("Unhandled DICompileUnit::DebugNameTableKind enum"
, "llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp", 1387)
;
1388}
1389
1390/// addGlobalName - Add a new global name to the compile unit.
1391void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1392 const DIScope *Context) {
1393 if (!hasDwarfPubSections())
1394 return;
1395 std::string FullName = getParentContextString(Context) + Name.str();
1396 GlobalNames[FullName] = &Die;
1397}
1398
1399void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1400 const DIScope *Context) {
1401 if (!hasDwarfPubSections())
1402 return;
1403 std::string FullName = getParentContextString(Context) + Name.str();
1404 // Insert, allowing the entry to remain as-is if it's already present
1405 // This way the CU-level type DIE is preferred over the "can't describe this
1406 // type as a unit offset because it's not really in the CU at all, it's only
1407 // in a type unit"
1408 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1409}
1410
1411/// Add a new global type to the unit.
1412void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1413 const DIScope *Context) {
1414 if (!hasDwarfPubSections())
1415 return;
1416 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1417 GlobalTypes[FullName] = &Die;
1418}
1419
1420void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1421 const DIScope *Context) {
1422 if (!hasDwarfPubSections())
1423 return;
1424 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1425 // Insert, allowing the entry to remain as-is if it's already present
1426 // This way the CU-level type DIE is preferred over the "can't describe this
1427 // type as a unit offset because it's not really in the CU at all, it's only
1428 // in a type unit"
1429 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1430}
1431
1432void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1433 MachineLocation Location) {
1434 if (DV.hasComplexAddress())
1435 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1436 else
1437 addAddress(Die, dwarf::DW_AT_location, Location);
1438}
1439
1440/// Add an address attribute to a die based on the location provided.
1441void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1442 const MachineLocation &Location) {
1443 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1444 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1445 if (Location.isIndirect())
1446 DwarfExpr.setMemoryLocationKind();
1447
1448 DIExpressionCursor Cursor({});
1449 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1450 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1451 return;
1452 DwarfExpr.addExpression(std::move(Cursor));
1453
1454 // Now attach the location information to the DIE.
1455 addBlock(Die, Attribute, DwarfExpr.finalize());
1456
1457 if (DwarfExpr.TagOffset)
1458 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1459 *DwarfExpr.TagOffset);
1460}
1461
1462/// Start with the address based on the location provided, and generate the
1463/// DWARF information necessary to find the actual variable given the extra
1464/// address information encoded in the DbgVariable, starting from the starting
1465/// location. Add the DWARF information to the die.
1466void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1467 dwarf::Attribute Attribute,
1468 const MachineLocation &Location) {
1469 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1470 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1471 const DIExpression *DIExpr = DV.getSingleExpression();
1472 DwarfExpr.addFragmentOffset(DIExpr);
1473 DwarfExpr.setLocation(Location, DIExpr);
1474
1475 DIExpressionCursor Cursor(DIExpr);
1476
1477 if (DIExpr->isEntryValue())
1478 DwarfExpr.beginEntryValueExpression(Cursor);
1479
1480 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1481 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1482 return;
1483 DwarfExpr.addExpression(std::move(Cursor));
1484
1485 // Now attach the location information to the DIE.
1486 addBlock(Die, Attribute, DwarfExpr.finalize());
1487
1488 if (DwarfExpr.TagOffset)
1489 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1490 *DwarfExpr.TagOffset);
1491}
1492
1493/// Add a Dwarf loclistptr attribute data and value.
1494void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1495 unsigned Index) {
1496 dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1497 ? dwarf::DW_FORM_loclistx
1498 : DD->getDwarfSectionOffsetForm();
1499 addAttribute(Die, Attribute, Form, DIELocList(Index));
1500}
1501
1502void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1503 DIE &VariableDie) {
1504 StringRef Name = Var.getName();
1505 if (!Name.empty())
1506 addString(VariableDie, dwarf::DW_AT_name, Name);
1507 const auto *DIVar = Var.getVariable();
1508 if (DIVar) {
1509 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1510 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1511 AlignInBytes);
1512 addAnnotation(VariableDie, DIVar->getAnnotations());
1513 }
1514
1515 addSourceLine(VariableDie, DIVar);
1516 addType(VariableDie, Var.getType());
1517 if (Var.isArtificial())
1518 addFlag(VariableDie, dwarf::DW_AT_artificial);
1519}
1520
1521void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1522 DIE &LabelDie) {
1523 StringRef Name = Label.getName();
1524 if (!Name.empty())
1525 addString(LabelDie, dwarf::DW_AT_name, Name);
1526 const auto *DILabel = Label.getLabel();
1527 addSourceLine(LabelDie, DILabel);
1528}
1529
1530/// Add a Dwarf expression attribute data and value.
1531void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1532 const MCExpr *Expr) {
1533 addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1534}
1535
1536void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1537 const DISubprogram *SP, DIE &SPDie) {
1538 auto *SPDecl = SP->getDeclaration();
1539 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1540 applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1541 addGlobalName(SP->getName(), SPDie, Context);
1542}
1543
1544bool DwarfCompileUnit::isDwoUnit() const {
1545 return DD->useSplitDwarf() && Skeleton;
1546}
1547
1548void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1549 constructTypeDIE(D, CTy);
1550}
1551
1552bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1553 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1554 (DD->useSplitDwarf() && !Skeleton);
1555}
1556
1557void DwarfCompileUnit::addAddrTableBase() {
1558 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1559 MCSymbol *Label = DD->getAddressPool().getLabel();
1560 addSectionLabel(getUnitDie(),
1561 DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1562 : dwarf::DW_AT_GNU_addr_base,
1563 Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1564}
1565
1566void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1567 addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1568 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1569}
1570
1571void DwarfCompileUnit::createBaseTypeDIEs() {
1572 // Insert the base_type DIEs directly after the CU so that their offsets will
1573 // fit in the fixed size ULEB128 used inside the location expressions.
1574 // Maintain order by iterating backwards and inserting to the front of CU
1575 // child list.
1576 for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1577 DIE &Die = getUnitDie().addChildFront(
1578 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1579 SmallString<32> Str;
1580 addString(Die, dwarf::DW_AT_name,
1581 Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1582 "_" + Twine(Btr.BitSize)).toStringRef(Str));
1583 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1584 addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1585
1586 Btr.Die = &Die;
1587 }
1588}