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