Bug Summary

File:lib/CodeGen/AsmPrinter/DwarfDebug.cpp
Warning:line 1274, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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