Bug Summary

File:build/source/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
Warning:line 1573, column 3
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 DwarfDebug.cpp -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/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I lib/CodeGen/AsmPrinter -I /build/source/llvm/lib/CodeGen/AsmPrinter -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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-17/lib/clang/17/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/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -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 -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -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-2023-05-10-133810-16478-1 -x c++ /build/source/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
1//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
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 writing dwarf debug info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfDebug.h"
14#include "ByteStreamer.h"
15#include "DIEHash.h"
16#include "DwarfCompileUnit.h"
17#include "DwarfExpression.h"
18#include "DwarfUnit.h"
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/CodeGen/AsmPrinter.h"
23#include "llvm/CodeGen/DIE.h"
24#include "llvm/CodeGen/LexicalScopes.h"
25#include "llvm/CodeGen/MachineBasicBlock.h"
26#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/CodeGen/MachineOperand.h"
29#include "llvm/CodeGen/TargetInstrInfo.h"
30#include "llvm/CodeGen/TargetLowering.h"
31#include "llvm/CodeGen/TargetRegisterInfo.h"
32#include "llvm/CodeGen/TargetSubtargetInfo.h"
33#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
34#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Module.h"
39#include "llvm/MC/MCAsmInfo.h"
40#include "llvm/MC/MCContext.h"
41#include "llvm/MC/MCSection.h"
42#include "llvm/MC/MCStreamer.h"
43#include "llvm/MC/MCSymbol.h"
44#include "llvm/MC/MCTargetOptions.h"
45#include "llvm/MC/MachineLocation.h"
46#include "llvm/MC/SectionKind.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/MD5.h"
52#include "llvm/Support/raw_ostream.h"
53#include "llvm/Target/TargetLoweringObjectFile.h"
54#include "llvm/Target/TargetMachine.h"
55#include "llvm/TargetParser/Triple.h"
56#include <algorithm>
57#include <cstddef>
58#include <iterator>
59#include <optional>
60#include <string>
61
62using namespace llvm;
63
64#define DEBUG_TYPE"dwarfdebug" "dwarfdebug"
65
66STATISTIC(NumCSParams, "Number of dbg call site params created")static llvm::Statistic NumCSParams = {"dwarfdebug", "NumCSParams"
, "Number of dbg call site params created"}
;
67
68static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
69 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
70 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
71
72static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73 cl::Hidden,
74 cl::desc("Generate dwarf aranges"),
75 cl::init(false));
76
77static cl::opt<bool>
78 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
79 cl::desc("Generate DWARF4 type units."),
80 cl::init(false));
81
82static cl::opt<bool> SplitDwarfCrossCuReferences(
83 "split-dwarf-cross-cu-references", cl::Hidden,
84 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
85
86enum DefaultOnOff { Default, Enable, Disable };
87
88static cl::opt<DefaultOnOff> UnknownLocations(
89 "use-unknown-locations", cl::Hidden,
90 cl::desc("Make an absence of debug location information explicit."),
91 cl::values(clEnumVal(Default, "At top of block or after label")llvm::cl::OptionEnumValue { "Default", int(Default), "At top of block or after label"
}
,
92 clEnumVal(Enable, "In all cases")llvm::cl::OptionEnumValue { "Enable", int(Enable), "In all cases"
}
, clEnumVal(Disable, "Never")llvm::cl::OptionEnumValue { "Disable", int(Disable), "Never" }),
93 cl::init(Default));
94
95static cl::opt<AccelTableKind> AccelTables(
96 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
97 cl::values(clEnumValN(AccelTableKind::Default, "Default",llvm::cl::OptionEnumValue { "Default", int(AccelTableKind::Default
), "Default for platform" }
98 "Default for platform")llvm::cl::OptionEnumValue { "Default", int(AccelTableKind::Default
), "Default for platform" }
,
99 clEnumValN(AccelTableKind::None, "Disable", "Disabled.")llvm::cl::OptionEnumValue { "Disable", int(AccelTableKind::None
), "Disabled." }
,
100 clEnumValN(AccelTableKind::Apple, "Apple", "Apple")llvm::cl::OptionEnumValue { "Apple", int(AccelTableKind::Apple
), "Apple" }
,
101 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")llvm::cl::OptionEnumValue { "Dwarf", int(AccelTableKind::Dwarf
), "DWARF" }
),
102 cl::init(AccelTableKind::Default));
103
104static cl::opt<DefaultOnOff>
105DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
106 cl::desc("Use inlined strings rather than string section."),
107 cl::values(clEnumVal(Default, "Default for platform")llvm::cl::OptionEnumValue { "Default", int(Default), "Default for platform"
}
,
108 clEnumVal(Enable, "Enabled")llvm::cl::OptionEnumValue { "Enable", int(Enable), "Enabled" },
109 clEnumVal(Disable, "Disabled")llvm::cl::OptionEnumValue { "Disable", int(Disable), "Disabled"
}
),
110 cl::init(Default));
111
112static cl::opt<bool>
113 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
114 cl::desc("Disable emission .debug_ranges section."),
115 cl::init(false));
116
117static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
118 "dwarf-sections-as-references", cl::Hidden,
119 cl::desc("Use sections+offset as references rather than labels."),
120 cl::values(clEnumVal(Default, "Default for platform")llvm::cl::OptionEnumValue { "Default", int(Default), "Default for platform"
}
,
121 clEnumVal(Enable, "Enabled")llvm::cl::OptionEnumValue { "Enable", int(Enable), "Enabled" }, clEnumVal(Disable, "Disabled")llvm::cl::OptionEnumValue { "Disable", int(Disable), "Disabled"
}
),
122 cl::init(Default));
123
124static cl::opt<bool>
125 UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
126 cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
127 cl::init(false));
128
129static cl::opt<DefaultOnOff> DwarfOpConvert(
130 "dwarf-op-convert", cl::Hidden,
131 cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
132 cl::values(clEnumVal(Default, "Default for platform")llvm::cl::OptionEnumValue { "Default", int(Default), "Default for platform"
}
,
133 clEnumVal(Enable, "Enabled")llvm::cl::OptionEnumValue { "Enable", int(Enable), "Enabled" }, clEnumVal(Disable, "Disabled")llvm::cl::OptionEnumValue { "Disable", int(Disable), "Disabled"
}
),
134 cl::init(Default));
135
136enum LinkageNameOption {
137 DefaultLinkageNames,
138 AllLinkageNames,
139 AbstractLinkageNames
140};
141
142static cl::opt<LinkageNameOption>
143 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
144 cl::desc("Which DWARF linkage-name attributes to emit."),
145 cl::values(clEnumValN(DefaultLinkageNames, "Default",llvm::cl::OptionEnumValue { "Default", int(DefaultLinkageNames
), "Default for platform" }
146 "Default for platform")llvm::cl::OptionEnumValue { "Default", int(DefaultLinkageNames
), "Default for platform" }
,
147 clEnumValN(AllLinkageNames, "All", "All")llvm::cl::OptionEnumValue { "All", int(AllLinkageNames), "All"
}
,
148 clEnumValN(AbstractLinkageNames, "Abstract",llvm::cl::OptionEnumValue { "Abstract", int(AbstractLinkageNames
), "Abstract subprograms" }
149 "Abstract subprograms")llvm::cl::OptionEnumValue { "Abstract", int(AbstractLinkageNames
), "Abstract subprograms" }
),
150 cl::init(DefaultLinkageNames));
151
152static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
153 "minimize-addr-in-v5", cl::Hidden,
154 cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
155 "address pool entry sharing to reduce relocations/object size"),
156 cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",llvm::cl::OptionEnumValue { "Default", int(DwarfDebug::MinimizeAddrInV5
::Default), "Default address minimization strategy" }
157 "Default address minimization strategy")llvm::cl::OptionEnumValue { "Default", int(DwarfDebug::MinimizeAddrInV5
::Default), "Default address minimization strategy" }
,
158 clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",llvm::cl::OptionEnumValue { "Ranges", int(DwarfDebug::MinimizeAddrInV5
::Ranges), "Use rnglists for contiguous ranges if that allows "
"using a pre-existing base address" }
159 "Use rnglists for contiguous ranges if that allows "llvm::cl::OptionEnumValue { "Ranges", int(DwarfDebug::MinimizeAddrInV5
::Ranges), "Use rnglists for contiguous ranges if that allows "
"using a pre-existing base address" }
160 "using a pre-existing base address")llvm::cl::OptionEnumValue { "Ranges", int(DwarfDebug::MinimizeAddrInV5
::Ranges), "Use rnglists for contiguous ranges if that allows "
"using a pre-existing base address" }
,
161 clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,llvm::cl::OptionEnumValue { "Expressions", int(DwarfDebug::MinimizeAddrInV5
::Expressions), "Use exprloc addrx+offset expressions for any "
"address with a prior base address" }
162 "Expressions",llvm::cl::OptionEnumValue { "Expressions", int(DwarfDebug::MinimizeAddrInV5
::Expressions), "Use exprloc addrx+offset expressions for any "
"address with a prior base address" }
163 "Use exprloc addrx+offset expressions for any "llvm::cl::OptionEnumValue { "Expressions", int(DwarfDebug::MinimizeAddrInV5
::Expressions), "Use exprloc addrx+offset expressions for any "
"address with a prior base address" }
164 "address with a prior base address")llvm::cl::OptionEnumValue { "Expressions", int(DwarfDebug::MinimizeAddrInV5
::Expressions), "Use exprloc addrx+offset expressions for any "
"address with a prior base address" }
,
165 clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",llvm::cl::OptionEnumValue { "Form", int(DwarfDebug::MinimizeAddrInV5
::Form), "Use addrx+offset extension form for any address " "with a prior base address"
}
166 "Use addrx+offset extension form for any address "llvm::cl::OptionEnumValue { "Form", int(DwarfDebug::MinimizeAddrInV5
::Form), "Use addrx+offset extension form for any address " "with a prior base address"
}
167 "with a prior base address")llvm::cl::OptionEnumValue { "Form", int(DwarfDebug::MinimizeAddrInV5
::Form), "Use addrx+offset extension form for any address " "with a prior base address"
}
,
168 clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",llvm::cl::OptionEnumValue { "Disabled", int(DwarfDebug::MinimizeAddrInV5
::Disabled), "Stuff" }
169 "Stuff")llvm::cl::OptionEnumValue { "Disabled", int(DwarfDebug::MinimizeAddrInV5
::Disabled), "Stuff" }
),
170 cl::init(DwarfDebug::MinimizeAddrInV5::Default));
171
172static constexpr unsigned ULEB128PadSize = 4;
173
174void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
175 getActiveStreamer().emitInt8(
176 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
177 : dwarf::OperationEncodingString(Op));
178}
179
180void DebugLocDwarfExpression::emitSigned(int64_t Value) {
181 getActiveStreamer().emitSLEB128(Value, Twine(Value));
182}
183
184void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
185 getActiveStreamer().emitULEB128(Value, Twine(Value));
186}
187
188void DebugLocDwarfExpression::emitData1(uint8_t Value) {
189 getActiveStreamer().emitInt8(Value, Twine(Value));
190}
191
192void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
193 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit")(static_cast <bool> (Idx < (1ULL << (ULEB128PadSize
* 7)) && "Idx wont fit") ? void (0) : __assert_fail (
"Idx < (1ULL << (ULEB128PadSize * 7)) && \"Idx wont fit\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 193, __extension__
__PRETTY_FUNCTION__))
;
194 getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
195}
196
197bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
198 llvm::Register MachineReg) {
199 // This information is not available while emitting .debug_loc entries.
200 return false;
201}
202
203void DebugLocDwarfExpression::enableTemporaryBuffer() {
204 assert(!IsBuffering && "Already buffering?")(static_cast <bool> (!IsBuffering && "Already buffering?"
) ? void (0) : __assert_fail ("!IsBuffering && \"Already buffering?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 204, __extension__
__PRETTY_FUNCTION__))
;
205 if (!TmpBuf)
206 TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
207 IsBuffering = true;
208}
209
210void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
211
212unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
213 return TmpBuf ? TmpBuf->Bytes.size() : 0;
214}
215
216void DebugLocDwarfExpression::commitTemporaryBuffer() {
217 if (!TmpBuf)
218 return;
219 for (auto Byte : enumerate(TmpBuf->Bytes)) {
220 const char *Comment = (Byte.index() < TmpBuf->Comments.size())
221 ? TmpBuf->Comments[Byte.index()].c_str()
222 : "";
223 OutBS.emitInt8(Byte.value(), Comment);
224 }
225 TmpBuf->Bytes.clear();
226 TmpBuf->Comments.clear();
227}
228
229const DIType *DbgVariable::getType() const {
230 return getVariable()->getType();
231}
232
233/// Get .debug_loc entry for the instruction range starting at MI.
234static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
235 const DIExpression *Expr = MI->getDebugExpression();
236 const bool IsVariadic = MI->isDebugValueList();
237 assert(MI->getNumOperands() >= 3)(static_cast <bool> (MI->getNumOperands() >= 3) ?
void (0) : __assert_fail ("MI->getNumOperands() >= 3",
"llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 237, __extension__
__PRETTY_FUNCTION__))
;
238 SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
239 for (const MachineOperand &Op : MI->debug_operands()) {
240 if (Op.isReg()) {
241 MachineLocation MLoc(Op.getReg(),
242 MI->isNonListDebugValue() && MI->isDebugOffsetImm());
243 DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
244 } else if (Op.isTargetIndex()) {
245 DbgValueLocEntries.push_back(
246 DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
247 } else if (Op.isImm())
248 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
249 else if (Op.isFPImm())
250 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
251 else if (Op.isCImm())
252 DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
253 else
254 llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!")::llvm::llvm_unreachable_internal("Unexpected debug operand in DBG_VALUE* instruction!"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 254)
;
255 }
256 return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
257}
258
259void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
260 assert(FrameIndexExprs.empty() && "Already initialized?")(static_cast <bool> (FrameIndexExprs.empty() &&
"Already initialized?") ? void (0) : __assert_fail ("FrameIndexExprs.empty() && \"Already initialized?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 260, __extension__
__PRETTY_FUNCTION__))
;
261 assert(!ValueLoc.get() && "Already initialized?")(static_cast <bool> (!ValueLoc.get() && "Already initialized?"
) ? void (0) : __assert_fail ("!ValueLoc.get() && \"Already initialized?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 261, __extension__
__PRETTY_FUNCTION__))
;
262
263 assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable")(static_cast <bool> (getVariable() == DbgValue->getDebugVariable
() && "Wrong variable") ? void (0) : __assert_fail ("getVariable() == DbgValue->getDebugVariable() && \"Wrong variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 263, __extension__
__PRETTY_FUNCTION__))
;
264 assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&(static_cast <bool> (getInlinedAt() == DbgValue->getDebugLoc
()->getInlinedAt() && "Wrong inlined-at") ? void (
0) : __assert_fail ("getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() && \"Wrong inlined-at\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 265, __extension__
__PRETTY_FUNCTION__))
265 "Wrong inlined-at")(static_cast <bool> (getInlinedAt() == DbgValue->getDebugLoc
()->getInlinedAt() && "Wrong inlined-at") ? void (
0) : __assert_fail ("getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() && \"Wrong inlined-at\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 265, __extension__
__PRETTY_FUNCTION__))
;
266
267 ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
268 if (auto *E = DbgValue->getDebugExpression())
269 if (E->getNumElements())
270 FrameIndexExprs.push_back({0, E});
271}
272
273ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
274 if (FrameIndexExprs.size() == 1)
275 return FrameIndexExprs;
276
277 assert(llvm::all_of(FrameIndexExprs,(static_cast <bool> (llvm::all_of(FrameIndexExprs, [](const
FrameIndexExpr &A) { return A.Expr->isFragment(); }) &&
"multiple FI expressions without DW_OP_LLVM_fragment") ? void
(0) : __assert_fail ("llvm::all_of(FrameIndexExprs, [](const FrameIndexExpr &A) { return A.Expr->isFragment(); }) && \"multiple FI expressions without DW_OP_LLVM_fragment\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 281, __extension__
__PRETTY_FUNCTION__))
278 [](const FrameIndexExpr &A) {(static_cast <bool> (llvm::all_of(FrameIndexExprs, [](const
FrameIndexExpr &A) { return A.Expr->isFragment(); }) &&
"multiple FI expressions without DW_OP_LLVM_fragment") ? void
(0) : __assert_fail ("llvm::all_of(FrameIndexExprs, [](const FrameIndexExpr &A) { return A.Expr->isFragment(); }) && \"multiple FI expressions without DW_OP_LLVM_fragment\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 281, __extension__
__PRETTY_FUNCTION__))
279 return A.Expr->isFragment();(static_cast <bool> (llvm::all_of(FrameIndexExprs, [](const
FrameIndexExpr &A) { return A.Expr->isFragment(); }) &&
"multiple FI expressions without DW_OP_LLVM_fragment") ? void
(0) : __assert_fail ("llvm::all_of(FrameIndexExprs, [](const FrameIndexExpr &A) { return A.Expr->isFragment(); }) && \"multiple FI expressions without DW_OP_LLVM_fragment\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 281, __extension__
__PRETTY_FUNCTION__))
280 }) &&(static_cast <bool> (llvm::all_of(FrameIndexExprs, [](const
FrameIndexExpr &A) { return A.Expr->isFragment(); }) &&
"multiple FI expressions without DW_OP_LLVM_fragment") ? void
(0) : __assert_fail ("llvm::all_of(FrameIndexExprs, [](const FrameIndexExpr &A) { return A.Expr->isFragment(); }) && \"multiple FI expressions without DW_OP_LLVM_fragment\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 281, __extension__
__PRETTY_FUNCTION__))
281 "multiple FI expressions without DW_OP_LLVM_fragment")(static_cast <bool> (llvm::all_of(FrameIndexExprs, [](const
FrameIndexExpr &A) { return A.Expr->isFragment(); }) &&
"multiple FI expressions without DW_OP_LLVM_fragment") ? void
(0) : __assert_fail ("llvm::all_of(FrameIndexExprs, [](const FrameIndexExpr &A) { return A.Expr->isFragment(); }) && \"multiple FI expressions without DW_OP_LLVM_fragment\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 281, __extension__
__PRETTY_FUNCTION__))
;
282 llvm::sort(FrameIndexExprs,
283 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
284 return A.Expr->getFragmentInfo()->OffsetInBits <
285 B.Expr->getFragmentInfo()->OffsetInBits;
286 });
287
288 return FrameIndexExprs;
289}
290
291void DbgVariable::addMMIEntry(const DbgVariable &V) {
292 assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry")(static_cast <bool> (DebugLocListIndex == ~0U &&
!ValueLoc.get() && "not an MMI entry") ? void (0) : __assert_fail
("DebugLocListIndex == ~0U && !ValueLoc.get() && \"not an MMI entry\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 292, __extension__
__PRETTY_FUNCTION__))
;
293 assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry")(static_cast <bool> (V.DebugLocListIndex == ~0U &&
!V.ValueLoc.get() && "not an MMI entry") ? void (0) :
__assert_fail ("V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && \"not an MMI entry\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 293, __extension__
__PRETTY_FUNCTION__))
;
294 assert(V.getVariable() == getVariable() && "conflicting variable")(static_cast <bool> (V.getVariable() == getVariable() &&
"conflicting variable") ? void (0) : __assert_fail ("V.getVariable() == getVariable() && \"conflicting variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 294, __extension__
__PRETTY_FUNCTION__))
;
295 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location")(static_cast <bool> (V.getInlinedAt() == getInlinedAt()
&& "conflicting inlined-at location") ? void (0) : __assert_fail
("V.getInlinedAt() == getInlinedAt() && \"conflicting inlined-at location\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 295, __extension__
__PRETTY_FUNCTION__))
;
296
297 assert(!FrameIndexExprs.empty() && "Expected an MMI entry")(static_cast <bool> (!FrameIndexExprs.empty() &&
"Expected an MMI entry") ? void (0) : __assert_fail ("!FrameIndexExprs.empty() && \"Expected an MMI entry\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 297, __extension__
__PRETTY_FUNCTION__))
;
298 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry")(static_cast <bool> (!V.FrameIndexExprs.empty() &&
"Expected an MMI entry") ? void (0) : __assert_fail ("!V.FrameIndexExprs.empty() && \"Expected an MMI entry\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 298, __extension__
__PRETTY_FUNCTION__))
;
299
300 // FIXME: This logic should not be necessary anymore, as we now have proper
301 // deduplication. However, without it, we currently run into the assertion
302 // below, which means that we are likely dealing with broken input, i.e. two
303 // non-fragment entries for the same variable at different frame indices.
304 if (FrameIndexExprs.size()) {
305 auto *Expr = FrameIndexExprs.back().Expr;
306 if (!Expr || !Expr->isFragment())
307 return;
308 }
309
310 for (const auto &FIE : V.FrameIndexExprs)
311 // Ignore duplicate entries.
312 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
313 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
314 }))
315 FrameIndexExprs.push_back(FIE);
316
317 assert((FrameIndexExprs.size() == 1 ||(static_cast <bool> ((FrameIndexExprs.size() == 1 || llvm
::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return
FIE.Expr && FIE.Expr->isFragment(); })) &&
"conflicting locations for variable") ? void (0) : __assert_fail
("(FrameIndexExprs.size() == 1 || llvm::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return FIE.Expr && FIE.Expr->isFragment(); })) && \"conflicting locations for variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 322, __extension__
__PRETTY_FUNCTION__))
318 llvm::all_of(FrameIndexExprs,(static_cast <bool> ((FrameIndexExprs.size() == 1 || llvm
::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return
FIE.Expr && FIE.Expr->isFragment(); })) &&
"conflicting locations for variable") ? void (0) : __assert_fail
("(FrameIndexExprs.size() == 1 || llvm::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return FIE.Expr && FIE.Expr->isFragment(); })) && \"conflicting locations for variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 322, __extension__
__PRETTY_FUNCTION__))
319 [](FrameIndexExpr &FIE) {(static_cast <bool> ((FrameIndexExprs.size() == 1 || llvm
::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return
FIE.Expr && FIE.Expr->isFragment(); })) &&
"conflicting locations for variable") ? void (0) : __assert_fail
("(FrameIndexExprs.size() == 1 || llvm::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return FIE.Expr && FIE.Expr->isFragment(); })) && \"conflicting locations for variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 322, __extension__
__PRETTY_FUNCTION__))
320 return FIE.Expr && FIE.Expr->isFragment();(static_cast <bool> ((FrameIndexExprs.size() == 1 || llvm
::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return
FIE.Expr && FIE.Expr->isFragment(); })) &&
"conflicting locations for variable") ? void (0) : __assert_fail
("(FrameIndexExprs.size() == 1 || llvm::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return FIE.Expr && FIE.Expr->isFragment(); })) && \"conflicting locations for variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 322, __extension__
__PRETTY_FUNCTION__))
321 })) &&(static_cast <bool> ((FrameIndexExprs.size() == 1 || llvm
::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return
FIE.Expr && FIE.Expr->isFragment(); })) &&
"conflicting locations for variable") ? void (0) : __assert_fail
("(FrameIndexExprs.size() == 1 || llvm::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return FIE.Expr && FIE.Expr->isFragment(); })) && \"conflicting locations for variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 322, __extension__
__PRETTY_FUNCTION__))
322 "conflicting locations for variable")(static_cast <bool> ((FrameIndexExprs.size() == 1 || llvm
::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return
FIE.Expr && FIE.Expr->isFragment(); })) &&
"conflicting locations for variable") ? void (0) : __assert_fail
("(FrameIndexExprs.size() == 1 || llvm::all_of(FrameIndexExprs, [](FrameIndexExpr &FIE) { return FIE.Expr && FIE.Expr->isFragment(); })) && \"conflicting locations for variable\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 322, __extension__
__PRETTY_FUNCTION__))
;
323}
324
325static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
326 bool GenerateTypeUnits,
327 DebuggerKind Tuning,
328 const Triple &TT) {
329 // Honor an explicit request.
330 if (AccelTables != AccelTableKind::Default)
331 return AccelTables;
332
333 // Accelerator tables with type units are currently not supported.
334 if (GenerateTypeUnits)
335 return AccelTableKind::None;
336
337 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
338 // always implies debug_names. For lower standard versions we use apple
339 // accelerator tables on apple platforms and debug_names elsewhere.
340 if (DwarfVersion >= 5)
341 return AccelTableKind::Dwarf;
342 if (Tuning == DebuggerKind::LLDB)
343 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
344 : AccelTableKind::Dwarf;
345 return AccelTableKind::None;
346}
347
348DwarfDebug::DwarfDebug(AsmPrinter *A)
349 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
350 InfoHolder(A, "info_string", DIEValueAllocator),
351 SkeletonHolder(A, "skel_string", DIEValueAllocator),
352 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
353 const Triple &TT = Asm->TM.getTargetTriple();
354
355 // Make sure we know our "debugger tuning". The target option takes
356 // precedence; fall back to triple-based defaults.
357 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
358 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
359 else if (IsDarwin)
360 DebuggerTuning = DebuggerKind::LLDB;
361 else if (TT.isPS())
362 DebuggerTuning = DebuggerKind::SCE;
363 else if (TT.isOSAIX())
364 DebuggerTuning = DebuggerKind::DBX;
365 else
366 DebuggerTuning = DebuggerKind::GDB;
367
368 if (DwarfInlinedStrings == Default)
369 UseInlineStrings = TT.isNVPTX() || tuneForDBX();
370 else
371 UseInlineStrings = DwarfInlinedStrings == Enable;
372
373 UseLocSection = !TT.isNVPTX();
374
375 HasAppleExtensionAttributes = tuneForLLDB();
376
377 // Handle split DWARF.
378 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
379
380 // SCE defaults to linkage names only for abstract subprograms.
381 if (DwarfLinkageNames == DefaultLinkageNames)
382 UseAllLinkageNames = !tuneForSCE();
383 else
384 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
385
386 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
387 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
388 : MMI->getModule()->getDwarfVersion();
389 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
390 DwarfVersion =
391 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
392
393 bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
394 TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.
395
396 // Support DWARF64
397 // 1: For ELF when requested.
398 // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
399 // according to the DWARF64 format for 64-bit assembly, so we must use
400 // DWARF64 in the compiler too for 64-bit mode.
401 Dwarf64 &=
402 ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
403 TT.isOSBinFormatELF()) ||
404 TT.isOSBinFormatXCOFF();
405
406 if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
407 report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
408
409 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
410
411 // Use sections as references. Force for NVPTX.
412 if (DwarfSectionsAsReferences == Default)
413 UseSectionsAsReferences = TT.isNVPTX();
414 else
415 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
416
417 // Don't generate type units for unsupported object file formats.
418 GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
419 A->TM.getTargetTriple().isOSBinFormatWasm()) &&
420 GenerateDwarfTypeUnits;
421
422 TheAccelTableKind = computeAccelTableKind(
423 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
424
425 // Work around a GDB bug. GDB doesn't support the standard opcode;
426 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
427 // is defined as of DWARF 3.
428 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
429 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
430 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
431
432 UseDWARF2Bitfields = DwarfVersion < 4;
433
434 // The DWARF v5 string offsets table has - possibly shared - contributions
435 // from each compile and type unit each preceded by a header. The string
436 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
437 // a monolithic string offsets table without any header.
438 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
439
440 // Emit call-site-param debug info for GDB and LLDB, if the target supports
441 // the debug entry values feature. It can also be enabled explicitly.
442 EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
443
444 // It is unclear if the GCC .debug_macro extension is well-specified
445 // for split DWARF. For now, do not allow LLVM to emit it.
446 UseDebugMacroSection =
447 DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
448 if (DwarfOpConvert == Default)
449 EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
450 else
451 EnableOpConvert = (DwarfOpConvert == Enable);
452
453 // Split DWARF would benefit object size significantly by trading reductions
454 // in address pool usage for slightly increased range list encodings.
455 if (DwarfVersion >= 5)
456 MinimizeAddr = MinimizeAddrInV5Option;
457
458 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
459 Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
460 : dwarf::DWARF32);
461}
462
463// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
464DwarfDebug::~DwarfDebug() = default;
465
466static bool isObjCClass(StringRef Name) {
467 return Name.startswith("+") || Name.startswith("-");
468}
469
470static bool hasObjCCategory(StringRef Name) {
471 if (!isObjCClass(Name))
472 return false;
473
474 return Name.contains(") ");
475}
476
477static void getObjCClassCategory(StringRef In, StringRef &Class,
478 StringRef &Category) {
479 if (!hasObjCCategory(In)) {
480 Class = In.slice(In.find('[') + 1, In.find(' '));
481 Category = "";
482 return;
483 }
484
485 Class = In.slice(In.find('[') + 1, In.find('('));
486 Category = In.slice(In.find('[') + 1, In.find(' '));
487}
488
489static StringRef getObjCMethodName(StringRef In) {
490 return In.slice(In.find(' ') + 1, In.find(']'));
491}
492
493// Add the various names to the Dwarf accelerator table names.
494void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
495 const DISubprogram *SP, DIE &Die) {
496 if (getAccelTableKind() != AccelTableKind::Apple &&
497 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
498 return;
499
500 if (!SP->isDefinition())
501 return;
502
503 if (SP->getName() != "")
504 addAccelName(CU, SP->getName(), Die);
505
506 // If the linkage name is different than the name, go ahead and output that as
507 // well into the name table. Only do that if we are going to actually emit
508 // that name.
509 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
510 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
511 addAccelName(CU, SP->getLinkageName(), Die);
512
513 // If this is an Objective-C selector name add it to the ObjC accelerator
514 // too.
515 if (isObjCClass(SP->getName())) {
516 StringRef Class, Category;
517 getObjCClassCategory(SP->getName(), Class, Category);
518 addAccelObjC(CU, Class, Die);
519 if (Category != "")
520 addAccelObjC(CU, Category, Die);
521 // Also add the base method name to the name table.
522 addAccelName(CU, getObjCMethodName(SP->getName()), Die);
523 }
524}
525
526/// Check whether we should create a DIE for the given Scope, return true
527/// if we don't create a DIE (the corresponding DIE is null).
528bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
529 if (Scope->isAbstractScope())
530 return false;
531
532 // We don't create a DIE if there is no Range.
533 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
534 if (Ranges.empty())
535 return true;
536
537 if (Ranges.size() > 1)
538 return false;
539
540 // We don't create a DIE if we have a single Range and the end label
541 // is null.
542 return !getLabelAfterInsn(Ranges.front().second);
543}
544
545template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
546 F(CU);
547 if (auto *SkelCU = CU.getSkeleton())
548 if (CU.getCUNode()->getSplitDebugInlining())
549 F(*SkelCU);
550}
551
552bool DwarfDebug::shareAcrossDWOCUs() const {
553 return SplitDwarfCrossCuReferences;
554}
555
556void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
557 LexicalScope *Scope) {
558 assert(Scope && Scope->getScopeNode())(static_cast <bool> (Scope && Scope->getScopeNode
()) ? void (0) : __assert_fail ("Scope && Scope->getScopeNode()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 558, __extension__
__PRETTY_FUNCTION__))
;
559 assert(Scope->isAbstractScope())(static_cast <bool> (Scope->isAbstractScope()) ? void
(0) : __assert_fail ("Scope->isAbstractScope()", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 559, __extension__ __PRETTY_FUNCTION__))
;
560 assert(!Scope->getInlinedAt())(static_cast <bool> (!Scope->getInlinedAt()) ? void (
0) : __assert_fail ("!Scope->getInlinedAt()", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 560, __extension__ __PRETTY_FUNCTION__))
;
561
562 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
563
564 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
565 // was inlined from another compile unit.
566 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
567 // Avoid building the original CU if it won't be used
568 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
569 else {
570 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
571 if (auto *SkelCU = CU.getSkeleton()) {
572 (shareAcrossDWOCUs() ? CU : SrcCU)
573 .constructAbstractSubprogramScopeDIE(Scope);
574 if (CU.getCUNode()->getSplitDebugInlining())
575 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
576 } else
577 CU.constructAbstractSubprogramScopeDIE(Scope);
578 }
579}
580
581/// Represents a parameter whose call site value can be described by applying a
582/// debug expression to a register in the forwarded register worklist.
583struct FwdRegParamInfo {
584 /// The described parameter register.
585 unsigned ParamReg;
586
587 /// Debug expression that has been built up when walking through the
588 /// instruction chain that produces the parameter's value.
589 const DIExpression *Expr;
590};
591
592/// Register worklist for finding call site values.
593using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
594/// Container for the set of registers known to be clobbered on the path to a
595/// call site.
596using ClobberedRegSet = SmallSet<Register, 16>;
597
598/// Append the expression \p Addition to \p Original and return the result.
599static const DIExpression *combineDIExpressions(const DIExpression *Original,
600 const DIExpression *Addition) {
601 std::vector<uint64_t> Elts = Addition->getElements().vec();
602 // Avoid multiple DW_OP_stack_values.
603 if (Original->isImplicit() && Addition->isImplicit())
604 erase_value(Elts, dwarf::DW_OP_stack_value);
605 const DIExpression *CombinedExpr =
606 (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
607 return CombinedExpr;
608}
609
610/// Emit call site parameter entries that are described by the given value and
611/// debug expression.
612template <typename ValT>
613static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
614 ArrayRef<FwdRegParamInfo> DescribedParams,
615 ParamSet &Params) {
616 for (auto Param : DescribedParams) {
617 bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
618
619 // TODO: Entry value operations can currently not be combined with any
620 // other expressions, so we can't emit call site entries in those cases.
621 if (ShouldCombineExpressions && Expr->isEntryValue())
622 continue;
623
624 // If a parameter's call site value is produced by a chain of
625 // instructions we may have already created an expression for the
626 // parameter when walking through the instructions. Append that to the
627 // base expression.
628 const DIExpression *CombinedExpr =
629 ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
630 : Expr;
631 assert((!CombinedExpr || CombinedExpr->isValid()) &&(static_cast <bool> ((!CombinedExpr || CombinedExpr->
isValid()) && "Combined debug expression is invalid")
? void (0) : __assert_fail ("(!CombinedExpr || CombinedExpr->isValid()) && \"Combined debug expression is invalid\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 632, __extension__
__PRETTY_FUNCTION__))
632 "Combined debug expression is invalid")(static_cast <bool> ((!CombinedExpr || CombinedExpr->
isValid()) && "Combined debug expression is invalid")
? void (0) : __assert_fail ("(!CombinedExpr || CombinedExpr->isValid()) && \"Combined debug expression is invalid\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 632, __extension__
__PRETTY_FUNCTION__))
;
633
634 DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
635 DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
636 Params.push_back(CSParm);
637 ++NumCSParams;
638 }
639}
640
641/// Add \p Reg to the worklist, if it's not already present, and mark that the
642/// given parameter registers' values can (potentially) be described using
643/// that register and an debug expression.
644static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
645 const DIExpression *Expr,
646 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
647 auto I = Worklist.insert({Reg, {}});
648 auto &ParamsForFwdReg = I.first->second;
649 for (auto Param : ParamsToAdd) {
650 assert(none_of(ParamsForFwdReg,(static_cast <bool> (none_of(ParamsForFwdReg, [Param](const
FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg
; }) && "Same parameter described twice by forwarding reg"
) ? void (0) : __assert_fail ("none_of(ParamsForFwdReg, [Param](const FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg; }) && \"Same parameter described twice by forwarding reg\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 654, __extension__
__PRETTY_FUNCTION__))
651 [Param](const FwdRegParamInfo &D) {(static_cast <bool> (none_of(ParamsForFwdReg, [Param](const
FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg
; }) && "Same parameter described twice by forwarding reg"
) ? void (0) : __assert_fail ("none_of(ParamsForFwdReg, [Param](const FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg; }) && \"Same parameter described twice by forwarding reg\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 654, __extension__
__PRETTY_FUNCTION__))
652 return D.ParamReg == Param.ParamReg;(static_cast <bool> (none_of(ParamsForFwdReg, [Param](const
FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg
; }) && "Same parameter described twice by forwarding reg"
) ? void (0) : __assert_fail ("none_of(ParamsForFwdReg, [Param](const FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg; }) && \"Same parameter described twice by forwarding reg\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 654, __extension__
__PRETTY_FUNCTION__))
653 }) &&(static_cast <bool> (none_of(ParamsForFwdReg, [Param](const
FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg
; }) && "Same parameter described twice by forwarding reg"
) ? void (0) : __assert_fail ("none_of(ParamsForFwdReg, [Param](const FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg; }) && \"Same parameter described twice by forwarding reg\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 654, __extension__
__PRETTY_FUNCTION__))
654 "Same parameter described twice by forwarding reg")(static_cast <bool> (none_of(ParamsForFwdReg, [Param](const
FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg
; }) && "Same parameter described twice by forwarding reg"
) ? void (0) : __assert_fail ("none_of(ParamsForFwdReg, [Param](const FwdRegParamInfo &D) { return D.ParamReg == Param.ParamReg; }) && \"Same parameter described twice by forwarding reg\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 654, __extension__
__PRETTY_FUNCTION__))
;
655
656 // If a parameter's call site value is produced by a chain of
657 // instructions we may have already created an expression for the
658 // parameter when walking through the instructions. Append that to the
659 // new expression.
660 const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
661 ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
662 }
663}
664
665/// Interpret values loaded into registers by \p CurMI.
666static void interpretValues(const MachineInstr *CurMI,
667 FwdRegWorklist &ForwardedRegWorklist,
668 ParamSet &Params,
669 ClobberedRegSet &ClobberedRegUnits) {
670
671 const MachineFunction *MF = CurMI->getMF();
672 const DIExpression *EmptyExpr =
673 DIExpression::get(MF->getFunction().getContext(), {});
674 const auto &TRI = *MF->getSubtarget().getRegisterInfo();
675 const auto &TII = *MF->getSubtarget().getInstrInfo();
676 const auto &TLI = *MF->getSubtarget().getTargetLowering();
677
678 // If an instruction defines more than one item in the worklist, we may run
679 // into situations where a worklist register's value is (potentially)
680 // described by the previous value of another register that is also defined
681 // by that instruction.
682 //
683 // This can for example occur in cases like this:
684 //
685 // $r1 = mov 123
686 // $r0, $r1 = mvrr $r1, 456
687 // call @foo, $r0, $r1
688 //
689 // When describing $r1's value for the mvrr instruction, we need to make sure
690 // that we don't finalize an entry value for $r0, as that is dependent on the
691 // previous value of $r1 (123 rather than 456).
692 //
693 // In order to not have to distinguish between those cases when finalizing
694 // entry values, we simply postpone adding new parameter registers to the
695 // worklist, by first keeping them in this temporary container until the
696 // instruction has been handled.
697 FwdRegWorklist TmpWorklistItems;
698
699 // If the MI is an instruction defining one or more parameters' forwarding
700 // registers, add those defines.
701 ClobberedRegSet NewClobberedRegUnits;
702 auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
703 SmallSetVector<unsigned, 4> &Defs) {
704 if (MI.isDebugInstr())
705 return;
706
707 for (const MachineOperand &MO : MI.operands()) {
708 if (MO.isReg() && MO.isDef() && MO.getReg().isPhysical()) {
709 for (auto &FwdReg : ForwardedRegWorklist)
710 if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
711 Defs.insert(FwdReg.first);
712 for (MCRegUnitIterator Units(MO.getReg(), &TRI); Units.isValid(); ++Units)
713 NewClobberedRegUnits.insert(*Units);
714 }
715 }
716 };
717
718 // Set of worklist registers that are defined by this instruction.
719 SmallSetVector<unsigned, 4> FwdRegDefs;
720
721 getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
722 if (FwdRegDefs.empty()) {
723 // Any definitions by this instruction will clobber earlier reg movements.
724 ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
725 NewClobberedRegUnits.end());
726 return;
727 }
728
729 // It's possible that we find a copy from a non-volatile register to the param
730 // register, which is clobbered in the meantime. Test for clobbered reg unit
731 // overlaps before completing.
732 auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
733 for (auto &RegUnit : ClobberedRegUnits)
734 if (TRI.hasRegUnit(Reg, RegUnit))
735 return true;
736 return false;
737 };
738
739 for (auto ParamFwdReg : FwdRegDefs) {
740 if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
741 if (ParamValue->first.isImm()) {
742 int64_t Val = ParamValue->first.getImm();
743 finishCallSiteParams(Val, ParamValue->second,
744 ForwardedRegWorklist[ParamFwdReg], Params);
745 } else if (ParamValue->first.isReg()) {
746 Register RegLoc = ParamValue->first.getReg();
747 Register SP = TLI.getStackPointerRegisterToSaveRestore();
748 Register FP = TRI.getFrameRegister(*MF);
749 bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
750 if (!IsRegClobberedInMeantime(RegLoc) &&
751 (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
752 MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
753 finishCallSiteParams(MLoc, ParamValue->second,
754 ForwardedRegWorklist[ParamFwdReg], Params);
755 } else {
756 // ParamFwdReg was described by the non-callee saved register
757 // RegLoc. Mark that the call site values for the parameters are
758 // dependent on that register instead of ParamFwdReg. Since RegLoc
759 // may be a register that will be handled in this iteration, we
760 // postpone adding the items to the worklist, and instead keep them
761 // in a temporary container.
762 addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
763 ForwardedRegWorklist[ParamFwdReg]);
764 }
765 }
766 }
767 }
768
769 // Remove all registers that this instruction defines from the worklist.
770 for (auto ParamFwdReg : FwdRegDefs)
771 ForwardedRegWorklist.erase(ParamFwdReg);
772
773 // Any definitions by this instruction will clobber earlier reg movements.
774 ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
775 NewClobberedRegUnits.end());
776
777 // Now that we are done handling this instruction, add items from the
778 // temporary worklist to the real one.
779 for (auto &New : TmpWorklistItems)
780 addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
781 TmpWorklistItems.clear();
782}
783
784static bool interpretNextInstr(const MachineInstr *CurMI,
785 FwdRegWorklist &ForwardedRegWorklist,
786 ParamSet &Params,
787 ClobberedRegSet &ClobberedRegUnits) {
788 // Skip bundle headers.
789 if (CurMI->isBundle())
790 return true;
791
792 // If the next instruction is a call we can not interpret parameter's
793 // forwarding registers or we finished the interpretation of all
794 // parameters.
795 if (CurMI->isCall())
796 return false;
797
798 if (ForwardedRegWorklist.empty())
799 return false;
800
801 // Avoid NOP description.
802 if (CurMI->getNumOperands() == 0)
803 return true;
804
805 interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
806
807 return true;
808}
809
810/// Try to interpret values loaded into registers that forward parameters
811/// for \p CallMI. Store parameters with interpreted value into \p Params.
812static void collectCallSiteParameters(const MachineInstr *CallMI,
813 ParamSet &Params) {
814 const MachineFunction *MF = CallMI->getMF();
815 const auto &CalleesMap = MF->getCallSitesInfo();
816 auto CallFwdRegsInfo = CalleesMap.find(CallMI);
817
818 // There is no information for the call instruction.
819 if (CallFwdRegsInfo == CalleesMap.end())
820 return;
821
822 const MachineBasicBlock *MBB = CallMI->getParent();
823
824 // Skip the call instruction.
825 auto I = std::next(CallMI->getReverseIterator());
826
827 FwdRegWorklist ForwardedRegWorklist;
828
829 const DIExpression *EmptyExpr =
830 DIExpression::get(MF->getFunction().getContext(), {});
831
832 // Add all the forwarding registers into the ForwardedRegWorklist.
833 for (const auto &ArgReg : CallFwdRegsInfo->second) {
834 bool InsertedReg =
835 ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
836 .second;
837 assert(InsertedReg && "Single register used to forward two arguments?")(static_cast <bool> (InsertedReg && "Single register used to forward two arguments?"
) ? void (0) : __assert_fail ("InsertedReg && \"Single register used to forward two arguments?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 837, __extension__
__PRETTY_FUNCTION__))
;
838 (void)InsertedReg;
839 }
840
841 // Do not emit CSInfo for undef forwarding registers.
842 for (const auto &MO : CallMI->uses())
843 if (MO.isReg() && MO.isUndef())
844 ForwardedRegWorklist.erase(MO.getReg());
845
846 // We erase, from the ForwardedRegWorklist, those forwarding registers for
847 // which we successfully describe a loaded value (by using
848 // the describeLoadedValue()). For those remaining arguments in the working
849 // list, for which we do not describe a loaded value by
850 // the describeLoadedValue(), we try to generate an entry value expression
851 // for their call site value description, if the call is within the entry MBB.
852 // TODO: Handle situations when call site parameter value can be described
853 // as the entry value within basic blocks other than the first one.
854 bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
855
856 // Search for a loading value in forwarding registers inside call delay slot.
857 ClobberedRegSet ClobberedRegUnits;
858 if (CallMI->hasDelaySlot()) {
859 auto Suc = std::next(CallMI->getIterator());
860 // Only one-instruction delay slot is supported.
861 auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
862 (void)BundleEnd;
863 assert(std::next(Suc) == BundleEnd &&(static_cast <bool> (std::next(Suc) == BundleEnd &&
"More than one instruction in call delay slot") ? void (0) :
__assert_fail ("std::next(Suc) == BundleEnd && \"More than one instruction in call delay slot\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 864, __extension__
__PRETTY_FUNCTION__))
864 "More than one instruction in call delay slot")(static_cast <bool> (std::next(Suc) == BundleEnd &&
"More than one instruction in call delay slot") ? void (0) :
__assert_fail ("std::next(Suc) == BundleEnd && \"More than one instruction in call delay slot\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 864, __extension__
__PRETTY_FUNCTION__))
;
865 // Try to interpret value loaded by instruction.
866 if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
867 return;
868 }
869
870 // Search for a loading value in forwarding registers.
871 for (; I != MBB->rend(); ++I) {
872 // Try to interpret values loaded by instruction.
873 if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
874 return;
875 }
876
877 // Emit the call site parameter's value as an entry value.
878 if (ShouldTryEmitEntryVals) {
879 // Create an expression where the register's entry value is used.
880 DIExpression *EntryExpr = DIExpression::get(
881 MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
882 for (auto &RegEntry : ForwardedRegWorklist) {
883 MachineLocation MLoc(RegEntry.first);
884 finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
885 }
886 }
887}
888
889void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
890 DwarfCompileUnit &CU, DIE &ScopeDIE,
891 const MachineFunction &MF) {
892 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
893 // the subprogram is required to have one.
894 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
895 return;
896
897 // Use DW_AT_call_all_calls to express that call site entries are present
898 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
899 // because one of its requirements is not met: call site entries for
900 // optimized-out calls are elided.
901 CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
902
903 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
904 assert(TII && "TargetInstrInfo not found: cannot label tail calls")(static_cast <bool> (TII && "TargetInstrInfo not found: cannot label tail calls"
) ? void (0) : __assert_fail ("TII && \"TargetInstrInfo not found: cannot label tail calls\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 904, __extension__
__PRETTY_FUNCTION__))
;
905
906 // Delay slot support check.
907 auto delaySlotSupported = [&](const MachineInstr &MI) {
908 if (!MI.isBundledWithSucc())
909 return false;
910 auto Suc = std::next(MI.getIterator());
911 auto CallInstrBundle = getBundleStart(MI.getIterator());
912 (void)CallInstrBundle;
913 auto DelaySlotBundle = getBundleStart(Suc);
914 (void)DelaySlotBundle;
915 // Ensure that label after call is following delay slot instruction.
916 // Ex. CALL_INSTRUCTION {
917 // DELAY_SLOT_INSTRUCTION }
918 // LABEL_AFTER_CALL
919 assert(getLabelAfterInsn(&*CallInstrBundle) ==(static_cast <bool> (getLabelAfterInsn(&*CallInstrBundle
) == getLabelAfterInsn(&*DelaySlotBundle) && "Call and its successor instruction don't have same label after."
) ? void (0) : __assert_fail ("getLabelAfterInsn(&*CallInstrBundle) == getLabelAfterInsn(&*DelaySlotBundle) && \"Call and its successor instruction don't have same label after.\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 921, __extension__
__PRETTY_FUNCTION__))
920 getLabelAfterInsn(&*DelaySlotBundle) &&(static_cast <bool> (getLabelAfterInsn(&*CallInstrBundle
) == getLabelAfterInsn(&*DelaySlotBundle) && "Call and its successor instruction don't have same label after."
) ? void (0) : __assert_fail ("getLabelAfterInsn(&*CallInstrBundle) == getLabelAfterInsn(&*DelaySlotBundle) && \"Call and its successor instruction don't have same label after.\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 921, __extension__
__PRETTY_FUNCTION__))
921 "Call and its successor instruction don't have same label after.")(static_cast <bool> (getLabelAfterInsn(&*CallInstrBundle
) == getLabelAfterInsn(&*DelaySlotBundle) && "Call and its successor instruction don't have same label after."
) ? void (0) : __assert_fail ("getLabelAfterInsn(&*CallInstrBundle) == getLabelAfterInsn(&*DelaySlotBundle) && \"Call and its successor instruction don't have same label after.\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 921, __extension__
__PRETTY_FUNCTION__))
;
922 return true;
923 };
924
925 // Emit call site entries for each call or tail call in the function.
926 for (const MachineBasicBlock &MBB : MF) {
927 for (const MachineInstr &MI : MBB.instrs()) {
928 // Bundles with call in them will pass the isCall() test below but do not
929 // have callee operand information so skip them here. Iterator will
930 // eventually reach the call MI.
931 if (MI.isBundle())
932 continue;
933
934 // Skip instructions which aren't calls. Both calls and tail-calling jump
935 // instructions (e.g TAILJMPd64) are classified correctly here.
936 if (!MI.isCandidateForCallSiteEntry())
937 continue;
938
939 // Skip instructions marked as frame setup, as they are not interesting to
940 // the user.
941 if (MI.getFlag(MachineInstr::FrameSetup))
942 continue;
943
944 // Check if delay slot support is enabled.
945 if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
946 return;
947
948 // If this is a direct call, find the callee's subprogram.
949 // In the case of an indirect call find the register that holds
950 // the callee.
951 const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
952 if (!CalleeOp.isGlobal() &&
953 (!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))
954 continue;
955
956 unsigned CallReg = 0;
957 const DISubprogram *CalleeSP = nullptr;
958 const Function *CalleeDecl = nullptr;
959 if (CalleeOp.isReg()) {
960 CallReg = CalleeOp.getReg();
961 if (!CallReg)
962 continue;
963 } else {
964 CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
965 if (!CalleeDecl || !CalleeDecl->getSubprogram())
966 continue;
967 CalleeSP = CalleeDecl->getSubprogram();
968 }
969
970 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
971
972 bool IsTail = TII->isTailCall(MI);
973
974 // If MI is in a bundle, the label was created after the bundle since
975 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
976 // to search for that label below.
977 const MachineInstr *TopLevelCallMI =
978 MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
979
980 // For non-tail calls, the return PC is needed to disambiguate paths in
981 // the call graph which could lead to some target function. For tail
982 // calls, no return PC information is needed, unless tuning for GDB in
983 // DWARF4 mode in which case we fake a return PC for compatibility.
984 const MCSymbol *PCAddr =
985 (!IsTail || CU.useGNUAnalogForDwarf5Feature())
986 ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
987 : nullptr;
988
989 // For tail calls, it's necessary to record the address of the branch
990 // instruction so that the debugger can show where the tail call occurred.
991 const MCSymbol *CallAddr =
992 IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
993
994 assert((IsTail || PCAddr) && "Non-tail call without return PC")(static_cast <bool> ((IsTail || PCAddr) && "Non-tail call without return PC"
) ? void (0) : __assert_fail ("(IsTail || PCAddr) && \"Non-tail call without return PC\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 994, __extension__
__PRETTY_FUNCTION__))
;
995
996 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "CallSiteEntry: " << MF
.getName() << " -> " << (CalleeDecl ? CalleeDecl
->getName() : StringRef(MF.getSubtarget() .getRegisterInfo
() ->getName(CallReg))) << (IsTail ? " [IsTail]" : ""
) << "\n"; } } while (false)
997 << (CalleeDecl ? CalleeDecl->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "CallSiteEntry: " << MF
.getName() << " -> " << (CalleeDecl ? CalleeDecl
->getName() : StringRef(MF.getSubtarget() .getRegisterInfo
() ->getName(CallReg))) << (IsTail ? " [IsTail]" : ""
) << "\n"; } } while (false)
998 : StringRef(MF.getSubtarget()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "CallSiteEntry: " << MF
.getName() << " -> " << (CalleeDecl ? CalleeDecl
->getName() : StringRef(MF.getSubtarget() .getRegisterInfo
() ->getName(CallReg))) << (IsTail ? " [IsTail]" : ""
) << "\n"; } } while (false)
999 .getRegisterInfo()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "CallSiteEntry: " << MF
.getName() << " -> " << (CalleeDecl ? CalleeDecl
->getName() : StringRef(MF.getSubtarget() .getRegisterInfo
() ->getName(CallReg))) << (IsTail ? " [IsTail]" : ""
) << "\n"; } } while (false)
1000 ->getName(CallReg)))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "CallSiteEntry: " << MF
.getName() << " -> " << (CalleeDecl ? CalleeDecl
->getName() : StringRef(MF.getSubtarget() .getRegisterInfo
() ->getName(CallReg))) << (IsTail ? " [IsTail]" : ""
) << "\n"; } } while (false)
1001 << (IsTail ? " [IsTail]" : "") << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "CallSiteEntry: " << MF
.getName() << " -> " << (CalleeDecl ? CalleeDecl
->getName() : StringRef(MF.getSubtarget() .getRegisterInfo
() ->getName(CallReg))) << (IsTail ? " [IsTail]" : ""
) << "\n"; } } while (false)
;
1002
1003 DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
1004 ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
1005
1006 // Optionally emit call-site-param debug info.
1007 if (emitDebugEntryValues()) {
1008 ParamSet Params;
1009 // Try to interpret values of call site parameters.
1010 collectCallSiteParameters(&MI, Params);
1011 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
1012 }
1013 }
1014 }
1015}
1016
1017void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
1018 if (!U.hasDwarfPubSections())
1019 return;
1020
1021 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
1022}
1023
1024void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
1025 DwarfCompileUnit &NewCU) {
1026 DIE &Die = NewCU.getUnitDie();
1027 StringRef FN = DIUnit->getFilename();
1028
1029 StringRef Producer = DIUnit->getProducer();
1030 StringRef Flags = DIUnit->getFlags();
1031 if (!Flags.empty() && !useAppleExtensionAttributes()) {
1032 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
1033 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
1034 } else
1035 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
1036
1037 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1038 DIUnit->getSourceLanguage());
1039 NewCU.addString(Die, dwarf::DW_AT_name, FN);
1040 StringRef SysRoot = DIUnit->getSysRoot();
1041 if (!SysRoot.empty())
1042 NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
1043 StringRef SDK = DIUnit->getSDK();
1044 if (!SDK.empty())
1045 NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
1046
1047 if (!useSplitDwarf()) {
1048 // Add DW_str_offsets_base to the unit DIE, except for split units.
1049 if (useSegmentedStringOffsetsTable())
1050 NewCU.addStringOffsetsStart();
1051
1052 NewCU.initStmtList();
1053
1054 // If we're using split dwarf the compilation dir is going to be in the
1055 // skeleton CU and so we don't need to duplicate it here.
1056 if (!CompilationDir.empty())
1057 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1058 addGnuPubAttributes(NewCU, Die);
1059 }
1060
1061 if (useAppleExtensionAttributes()) {
1062 if (DIUnit->isOptimized())
1063 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1064
1065 StringRef Flags = DIUnit->getFlags();
1066 if (!Flags.empty())
1067 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1068
1069 if (unsigned RVer = DIUnit->getRuntimeVersion())
1070 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1071 dwarf::DW_FORM_data1, RVer);
1072 }
1073
1074 if (DIUnit->getDWOId()) {
1075 // This CU is either a clang module DWO or a skeleton CU.
1076 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1077 DIUnit->getDWOId());
1078 if (!DIUnit->getSplitDebugFilename().empty()) {
1079 // This is a prefabricated skeleton CU.
1080 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1081 ? dwarf::DW_AT_dwo_name
1082 : dwarf::DW_AT_GNU_dwo_name;
1083 NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1084 }
1085 }
1086}
1087// Create new DwarfCompileUnit for the given metadata node with tag
1088// DW_TAG_compile_unit.
1089DwarfCompileUnit &
1090DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
1091 if (auto *CU = CUMap.lookup(DIUnit))
1092 return *CU;
1093
1094 CompilationDir = DIUnit->getDirectory();
1095
1096 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1097 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
1098 DwarfCompileUnit &NewCU = *OwnedUnit;
1099 InfoHolder.addUnit(std::move(OwnedUnit));
1100
1101 for (auto *IE : DIUnit->getImportedEntities())
1102 NewCU.addImportedEntity(IE);
1103
1104 // LTO with assembly output shares a single line table amongst multiple CUs.
1105 // To avoid the compilation directory being ambiguous, let the line table
1106 // explicitly describe the directory of all files, never relying on the
1107 // compilation directory.
1108 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1109 Asm->OutStreamer->emitDwarfFile0Directive(
1110 CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1111 DIUnit->getSource(), NewCU.getUniqueID());
1112
1113 if (useSplitDwarf()) {
1114 NewCU.setSkeleton(constructSkeletonCU(NewCU));
1115 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1116 } else {
1117 finishUnitAttributes(DIUnit, NewCU);
1118 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1119 }
1120
1121 CUMap.insert({DIUnit, &NewCU});
1122 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1123 return NewCU;
1124}
1125
1126void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
1127 const DIImportedEntity *N) {
1128 if (isa<DILocalScope>(N->getScope()))
1129 return;
1130 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
1131 D->addChild(TheCU.constructImportedEntityDIE(N));
1132}
1133
1134/// Sort and unique GVEs by comparing their fragment offset.
1135static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
1136sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1137 llvm::sort(
1138 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1139 // Sort order: first null exprs, then exprs without fragment
1140 // info, then sort by fragment offset in bits.
1141 // FIXME: Come up with a more comprehensive comparator so
1142 // the sorting isn't non-deterministic, and so the following
1143 // std::unique call works correctly.
1144 if (!A.Expr || !B.Expr)
1145 return !!B.Expr;
1146 auto FragmentA = A.Expr->getFragmentInfo();
1147 auto FragmentB = B.Expr->getFragmentInfo();
1148 if (!FragmentA || !FragmentB)
1149 return !!FragmentB;
1150 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1151 });
1152 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
1153 [](DwarfCompileUnit::GlobalExpr A,
1154 DwarfCompileUnit::GlobalExpr B) {
1155 return A.Expr == B.Expr;
1156 }),
1157 GVEs.end());
1158 return GVEs;
1159}
1160
1161// Emit all Dwarf sections that should come prior to the content. Create
1162// global DIEs and emit initial debug info sections. This is invoked by
1163// the target AsmPrinter.
1164void DwarfDebug::beginModule(Module *M) {
1165 DebugHandlerBase::beginModule(M);
1166
1167 if (!Asm || !MMI->hasDebugInfo())
1168 return;
1169
1170 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1171 M->debug_compile_units_end());
1172 assert(NumDebugCUs > 0 && "Asm unexpectedly initialized")(static_cast <bool> (NumDebugCUs > 0 && "Asm unexpectedly initialized"
) ? void (0) : __assert_fail ("NumDebugCUs > 0 && \"Asm unexpectedly initialized\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1172, __extension__
__PRETTY_FUNCTION__))
;
1173 assert(MMI->hasDebugInfo() &&(static_cast <bool> (MMI->hasDebugInfo() && "DebugInfoAvailabilty unexpectedly not initialized"
) ? void (0) : __assert_fail ("MMI->hasDebugInfo() && \"DebugInfoAvailabilty unexpectedly not initialized\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1174, __extension__
__PRETTY_FUNCTION__))
1174 "DebugInfoAvailabilty unexpectedly not initialized")(static_cast <bool> (MMI->hasDebugInfo() && "DebugInfoAvailabilty unexpectedly not initialized"
) ? void (0) : __assert_fail ("MMI->hasDebugInfo() && \"DebugInfoAvailabilty unexpectedly not initialized\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1174, __extension__
__PRETTY_FUNCTION__))
;
1175 SingleCU = NumDebugCUs == 1;
1176 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1177 GVMap;
1178 for (const GlobalVariable &Global : M->globals()) {
1179 SmallVector<DIGlobalVariableExpression *, 1> GVs;
1180 Global.getDebugInfo(GVs);
1181 for (auto *GVE : GVs)
1182 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1183 }
1184
1185 // Create the symbol that designates the start of the unit's contribution
1186 // to the string offsets table. In a split DWARF scenario, only the skeleton
1187 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1188 if (useSegmentedStringOffsetsTable())
1189 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1190 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1191
1192
1193 // Create the symbols that designates the start of the DWARF v5 range list
1194 // and locations list tables. They are located past the table headers.
1195 if (getDwarfVersion() >= 5) {
1196 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1197 Holder.setRnglistsTableBaseSym(
1198 Asm->createTempSymbol("rnglists_table_base"));
1199
1200 if (useSplitDwarf())
1201 InfoHolder.setRnglistsTableBaseSym(
1202 Asm->createTempSymbol("rnglists_dwo_table_base"));
1203 }
1204
1205 // Create the symbol that points to the first entry following the debug
1206 // address table (.debug_addr) header.
1207 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1208 DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1209
1210 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1211 // FIXME: Move local imported entities into a list attached to the
1212 // subprogram, then this search won't be needed and a
1213 // getImportedEntities().empty() test should go below with the rest.
1214 bool HasNonLocalImportedEntities = llvm::any_of(
1215 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1216 return !isa<DILocalScope>(IE->getScope());
1217 });
1218
1219 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1220 CUNode->getRetainedTypes().empty() &&
1221 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1222 continue;
1223
1224 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1225
1226 // Global Variables.
1227 for (auto *GVE : CUNode->getGlobalVariables()) {
1228 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1229 // already know about the variable and it isn't adding a constant
1230 // expression.
1231 auto &GVMapEntry = GVMap[GVE->getVariable()];
1232 auto *Expr = GVE->getExpression();
1233 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1234 GVMapEntry.push_back({nullptr, Expr});
1235 }
1236
1237 DenseSet<DIGlobalVariable *> Processed;
1238 for (auto *GVE : CUNode->getGlobalVariables()) {
1239 DIGlobalVariable *GV = GVE->getVariable();
1240 if (Processed.insert(GV).second)
1241 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1242 }
1243
1244 for (auto *Ty : CUNode->getEnumTypes())
1245 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1246
1247 for (auto *Ty : CUNode->getRetainedTypes()) {
1248 // The retained types array by design contains pointers to
1249 // MDNodes rather than DIRefs. Unique them here.
1250 if (DIType *RT = dyn_cast<DIType>(Ty))
1251 // There is no point in force-emitting a forward declaration.
1252 CU.getOrCreateTypeDIE(RT);
1253 }
1254 // Emit imported_modules last so that the relevant context is already
1255 // available.
1256 for (auto *IE : CUNode->getImportedEntities())
1257 constructAndAddImportedEntityDIE(CU, IE);
1258 }
1259}
1260
1261void DwarfDebug::finishEntityDefinitions() {
1262 for (const auto &Entity : ConcreteEntities) {
1263 DIE *Die = Entity->getDIE();
1264 assert(Die)(static_cast <bool> (Die) ? void (0) : __assert_fail ("Die"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1264, __extension__
__PRETTY_FUNCTION__))
;
1265 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1266 // in the ConcreteEntities list, rather than looking it up again here.
1267 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1268 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1269 assert(Unit)(static_cast <bool> (Unit) ? void (0) : __assert_fail (
"Unit", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1269, __extension__
__PRETTY_FUNCTION__))
;
1270 Unit->finishEntityDefinition(Entity.get());
1271 }
1272}
1273
1274void DwarfDebug::finishSubprogramDefinitions() {
1275 for (const DISubprogram *SP : ProcessedSPNodes) {
1276 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug)(static_cast <bool> (SP->getUnit()->getEmissionKind
() != DICompileUnit::NoDebug) ? void (0) : __assert_fail ("SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1276, __extension__
__PRETTY_FUNCTION__))
;
1277 forBothCUs(
1278 getOrCreateDwarfCompileUnit(SP->getUnit()),
1279 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1280 }
1281}
1282
1283void DwarfDebug::finalizeModuleInfo() {
1284 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1285
1286 finishSubprogramDefinitions();
1287
1288 finishEntityDefinitions();
1289
1290 // Include the DWO file name in the hash if there's more than one CU.
1291 // This handles ThinLTO's situation where imported CUs may very easily be
1292 // duplicate with the same CU partially imported into another ThinLTO unit.
1293 StringRef DWOName;
1294 if (CUMap.size() > 1)
1295 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1296
1297 // Handle anything that needs to be done on a per-unit basis after
1298 // all other generation.
1299 for (const auto &P : CUMap) {
1300 auto &TheCU = *P.second;
1301 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1302 continue;
1303 // Emit DW_AT_containing_type attribute to connect types with their
1304 // vtable holding type.
1305 TheCU.constructContainingTypeDIEs();
1306
1307 // Add CU specific attributes if we need to add any.
1308 // If we're splitting the dwarf out now that we've got the entire
1309 // CU then add the dwo id to it.
1310 auto *SkCU = TheCU.getSkeleton();
1311
1312 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1313
1314 if (HasSplitUnit) {
1315 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1316 ? dwarf::DW_AT_dwo_name
1317 : dwarf::DW_AT_GNU_dwo_name;
1318 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1319 TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1320 Asm->TM.Options.MCOptions.SplitDwarfFile);
1321 SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1322 Asm->TM.Options.MCOptions.SplitDwarfFile);
1323 // Emit a unique identifier for this CU.
1324 uint64_t ID =
1325 DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1326 if (getDwarfVersion() >= 5) {
1327 TheCU.setDWOId(ID);
1328 SkCU->setDWOId(ID);
1329 } else {
1330 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1331 dwarf::DW_FORM_data8, ID);
1332 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1333 dwarf::DW_FORM_data8, ID);
1334 }
1335
1336 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1337 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1338 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1339 Sym, Sym);
1340 }
1341 } else if (SkCU) {
1342 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1343 }
1344
1345 // If we have code split among multiple sections or non-contiguous
1346 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1347 // remain in the .o file, otherwise add a DW_AT_low_pc.
1348 // FIXME: We should use ranges allow reordering of code ala
1349 // .subsections_via_symbols in mach-o. This would mean turning on
1350 // ranges for all subprogram DIEs for mach-o.
1351 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1352
1353 if (unsigned NumRanges = TheCU.getRanges().size()) {
1354 if (NumRanges > 1 && useRangesSection())
1355 // A DW_AT_low_pc attribute may also be specified in combination with
1356 // DW_AT_ranges to specify the default base address for use in
1357 // location lists (see Section 2.6.2) and range lists (see Section
1358 // 2.17.3).
1359 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1360 else
1361 U.setBaseAddress(TheCU.getRanges().front().Begin);
1362 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1363 }
1364
1365 // We don't keep track of which addresses are used in which CU so this
1366 // is a bit pessimistic under LTO.
1367 if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1368 U.addAddrTableBase();
1369
1370 if (getDwarfVersion() >= 5) {
1371 if (U.hasRangeLists())
1372 U.addRnglistsBase();
1373
1374 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
1375 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1376 DebugLocs.getSym(),
1377 TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1378 }
1379 }
1380
1381 auto *CUNode = cast<DICompileUnit>(P.first);
1382 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1383 // attribute.
1384 if (CUNode->getMacros()) {
1385 if (UseDebugMacroSection) {
1386 if (useSplitDwarf())
1387 TheCU.addSectionDelta(
1388 TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
1389 TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
1390 else {
1391 dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1392 ? dwarf::DW_AT_macros
1393 : dwarf::DW_AT_GNU_macros;
1394 U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
1395 TLOF.getDwarfMacroSection()->getBeginSymbol());
1396 }
1397 } else {
1398 if (useSplitDwarf())
1399 TheCU.addSectionDelta(
1400 TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1401 U.getMacroLabelBegin(),
1402 TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1403 else
1404 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1405 U.getMacroLabelBegin(),
1406 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1407 }
1408 }
1409 }
1410
1411 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1412 for (auto *CUNode : MMI->getModule()->debug_compile_units())
1413 if (CUNode->getDWOId())
1414 getOrCreateDwarfCompileUnit(CUNode);
1415
1416 // Compute DIE offsets and sizes.
1417 InfoHolder.computeSizeAndOffsets();
1418 if (useSplitDwarf())
1419 SkeletonHolder.computeSizeAndOffsets();
1420}
1421
1422// Emit all Dwarf sections that should come after the content.
1423void DwarfDebug::endModule() {
1424 // Terminate the pending line table.
1425 if (PrevCU)
1426 terminateLineTable(PrevCU);
1427 PrevCU = nullptr;
1428 assert(CurFn == nullptr)(static_cast <bool> (CurFn == nullptr) ? void (0) : __assert_fail
("CurFn == nullptr", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 1428, __extension__ __PRETTY_FUNCTION__))
;
1429 assert(CurMI == nullptr)(static_cast <bool> (CurMI == nullptr) ? void (0) : __assert_fail
("CurMI == nullptr", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 1429, __extension__ __PRETTY_FUNCTION__))
;
1430
1431 for (const auto &P : CUMap) {
1432 auto &CU = *P.second;
1433 CU.createBaseTypeDIEs();
1434 }
1435
1436 // If we aren't actually generating debug info (check beginModule -
1437 // conditionalized on the presence of the llvm.dbg.cu metadata node)
1438 if (!Asm || !MMI->hasDebugInfo())
1439 return;
1440
1441 // Finalize the debug info for the module.
1442 finalizeModuleInfo();
1443
1444 if (useSplitDwarf())
1445 // Emit debug_loc.dwo/debug_loclists.dwo section.
1446 emitDebugLocDWO();
1447 else
1448 // Emit debug_loc/debug_loclists section.
1449 emitDebugLoc();
1450
1451 // Corresponding abbreviations into a abbrev section.
1452 emitAbbreviations();
1453
1454 // Emit all the DIEs into a debug info section.
1455 emitDebugInfo();
1456
1457 // Emit info into a debug aranges section.
1458 if (GenerateARangeSection)
1459 emitDebugARanges();
1460
1461 // Emit info into a debug ranges section.
1462 emitDebugRanges();
1463
1464 if (useSplitDwarf())
1465 // Emit info into a debug macinfo.dwo section.
1466 emitDebugMacinfoDWO();
1467 else
1468 // Emit info into a debug macinfo/macro section.
1469 emitDebugMacinfo();
1470
1471 emitDebugStr();
1472
1473 if (useSplitDwarf()) {
1474 emitDebugStrDWO();
1475 emitDebugInfoDWO();
1476 emitDebugAbbrevDWO();
1477 emitDebugLineDWO();
1478 emitDebugRangesDWO();
1479 }
1480
1481 emitDebugAddr();
1482
1483 // Emit info into the dwarf accelerator table sections.
1484 switch (getAccelTableKind()) {
1485 case AccelTableKind::Apple:
1486 emitAccelNames();
1487 emitAccelObjC();
1488 emitAccelNamespaces();
1489 emitAccelTypes();
1490 break;
1491 case AccelTableKind::Dwarf:
1492 emitAccelDebugNames();
1493 break;
1494 case AccelTableKind::None:
1495 break;
1496 case AccelTableKind::Default:
1497 llvm_unreachable("Default should have already been resolved.")::llvm::llvm_unreachable_internal("Default should have already been resolved."
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1497)
;
1498 }
1499
1500 // Emit the pubnames and pubtypes sections if requested.
1501 emitDebugPubSections();
1502
1503 // clean up.
1504 // FIXME: AbstractVariables.clear();
1505}
1506
1507void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1508 const DINode *Node,
1509 const MDNode *ScopeNode) {
1510 if (CU.getExistingAbstractEntity(Node))
1511 return;
1512
1513 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1514 cast<DILocalScope>(ScopeNode)));
1515}
1516
1517void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1518 const DINode *Node, const MDNode *ScopeNode) {
1519 if (CU.getExistingAbstractEntity(Node))
1520 return;
1521
1522 if (LexicalScope *Scope =
1523 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1524 CU.createAbstractEntity(Node, Scope);
1525}
1526
1527// Collect variable information from side table maintained by MF.
1528void DwarfDebug::collectVariableInfoFromMFTable(
1529 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1530 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1531 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "DwarfDebug: collecting variables from MF side table\n"
; } } while (false)
;
1532 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1533 if (!VI.Var)
1534 continue;
1535 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&(static_cast <bool> (VI.Var->isValidLocationForIntrinsic
(VI.Loc) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("VI.Var->isValidLocationForIntrinsic(VI.Loc) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1536, __extension__
__PRETTY_FUNCTION__))
1536 "Expected inlined-at fields to agree")(static_cast <bool> (VI.Var->isValidLocationForIntrinsic
(VI.Loc) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("VI.Var->isValidLocationForIntrinsic(VI.Loc) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1536, __extension__
__PRETTY_FUNCTION__))
;
1537
1538 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1539 Processed.insert(Var);
1540 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1541
1542 // If variable scope is not found then skip this variable.
1543 if (!Scope) {
1544 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Dropping debug info for " <<
VI.Var->getName() << ", no variable scope found\n";
} } while (false)
1545 << ", no variable scope found\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Dropping debug info for " <<
VI.Var->getName() << ", no variable scope found\n";
} } while (false)
;
1546 continue;
1547 }
1548
1549 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1550 auto RegVar = std::make_unique<DbgVariable>(
1551 cast<DILocalVariable>(Var.first), Var.second);
1552 RegVar->initializeMMI(VI.Expr, VI.Slot);
1553 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Created DbgVariable for " <<
VI.Var->getName() << "\n"; } } while (false)
1554 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Created DbgVariable for " <<
VI.Var->getName() << "\n"; } } while (false)
;
1555
1556 if (DbgVariable *DbgVar = MFVars.lookup(Var))
1557 DbgVar->addMMIEntry(*RegVar);
1558 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1559 MFVars.insert({Var, RegVar.get()});
1560 ConcreteEntities.push_back(std::move(RegVar));
1561 }
1562 }
1563}
1564
1565/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1566/// enclosing lexical scope. The check ensures there are no other instructions
1567/// in the same lexical scope preceding the DBG_VALUE and that its range is
1568/// either open or otherwise rolls off the end of the scope.
1569static bool validThroughout(LexicalScopes &LScopes,
1570 const MachineInstr *DbgValue,
1571 const MachineInstr *RangeEnd,
1572 const InstructionOrdering &Ordering) {
1573 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location")(static_cast <bool> (DbgValue->getDebugLoc() &&
"DBG_VALUE without a debug location") ? void (0) : __assert_fail
("DbgValue->getDebugLoc() && \"DBG_VALUE without a debug location\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1573, __extension__
__PRETTY_FUNCTION__))
;
5
Called C++ object pointer is null
1574 auto MBB = DbgValue->getParent();
1575 auto DL = DbgValue->getDebugLoc();
1576 auto *LScope = LScopes.findLexicalScope(DL);
1577 // Scope doesn't exist; this is a dead DBG_VALUE.
1578 if (!LScope)
1579 return false;
1580 auto &LSRange = LScope->getRanges();
1581 if (LSRange.size() == 0)
1582 return false;
1583
1584 const MachineInstr *LScopeBegin = LSRange.front().first;
1585 // If the scope starts before the DBG_VALUE then we may have a negative
1586 // result. Otherwise the location is live coming into the scope and we
1587 // can skip the following checks.
1588 if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1589 // Exit if the lexical scope begins outside of the current block.
1590 if (LScopeBegin->getParent() != MBB)
1591 return false;
1592
1593 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1594 for (++Pred; Pred != MBB->rend(); ++Pred) {
1595 if (Pred->getFlag(MachineInstr::FrameSetup))
1596 break;
1597 auto PredDL = Pred->getDebugLoc();
1598 if (!PredDL || Pred->isMetaInstruction())
1599 continue;
1600 // Check whether the instruction preceding the DBG_VALUE is in the same
1601 // (sub)scope as the DBG_VALUE.
1602 if (DL->getScope() == PredDL->getScope())
1603 return false;
1604 auto *PredScope = LScopes.findLexicalScope(PredDL);
1605 if (!PredScope || LScope->dominates(PredScope))
1606 return false;
1607 }
1608 }
1609
1610 // If the range of the DBG_VALUE is open-ended, report success.
1611 if (!RangeEnd)
1612 return true;
1613
1614 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1615 // throughout the function. This is a hack, presumably for DWARF v2 and not
1616 // necessarily correct. It would be much better to use a dbg.declare instead
1617 // if we know the constant is live throughout the scope.
1618 if (MBB->pred_empty() &&
1619 all_of(DbgValue->debug_operands(),
1620 [](const MachineOperand &Op) { return Op.isImm(); }))
1621 return true;
1622
1623 // Test if the location terminates before the end of the scope.
1624 const MachineInstr *LScopeEnd = LSRange.back().second;
1625 if (Ordering.isBefore(RangeEnd, LScopeEnd))
1626 return false;
1627
1628 // There's a single location which starts at the scope start, and ends at or
1629 // after the scope end.
1630 return true;
1631}
1632
1633/// Build the location list for all DBG_VALUEs in the function that
1634/// describe the same variable. The resulting DebugLocEntries will have
1635/// strict monotonically increasing begin addresses and will never
1636/// overlap. If the resulting list has only one entry that is valid
1637/// throughout variable's scope return true.
1638//
1639// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1640// different kinds of history map entries. One thing to be aware of is that if
1641// a debug value is ended by another entry (rather than being valid until the
1642// end of the function), that entry's instruction may or may not be included in
1643// the range, depending on if the entry is a clobbering entry (it has an
1644// instruction that clobbers one or more preceding locations), or if it is an
1645// (overlapping) debug value entry. This distinction can be seen in the example
1646// below. The first debug value is ended by the clobbering entry 2, and the
1647// second and third debug values are ended by the overlapping debug value entry
1648// 4.
1649//
1650// Input:
1651//
1652// History map entries [type, end index, mi]
1653//
1654// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1655// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1656// 2 | | [Clobber, $reg0 = [...], -, -]
1657// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1658// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1659//
1660// Output [start, end) [Value...]:
1661//
1662// [0-1) [(reg0, fragment 0, 32)]
1663// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1664// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1665// [4-) [(@g, fragment 0, 96)]
1666bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1667 const DbgValueHistoryMap::Entries &Entries) {
1668 using OpenRange =
1669 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1670 SmallVector<OpenRange, 4> OpenRanges;
1671 bool isSafeForSingleLocation = true;
1672 const MachineInstr *StartDebugMI = nullptr;
1
'StartDebugMI' initialized to a null pointer value
1673 const MachineInstr *EndMI = nullptr;
1674
1675 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
2
Assuming 'EI' is equal to 'EE'
1676 const MachineInstr *Instr = EI->getInstr();
1677
1678 // Remove all values that are no longer live.
1679 size_t Index = std::distance(EB, EI);
1680 erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1681
1682 // If we are dealing with a clobbering entry, this iteration will result in
1683 // a location list entry starting after the clobbering instruction.
1684 const MCSymbol *StartLabel =
1685 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1686 assert(StartLabel &&(static_cast <bool> (StartLabel && "Forgot label before/after instruction starting a range!"
) ? void (0) : __assert_fail ("StartLabel && \"Forgot label before/after instruction starting a range!\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1687, __extension__
__PRETTY_FUNCTION__))
1687 "Forgot label before/after instruction starting a range!")(static_cast <bool> (StartLabel && "Forgot label before/after instruction starting a range!"
) ? void (0) : __assert_fail ("StartLabel && \"Forgot label before/after instruction starting a range!\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1687, __extension__
__PRETTY_FUNCTION__))
;
1688
1689 const MCSymbol *EndLabel;
1690 if (std::next(EI) == Entries.end()) {
1691 const MachineBasicBlock &EndMBB = Asm->MF->back();
1692 EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
1693 if (EI->isClobber())
1694 EndMI = EI->getInstr();
1695 }
1696 else if (std::next(EI)->isClobber())
1697 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1698 else
1699 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1700 assert(EndLabel && "Forgot label after instruction ending a range!")(static_cast <bool> (EndLabel && "Forgot label after instruction ending a range!"
) ? void (0) : __assert_fail ("EndLabel && \"Forgot label after instruction ending a range!\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1700, __extension__
__PRETTY_FUNCTION__))
;
1701
1702 if (EI->isDbgValue())
1703 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "DotDebugLoc: " << *Instr
<< "\n"; } } while (false)
;
1704
1705 // If this history map entry has a debug value, add that to the list of
1706 // open ranges and check if its location is valid for a single value
1707 // location.
1708 if (EI->isDbgValue()) {
1709 // Do not add undef debug values, as they are redundant information in
1710 // the location list entries. An undef debug results in an empty location
1711 // description. If there are any non-undef fragments then padding pieces
1712 // with empty location descriptions will automatically be inserted, and if
1713 // all fragments are undef then the whole location list entry is
1714 // redundant.
1715 if (!Instr->isUndefDebugValue()) {
1716 auto Value = getDebugLocValue(Instr);
1717 OpenRanges.emplace_back(EI->getEndIndex(), Value);
1718
1719 // TODO: Add support for single value fragment locations.
1720 if (Instr->getDebugExpression()->isFragment())
1721 isSafeForSingleLocation = false;
1722
1723 if (!StartDebugMI)
1724 StartDebugMI = Instr;
1725 } else {
1726 isSafeForSingleLocation = false;
1727 }
1728 }
1729
1730 // Location list entries with empty location descriptions are redundant
1731 // information in DWARF, so do not emit those.
1732 if (OpenRanges.empty())
1733 continue;
1734
1735 // Omit entries with empty ranges as they do not have any effect in DWARF.
1736 if (StartLabel == EndLabel) {
1737 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Omitting location list entry with empty range.\n"
; } } while (false)
;
1738 continue;
1739 }
1740
1741 SmallVector<DbgValueLoc, 4> Values;
1742 for (auto &R : OpenRanges)
1743 Values.push_back(R.second);
1744
1745 // With Basic block sections, it is posssible that the StartLabel and the
1746 // Instr are not in the same section. This happens when the StartLabel is
1747 // the function begin label and the dbg value appears in a basic block
1748 // that is not the entry. In this case, the range needs to be split to
1749 // span each individual section in the range from StartLabel to EndLabel.
1750 if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1751 !Instr->getParent()->sameSection(&Asm->MF->front())) {
1752 const MCSymbol *BeginSectionLabel = StartLabel;
1753
1754 for (const MachineBasicBlock &MBB : *Asm->MF) {
1755 if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
1756 BeginSectionLabel = MBB.getSymbol();
1757
1758 if (MBB.sameSection(Instr->getParent())) {
1759 DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
1760 break;
1761 }
1762 if (MBB.isEndSection())
1763 DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
1764 }
1765 } else {
1766 DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1767 }
1768
1769 // Attempt to coalesce the ranges of two otherwise identical
1770 // DebugLocEntries.
1771 auto CurEntry = DebugLoc.rbegin();
1772 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { { dbgs() << CurEntry->getValues().
size() << " Values:\n"; for (auto &Value : CurEntry
->getValues()) Value.dump(); dbgs() << "-----\n"; };
} } while (false)
1773 dbgs() << CurEntry->getValues().size() << " Values:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { { dbgs() << CurEntry->getValues().
size() << " Values:\n"; for (auto &Value : CurEntry
->getValues()) Value.dump(); dbgs() << "-----\n"; };
} } while (false)
1774 for (auto &Value : CurEntry->getValues())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { { dbgs() << CurEntry->getValues().
size() << " Values:\n"; for (auto &Value : CurEntry
->getValues()) Value.dump(); dbgs() << "-----\n"; };
} } while (false)
1775 Value.dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { { dbgs() << CurEntry->getValues().
size() << " Values:\n"; for (auto &Value : CurEntry
->getValues()) Value.dump(); dbgs() << "-----\n"; };
} } while (false)
1776 dbgs() << "-----\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { { dbgs() << CurEntry->getValues().
size() << " Values:\n"; for (auto &Value : CurEntry
->getValues()) Value.dump(); dbgs() << "-----\n"; };
} } while (false)
1777 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { { dbgs() << CurEntry->getValues().
size() << " Values:\n"; for (auto &Value : CurEntry
->getValues()) Value.dump(); dbgs() << "-----\n"; };
} } while (false)
;
1778
1779 auto PrevEntry = std::next(CurEntry);
1780 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1781 DebugLoc.pop_back();
1782 }
1783
1784 if (!isSafeForSingleLocation
2.1
'isSafeForSingleLocation' is true
||
1785 !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
3
Passing null pointer value via 2nd parameter 'DbgValue'
4
Calling 'validThroughout'
1786 return false;
1787
1788 if (DebugLoc.size() == 1)
1789 return true;
1790
1791 if (!Asm->MF->hasBBSections())
1792 return false;
1793
1794 // Check here to see if loclist can be merged into a single range. If not,
1795 // we must keep the split loclists per section. This does exactly what
1796 // MergeRanges does without sections. We don't actually merge the ranges
1797 // as the split ranges must be kept intact if this cannot be collapsed
1798 // into a single range.
1799 const MachineBasicBlock *RangeMBB = nullptr;
1800 if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1801 RangeMBB = &Asm->MF->front();
1802 else
1803 RangeMBB = Entries.begin()->getInstr()->getParent();
1804 auto *CurEntry = DebugLoc.begin();
1805 auto *NextEntry = std::next(CurEntry);
1806 while (NextEntry != DebugLoc.end()) {
1807 // Get the last machine basic block of this section.
1808 while (!RangeMBB->isEndSection())
1809 RangeMBB = RangeMBB->getNextNode();
1810 if (!RangeMBB->getNextNode())
1811 return false;
1812 // CurEntry should end the current section and NextEntry should start
1813 // the next section and the Values must match for these two ranges to be
1814 // merged.
1815 if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
1816 NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
1817 CurEntry->getValues() != NextEntry->getValues())
1818 return false;
1819 RangeMBB = RangeMBB->getNextNode();
1820 CurEntry = NextEntry;
1821 NextEntry = std::next(CurEntry);
1822 }
1823 return true;
1824}
1825
1826DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1827 LexicalScope &Scope,
1828 const DINode *Node,
1829 const DILocation *Location,
1830 const MCSymbol *Sym) {
1831 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1832 if (isa<const DILocalVariable>(Node)) {
1833 ConcreteEntities.push_back(
1834 std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1835 Location));
1836 InfoHolder.addScopeVariable(&Scope,
1837 cast<DbgVariable>(ConcreteEntities.back().get()));
1838 } else if (isa<const DILabel>(Node)) {
1839 ConcreteEntities.push_back(
1840 std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1841 Location, Sym));
1842 InfoHolder.addScopeLabel(&Scope,
1843 cast<DbgLabel>(ConcreteEntities.back().get()));
1844 }
1845 return ConcreteEntities.back().get();
1846}
1847
1848// Find variables for each lexical scope.
1849void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1850 const DISubprogram *SP,
1851 DenseSet<InlinedEntity> &Processed) {
1852 // Grab the variable info that was squirreled away in the MMI side-table.
1853 collectVariableInfoFromMFTable(TheCU, Processed);
1854
1855 for (const auto &I : DbgValues) {
1856 InlinedEntity IV = I.first;
1857 if (Processed.count(IV))
1858 continue;
1859
1860 // Instruction ranges, specifying where IV is accessible.
1861 const auto &HistoryMapEntries = I.second;
1862
1863 // Try to find any non-empty variable location. Do not create a concrete
1864 // entity if there are no locations.
1865 if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
1866 continue;
1867
1868 LexicalScope *Scope = nullptr;
1869 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1870 if (const DILocation *IA = IV.second)
1871 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1872 else
1873 Scope = LScopes.findLexicalScope(LocalVar->getScope());
1874 // If variable scope is not found then skip this variable.
1875 if (!Scope)
1876 continue;
1877
1878 Processed.insert(IV);
1879 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1880 *Scope, LocalVar, IV.second));
1881
1882 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1883 assert(MInsn->isDebugValue() && "History must begin with debug value")(static_cast <bool> (MInsn->isDebugValue() &&
"History must begin with debug value") ? void (0) : __assert_fail
("MInsn->isDebugValue() && \"History must begin with debug value\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1883, __extension__
__PRETTY_FUNCTION__))
;
1884
1885 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1886 // If the history map contains a single debug value, there may be an
1887 // additional entry which clobbers the debug value.
1888 size_t HistSize = HistoryMapEntries.size();
1889 bool SingleValueWithClobber =
1890 HistSize == 2 && HistoryMapEntries[1].isClobber();
1891 if (HistSize == 1 || SingleValueWithClobber) {
1892 const auto *End =
1893 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1894 if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
1895 RegVar->initializeDbgValue(MInsn);
1896 continue;
1897 }
1898 }
1899
1900 // Do not emit location lists if .debug_loc secton is disabled.
1901 if (!useLocSection())
1902 continue;
1903
1904 // Handle multiple DBG_VALUE instructions describing one variable.
1905 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1906
1907 // Build the location list for this variable.
1908 SmallVector<DebugLocEntry, 8> Entries;
1909 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1910
1911 // Check whether buildLocationList managed to merge all locations to one
1912 // that is valid throughout the variable's scope. If so, produce single
1913 // value location.
1914 if (isValidSingleLocation) {
1915 RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1916 continue;
1917 }
1918
1919 // If the variable has a DIBasicType, extract it. Basic types cannot have
1920 // unique identifiers, so don't bother resolving the type with the
1921 // identifier map.
1922 const DIBasicType *BT = dyn_cast<DIBasicType>(
1923 static_cast<const Metadata *>(LocalVar->getType()));
1924
1925 // Finalize the entry by lowering it into a DWARF bytestream.
1926 for (auto &Entry : Entries)
1927 Entry.finalize(*Asm, List, BT, TheCU);
1928 }
1929
1930 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1931 // DWARF-related DbgLabel.
1932 for (const auto &I : DbgLabels) {
1933 InlinedEntity IL = I.first;
1934 const MachineInstr *MI = I.second;
1935 if (MI == nullptr)
1936 continue;
1937
1938 LexicalScope *Scope = nullptr;
1939 const DILabel *Label = cast<DILabel>(IL.first);
1940 // The scope could have an extra lexical block file.
1941 const DILocalScope *LocalScope =
1942 Label->getScope()->getNonLexicalBlockFileScope();
1943 // Get inlined DILocation if it is inlined label.
1944 if (const DILocation *IA = IL.second)
1945 Scope = LScopes.findInlinedScope(LocalScope, IA);
1946 else
1947 Scope = LScopes.findLexicalScope(LocalScope);
1948 // If label scope is not found then skip this label.
1949 if (!Scope)
1950 continue;
1951
1952 Processed.insert(IL);
1953 /// At this point, the temporary label is created.
1954 /// Save the temporary label to DbgLabel entity to get the
1955 /// actually address when generating Dwarf DIE.
1956 MCSymbol *Sym = getLabelBeforeInsn(MI);
1957 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1958 }
1959
1960 // Collect info for variables/labels that were optimized out.
1961 for (const DINode *DN : SP->getRetainedNodes()) {
1962 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1963 continue;
1964 LexicalScope *Scope = nullptr;
1965 if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1966 Scope = LScopes.findLexicalScope(DV->getScope());
1967 } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1968 Scope = LScopes.findLexicalScope(DL->getScope());
1969 }
1970
1971 if (Scope)
1972 createConcreteEntity(TheCU, *Scope, DN, nullptr);
1973 }
1974}
1975
1976// Process beginning of an instruction.
1977void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1978 const MachineFunction &MF = *MI->getMF();
1979 const auto *SP = MF.getFunction().getSubprogram();
1980 bool NoDebug =
1981 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
1982
1983 // Delay slot support check.
1984 auto delaySlotSupported = [](const MachineInstr &MI) {
1985 if (!MI.isBundledWithSucc())
1986 return false;
1987 auto Suc = std::next(MI.getIterator());
1988 (void)Suc;
1989 // Ensure that delay slot instruction is successor of the call instruction.
1990 // Ex. CALL_INSTRUCTION {
1991 // DELAY_SLOT_INSTRUCTION }
1992 assert(Suc->isBundledWithPred() &&(static_cast <bool> (Suc->isBundledWithPred() &&
"Call bundle instructions are out of order") ? void (0) : __assert_fail
("Suc->isBundledWithPred() && \"Call bundle instructions are out of order\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1993, __extension__
__PRETTY_FUNCTION__))
1993 "Call bundle instructions are out of order")(static_cast <bool> (Suc->isBundledWithPred() &&
"Call bundle instructions are out of order") ? void (0) : __assert_fail
("Suc->isBundledWithPred() && \"Call bundle instructions are out of order\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 1993, __extension__
__PRETTY_FUNCTION__))
;
1994 return true;
1995 };
1996
1997 // When describing calls, we need a label for the call instruction.
1998 if (!NoDebug && SP->areAllCallsDescribed() &&
1999 MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
2000 (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
2001 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2002 bool IsTail = TII->isTailCall(*MI);
2003 // For tail calls, we need the address of the branch instruction for
2004 // DW_AT_call_pc.
2005 if (IsTail)
2006 requestLabelBeforeInsn(MI);
2007 // For non-tail calls, we need the return address for the call for
2008 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
2009 // tail calls as well.
2010 requestLabelAfterInsn(MI);
2011 }
2012
2013 DebugHandlerBase::beginInstruction(MI);
2014 if (!CurMI)
2015 return;
2016
2017 if (NoDebug)
2018 return;
2019
2020 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2021 // If the instruction is part of the function frame setup code, do not emit
2022 // any line record, as there is no correspondence with any user code.
2023 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
2024 return;
2025 const DebugLoc &DL = MI->getDebugLoc();
2026 unsigned Flags = 0;
2027
2028 if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
2029 const MachineBasicBlock *MBB = MI->getParent();
2030 if (MBB && (MBB != EpilogBeginBlock)) {
2031 // First time FrameDestroy has been seen in this basic block
2032 EpilogBeginBlock = MBB;
2033 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN(1 << 3);
2034 }
2035 }
2036
2037 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2038 // the last line number actually emitted, to see if it was line 0.
2039 unsigned LastAsmLine =
2040 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2041
2042 bool PrevInstInSameSection =
2043 (!PrevInstBB ||
2044 PrevInstBB->getSectionIDNum() == MI->getParent()->getSectionIDNum());
2045 if (DL == PrevInstLoc && PrevInstInSameSection) {
2046 // If we have an ongoing unspecified location, nothing to do here.
2047 if (!DL)
2048 return;
2049 // We have an explicit location, same as the previous location.
2050 // But we might be coming back to it after a line 0 record.
2051 if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
2052 // Reinstate the source location but not marked as a statement.
2053 const MDNode *Scope = DL.getScope();
2054 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2055 }
2056 return;
2057 }
2058
2059 if (!DL) {
2060 // We have an unspecified location, which might want to be line 0.
2061 // If we have already emitted a line-0 record, don't repeat it.
2062 if (LastAsmLine == 0)
2063 return;
2064 // If user said Don't Do That, don't do that.
2065 if (UnknownLocations == Disable)
2066 return;
2067 // See if we have a reason to emit a line-0 record now.
2068 // Reasons to emit a line-0 record include:
2069 // - User asked for it (UnknownLocations).
2070 // - Instruction has a label, so it's referenced from somewhere else,
2071 // possibly debug information; we want it to have a source location.
2072 // - Instruction is at the top of a block; we don't want to inherit the
2073 // location from the physically previous (maybe unrelated) block.
2074 if (UnknownLocations == Enable || PrevLabel ||
2075 (PrevInstBB && PrevInstBB != MI->getParent())) {
2076 // Preserve the file and column numbers, if we can, to save space in
2077 // the encoded line table.
2078 // Do not update PrevInstLoc, it remembers the last non-0 line.
2079 const MDNode *Scope = nullptr;
2080 unsigned Column = 0;
2081 if (PrevInstLoc) {
2082 Scope = PrevInstLoc.getScope();
2083 Column = PrevInstLoc.getCol();
2084 }
2085 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
2086 }
2087 return;
2088 }
2089
2090 // We have an explicit location, different from the previous location.
2091 // Don't repeat a line-0 record, but otherwise emit the new location.
2092 // (The new location might be an explicit line 0, which we do emit.)
2093 if (DL.getLine() == 0 && LastAsmLine == 0)
2094 return;
2095 if (DL == PrologEndLoc) {
2096 Flags |= DWARF2_FLAG_PROLOGUE_END(1 << 2) | DWARF2_FLAG_IS_STMT(1 << 0);
2097 PrologEndLoc = DebugLoc();
2098 }
2099 // If the line changed, we call that a new statement; unless we went to
2100 // line 0 and came back, in which case it is not a new statement.
2101 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2102 if (DL.getLine() && DL.getLine() != OldLine)
2103 Flags |= DWARF2_FLAG_IS_STMT(1 << 0);
2104
2105 const MDNode *Scope = DL.getScope();
2106 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2107
2108 // If we're not at line 0, remember this location.
2109 if (DL.getLine())
2110 PrevInstLoc = DL;
2111}
2112
2113static std::pair<DebugLoc, bool> findPrologueEndLoc(const MachineFunction *MF) {
2114 // First known non-DBG_VALUE and non-frame setup location marks
2115 // the beginning of the function body.
2116 DebugLoc LineZeroLoc;
2117 const Function &F = MF->getFunction();
2118
2119 // Some instructions may be inserted into prologue after this function. Must
2120 // keep prologue for these cases.
2121 bool IsEmptyPrologue =
2122 !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2123 for (const auto &MBB : *MF) {
2124 for (const auto &MI : MBB) {
2125 if (!MI.isMetaInstruction()) {
2126 if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {
2127 // Scan forward to try to find a non-zero line number. The
2128 // prologue_end marks the first breakpoint in the function after the
2129 // frame setup, and a compiler-generated line 0 location is not a
2130 // meaningful breakpoint. If none is found, return the first
2131 // location after the frame setup.
2132 if (MI.getDebugLoc().getLine())
2133 return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);
2134
2135 LineZeroLoc = MI.getDebugLoc();
2136 }
2137 IsEmptyPrologue = false;
2138 }
2139 }
2140 }
2141 return std::make_pair(LineZeroLoc, IsEmptyPrologue);
2142}
2143
2144/// Register a source line with debug info. Returns the unique label that was
2145/// emitted and which provides correspondence to the source line list.
2146static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2147 const MDNode *S, unsigned Flags, unsigned CUID,
2148 uint16_t DwarfVersion,
2149 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2150 StringRef Fn;
2151 unsigned FileNo = 1;
2152 unsigned Discriminator = 0;
2153 if (auto *Scope = cast_or_null<DIScope>(S)) {
2154 Fn = Scope->getFilename();
2155 if (Line != 0 && DwarfVersion >= 4)
2156 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2157 Discriminator = LBF->getDiscriminator();
2158
2159 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2160 .getOrCreateSourceID(Scope->getFile());
2161 }
2162 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2163 Discriminator, Fn);
2164}
2165
2166DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
2167 unsigned CUID) {
2168 std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);
2169 DebugLoc PrologEndLoc = PrologEnd.first;
2170 bool IsEmptyPrologue = PrologEnd.second;
2171
2172 // Get beginning of function.
2173 if (PrologEndLoc) {
2174 // If the prolog is empty, no need to generate scope line for the proc.
2175 if (IsEmptyPrologue)
2176 return PrologEndLoc;
2177
2178 // Ensure the compile unit is created if the function is called before
2179 // beginFunction().
2180 (void)getOrCreateDwarfCompileUnit(
2181 MF.getFunction().getSubprogram()->getUnit());
2182 // We'd like to list the prologue as "not statements" but GDB behaves
2183 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2184 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
2185 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT(1 << 0),
2186 CUID, getDwarfVersion(), getUnits());
2187 return PrologEndLoc;
2188 }
2189 return DebugLoc();
2190}
2191
2192// Gather pre-function debug information. Assumes being called immediately
2193// after the function entry point has been emitted.
2194void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
2195 CurFn = MF;
2196
2197 auto *SP = MF->getFunction().getSubprogram();
2198 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode())(static_cast <bool> (LScopes.empty() || SP == LScopes.getCurrentFunctionScope
()->getScopeNode()) ? void (0) : __assert_fail ("LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2198, __extension__
__PRETTY_FUNCTION__))
;
2199 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2200 return;
2201
2202 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2203
2204 Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2205 getDwarfCompileUnitIDForLineTable(CU));
2206
2207 // Record beginning of function.
2208 PrologEndLoc = emitInitialLocDirective(
2209 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2210}
2211
2212unsigned
2213DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {
2214 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2215 // belongs to so that we add to the correct per-cu line table in the
2216 // non-asm case.
2217 if (Asm->OutStreamer->hasRawTextSupport())
2218 // Use a single line table if we are generating assembly.
2219 return 0;
2220 else
2221 return CU.getUniqueID();
2222}
2223
2224void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {
2225 const auto &CURanges = CU->getRanges();
2226 auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2227 getDwarfCompileUnitIDForLineTable(*CU));
2228 // Add the last range label for the given CU.
2229 LineTable.getMCLineSections().addEndEntry(
2230 const_cast<MCSymbol *>(CURanges.back().End));
2231}
2232
2233void DwarfDebug::skippedNonDebugFunction() {
2234 // If we don't have a subprogram for this function then there will be a hole
2235 // in the range information. Keep note of this by setting the previously used
2236 // section to nullptr.
2237 // Terminate the pending line table.
2238 if (PrevCU)
2239 terminateLineTable(PrevCU);
2240 PrevCU = nullptr;
2241 CurFn = nullptr;
2242}
2243
2244// Gather and emit post-function debug information.
2245void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
2246 const DISubprogram *SP = MF->getFunction().getSubprogram();
2247
2248 assert(CurFn == MF &&(static_cast <bool> (CurFn == MF && "endFunction should be called with the same function as beginFunction"
) ? void (0) : __assert_fail ("CurFn == MF && \"endFunction should be called with the same function as beginFunction\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2249, __extension__
__PRETTY_FUNCTION__))
2249 "endFunction should be called with the same function as beginFunction")(static_cast <bool> (CurFn == MF && "endFunction should be called with the same function as beginFunction"
) ? void (0) : __assert_fail ("CurFn == MF && \"endFunction should be called with the same function as beginFunction\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2249, __extension__
__PRETTY_FUNCTION__))
;
2250
2251 // Set DwarfDwarfCompileUnitID in MCContext to default value.
2252 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2253
2254 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
2255 assert(!FnScope || SP == FnScope->getScopeNode())(static_cast <bool> (!FnScope || SP == FnScope->getScopeNode
()) ? void (0) : __assert_fail ("!FnScope || SP == FnScope->getScopeNode()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2255, __extension__
__PRETTY_FUNCTION__))
;
2256 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
2257 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2258 PrevLabel = nullptr;
2259 CurFn = nullptr;
2260 return;
2261 }
2262
2263 DenseSet<InlinedEntity> Processed;
2264 collectEntityInfo(TheCU, SP, Processed);
2265
2266 // Add the range of this function to the list of ranges for the CU.
2267 // With basic block sections, add ranges for all basic block sections.
2268 for (const auto &R : Asm->MBBSectionRanges)
2269 TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
2270
2271 // Under -gmlt, skip building the subprogram if there are no inlined
2272 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2273 // is still needed as we need its source location.
2274 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2275 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
2276 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2277 for (const auto &R : Asm->MBBSectionRanges)
2278 addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
2279
2280 assert(InfoHolder.getScopeVariables().empty())(static_cast <bool> (InfoHolder.getScopeVariables().empty
()) ? void (0) : __assert_fail ("InfoHolder.getScopeVariables().empty()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2280, __extension__
__PRETTY_FUNCTION__))
;
2281 PrevLabel = nullptr;
2282 CurFn = nullptr;
2283 return;
2284 }
2285
2286#ifndef NDEBUG
2287 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
2288#endif
2289 // Construct abstract scopes.
2290 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2291 const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2292 for (const DINode *DN : SP->getRetainedNodes()) {
2293 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
2294 continue;
2295
2296 const MDNode *Scope = nullptr;
2297 if (auto *DV = dyn_cast<DILocalVariable>(DN))
2298 Scope = DV->getScope();
2299 else if (auto *DL = dyn_cast<DILabel>(DN))
2300 Scope = DL->getScope();
2301 else
2302 llvm_unreachable("Unexpected DI type!")::llvm::llvm_unreachable_internal("Unexpected DI type!", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 2302)
;
2303
2304 // Collect info for variables/labels that were optimized out.
2305 ensureAbstractEntityIsCreated(TheCU, DN, Scope);
2306 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes(static_cast <bool> (LScopes.getAbstractScopesList().size
() == NumAbstractScopes && "ensureAbstractEntityIsCreated inserted abstract scopes"
) ? void (0) : __assert_fail ("LScopes.getAbstractScopesList().size() == NumAbstractScopes && \"ensureAbstractEntityIsCreated inserted abstract scopes\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2307, __extension__
__PRETTY_FUNCTION__))
2307 && "ensureAbstractEntityIsCreated inserted abstract scopes")(static_cast <bool> (LScopes.getAbstractScopesList().size
() == NumAbstractScopes && "ensureAbstractEntityIsCreated inserted abstract scopes"
) ? void (0) : __assert_fail ("LScopes.getAbstractScopesList().size() == NumAbstractScopes && \"ensureAbstractEntityIsCreated inserted abstract scopes\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2307, __extension__
__PRETTY_FUNCTION__))
;
2308 }
2309 constructAbstractSubprogramScopeDIE(TheCU, AScope);
2310 }
2311
2312 ProcessedSPNodes.insert(SP);
2313 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2314 if (auto *SkelCU = TheCU.getSkeleton())
2315 if (!LScopes.getAbstractScopesList().empty() &&
2316 TheCU.getCUNode()->getSplitDebugInlining())
2317 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2318
2319 // Construct call site entries.
2320 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2321
2322 // Clear debug info
2323 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2324 // DbgVariables except those that are also in AbstractVariables (since they
2325 // can be used cross-function)
2326 InfoHolder.getScopeVariables().clear();
2327 InfoHolder.getScopeLabels().clear();
2328 PrevLabel = nullptr;
2329 CurFn = nullptr;
2330}
2331
2332// Register a source line with debug info. Returns the unique label that was
2333// emitted and which provides correspondence to the source line list.
2334void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2335 unsigned Flags) {
2336 ::recordSourceLine(*Asm, Line, Col, S, Flags,
2337 Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2338 getDwarfVersion(), getUnits());
2339}
2340
2341//===----------------------------------------------------------------------===//
2342// Emit Methods
2343//===----------------------------------------------------------------------===//
2344
2345// Emit the debug info section.
2346void DwarfDebug::emitDebugInfo() {
2347 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2348 Holder.emitUnits(/* UseOffsets */ false);
2349}
2350
2351// Emit the abbreviation section.
2352void DwarfDebug::emitAbbreviations() {
2353 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2354
2355 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2356}
2357
2358void DwarfDebug::emitStringOffsetsTableHeader() {
2359 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2360 Holder.getStringPool().emitStringOffsetsTableHeader(
2361 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2362 Holder.getStringOffsetsStartSym());
2363}
2364
2365template <typename AccelTableT>
2366void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2367 StringRef TableName) {
2368 Asm->OutStreamer->switchSection(Section);
2369
2370 // Emit the full data.
2371 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2372}
2373
2374void DwarfDebug::emitAccelDebugNames() {
2375 // Don't emit anything if we have no compilation units to index.
2376 if (getUnits().empty())
2377 return;
2378
2379 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2380}
2381
2382// Emit visible names into a hashed accelerator table section.
2383void DwarfDebug::emitAccelNames() {
2384 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2385 "Names");
2386}
2387
2388// Emit objective C classes and categories into a hashed accelerator table
2389// section.
2390void DwarfDebug::emitAccelObjC() {
2391 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2392 "ObjC");
2393}
2394
2395// Emit namespace dies into a hashed accelerator table.
2396void DwarfDebug::emitAccelNamespaces() {
2397 emitAccel(AccelNamespace,
2398 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2399 "namespac");
2400}
2401
2402// Emit type dies into a hashed accelerator table.
2403void DwarfDebug::emitAccelTypes() {
2404 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2405 "types");
2406}
2407
2408// Public name handling.
2409// The format for the various pubnames:
2410//
2411// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2412// for the DIE that is named.
2413//
2414// gnu pubnames - offset/index value/name tuples where the offset is the offset
2415// into the CU and the index value is computed according to the type of value
2416// for the DIE that is named.
2417//
2418// For type units the offset is the offset of the skeleton DIE. For split dwarf
2419// it's the offset within the debug_info/debug_types dwo section, however, the
2420// reference in the pubname header doesn't change.
2421
2422/// computeIndexValue - Compute the gdb index value for the DIE and CU.
2423static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2424 const DIE *Die) {
2425 // Entities that ended up only in a Type Unit reference the CU instead (since
2426 // the pub entry has offsets within the CU there's no real offset that can be
2427 // provided anyway). As it happens all such entities (namespaces and types,
2428 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2429 // not to be true it would be necessary to persist this information from the
2430 // point at which the entry is added to the index data structure - since by
2431 // the time the index is built from that, the original type/namespace DIE in a
2432 // type unit has already been destroyed so it can't be queried for properties
2433 // like tag, etc.
2434 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2435 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2436 dwarf::GIEL_EXTERNAL);
2437 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2438
2439 // We could have a specification DIE that has our most of our knowledge,
2440 // look for that now.
2441 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2442 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2443 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2444 Linkage = dwarf::GIEL_EXTERNAL;
2445 } else if (Die->findAttribute(dwarf::DW_AT_external))
2446 Linkage = dwarf::GIEL_EXTERNAL;
2447
2448 switch (Die->getTag()) {
2449 case dwarf::DW_TAG_class_type:
2450 case dwarf::DW_TAG_structure_type:
2451 case dwarf::DW_TAG_union_type:
2452 case dwarf::DW_TAG_enumeration_type:
2453 return dwarf::PubIndexEntryDescriptor(
2454 dwarf::GIEK_TYPE,
2455 dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2456 ? dwarf::GIEL_EXTERNAL
2457 : dwarf::GIEL_STATIC);
2458 case dwarf::DW_TAG_typedef:
2459 case dwarf::DW_TAG_base_type:
2460 case dwarf::DW_TAG_subrange_type:
2461 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2462 case dwarf::DW_TAG_namespace:
2463 return dwarf::GIEK_TYPE;
2464 case dwarf::DW_TAG_subprogram:
2465 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2466 case dwarf::DW_TAG_variable:
2467 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2468 case dwarf::DW_TAG_enumerator:
2469 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2470 dwarf::GIEL_STATIC);
2471 default:
2472 return dwarf::GIEK_NONE;
2473 }
2474}
2475
2476/// emitDebugPubSections - Emit visible names and types into debug pubnames and
2477/// pubtypes sections.
2478void DwarfDebug::emitDebugPubSections() {
2479 for (const auto &NU : CUMap) {
2480 DwarfCompileUnit *TheU = NU.second;
2481 if (!TheU->hasDwarfPubSections())
2482 continue;
2483
2484 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2485 DICompileUnit::DebugNameTableKind::GNU;
2486
2487 Asm->OutStreamer->switchSection(
2488 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2489 : Asm->getObjFileLowering().getDwarfPubNamesSection());
2490 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2491
2492 Asm->OutStreamer->switchSection(
2493 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2494 : Asm->getObjFileLowering().getDwarfPubTypesSection());
2495 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2496 }
2497}
2498
2499void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2500 if (useSectionsAsReferences())
2501 Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2502 CU.getDebugSectionOffset());
2503 else
2504 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2505}
2506
2507void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2508 DwarfCompileUnit *TheU,
2509 const StringMap<const DIE *> &Globals) {
2510 if (auto *Skeleton = TheU->getSkeleton())
2511 TheU = Skeleton;
2512
2513 // Emit the header.
2514 MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
2515 "pub" + Name, "Length of Public " + Name + " Info");
2516
2517 Asm->OutStreamer->AddComment("DWARF Version");
2518 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2519
2520 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2521 emitSectionReference(*TheU);
2522
2523 Asm->OutStreamer->AddComment("Compilation Unit Length");
2524 Asm->emitDwarfLengthOrOffset(TheU->getLength());
2525
2526 // Emit the pubnames for this compilation unit.
2527 for (const auto &GI : Globals) {
2528 const char *Name = GI.getKeyData();
2529 const DIE *Entity = GI.second;
2530
2531 Asm->OutStreamer->AddComment("DIE offset");
2532 Asm->emitDwarfLengthOrOffset(Entity->getOffset());
2533
2534 if (GnuStyle) {
2535 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2536 Asm->OutStreamer->AddComment(
2537 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2538 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2539 Asm->emitInt8(Desc.toBits());
2540 }
2541
2542 Asm->OutStreamer->AddComment("External Name");
2543 Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
2544 }
2545
2546 Asm->OutStreamer->AddComment("End Mark");
2547 Asm->emitDwarfLengthOrOffset(0);
2548 Asm->OutStreamer->emitLabel(EndLabel);
2549}
2550
2551/// Emit null-terminated strings into a debug str section.
2552void DwarfDebug::emitDebugStr() {
2553 MCSection *StringOffsetsSection = nullptr;
2554 if (useSegmentedStringOffsetsTable()) {
2555 emitStringOffsetsTableHeader();
2556 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2557 }
2558 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2559 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2560 StringOffsetsSection, /* UseRelativeOffsets = */ true);
2561}
2562
2563void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2564 const DebugLocStream::Entry &Entry,
2565 const DwarfCompileUnit *CU) {
2566 auto &&Comments = DebugLocs.getComments(Entry);
2567 auto Comment = Comments.begin();
2568 auto End = Comments.end();
2569
2570 // The expressions are inserted into a byte stream rather early (see
2571 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2572 // need to reference a base_type DIE the offset of that DIE is not yet known.
2573 // To deal with this we instead insert a placeholder early and then extract
2574 // it here and replace it with the real reference.
2575 unsigned PtrSize = Asm->MAI->getCodePointerSize();
2576 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2577 DebugLocs.getBytes(Entry).size()),
2578 Asm->getDataLayout().isLittleEndian(), PtrSize);
2579 DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
2580
2581 using Encoding = DWARFExpression::Operation::Encoding;
2582 uint64_t Offset = 0;
2583 for (const auto &Op : Expr) {
2584 assert(Op.getCode() != dwarf::DW_OP_const_type &&(static_cast <bool> (Op.getCode() != dwarf::DW_OP_const_type
&& "3 operand ops not yet supported") ? void (0) : __assert_fail
("Op.getCode() != dwarf::DW_OP_const_type && \"3 operand ops not yet supported\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2585, __extension__
__PRETTY_FUNCTION__))
2585 "3 operand ops not yet supported")(static_cast <bool> (Op.getCode() != dwarf::DW_OP_const_type
&& "3 operand ops not yet supported") ? void (0) : __assert_fail
("Op.getCode() != dwarf::DW_OP_const_type && \"3 operand ops not yet supported\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2585, __extension__
__PRETTY_FUNCTION__))
;
2586 Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2587 Offset++;
2588 for (unsigned I = 0; I < 2; ++I) {
2589 if (Op.getDescription().Op[I] == Encoding::SizeNA)
2590 continue;
2591 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2592 unsigned Length =
2593 Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
2594 // Make sure comments stay aligned.
2595 for (unsigned J = 0; J < Length; ++J)
2596 if (Comment != End)
2597 Comment++;
2598 } else {
2599 for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2600 Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2601 }
2602 Offset = Op.getOperandEndOffset(I);
2603 }
2604 assert(Offset == Op.getEndOffset())(static_cast <bool> (Offset == Op.getEndOffset()) ? void
(0) : __assert_fail ("Offset == Op.getEndOffset()", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 2604, __extension__ __PRETTY_FUNCTION__))
;
2605 }
2606}
2607
2608void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2609 const DbgValueLoc &Value,
2610 DwarfExpression &DwarfExpr) {
2611 auto *DIExpr = Value.getExpression();
2612 DIExpressionCursor ExprCursor(DIExpr);
2613 DwarfExpr.addFragmentOffset(DIExpr);
2614
2615 // If the DIExpr is is an Entry Value, we want to follow the same code path
2616 // regardless of whether the DBG_VALUE is variadic or not.
2617 if (DIExpr && DIExpr->isEntryValue()) {
2618 // Entry values can only be a single register with no additional DIExpr,
2619 // so just add it directly.
2620 assert(Value.getLocEntries().size() == 1)(static_cast <bool> (Value.getLocEntries().size() == 1)
? void (0) : __assert_fail ("Value.getLocEntries().size() == 1"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2620, __extension__
__PRETTY_FUNCTION__))
;
2621 assert(Value.getLocEntries()[0].isLocation())(static_cast <bool> (Value.getLocEntries()[0].isLocation
()) ? void (0) : __assert_fail ("Value.getLocEntries()[0].isLocation()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2621, __extension__
__PRETTY_FUNCTION__))
;
2622 MachineLocation Location = Value.getLocEntries()[0].getLoc();
2623 DwarfExpr.setLocation(Location, DIExpr);
2624
2625 DwarfExpr.beginEntryValueExpression(ExprCursor);
2626
2627 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2628 if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
2629 return;
2630 return DwarfExpr.addExpression(std::move(ExprCursor));
2631 }
2632
2633 // Regular entry.
2634 auto EmitValueLocEntry = [&DwarfExpr, &BT,
2635 &AP](const DbgValueLocEntry &Entry,
2636 DIExpressionCursor &Cursor) -> bool {
2637 if (Entry.isInt()) {
2638 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2639 BT->getEncoding() == dwarf::DW_ATE_signed_char))
2640 DwarfExpr.addSignedConstant(Entry.getInt());
2641 else
2642 DwarfExpr.addUnsignedConstant(Entry.getInt());
2643 } else if (Entry.isLocation()) {
2644 MachineLocation Location = Entry.getLoc();
2645 if (Location.isIndirect())
2646 DwarfExpr.setMemoryLocationKind();
2647
2648 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2649 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2650 return false;
2651 } else if (Entry.isTargetIndexLocation()) {
2652 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
2653 // TODO TargetIndexLocation is a target-independent. Currently only the
2654 // WebAssembly-specific encoding is supported.
2655 assert(AP.TM.getTargetTriple().isWasm())(static_cast <bool> (AP.TM.getTargetTriple().isWasm()) ?
void (0) : __assert_fail ("AP.TM.getTargetTriple().isWasm()"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2655, __extension__
__PRETTY_FUNCTION__))
;
2656 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2657 } else if (Entry.isConstantFP()) {
2658 if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2659 !Cursor) {
2660 DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2661 } else if (Entry.getConstantFP()
2662 ->getValueAPF()
2663 .bitcastToAPInt()
2664 .getBitWidth() <= 64 /*bits*/) {
2665 DwarfExpr.addUnsignedConstant(
2666 Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2667 } else {
2668 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
2669 dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
2670 << Entry.getConstantFP()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
2671 ->getValueAPF()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
2672 .bitcastToAPInt()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
2673 .getBitWidth()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
2674 << " bits\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dwarfdebug")) { dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
<< Entry.getConstantFP() ->getValueAPF() .bitcastToAPInt
() .getBitWidth() << " bits\n"; } } while (false)
;
2675 return false;
2676 }
2677 }
2678 return true;
2679 };
2680
2681 if (!Value.isVariadic()) {
2682 if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
2683 return;
2684 DwarfExpr.addExpression(std::move(ExprCursor));
2685 return;
2686 }
2687
2688 // If any of the location entries are registers with the value 0, then the
2689 // location is undefined.
2690 if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
2691 return Entry.isLocation() && !Entry.getLoc().getReg();
2692 }))
2693 return;
2694
2695 DwarfExpr.addExpression(
2696 std::move(ExprCursor),
2697 [EmitValueLocEntry, &Value](unsigned Idx,
2698 DIExpressionCursor &Cursor) -> bool {
2699 return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
2700 });
2701}
2702
2703void DebugLocEntry::finalize(const AsmPrinter &AP,
2704 DebugLocStream::ListBuilder &List,
2705 const DIBasicType *BT,
2706 DwarfCompileUnit &TheCU) {
2707 assert(!Values.empty() &&(static_cast <bool> (!Values.empty() && "location list entries without values are redundant"
) ? void (0) : __assert_fail ("!Values.empty() && \"location list entries without values are redundant\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2708, __extension__
__PRETTY_FUNCTION__))
2708 "location list entries without values are redundant")(static_cast <bool> (!Values.empty() && "location list entries without values are redundant"
) ? void (0) : __assert_fail ("!Values.empty() && \"location list entries without values are redundant\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2708, __extension__
__PRETTY_FUNCTION__))
;
2709 assert(Begin != End && "unexpected location list entry with empty range")(static_cast <bool> (Begin != End && "unexpected location list entry with empty range"
) ? void (0) : __assert_fail ("Begin != End && \"unexpected location list entry with empty range\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2709, __extension__
__PRETTY_FUNCTION__))
;
2710 DebugLocStream::EntryBuilder Entry(List, Begin, End);
2711 BufferByteStreamer Streamer = Entry.getStreamer();
2712 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2713 const DbgValueLoc &Value = Values[0];
2714 if (Value.isFragment()) {
2715 // Emit all fragments that belong to the same variable and range.
2716 assert(llvm::all_of(Values, [](DbgValueLoc P) {(static_cast <bool> (llvm::all_of(Values, [](DbgValueLoc
P) { return P.isFragment(); }) && "all values are expected to be fragments"
) ? void (0) : __assert_fail ("llvm::all_of(Values, [](DbgValueLoc P) { return P.isFragment(); }) && \"all values are expected to be fragments\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2718, __extension__
__PRETTY_FUNCTION__))
2717 return P.isFragment();(static_cast <bool> (llvm::all_of(Values, [](DbgValueLoc
P) { return P.isFragment(); }) && "all values are expected to be fragments"
) ? void (0) : __assert_fail ("llvm::all_of(Values, [](DbgValueLoc P) { return P.isFragment(); }) && \"all values are expected to be fragments\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2718, __extension__
__PRETTY_FUNCTION__))
2718 }) && "all values are expected to be fragments")(static_cast <bool> (llvm::all_of(Values, [](DbgValueLoc
P) { return P.isFragment(); }) && "all values are expected to be fragments"
) ? void (0) : __assert_fail ("llvm::all_of(Values, [](DbgValueLoc P) { return P.isFragment(); }) && \"all values are expected to be fragments\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2718, __extension__
__PRETTY_FUNCTION__))
;
2719 assert(llvm::is_sorted(Values) && "fragments are expected to be sorted")(static_cast <bool> (llvm::is_sorted(Values) &&
"fragments are expected to be sorted") ? void (0) : __assert_fail
("llvm::is_sorted(Values) && \"fragments are expected to be sorted\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2719, __extension__
__PRETTY_FUNCTION__))
;
2720
2721 for (const auto &Fragment : Values)
2722 DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2723
2724 } else {
2725 assert(Values.size() == 1 && "only fragments may have >1 value")(static_cast <bool> (Values.size() == 1 && "only fragments may have >1 value"
) ? void (0) : __assert_fail ("Values.size() == 1 && \"only fragments may have >1 value\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2725, __extension__
__PRETTY_FUNCTION__))
;
2726 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2727 }
2728 DwarfExpr.finalize();
2729 if (DwarfExpr.TagOffset)
2730 List.setTagOffset(*DwarfExpr.TagOffset);
2731}
2732
2733void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2734 const DwarfCompileUnit *CU) {
2735 // Emit the size.
2736 Asm->OutStreamer->AddComment("Loc expr size");
2737 if (getDwarfVersion() >= 5)
2738 Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2739 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2740 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2741 else {
2742 // The entry is too big to fit into 16 bit, drop it as there is nothing we
2743 // can do.
2744 Asm->emitInt16(0);
2745 return;
2746 }
2747 // Emit the entry.
2748 APByteStreamer Streamer(*Asm);
2749 emitDebugLocEntry(Streamer, Entry, CU);
2750}
2751
2752// Emit the header of a DWARF 5 range list table list table. Returns the symbol
2753// that designates the end of the table for the caller to emit when the table is
2754// complete.
2755static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2756 const DwarfFile &Holder) {
2757 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2758
2759 Asm->OutStreamer->AddComment("Offset entry count");
2760 Asm->emitInt32(Holder.getRangeLists().size());
2761 Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2762
2763 for (const RangeSpanList &List : Holder.getRangeLists())
2764 Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2765 Asm->getDwarfOffsetByteSize());
2766
2767 return TableEnd;
2768}
2769
2770// Emit the header of a DWARF 5 locations list table. Returns the symbol that
2771// designates the end of the table for the caller to emit when the table is
2772// complete.
2773static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2774 const DwarfDebug &DD) {
2775 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2776
2777 const auto &DebugLocs = DD.getDebugLocs();
2778
2779 Asm->OutStreamer->AddComment("Offset entry count");
2780 Asm->emitInt32(DebugLocs.getLists().size());
2781 Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2782
2783 for (const auto &List : DebugLocs.getLists())
2784 Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2785 Asm->getDwarfOffsetByteSize());
2786
2787 return TableEnd;
2788}
2789
2790template <typename Ranges, typename PayloadEmitter>
2791static void emitRangeList(
2792 DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2793 const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2794 unsigned StartxLength, unsigned EndOfList,
2795 StringRef (*StringifyEnum)(unsigned),
2796 bool ShouldUseBaseAddress,
2797 PayloadEmitter EmitPayload) {
2798
2799 auto Size = Asm->MAI->getCodePointerSize();
2800 bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2801
2802 // Emit our symbol so we can find the beginning of the range.
2803 Asm->OutStreamer->emitLabel(Sym);
2804
2805 // Gather all the ranges that apply to the same section so they can share
2806 // a base address entry.
2807 MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2808
2809 for (const auto &Range : R)
2810 SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2811
2812 const MCSymbol *CUBase = CU.getBaseAddress();
2813 bool BaseIsSet = false;
2814 for (const auto &P : SectionRanges) {
2815 auto *Base = CUBase;
2816 if (!Base && ShouldUseBaseAddress) {
2817 const MCSymbol *Begin = P.second.front()->Begin;
2818 const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2819 if (!UseDwarf5) {
2820 Base = NewBase;
2821 BaseIsSet = true;
2822 Asm->OutStreamer->emitIntValue(-1, Size);
2823 Asm->OutStreamer->AddComment(" base address");
2824 Asm->OutStreamer->emitSymbolValue(Base, Size);
2825 } else if (NewBase != Begin || P.second.size() > 1) {
2826 // Only use a base address if
2827 // * the existing pool address doesn't match (NewBase != Begin)
2828 // * or, there's more than one entry to share the base address
2829 Base = NewBase;
2830 BaseIsSet = true;
2831 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2832 Asm->emitInt8(BaseAddressx);
2833 Asm->OutStreamer->AddComment(" base address index");
2834 Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
2835 }
2836 } else if (BaseIsSet && !UseDwarf5) {
2837 BaseIsSet = false;
2838 assert(!Base)(static_cast <bool> (!Base) ? void (0) : __assert_fail (
"!Base", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2838, __extension__
__PRETTY_FUNCTION__))
;
2839 Asm->OutStreamer->emitIntValue(-1, Size);
2840 Asm->OutStreamer->emitIntValue(0, Size);
2841 }
2842
2843 for (const auto *RS : P.second) {
2844 const MCSymbol *Begin = RS->Begin;
2845 const MCSymbol *End = RS->End;
2846 assert(Begin && "Range without a begin symbol?")(static_cast <bool> (Begin && "Range without a begin symbol?"
) ? void (0) : __assert_fail ("Begin && \"Range without a begin symbol?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2846, __extension__
__PRETTY_FUNCTION__))
;
2847 assert(End && "Range without an end symbol?")(static_cast <bool> (End && "Range without an end symbol?"
) ? void (0) : __assert_fail ("End && \"Range without an end symbol?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2847, __extension__
__PRETTY_FUNCTION__))
;
2848 if (Base) {
2849 if (UseDwarf5) {
2850 // Emit offset_pair when we have a base.
2851 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2852 Asm->emitInt8(OffsetPair);
2853 Asm->OutStreamer->AddComment(" starting offset");
2854 Asm->emitLabelDifferenceAsULEB128(Begin, Base);
2855 Asm->OutStreamer->AddComment(" ending offset");
2856 Asm->emitLabelDifferenceAsULEB128(End, Base);
2857 } else {
2858 Asm->emitLabelDifference(Begin, Base, Size);
2859 Asm->emitLabelDifference(End, Base, Size);
2860 }
2861 } else if (UseDwarf5) {
2862 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2863 Asm->emitInt8(StartxLength);
2864 Asm->OutStreamer->AddComment(" start index");
2865 Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
2866 Asm->OutStreamer->AddComment(" length");
2867 Asm->emitLabelDifferenceAsULEB128(End, Begin);
2868 } else {
2869 Asm->OutStreamer->emitSymbolValue(Begin, Size);
2870 Asm->OutStreamer->emitSymbolValue(End, Size);
2871 }
2872 EmitPayload(*RS);
2873 }
2874 }
2875
2876 if (UseDwarf5) {
2877 Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2878 Asm->emitInt8(EndOfList);
2879 } else {
2880 // Terminate the list with two 0 values.
2881 Asm->OutStreamer->emitIntValue(0, Size);
2882 Asm->OutStreamer->emitIntValue(0, Size);
2883 }
2884}
2885
2886// Handles emission of both debug_loclist / debug_loclist.dwo
2887static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2888 emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2889 *List.CU, dwarf::DW_LLE_base_addressx,
2890 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2891 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2892 /* ShouldUseBaseAddress */ true,
2893 [&](const DebugLocStream::Entry &E) {
2894 DD.emitDebugLocEntryLocation(E, List.CU);
2895 });
2896}
2897
2898void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2899 if (DebugLocs.getLists().empty())
2900 return;
2901
2902 Asm->OutStreamer->switchSection(Sec);
2903
2904 MCSymbol *TableEnd = nullptr;
2905 if (getDwarfVersion() >= 5)
2906 TableEnd = emitLoclistsTableHeader(Asm, *this);
2907
2908 for (const auto &List : DebugLocs.getLists())
2909 emitLocList(*this, Asm, List);
2910
2911 if (TableEnd)
2912 Asm->OutStreamer->emitLabel(TableEnd);
2913}
2914
2915// Emit locations into the .debug_loc/.debug_loclists section.
2916void DwarfDebug::emitDebugLoc() {
2917 emitDebugLocImpl(
2918 getDwarfVersion() >= 5
2919 ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2920 : Asm->getObjFileLowering().getDwarfLocSection());
2921}
2922
2923// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2924void DwarfDebug::emitDebugLocDWO() {
2925 if (getDwarfVersion() >= 5) {
2926 emitDebugLocImpl(
2927 Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2928
2929 return;
2930 }
2931
2932 for (const auto &List : DebugLocs.getLists()) {
2933 Asm->OutStreamer->switchSection(
2934 Asm->getObjFileLowering().getDwarfLocDWOSection());
2935 Asm->OutStreamer->emitLabel(List.Label);
2936
2937 for (const auto &Entry : DebugLocs.getEntries(List)) {
2938 // GDB only supports startx_length in pre-standard split-DWARF.
2939 // (in v5 standard loclists, it currently* /only/ supports base_address +
2940 // offset_pair, so the implementations can't really share much since they
2941 // need to use different representations)
2942 // * as of October 2018, at least
2943 //
2944 // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2945 // addresses in the address pool to minimize object size/relocations.
2946 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2947 unsigned idx = AddrPool.getIndex(Entry.Begin);
2948 Asm->emitULEB128(idx);
2949 // Also the pre-standard encoding is slightly different, emitting this as
2950 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2951 Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2952 emitDebugLocEntryLocation(Entry, List.CU);
2953 }
2954 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2955 }
2956}
2957
2958struct ArangeSpan {
2959 const MCSymbol *Start, *End;
2960};
2961
2962// Emit a debug aranges section, containing a CU lookup for any
2963// address we can tie back to a CU.
2964void DwarfDebug::emitDebugARanges() {
2965 // Provides a unique id per text section.
2966 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2967
2968 // Filter labels by section.
2969 for (const SymbolCU &SCU : ArangeLabels) {
2970 if (SCU.Sym->isInSection()) {
2971 // Make a note of this symbol and it's section.
2972 MCSection *Section = &SCU.Sym->getSection();
2973 if (!Section->getKind().isMetadata())
2974 SectionMap[Section].push_back(SCU);
2975 } else {
2976 // Some symbols (e.g. common/bss on mach-o) can have no section but still
2977 // appear in the output. This sucks as we rely on sections to build
2978 // arange spans. We can do it without, but it's icky.
2979 SectionMap[nullptr].push_back(SCU);
2980 }
2981 }
2982
2983 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2984
2985 for (auto &I : SectionMap) {
2986 MCSection *Section = I.first;
2987 SmallVector<SymbolCU, 8> &List = I.second;
2988 if (List.size() < 1)
2989 continue;
2990
2991 // If we have no section (e.g. common), just write out
2992 // individual spans for each symbol.
2993 if (!Section) {
2994 for (const SymbolCU &Cur : List) {
2995 ArangeSpan Span;
2996 Span.Start = Cur.Sym;
2997 Span.End = nullptr;
2998 assert(Cur.CU)(static_cast <bool> (Cur.CU) ? void (0) : __assert_fail
("Cur.CU", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 2998
, __extension__ __PRETTY_FUNCTION__))
;
2999 Spans[Cur.CU].push_back(Span);
3000 }
3001 continue;
3002 }
3003
3004 // Sort the symbols by offset within the section.
3005 llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
3006 unsigned IA = A.Sym ? Asm->OutStreamer->getSymbolOrder(A.Sym) : 0;
3007 unsigned IB = B.Sym ? Asm->OutStreamer->getSymbolOrder(B.Sym) : 0;
3008
3009 // Symbols with no order assigned should be placed at the end.
3010 // (e.g. section end labels)
3011 if (IA == 0)
3012 return false;
3013 if (IB == 0)
3014 return true;
3015 return IA < IB;
3016 });
3017
3018 // Insert a final terminator.
3019 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
3020
3021 // Build spans between each label.
3022 const MCSymbol *StartSym = List[0].Sym;
3023 for (size_t n = 1, e = List.size(); n < e; n++) {
3024 const SymbolCU &Prev = List[n - 1];
3025 const SymbolCU &Cur = List[n];
3026
3027 // Try and build the longest span we can within the same CU.
3028 if (Cur.CU != Prev.CU) {
3029 ArangeSpan Span;
3030 Span.Start = StartSym;
3031 Span.End = Cur.Sym;
3032 assert(Prev.CU)(static_cast <bool> (Prev.CU) ? void (0) : __assert_fail
("Prev.CU", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3032
, __extension__ __PRETTY_FUNCTION__))
;
3033 Spans[Prev.CU].push_back(Span);
3034 StartSym = Cur.Sym;
3035 }
3036 }
3037 }
3038
3039 // Start the dwarf aranges section.
3040 Asm->OutStreamer->switchSection(
3041 Asm->getObjFileLowering().getDwarfARangesSection());
3042
3043 unsigned PtrSize = Asm->MAI->getCodePointerSize();
3044
3045 // Build a list of CUs used.
3046 std::vector<DwarfCompileUnit *> CUs;
3047 for (const auto &it : Spans) {
3048 DwarfCompileUnit *CU = it.first;
3049 CUs.push_back(CU);
3050 }
3051
3052 // Sort the CU list (again, to ensure consistent output order).
3053 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
3054 return A->getUniqueID() < B->getUniqueID();
3055 });
3056
3057 // Emit an arange table for each CU we used.
3058 for (DwarfCompileUnit *CU : CUs) {
3059 std::vector<ArangeSpan> &List = Spans[CU];
3060
3061 // Describe the skeleton CU's offset and length, not the dwo file's.
3062 if (auto *Skel = CU->getSkeleton())
3063 CU = Skel;
3064
3065 // Emit size of content not including length itself.
3066 unsigned ContentSize =
3067 sizeof(int16_t) + // DWARF ARange version number
3068 Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3069 // section
3070 sizeof(int8_t) + // Pointer Size (in bytes)
3071 sizeof(int8_t); // Segment Size (in bytes)
3072
3073 unsigned TupleSize = PtrSize * 2;
3074
3075 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3076 unsigned Padding = offsetToAlignment(
3077 Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
3078
3079 ContentSize += Padding;
3080 ContentSize += (List.size() + 1) * TupleSize;
3081
3082 // For each compile unit, write the list of spans it covers.
3083 Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
3084 Asm->OutStreamer->AddComment("DWARF Arange version number");
3085 Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
3086 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
3087 emitSectionReference(*CU);
3088 Asm->OutStreamer->AddComment("Address Size (in bytes)");
3089 Asm->emitInt8(PtrSize);
3090 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
3091 Asm->emitInt8(0);
3092
3093 Asm->OutStreamer->emitFill(Padding, 0xff);
3094
3095 for (const ArangeSpan &Span : List) {
3096 Asm->emitLabelReference(Span.Start, PtrSize);
3097
3098 // Calculate the size as being from the span start to its end.
3099 //
3100 // If the size is zero, then round it up to one byte. The DWARF
3101 // specification requires that entries in this table have nonzero
3102 // lengths.
3103 auto SizeRef = SymSize.find(Span.Start);
3104 if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3105 Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
3106 } else {
3107 // For symbols without an end marker (e.g. common), we
3108 // write a single arange entry containing just that one symbol.
3109 uint64_t Size;
3110 if (SizeRef == SymSize.end() || SizeRef->second == 0)
3111 Size = 1;
3112 else
3113 Size = SizeRef->second;
3114
3115 Asm->OutStreamer->emitIntValue(Size, PtrSize);
3116 }
3117 }
3118
3119 Asm->OutStreamer->AddComment("ARange terminator");
3120 Asm->OutStreamer->emitIntValue(0, PtrSize);
3121 Asm->OutStreamer->emitIntValue(0, PtrSize);
3122 }
3123}
3124
3125/// Emit a single range list. We handle both DWARF v5 and earlier.
3126static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
3127 const RangeSpanList &List) {
3128 emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
3129 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
3130 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
3131 llvm::dwarf::RangeListEncodingString,
3132 List.CU->getCUNode()->getRangesBaseAddress() ||
3133 DD.getDwarfVersion() >= 5,
3134 [](auto) {});
3135}
3136
3137void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3138 if (Holder.getRangeLists().empty())
3139 return;
3140
3141 assert(useRangesSection())(static_cast <bool> (useRangesSection()) ? void (0) : __assert_fail
("useRangesSection()", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 3141, __extension__ __PRETTY_FUNCTION__))
;
3142 assert(!CUMap.empty())(static_cast <bool> (!CUMap.empty()) ? void (0) : __assert_fail
("!CUMap.empty()", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 3142, __extension__ __PRETTY_FUNCTION__))
;
3143 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {(static_cast <bool> (llvm::any_of(CUMap, [](const decltype
(CUMap)::value_type &Pair) { return !Pair.second->getCUNode
()->isDebugDirectivesOnly(); })) ? void (0) : __assert_fail
("llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { return !Pair.second->getCUNode()->isDebugDirectivesOnly(); })"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3145, __extension__
__PRETTY_FUNCTION__))
3144 return !Pair.second->getCUNode()->isDebugDirectivesOnly();(static_cast <bool> (llvm::any_of(CUMap, [](const decltype
(CUMap)::value_type &Pair) { return !Pair.second->getCUNode
()->isDebugDirectivesOnly(); })) ? void (0) : __assert_fail
("llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { return !Pair.second->getCUNode()->isDebugDirectivesOnly(); })"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3145, __extension__
__PRETTY_FUNCTION__))
3145 }))(static_cast <bool> (llvm::any_of(CUMap, [](const decltype
(CUMap)::value_type &Pair) { return !Pair.second->getCUNode
()->isDebugDirectivesOnly(); })) ? void (0) : __assert_fail
("llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) { return !Pair.second->getCUNode()->isDebugDirectivesOnly(); })"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3145, __extension__
__PRETTY_FUNCTION__))
;
3146
3147 Asm->OutStreamer->switchSection(Section);
3148
3149 MCSymbol *TableEnd = nullptr;
3150 if (getDwarfVersion() >= 5)
3151 TableEnd = emitRnglistsTableHeader(Asm, Holder);
3152
3153 for (const RangeSpanList &List : Holder.getRangeLists())
3154 emitRangeList(*this, Asm, List);
3155
3156 if (TableEnd)
3157 Asm->OutStreamer->emitLabel(TableEnd);
3158}
3159
3160/// Emit address ranges into the .debug_ranges section or into the DWARF v5
3161/// .debug_rnglists section.
3162void DwarfDebug::emitDebugRanges() {
3163 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3164
3165 emitDebugRangesImpl(Holder,
3166 getDwarfVersion() >= 5
3167 ? Asm->getObjFileLowering().getDwarfRnglistsSection()
3168 : Asm->getObjFileLowering().getDwarfRangesSection());
3169}
3170
3171void DwarfDebug::emitDebugRangesDWO() {
3172 emitDebugRangesImpl(InfoHolder,
3173 Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
3174}
3175
3176/// Emit the header of a DWARF 5 macro section, or the GNU extension for
3177/// DWARF 4.
3178static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3179 const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
3180 enum HeaderFlagMask {
3181#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3182#include "llvm/BinaryFormat/Dwarf.def"
3183 };
3184 Asm->OutStreamer->AddComment("Macro information version");
3185 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3186 // We emit the line offset flag unconditionally here, since line offset should
3187 // be mostly present.
3188 if (Asm->isDwarf64()) {
3189 Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3190 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3191 } else {
3192 Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3193 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3194 }
3195 Asm->OutStreamer->AddComment("debug_line_offset");
3196 if (DD.useSplitDwarf())
3197 Asm->emitDwarfLengthOrOffset(0);
3198 else
3199 Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
3200}
3201
3202void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3203 for (auto *MN : Nodes) {
3204 if (auto *M = dyn_cast<DIMacro>(MN))
3205 emitMacro(*M);
3206 else if (auto *F = dyn_cast<DIMacroFile>(MN))
3207 emitMacroFile(*F, U);
3208 else
3209 llvm_unreachable("Unexpected DI type!")::llvm::llvm_unreachable_internal("Unexpected DI type!", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 3209)
;
3210 }
3211}
3212
3213void DwarfDebug::emitMacro(DIMacro &M) {
3214 StringRef Name = M.getName();
3215 StringRef Value = M.getValue();
3216
3217 // There should be one space between the macro name and the macro value in
3218 // define entries. In undef entries, only the macro name is emitted.
3219 std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3220
3221 if (UseDebugMacroSection) {
3222 if (getDwarfVersion() >= 5) {
3223 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3224 ? dwarf::DW_MACRO_define_strx
3225 : dwarf::DW_MACRO_undef_strx;
3226 Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
3227 Asm->emitULEB128(Type);
3228 Asm->OutStreamer->AddComment("Line Number");
3229 Asm->emitULEB128(M.getLine());
3230 Asm->OutStreamer->AddComment("Macro String");
3231 Asm->emitULEB128(
3232 InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3233 } else {
3234 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3235 ? dwarf::DW_MACRO_GNU_define_indirect
3236 : dwarf::DW_MACRO_GNU_undef_indirect;
3237 Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
3238 Asm->emitULEB128(Type);
3239 Asm->OutStreamer->AddComment("Line Number");
3240 Asm->emitULEB128(M.getLine());
3241 Asm->OutStreamer->AddComment("Macro String");
3242 Asm->emitDwarfSymbolReference(
3243 InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3244 }
3245 } else {
3246 Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
3247 Asm->emitULEB128(M.getMacinfoType());
3248 Asm->OutStreamer->AddComment("Line Number");
3249 Asm->emitULEB128(M.getLine());
3250 Asm->OutStreamer->AddComment("Macro String");
3251 Asm->OutStreamer->emitBytes(Str);
3252 Asm->emitInt8('\0');
3253 }
3254}
3255
3256void DwarfDebug::emitMacroFileImpl(
3257 DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3258 StringRef (*MacroFormToString)(unsigned Form)) {
3259
3260 Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3261 Asm->emitULEB128(StartFile);
3262 Asm->OutStreamer->AddComment("Line Number");
3263 Asm->emitULEB128(MF.getLine());
3264 Asm->OutStreamer->AddComment("File Number");
3265 DIFile &F = *MF.getFile();
3266 if (useSplitDwarf())
3267 Asm->emitULEB128(getDwoLineTable(U)->getFile(
3268 F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3269 Asm->OutContext.getDwarfVersion(), F.getSource()));
3270 else
3271 Asm->emitULEB128(U.getOrCreateSourceID(&F));
3272 handleMacroNodes(MF.getElements(), U);
3273 Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
3274 Asm->emitULEB128(EndFile);
3275}
3276
3277void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3278 // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3279 // so for readibility/uniformity, We are explicitly emitting those.
3280 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file)(static_cast <bool> (F.getMacinfoType() == dwarf::DW_MACINFO_start_file
) ? void (0) : __assert_fail ("F.getMacinfoType() == dwarf::DW_MACINFO_start_file"
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3280, __extension__
__PRETTY_FUNCTION__))
;
3281 if (UseDebugMacroSection)
3282 emitMacroFileImpl(
3283 F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3284 (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
3285 else
3286 emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
3287 dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
3288}
3289
3290void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3291 for (const auto &P : CUMap) {
3292 auto &TheCU = *P.second;
3293 auto *SkCU = TheCU.getSkeleton();
3294 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3295 auto *CUNode = cast<DICompileUnit>(P.first);
3296 DIMacroNodeArray Macros = CUNode->getMacros();
3297 if (Macros.empty())
3298 continue;
3299 Asm->OutStreamer->switchSection(Section);
3300 Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3301 if (UseDebugMacroSection)
3302 emitMacroHeader(Asm, *this, U, getDwarfVersion());
3303 handleMacroNodes(Macros, U);
3304 Asm->OutStreamer->AddComment("End Of Macro List Mark");
3305 Asm->emitInt8(0);
3306 }
3307}
3308
3309/// Emit macros into a debug macinfo/macro section.
3310void DwarfDebug::emitDebugMacinfo() {
3311 auto &ObjLower = Asm->getObjFileLowering();
3312 emitDebugMacinfoImpl(UseDebugMacroSection
3313 ? ObjLower.getDwarfMacroSection()
3314 : ObjLower.getDwarfMacinfoSection());
3315}
3316
3317void DwarfDebug::emitDebugMacinfoDWO() {
3318 auto &ObjLower = Asm->getObjFileLowering();
3319 emitDebugMacinfoImpl(UseDebugMacroSection
3320 ? ObjLower.getDwarfMacroDWOSection()
3321 : ObjLower.getDwarfMacinfoDWOSection());
3322}
3323
3324// DWARF5 Experimental Separate Dwarf emitters.
3325
3326void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
3327 std::unique_ptr<DwarfCompileUnit> NewU) {
3328
3329 if (!CompilationDir.empty())
3330 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3331 addGnuPubAttributes(*NewU, Die);
3332
3333 SkeletonHolder.addUnit(std::move(NewU));
3334}
3335
3336DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3337
3338 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3339 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3340 UnitKind::Skeleton);
3341 DwarfCompileUnit &NewCU = *OwnedUnit;
3342 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
3343
3344 NewCU.initStmtList();
3345
3346 if (useSegmentedStringOffsetsTable())
3347 NewCU.addStringOffsetsStart();
3348
3349 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
3350
3351 return NewCU;
3352}
3353
3354// Emit the .debug_info.dwo section for separated dwarf. This contains the
3355// compile units that would normally be in debug_info.
3356void DwarfDebug::emitDebugInfoDWO() {
3357 assert(useSplitDwarf() && "No split dwarf debug info?")(static_cast <bool> (useSplitDwarf() && "No split dwarf debug info?"
) ? void (0) : __assert_fail ("useSplitDwarf() && \"No split dwarf debug info?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3357, __extension__
__PRETTY_FUNCTION__))
;
3358 // Don't emit relocations into the dwo file.
3359 InfoHolder.emitUnits(/* UseOffsets */ true);
3360}
3361
3362// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3363// abbreviations for the .debug_info.dwo section.
3364void DwarfDebug::emitDebugAbbrevDWO() {
3365 assert(useSplitDwarf() && "No split dwarf?")(static_cast <bool> (useSplitDwarf() && "No split dwarf?"
) ? void (0) : __assert_fail ("useSplitDwarf() && \"No split dwarf?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3365, __extension__
__PRETTY_FUNCTION__))
;
3366 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3367}
3368
3369void DwarfDebug::emitDebugLineDWO() {
3370 assert(useSplitDwarf() && "No split dwarf?")(static_cast <bool> (useSplitDwarf() && "No split dwarf?"
) ? void (0) : __assert_fail ("useSplitDwarf() && \"No split dwarf?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3370, __extension__
__PRETTY_FUNCTION__))
;
3371 SplitTypeUnitFileTable.Emit(
3372 *Asm->OutStreamer, MCDwarfLineTableParams(),
3373 Asm->getObjFileLowering().getDwarfLineDWOSection());
3374}
3375
3376void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3377 assert(useSplitDwarf() && "No split dwarf?")(static_cast <bool> (useSplitDwarf() && "No split dwarf?"
) ? void (0) : __assert_fail ("useSplitDwarf() && \"No split dwarf?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3377, __extension__
__PRETTY_FUNCTION__))
;
3378 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
3379 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
3380 InfoHolder.getStringOffsetsStartSym());
3381}
3382
3383// Emit the .debug_str.dwo section for separated dwarf. This contains the
3384// string section and is identical in format to traditional .debug_str
3385// sections.
3386void DwarfDebug::emitDebugStrDWO() {
3387 if (useSegmentedStringOffsetsTable())
3388 emitStringOffsetsTableHeaderDWO();
3389 assert(useSplitDwarf() && "No split dwarf?")(static_cast <bool> (useSplitDwarf() && "No split dwarf?"
) ? void (0) : __assert_fail ("useSplitDwarf() && \"No split dwarf?\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3389, __extension__
__PRETTY_FUNCTION__))
;
3390 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3391 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3392 OffSec, /* UseRelativeOffsets = */ false);
3393}
3394
3395// Emit address pool.
3396void DwarfDebug::emitDebugAddr() {
3397 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
3398}
3399
3400MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
3401 if (!useSplitDwarf())
3402 return nullptr;
3403 const DICompileUnit *DIUnit = CU.getCUNode();
3404 SplitTypeUnitFileTable.maybeSetRootFile(
3405 DIUnit->getDirectory(), DIUnit->getFilename(),
3406 getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
3407 return &SplitTypeUnitFileTable;
3408}
3409
3410uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
3411 MD5 Hash;
3412 Hash.update(Identifier);
3413 // ... take the least significant 8 bytes and return those. Our MD5
3414 // implementation always returns its results in little endian, so we actually
3415 // need the "high" word.
3416 MD5::MD5Result Result;
3417 Hash.final(Result);
3418 return Result.high();
3419}
3420
3421void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
3422 StringRef Identifier, DIE &RefDie,
3423 const DICompositeType *CTy) {
3424 // Fast path if we're building some type units and one has already used the
3425 // address pool we know we're going to throw away all this work anyway, so
3426 // don't bother building dependent types.
3427 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3428 return;
3429
3430 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3431 if (!Ins.second) {
3432 CU.addDIETypeSignature(RefDie, Ins.first->second);
3433 return;
3434 }
3435
3436 bool TopLevelType = TypeUnitsUnderConstruction.empty();
3437 AddrPool.resetUsedFlag();
3438
3439 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
3440 getDwoLineTable(CU));
3441 DwarfTypeUnit &NewTU = *OwnedUnit;
3442 DIE &UnitDie = NewTU.getUnitDie();
3443 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3444
3445 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3446 CU.getLanguage());
3447
3448 uint64_t Signature = makeTypeSignature(Identifier);
3449 NewTU.setTypeSignature(Signature);
3450 Ins.first->second = Signature;
3451
3452 if (useSplitDwarf()) {
3453 MCSection *Section =
3454 getDwarfVersion() <= 4
3455 ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
3456 : Asm->getObjFileLowering().getDwarfInfoDWOSection();
3457 NewTU.setSection(Section);
3458 } else {
3459 MCSection *Section =
3460 getDwarfVersion() <= 4
3461 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
3462 : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
3463 NewTU.setSection(Section);
3464 // Non-split type units reuse the compile unit's line table.
3465 CU.applyStmtList(UnitDie);
3466 }
3467
3468 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3469 // units.
3470 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3471 NewTU.addStringOffsetsStart();
3472
3473 NewTU.setType(NewTU.createTypeDIE(CTy));
3474
3475 if (TopLevelType) {
3476 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3477 TypeUnitsUnderConstruction.clear();
3478
3479 // Types referencing entries in the address table cannot be placed in type
3480 // units.
3481 if (AddrPool.hasBeenUsed()) {
3482
3483 // Remove all the types built while building this type.
3484 // This is pessimistic as some of these types might not be dependent on
3485 // the type that used an address.
3486 for (const auto &TU : TypeUnitsToAdd)
3487 TypeSignatures.erase(TU.second);
3488
3489 // Construct this type in the CU directly.
3490 // This is inefficient because all the dependent types will be rebuilt
3491 // from scratch, including building them in type units, discovering that
3492 // they depend on addresses, throwing them out and rebuilding them.
3493 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3494 return;
3495 }
3496
3497 // If the type wasn't dependent on fission addresses, finish adding the type
3498 // and all its dependent types.
3499 for (auto &TU : TypeUnitsToAdd) {
3500 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3501 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3502 }
3503 }
3504 CU.addDIETypeSignature(RefDie, Signature);
3505}
3506
3507// Add the Name along with its companion DIE to the appropriate accelerator
3508// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3509// AccelTableKind::Apple, we use the table we got as an argument). If
3510// accelerator tables are disabled, this function does nothing.
3511template <typename DataT>
3512void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3513 AccelTable<DataT> &AppleAccel, StringRef Name,
3514 const DIE &Die) {
3515 if (getAccelTableKind() == AccelTableKind::None)
3516 return;
3517
3518 if (getAccelTableKind() != AccelTableKind::Apple &&
3519 CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3520 return;
3521
3522 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3523 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3524
3525 switch (getAccelTableKind()) {
3526 case AccelTableKind::Apple:
3527 AppleAccel.addName(Ref, Die);
3528 break;
3529 case AccelTableKind::Dwarf:
3530 AccelDebugNames.addName(Ref, Die);
3531 break;
3532 case AccelTableKind::Default:
3533 llvm_unreachable("Default should have already been resolved.")::llvm::llvm_unreachable_internal("Default should have already been resolved."
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3533)
;
3534 case AccelTableKind::None:
3535 llvm_unreachable("None handled above")::llvm::llvm_unreachable_internal("None handled above", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp"
, 3535)
;
3536 }
3537}
3538
3539void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3540 const DIE &Die) {
3541 addAccelNameImpl(CU, AccelNames, Name, Die);
3542}
3543
3544void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3545 const DIE &Die) {
3546 // ObjC names go only into the Apple accelerator tables.
3547 if (getAccelTableKind() == AccelTableKind::Apple)
3548 addAccelNameImpl(CU, AccelObjC, Name, Die);
3549}
3550
3551void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3552 const DIE &Die) {
3553 addAccelNameImpl(CU, AccelNamespace, Name, Die);
3554}
3555
3556void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3557 const DIE &Die, char Flags) {
3558 addAccelNameImpl(CU, AccelTypes, Name, Die);
3559}
3560
3561uint16_t DwarfDebug::getDwarfVersion() const {
3562 return Asm->OutStreamer->getContext().getDwarfVersion();
3563}
3564
3565dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
3566 if (Asm->getDwarfVersion() >= 4)
3567 return dwarf::Form::DW_FORM_sec_offset;
3568 assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&(static_cast <bool> ((!Asm->isDwarf64() || (Asm->
getDwarfVersion() == 3)) && "DWARF64 is not defined prior DWARFv3"
) ? void (0) : __assert_fail ("(!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) && \"DWARF64 is not defined prior DWARFv3\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3569, __extension__
__PRETTY_FUNCTION__))
3569 "DWARF64 is not defined prior DWARFv3")(static_cast <bool> ((!Asm->isDwarf64() || (Asm->
getDwarfVersion() == 3)) && "DWARF64 is not defined prior DWARFv3"
) ? void (0) : __assert_fail ("(!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) && \"DWARF64 is not defined prior DWARFv3\""
, "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3569, __extension__
__PRETTY_FUNCTION__))
;
3570 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3571 : dwarf::Form::DW_FORM_data4;
3572}
3573
3574const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3575 auto I = SectionLabels.find(S);
3576 if (I == SectionLabels.end())
3577 return nullptr;
3578 return I->second;
3579}
3580void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
3581 if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
3582 if (useSplitDwarf() || getDwarfVersion() >= 5)
3583 AddrPool.getIndex(S);
3584}
3585
3586std::optional<MD5::MD5Result>
3587DwarfDebug::getMD5AsBytes(const DIFile *File) const {
3588 assert(File)(static_cast <bool> (File) ? void (0) : __assert_fail (
"File", "llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp", 3588, __extension__
__PRETTY_FUNCTION__))
;
3589 if (getDwarfVersion() < 5)
3590 return std::nullopt;
3591 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3592 if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3593 return std::nullopt;
3594
3595 // Convert the string checksum to an MD5Result for the streamer.
3596 // The verifier validates the checksum so we assume it's okay.
3597 // An MD5 checksum is 16 bytes.
3598 std::string ChecksumString = fromHex(Checksum->Value);
3599 MD5::MD5Result CKMem;
3600 std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3601 return CKMem;
3602}
3603
3604bool DwarfDebug::alwaysUseRanges(const DwarfCompileUnit &CU) const {
3605 if (MinimizeAddr == MinimizeAddrInV5::Ranges)
3606 return true;
3607 if (MinimizeAddr != MinimizeAddrInV5::Default)
3608 return false;
3609 if (useSplitDwarf())
3610 return true;
3611 return false;
3612}