blob: 86baf73a096b5b1f69fc08ba6cd6908a17f1e06c [file] [log] [blame]
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00001//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
Bill Wendling2f921f82009-05-15 09:23:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf debug info into asm files.
11//
12//===----------------------------------------------------------------------===//
Chris Lattnerb14490d2010-03-09 00:39:24 +000013
Bill Wendling2f921f82009-05-15 09:23:25 +000014#include "DwarfDebug.h"
David Blaikie37c52312014-10-04 15:49:50 +000015#include "ByteStreamer.h"
Eric Christopher45731982013-08-08 23:45:55 +000016#include "DIEHash.h"
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +000017#include "DebugLocEntry.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000018#include "DebugLocStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000019#include "DwarfCompileUnit.h"
20#include "DwarfExpression.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000021#include "DwarfFile.h"
David Blaikie2c86a722013-12-02 19:33:15 +000022#include "DwarfUnit.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/MapVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000028#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/Triple.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000031#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/BinaryFormat/Dwarf.h"
Jonas Devlieghere855fc3b2018-01-29 14:52:41 +000033#include "llvm/CodeGen/AccelTable.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000034#include "llvm/CodeGen/AsmPrinter.h"
Frederic Risse541e0b2015-01-05 21:29:41 +000035#include "llvm/CodeGen/DIE.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000036#include "llvm/CodeGen/LexicalScopes.h"
37#include "llvm/CodeGen/MachineBasicBlock.h"
David Greene829b3e82009-08-19 21:52:55 +000038#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000039#include "llvm/CodeGen/MachineInstr.h"
Bill Wendling2f921f82009-05-15 09:23:25 +000040#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000041#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000042#include "llvm/CodeGen/TargetRegisterInfo.h"
43#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Constants.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000045#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Module.h"
Chris Lattnere13c3722010-03-09 01:58:53 +000050#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000051#include "llvm/MC/MCContext.h"
Frederic Rissa5ab8442015-08-07 15:14:08 +000052#include "llvm/MC/MCDwarf.h"
Chris Lattner4d2c0f92009-07-31 18:48:30 +000053#include "llvm/MC/MCSection.h"
Chris Lattner4b7dadb2009-08-19 05:49:37 +000054#include "llvm/MC/MCStreamer.h"
Chris Lattnere13c3722010-03-09 01:58:53 +000055#include "llvm/MC/MCSymbol.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000056#include "llvm/MC/MCTargetOptions.h"
57#include "llvm/MC/MachineLocation.h"
58#include "llvm/MC/SectionKind.h"
59#include "llvm/Pass.h"
60#include "llvm/Support/Casting.h"
Devang Patel6c74a872010-04-27 19:46:33 +000061#include "llvm/Support/CommandLine.h"
Daniel Dunbarcdf01b52009-10-13 06:47:08 +000062#include "llvm/Support/Debug.h"
63#include "llvm/Support/ErrorHandling.h"
Eric Christopher67646432013-07-26 17:02:41 +000064#include "llvm/Support/MD5.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000065#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/Support/Timer.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000067#include "llvm/Support/raw_ostream.h"
David Blaikie6054e652018-03-23 23:58:19 +000068#include "llvm/Target/TargetLoweringObjectFile.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000069#include "llvm/Target/TargetMachine.h"
70#include "llvm/Target/TargetOptions.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000071#include <algorithm>
72#include <cassert>
73#include <cstddef>
74#include <cstdint>
75#include <iterator>
76#include <string>
77#include <utility>
78#include <vector>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000079
Bill Wendling2f921f82009-05-15 09:23:25 +000080using namespace llvm;
81
Chandler Carruth1b9dde02014-04-22 02:02:50 +000082#define DEBUG_TYPE "dwarfdebug"
83
Eric Christopher7f2b5512013-07-23 22:16:41 +000084static cl::opt<bool>
85DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
86 cl::desc("Disable debug info printing"));
Devang Patel6c74a872010-04-27 19:46:33 +000087
David Blaikie038e28a2017-07-31 21:48:42 +000088static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
89 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
David Blaikiec2be8632017-08-01 14:50:50 +000090 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
David Blaikie038e28a2017-07-31 21:48:42 +000091
Eric Christopher02dbadb2014-02-14 01:26:55 +000092static cl::opt<bool> GenerateARangeSection("generate-arange-section",
93 cl::Hidden,
94 cl::desc("Generate dwarf aranges"),
95 cl::init(false));
96
Pavel Labathf9adc202018-07-20 12:59:05 +000097static cl::opt<bool>
98 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
99 cl::desc("Generate DWARF4 type units."),
100 cl::init(false));
101
David Blaikie488393f2017-05-12 01:13:45 +0000102static cl::opt<bool> SplitDwarfCrossCuReferences(
103 "split-dwarf-cross-cu-references", cl::Hidden,
104 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
105
Eric Christopherf07ee3a2014-01-27 23:50:03 +0000106enum DefaultOnOff { Default, Enable, Disable };
Eric Christopher4996c702011-11-07 09:24:32 +0000107
Paul Robinsonac7fe5e2016-12-12 20:49:11 +0000108static cl::opt<DefaultOnOff> UnknownLocations(
109 "use-unknown-locations", cl::Hidden,
110 cl::desc("Make an absence of debug location information explicit."),
111 cl::values(clEnumVal(Default, "At top of block or after label"),
112 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
113 cl::init(Default));
114
Pavel Labath6088c232018-04-04 14:42:14 +0000115static cl::opt<AccelTableKind> AccelTables(
116 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
117 cl::values(clEnumValN(AccelTableKind::Default, "Default",
118 "Default for platform"),
119 clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
120 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
121 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
122 cl::init(AccelTableKind::Default));
Eric Christopher20b76a72012-08-23 22:36:40 +0000123
Alexey Bataev0d6aead2018-02-20 15:28:08 +0000124static cl::opt<DefaultOnOff>
125DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
126 cl::desc("Use inlined strings rather than string section."),
127 cl::values(clEnumVal(Default, "Default for platform"),
128 clEnumVal(Enable, "Enabled"),
129 clEnumVal(Disable, "Disabled")),
130 cl::init(Default));
131
Alexey Bataev648ed2d2018-03-20 16:04:40 +0000132static cl::opt<bool>
133 NoDwarfPubSections("no-dwarf-pub-sections", cl::Hidden,
134 cl::desc("Disable emission of DWARF pub sections."),
135 cl::init(false));
136
Alexey Bataev858a7dd2018-03-20 20:21:38 +0000137static cl::opt<bool>
138 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
139 cl::desc("Disable emission .debug_ranges section."),
140 cl::init(false));
141
Alexey Bataevbff36082018-03-23 13:35:54 +0000142static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
143 "dwarf-sections-as-references", cl::Hidden,
144 cl::desc("Use sections+offset as references rather than labels."),
145 cl::values(clEnumVal(Default, "Default for platform"),
146 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
147 cl::init(Default));
148
Paul Robinson43d1e452016-04-18 22:41:41 +0000149enum LinkageNameOption {
150 DefaultLinkageNames,
151 AllLinkageNames,
152 AbstractLinkageNames
153};
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000154
Paul Robinson43d1e452016-04-18 22:41:41 +0000155static cl::opt<LinkageNameOption>
156 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
157 cl::desc("Which DWARF linkage-name attributes to emit."),
158 cl::values(clEnumValN(DefaultLinkageNames, "Default",
159 "Default for platform"),
160 clEnumValN(AllLinkageNames, "All", "All"),
161 clEnumValN(AbstractLinkageNames, "Abstract",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000162 "Abstract subprograms")),
Paul Robinson43d1e452016-04-18 22:41:41 +0000163 cl::init(DefaultLinkageNames));
Paul Robinson78046b42015-08-11 21:36:45 +0000164
Matthias Braun9f15a792016-11-18 19:43:18 +0000165static const char *const DWARFGroupName = "dwarf";
166static const char *const DWARFGroupDescription = "DWARF Emission";
167static const char *const DbgTimerName = "writer";
168static const char *const DbgTimerDescription = "DWARF Debug Writer";
Bill Wendlingfcc14142010-04-07 09:28:04 +0000169
Adrian Prantla63b8e82017-03-16 17:42:45 +0000170void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000171 BS.EmitInt8(
172 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
173 : dwarf::OperationEncodingString(Op));
174}
175
Adrian Prantla63b8e82017-03-16 17:42:45 +0000176void DebugLocDwarfExpression::emitSigned(int64_t Value) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000177 BS.EmitSLEB128(Value, Twine(Value));
178}
179
Adrian Prantla63b8e82017-03-16 17:42:45 +0000180void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000181 BS.EmitULEB128(Value, Twine(Value));
182}
183
Peter Collingbourne96c9ae62016-05-20 19:35:17 +0000184bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
185 unsigned MachineReg) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000186 // This information is not available while emitting .debug_loc entries.
187 return false;
188}
189
Adrian Prantl1a1647c2014-03-18 02:34:58 +0000190bool DbgVariable::isBlockByrefVariable() const {
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000191 assert(getVariable() && "Invalid complex DbgVariable!");
192 return getVariable()->getType().resolve()->isBlockByrefStruct();
Adrian Prantl1a1647c2014-03-18 02:34:58 +0000193}
194
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000195const DIType *DbgVariable::getType() const {
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000196 DIType *Ty = getVariable()->getType().resolve();
Devang Patelf20c4f72011-04-12 22:53:02 +0000197 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
198 // addresses instead.
Duncan P. N. Exon Smith571baeb2015-04-14 01:59:58 +0000199 if (Ty->isBlockByrefStruct()) {
Devang Patelf20c4f72011-04-12 22:53:02 +0000200 /* Byref variables, in Blocks, are declared by the programmer as
201 "SomeType VarName;", but the compiler creates a
202 __Block_byref_x_VarName struct, and gives the variable VarName
203 either the struct, or a pointer to the struct, as its type. This
204 is necessary for various behind-the-scenes things the compiler
205 needs to do with by-reference variables in blocks.
Eric Christopher6a841382012-11-19 22:42:10 +0000206
Devang Patelf20c4f72011-04-12 22:53:02 +0000207 However, as far as the original *programmer* is concerned, the
208 variable should still have type 'SomeType', as originally declared.
Eric Christopher6a841382012-11-19 22:42:10 +0000209
Devang Patelf20c4f72011-04-12 22:53:02 +0000210 The following function dives into the __Block_byref_x_VarName
211 struct to find the original type of the variable. This will be
212 passed back to the code generating the type for the Debug
213 Information Entry for the variable 'VarName'. 'VarName' will then
214 have the original type 'SomeType' in its debug information.
Eric Christopher6a841382012-11-19 22:42:10 +0000215
Devang Patelf20c4f72011-04-12 22:53:02 +0000216 The original type 'SomeType' will be the type of the field named
217 'VarName' inside the __Block_byref_x_VarName struct.
Eric Christopher6a841382012-11-19 22:42:10 +0000218
Devang Patelf20c4f72011-04-12 22:53:02 +0000219 NOTE: In order for this to not completely fail on the debugger
220 side, the Debug Information Entry for the variable VarName needs to
221 have a DW_AT_location that tells the debugger how to unwind through
222 the pointers and __Block_byref_x_VarName struct to find the actual
223 value of the variable. The function addBlockByrefType does this. */
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000224 DIType *subType = Ty;
Duncan P. N. Exon Smithb1055642015-04-16 01:01:28 +0000225 uint16_t tag = Ty->getTag();
Eric Christopher6a841382012-11-19 22:42:10 +0000226
Eric Christopher9adc55f2013-09-04 19:53:21 +0000227 if (tag == dwarf::DW_TAG_pointer_type)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000228 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
Eric Christopher6a841382012-11-19 22:42:10 +0000229
Duncan P. N. Exon Smith6ac940d2015-07-24 18:17:17 +0000230 auto Elements = cast<DICompositeType>(subType)->getElements();
Duncan P. N. Exon Smith000fa2c2015-04-07 04:14:33 +0000231 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
Duncan P. N. Exon Smith099ea1c2015-07-24 18:58:32 +0000232 auto *DT = cast<DIDerivedType>(Elements[i]);
Duncan P. N. Exon Smithb1055642015-04-16 01:01:28 +0000233 if (getName() == DT->getName())
Duncan P. N. Exon Smith848af382015-04-20 18:20:03 +0000234 return resolve(DT->getBaseType());
Devang Patel6d9f9fe2010-08-09 21:01:39 +0000235 }
Devang Patel6d9f9fe2010-08-09 21:01:39 +0000236 }
Devang Patelf20c4f72011-04-12 22:53:02 +0000237 return Ty;
238}
Bill Wendling2f921f82009-05-15 09:23:25 +0000239
Adrian Prantl67c24422017-02-17 19:42:32 +0000240ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
Adrian Prantl55030772017-03-22 16:50:16 +0000241 if (FrameIndexExprs.size() == 1)
242 return FrameIndexExprs;
243
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000244 assert(llvm::all_of(FrameIndexExprs,
245 [](const FrameIndexExpr &A) {
246 return A.Expr->isFragment();
247 }) &&
Adrian Prantl55030772017-03-22 16:50:16 +0000248 "multiple FI expressions without DW_OP_LLVM_fragment");
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +0000249 llvm::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
250 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
251 return A.Expr->getFragmentInfo()->OffsetInBits <
252 B.Expr->getFragmentInfo()->OffsetInBits;
253 });
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000254
Adrian Prantl67c24422017-02-17 19:42:32 +0000255 return FrameIndexExprs;
256}
257
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000258void DbgVariable::addMMIEntry(const DbgVariable &V) {
259 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
260 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000261 assert(V.getVariable() == getVariable() && "conflicting variable");
262 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000263
264 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
265 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
266
Daniel Jasper4d931202017-10-12 13:25:05 +0000267 // FIXME: This logic should not be necessary anymore, as we now have proper
268 // deduplication. However, without it, we currently run into the assertion
269 // below, which means that we are likely dealing with broken input, i.e. two
270 // non-fragment entries for the same variable at different frame indices.
271 if (FrameIndexExprs.size()) {
272 auto *Expr = FrameIndexExprs.back().Expr;
273 if (!Expr || !Expr->isFragment())
274 return;
275 }
276
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000277 for (const auto &FIE : V.FrameIndexExprs)
278 // Ignore duplicate entries.
279 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
280 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
281 }))
282 FrameIndexExprs.push_back(FIE);
283
284 assert((FrameIndexExprs.size() == 1 ||
285 llvm::all_of(FrameIndexExprs,
286 [](FrameIndexExpr &FIE) {
287 return FIE.Expr && FIE.Expr->isFragment();
288 })) &&
289 "conflicting locations for variable");
290}
291
Pavel Labathf9adc202018-07-20 12:59:05 +0000292static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
293 bool GenerateTypeUnits,
294 DebuggerKind Tuning,
295 const Triple &TT) {
296 // Honor an explicit request.
297 if (AccelTables != AccelTableKind::Default)
298 return AccelTables;
299
300 // Accelerator tables with type units are currently not supported.
301 if (GenerateTypeUnits)
302 return AccelTableKind::None;
303
304 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
305 // always implies debug_names. For lower standard versions we use apple
306 // accelerator tables on apple platforms and debug_names elsewhere.
307 if (DwarfVersion >= 5)
308 return AccelTableKind::Dwarf;
309 if (Tuning == DebuggerKind::LLDB)
310 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
311 : AccelTableKind::Dwarf;
312 return AccelTableKind::None;
313}
314
Chris Lattnerf0d6bd32010-04-05 05:11:15 +0000315DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000316 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
317 InfoHolder(A, "info_string", DIEValueAllocator),
Frederic Riss9412d632015-03-04 02:30:17 +0000318 SkeletonHolder(A, "skel_string", DIEValueAllocator),
Pavel Labatha7c457d2018-02-19 16:12:20 +0000319 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
Eric Christopher364dbe02016-10-01 01:50:29 +0000320 const Triple &TT = Asm->TM.getTargetTriple();
Eric Christopherad9fe892012-04-02 17:58:52 +0000321
Paul Robinson6c27a2c2015-12-16 19:58:30 +0000322 // Make sure we know our "debugger tuning." The target option takes
Paul Robinsonb9de1062015-07-15 22:04:54 +0000323 // precedence; fall back to triple-based defaults.
Paul Robinson6c27a2c2015-12-16 19:58:30 +0000324 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
325 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
Dimitry Andric2c364212016-01-07 22:09:12 +0000326 else if (IsDarwin)
Paul Robinsonb9de1062015-07-15 22:04:54 +0000327 DebuggerTuning = DebuggerKind::LLDB;
328 else if (TT.isPS4CPU())
329 DebuggerTuning = DebuggerKind::SCE;
330 else
331 DebuggerTuning = DebuggerKind::GDB;
332
Eric Christopher68f22182018-05-18 03:13:08 +0000333 if (DwarfInlinedStrings == Default)
334 UseInlineStrings = TT.isNVPTX();
335 else
336 UseInlineStrings = DwarfInlinedStrings == Enable;
337
Alexey Bataev2a03d422018-06-29 14:23:28 +0000338 UseLocSection = !TT.isNVPTX();
339
David Blaikiec53e18d2016-05-24 21:19:28 +0000340 HasAppleExtensionAttributes = tuneForLLDB();
341
David Blaikie96b1ed52017-04-21 23:35:26 +0000342 // Handle split DWARF.
343 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
Eric Christopher29424312012-11-12 22:22:20 +0000344
Paul Robinson43d1e452016-04-18 22:41:41 +0000345 // SCE defaults to linkage names only for abstract subprograms.
346 if (DwarfLinkageNames == DefaultLinkageNames)
347 UseAllLinkageNames = !tuneForSCE();
Paul Robinson78046b42015-08-11 21:36:45 +0000348 else
Paul Robinson43d1e452016-04-18 22:41:41 +0000349 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
Paul Robinson78046b42015-08-11 21:36:45 +0000350
Eric Christopher4c5bff32014-06-19 06:22:08 +0000351 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
Greg Claytone6543972016-11-23 23:30:37 +0000352 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
Eric Christopher793c7472014-04-28 20:42:22 +0000353 : MMI->getModule()->getDwarfVersion();
Eric Christopher68f22182018-05-18 03:13:08 +0000354 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
355 DwarfVersion =
356 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
Manman Renac8062b2013-07-02 23:40:10 +0000357
Eric Christopher68f22182018-05-18 03:13:08 +0000358 UsePubSections = !NoDwarfPubSections && !TT.isNVPTX();
359 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
Alexey Bataev648ed2d2018-03-20 16:04:40 +0000360
Eric Christopher68f22182018-05-18 03:13:08 +0000361 // Use sections as references. Force for NVPTX.
362 if (DwarfSectionsAsReferences == Default)
363 UseSectionsAsReferences = TT.isNVPTX();
364 else
365 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
Alexey Bataevbff36082018-03-23 13:35:54 +0000366
Jonas Devlieghere8acb74e2018-08-01 12:53:06 +0000367 // Don't generate type units for unsupported object file formats.
368 GenerateTypeUnits =
369 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
Pavel Labathf9adc202018-07-20 12:59:05 +0000370
371 TheAccelTableKind = computeAccelTableKind(
372 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
373
Paul Robinsonb9de1062015-07-15 22:04:54 +0000374 // Work around a GDB bug. GDB doesn't support the standard opcode;
375 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
376 // is defined as of DWARF 3.
377 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
378 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
379 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
Paul Robinson78cc0822015-03-04 20:55:11 +0000380
Adrian Prantl6323ddf2016-05-17 21:07:16 +0000381 // GDB does not fully support the DWARF 4 representation for bitfields.
382 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
383
Wolfgang Pieb456b5552018-01-26 18:52:58 +0000384 // The DWARF v5 string offsets table has - possibly shared - contributions
385 // from each compile and type unit each preceded by a header. The string
386 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
387 // a monolithic string offsets table without any header.
388 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
389
Lang Hames9ff69c82015-04-24 19:11:51 +0000390 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
Bill Wendling2f921f82009-05-15 09:23:25 +0000391}
Bill Wendling2f921f82009-05-15 09:23:25 +0000392
Reid Klecknerdd2647e2014-04-30 20:34:31 +0000393// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000394DwarfDebug::~DwarfDebug() = default;
Reid Klecknerdd2647e2014-04-30 20:34:31 +0000395
Eric Christopherd9843b32011-11-10 19:25:34 +0000396static bool isObjCClass(StringRef Name) {
397 return Name.startswith("+") || Name.startswith("-");
398}
399
400static bool hasObjCCategory(StringRef Name) {
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000401 if (!isObjCClass(Name))
402 return false;
Eric Christopherd9843b32011-11-10 19:25:34 +0000403
Benjamin Kramer260de742013-08-24 12:15:54 +0000404 return Name.find(") ") != StringRef::npos;
Eric Christopherd9843b32011-11-10 19:25:34 +0000405}
406
407static void getObjCClassCategory(StringRef In, StringRef &Class,
408 StringRef &Category) {
409 if (!hasObjCCategory(In)) {
410 Class = In.slice(In.find('[') + 1, In.find(' '));
411 Category = "";
412 return;
413 }
414
415 Class = In.slice(In.find('[') + 1, In.find('('));
416 Category = In.slice(In.find('[') + 1, In.find(' '));
Eric Christopherd9843b32011-11-10 19:25:34 +0000417}
418
419static StringRef getObjCMethodName(StringRef In) {
420 return In.slice(In.find(' ') + 1, In.find(']'));
421}
422
423// Add the various names to the Dwarf accelerator table names.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000424void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000425 if (!SP->isDefinition())
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000426 return;
Pavel Labath889bf9f2018-04-09 08:41:57 +0000427
428 if (SP->getName() != "")
429 addAccelName(SP->getName(), Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000430
Pavel Labath2a6afe52018-05-14 14:13:20 +0000431 // If the linkage name is different than the name, go ahead and output that as
432 // well into the name table. Only do that if we are going to actually emit
433 // that name.
434 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
435 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000436 addAccelName(SP->getLinkageName(), Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000437
438 // If this is an Objective-C selector name add it to the ObjC accelerator
439 // too.
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000440 if (isObjCClass(SP->getName())) {
Eric Christopherd9843b32011-11-10 19:25:34 +0000441 StringRef Class, Category;
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000442 getObjCClassCategory(SP->getName(), Class, Category);
David Blaikie0ee82b92014-04-24 00:53:32 +0000443 addAccelObjC(Class, Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000444 if (Category != "")
David Blaikie0ee82b92014-04-24 00:53:32 +0000445 addAccelObjC(Category, Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000446 // Also add the base method name to the name table.
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000447 addAccelName(getObjCMethodName(SP->getName()), Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000448 }
449}
450
Manman Ren5b2f4b02013-09-11 19:40:28 +0000451/// Check whether we should create a DIE for the given Scope, return true
452/// if we don't create a DIE (the corresponding DIE is null).
Manman Ren2312ed32013-09-10 18:40:41 +0000453bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
454 if (Scope->isAbstractScope())
455 return false;
456
Manman Ren5b2f4b02013-09-11 19:40:28 +0000457 // We don't create a DIE if there is no Range.
Manman Ren2312ed32013-09-10 18:40:41 +0000458 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
459 if (Ranges.empty())
460 return true;
461
462 if (Ranges.size() > 1)
463 return false;
464
Manman Ren5b2f4b02013-09-11 19:40:28 +0000465 // We don't create a DIE if we have a single Range and the end label
466 // is null.
David Blaikiecd4b8a22014-08-31 02:14:26 +0000467 return !getLabelAfterInsn(Ranges.front().second);
Manman Ren2312ed32013-09-10 18:40:41 +0000468}
469
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000470template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
David Blaikie3a443c22014-11-04 22:12:25 +0000471 F(CU);
472 if (auto *SkelCU = CU.getSkeleton())
David Blaikiea01f2952016-08-24 18:29:49 +0000473 if (CU.getCUNode()->getSplitDebugInlining())
474 F(*SkelCU);
David Blaikie3a443c22014-11-04 22:12:25 +0000475}
476
David Blaikie488393f2017-05-12 01:13:45 +0000477bool DwarfDebug::shareAcrossDWOCUs() const {
478 return SplitDwarfCrossCuReferences;
479}
480
481void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
482 LexicalScope *Scope) {
David Blaikiee872a6e2014-04-29 15:58:35 +0000483 assert(Scope && Scope->getScopeNode());
484 assert(Scope->isAbstractScope());
485 assert(!Scope->getInlinedAt());
486
David Blaikieb4614682016-12-14 19:38:39 +0000487 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
David Blaikiee872a6e2014-04-29 15:58:35 +0000488
David Blaikie1ea9db22014-05-21 23:14:12 +0000489 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
490 // was inlined from another compile unit.
Mehdi Amini41812052017-05-29 06:25:30 +0000491 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
492 // Avoid building the original CU if it won't be used
493 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
494 else {
495 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
496 if (auto *SkelCU = CU.getSkeleton()) {
497 (shareAcrossDWOCUs() ? CU : SrcCU)
498 .constructAbstractSubprogramScopeDIE(Scope);
499 if (CU.getCUNode()->getSplitDebugInlining())
500 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
501 } else
502 CU.constructAbstractSubprogramScopeDIE(Scope);
David Blaikie488393f2017-05-12 01:13:45 +0000503 }
David Blaikiee872a6e2014-04-29 15:58:35 +0000504}
505
David Blaikieb3cee2f2017-05-25 18:50:28 +0000506void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
Peter Collingbourneb52e2362017-09-12 21:50:41 +0000507 if (!U.hasDwarfPubSections())
David Blaikie3c842622013-12-04 21:31:26 +0000508 return;
509
David Blaikief9b6a552014-04-22 22:39:41 +0000510 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
David Blaikie3c842622013-12-04 21:31:26 +0000511}
512
Eric Christopher4287a492013-12-09 23:57:44 +0000513// Create new DwarfCompileUnit for the given metadata node with tag
Eric Christopher48fef592012-12-20 21:58:40 +0000514// DW_TAG_compile_unit.
Duncan P. N. Exon Smith2fbe1352015-04-20 22:10:08 +0000515DwarfCompileUnit &
David Blaikie07963bd2017-05-26 18:52:56 +0000516DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
517 if (auto *CU = CUMap.lookup(DIUnit))
518 return *CU;
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000519 StringRef FN = DIUnit->getFilename();
520 CompilationDir = DIUnit->getDirectory();
Bill Wendling2b128d72009-05-20 23:19:06 +0000521
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000522 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
David Blaikiebd579052014-04-28 21:14:27 +0000523 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
David Blaikief9b6a552014-04-22 22:39:41 +0000524 DwarfCompileUnit &NewCU = *OwnedUnit;
David Blaikie92a2f8a2014-04-28 21:04:29 +0000525 DIE &Die = NewCU.getUnitDie();
David Blaikief9b6a552014-04-22 22:39:41 +0000526 InfoHolder.addUnit(std::move(OwnedUnit));
David Blaikie0b214e42016-03-24 18:37:08 +0000527 if (useSplitDwarf()) {
David Blaikiecafd9622014-11-02 08:51:37 +0000528 NewCU.setSkeleton(constructSkeletonCU(NewCU));
David Blaikie0b214e42016-03-24 18:37:08 +0000529 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
David Blaikie96b1ed52017-04-21 23:35:26 +0000530 Asm->TM.Options.MCOptions.SplitDwarfFile);
David Blaikie0b214e42016-03-24 18:37:08 +0000531 }
David Blaikief9b6a552014-04-22 22:39:41 +0000532
David Blaikie89daf772017-07-28 03:06:25 +0000533 for (auto *IE : DIUnit->getImportedEntities())
534 NewCU.addImportedEntity(IE);
535
David Blaikie7ac51492014-03-20 17:05:45 +0000536 // LTO with assembly output shares a single line table amongst multiple CUs.
537 // To avoid the compilation directory being ambiguous, let the line table
538 // explicitly describe the directory of all files, never relying on the
539 // compilation directory.
Lang Hames9ff69c82015-04-24 19:11:51 +0000540 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
Paul Robinsonb271f312018-03-29 17:16:41 +0000541 Asm->OutStreamer->emitDwarfFile0Directive(
542 CompilationDir, FN, NewCU.getMD5AsBytes(DIUnit->getFile()),
543 DIUnit->getSource(), NewCU.getUniqueID());
David Blaikie2666e242013-12-06 19:38:46 +0000544
Eric Christopher9ea300f2017-03-29 23:34:27 +0000545 StringRef Producer = DIUnit->getProducer();
546 StringRef Flags = DIUnit->getFlags();
Jonas Devliegherecaacedb2018-08-08 16:33:22 +0000547 if (!Flags.empty() && !useAppleExtensionAttributes()) {
Eric Christopher9ea300f2017-03-29 23:34:27 +0000548 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
549 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
550 } else
551 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
552
David Blaikie92a2f8a2014-04-28 21:04:29 +0000553 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000554 DIUnit->getSourceLanguage());
David Blaikie92a2f8a2014-04-28 21:04:29 +0000555 NewCU.addString(Die, dwarf::DW_AT_name, FN);
Eric Christopher52ce7182013-04-09 19:23:15 +0000556
Wolfgang Pieb456b5552018-01-26 18:52:58 +0000557 // Add DW_str_offsets_base to the unit DIE, except for split units.
558 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
559 NewCU.addStringOffsetsStart();
560
Eric Christopher52ce7182013-04-09 19:23:15 +0000561 if (!useSplitDwarf()) {
Rafael Espindola063d7252015-03-10 16:58:10 +0000562 NewCU.initStmtList();
Eric Christophera51d3fc2013-09-27 22:50:48 +0000563
564 // If we're using split dwarf the compilation dir is going to be in the
565 // skeleton CU and so we don't need to duplicate it here.
566 if (!CompilationDir.empty())
David Blaikie92a2f8a2014-04-28 21:04:29 +0000567 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
Eric Christophera51d3fc2013-09-27 22:50:48 +0000568
David Blaikie92a2f8a2014-04-28 21:04:29 +0000569 addGnuPubAttributes(NewCU, Die);
Eric Christopher52ce7182013-04-09 19:23:15 +0000570 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000571
David Blaikiec53e18d2016-05-24 21:19:28 +0000572 if (useAppleExtensionAttributes()) {
573 if (DIUnit->isOptimized())
574 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
Bill Wendling2b128d72009-05-20 23:19:06 +0000575
David Blaikiec53e18d2016-05-24 21:19:28 +0000576 StringRef Flags = DIUnit->getFlags();
577 if (!Flags.empty())
578 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
Eric Christopher6a841382012-11-19 22:42:10 +0000579
David Blaikiec53e18d2016-05-24 21:19:28 +0000580 if (unsigned RVer = DIUnit->getRuntimeVersion())
581 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
582 dwarf::DW_FORM_data1, RVer);
583 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000584
David Blaikiecafd9622014-11-02 08:51:37 +0000585 if (useSplitDwarf())
Greg Clayton35630c32016-12-01 18:56:29 +0000586 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
David Blaikiecafd9622014-11-02 08:51:37 +0000587 else
Greg Clayton35630c32016-12-01 18:56:29 +0000588 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
Eric Christopherd039baa2013-12-30 03:40:32 +0000589
Adrian Prantldeef90d2015-09-14 22:10:22 +0000590 if (DIUnit->getDWOId()) {
Adrian Prantl77fefeb2015-09-22 23:21:00 +0000591 // This CU is either a clang module DWO or a skeleton CU.
Adrian Prantldeef90d2015-09-14 22:10:22 +0000592 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
593 DIUnit->getDWOId());
Adrian Prantl77fefeb2015-09-22 23:21:00 +0000594 if (!DIUnit->getSplitDebugFilename().empty())
595 // This is a prefabricated skeleton CU.
596 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
597 DIUnit->getSplitDebugFilename());
Adrian Prantldeef90d2015-09-14 22:10:22 +0000598 }
599
David Majnemer0a16c222016-08-11 21:15:00 +0000600 CUMap.insert({DIUnit, &NewCU});
601 CUDieMap.insert({&Die, &NewCU});
Devang Pateleb1bb4e2011-08-16 22:09:43 +0000602 return NewCU;
Devang Patel1a0df9a2010-05-10 22:49:55 +0000603}
604
David Blaikie8912df12014-08-31 05:41:15 +0000605void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000606 const DIImportedEntity *N) {
David Blaikie2195e132017-07-27 00:06:53 +0000607 if (isa<DILocalScope>(N->getScope()))
608 return;
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +0000609 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
610 D->addChild(TheCU.constructImportedEntityDIE(N));
David Blaikief55abea2013-04-22 06:12:31 +0000611}
612
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000613/// Sort and unique GVEs by comparing their fragment offset.
614static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
615sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +0000616 llvm::sort(GVEs.begin(), GVEs.end(),
617 [](DwarfCompileUnit::GlobalExpr A,
618 DwarfCompileUnit::GlobalExpr B) {
619 // Sort order: first null exprs, then exprs without fragment
620 // info, then sort by fragment offset in bits.
621 // FIXME: Come up with a more comprehensive comparator so
622 // the sorting isn't non-deterministic, and so the following
623 // std::unique call works correctly.
624 if (!A.Expr || !B.Expr)
625 return !!B.Expr;
626 auto FragmentA = A.Expr->getFragmentInfo();
627 auto FragmentB = B.Expr->getFragmentInfo();
628 if (!FragmentA || !FragmentB)
629 return !!FragmentB;
630 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
631 });
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000632 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
633 [](DwarfCompileUnit::GlobalExpr A,
634 DwarfCompileUnit::GlobalExpr B) {
635 return A.Expr == B.Expr;
636 }),
637 GVEs.end());
638 return GVEs;
639}
640
Eric Christopheracdcbdb2012-11-27 22:43:45 +0000641// Emit all Dwarf sections that should come prior to the content. Create
642// global DIEs and emit initial debug info sections. This is invoked by
643// the target AsmPrinter.
Eric Christopher58f41952012-11-19 22:42:15 +0000644void DwarfDebug::beginModule() {
Matthias Braun9f15a792016-11-18 19:43:18 +0000645 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
646 DWARFGroupDescription, TimePassesIsEnabled);
Devang Patel6c74a872010-04-27 19:46:33 +0000647 if (DisableDebugInfoPrinting)
648 return;
649
Eric Christopher58f41952012-11-19 22:42:15 +0000650 const Module *M = MMI->getModule();
651
Peter Collingbourneb3269862016-06-01 02:58:40 +0000652 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
653 M->debug_compile_units_end());
Adrian Prantl5992a722016-04-08 22:43:03 +0000654 // Tell MMI whether we have debug info.
655 MMI->setDebugInfoAvailability(NumDebugCUs > 0);
656 SingleCU = NumDebugCUs == 1;
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000657 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
658 GVMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000659 for (const GlobalVariable &Global : M->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000660 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000661 Global.getDebugInfo(GVs);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000662 for (auto *GVE : GVs)
663 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000664 }
665
Wolfgang Pieb456b5552018-01-26 18:52:58 +0000666 // Create the symbol that designates the start of the unit's contribution
667 // to the string offsets table. In a split DWARF scenario, only the skeleton
668 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
669 if (useSegmentedStringOffsetsTable())
670 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
671 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
672
Wolfgang Piebfcf38102018-07-12 18:18:21 +0000673 // Create the symbol that designates the start of the DWARF v5 range list
674 // table. It is located past the header and before the offsets table.
675 if (getDwarfVersion() >= 5)
676 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
677 .setRnglistsTableBaseSym(Asm->createTempSymbol("rnglists_table_base"));
678
Adrian Prantl5992a722016-04-08 22:43:03 +0000679 for (DICompileUnit *CUNode : M->debug_compile_units()) {
David Blaikie89daf772017-07-28 03:06:25 +0000680 // FIXME: Move local imported entities into a list attached to the
681 // subprogram, then this search won't be needed and a
682 // getImportedEntities().empty() test should go below with the rest.
683 bool HasNonLocalImportedEntities = llvm::any_of(
684 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
685 return !isa<DILocalScope>(IE->getScope());
686 });
687
688 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
689 CUNode->getRetainedTypes().empty() &&
690 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
David Blaikie07963bd2017-05-26 18:52:56 +0000691 continue;
692
693 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000694
695 // Global Variables.
Adrian Prantl2116dd32017-08-19 01:15:06 +0000696 for (auto *GVE : CUNode->getGlobalVariables()) {
697 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
698 // already know about the variable and it isn't adding a constant
699 // expression.
700 auto &GVMapEntry = GVMap[GVE->getVariable()];
701 auto *Expr = GVE->getExpression();
702 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
703 GVMapEntry.push_back({nullptr, Expr});
704 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000705 DenseSet<DIGlobalVariable *> Processed;
706 for (auto *GVE : CUNode->getGlobalVariables()) {
707 DIGlobalVariable *GV = GVE->getVariable();
708 if (Processed.insert(GV).second)
709 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
710 }
711
Duncan P. N. Exon Smith9928a902015-04-20 18:52:06 +0000712 for (auto *Ty : CUNode->getEnumTypes()) {
Manman Renbd1628a2014-07-28 23:04:20 +0000713 // The enum types array by design contains pointers to
714 // MDNodes rather than DIRefs. Unique them here.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000715 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
Manman Renbd1628a2014-07-28 23:04:20 +0000716 }
Duncan P. N. Exon Smith9928a902015-04-20 18:52:06 +0000717 for (auto *Ty : CUNode->getRetainedTypes()) {
Adrian Prantl0aa1aa22014-03-18 02:35:03 +0000718 // The retained types array by design contains pointers to
719 // MDNodes rather than DIRefs. Unique them here.
Amjad Aboud72da9392016-04-30 01:44:07 +0000720 if (DIType *RT = dyn_cast<DIType>(Ty))
Adrian Prantl75819ae2016-04-15 15:57:41 +0000721 // There is no point in force-emitting a forward declaration.
722 CU.getOrCreateTypeDIE(RT);
Adrian Prantl0aa1aa22014-03-18 02:35:03 +0000723 }
David Blaikief55abea2013-04-22 06:12:31 +0000724 // Emit imported_modules last so that the relevant context is already
725 // available.
Duncan P. N. Exon Smith000fa2c2015-04-07 04:14:33 +0000726 for (auto *IE : CUNode->getImportedEntities())
Amjad Aboud72da9392016-04-30 01:44:07 +0000727 constructAndAddImportedEntityDIE(CU, IE);
David Blaikiedc69ebb2013-03-11 23:39:23 +0000728 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000729}
730
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000731void DwarfDebug::finishEntityDefinitions() {
732 for (const auto &Entity : ConcreteEntities) {
733 DIE *Die = Entity->getDIE();
734 assert(Die);
David Blaikieeb1a2722014-06-13 22:18:23 +0000735 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000736 // in the ConcreteEntities list, rather than looking it up again here.
David Blaikieeb1a2722014-06-13 22:18:23 +0000737 // DIE::getUnit isn't simple - it walks parent pointers, etc.
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000738 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
David Blaikieeb1a2722014-06-13 22:18:23 +0000739 assert(Unit);
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000740 Unit->finishEntityDefinition(Entity.get());
David Blaikieeb1a2722014-06-13 22:18:23 +0000741 }
742}
743
David Blaikief7221ad2014-05-27 18:37:43 +0000744void DwarfDebug::finishSubprogramDefinitions() {
David Blaikie07963bd2017-05-26 18:52:56 +0000745 for (const DISubprogram *SP : ProcessedSPNodes) {
746 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
747 forBothCUs(
748 getOrCreateDwarfCompileUnit(SP->getUnit()),
749 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
750 }
Eric Christopher960ac372012-11-22 00:59:49 +0000751}
752
753void DwarfDebug::finalizeModuleInfo() {
Rafael Espindola063d7252015-03-10 16:58:10 +0000754 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
755
David Blaikie3c2fff32014-05-27 18:37:48 +0000756 finishSubprogramDefinitions();
757
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000758 finishEntityDefinitions();
David Blaikieeb1a2722014-06-13 22:18:23 +0000759
Mehdi Amini96ab48f2017-05-29 06:32:34 +0000760 // Include the DWO file name in the hash if there's more than one CU.
761 // This handles ThinLTO's situation where imported CUs may very easily be
762 // duplicate with the same CU partially imported into another ThinLTO unit.
763 StringRef DWOName;
764 if (CUMap.size() > 1)
765 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
766
Eric Christopherad10cb52013-12-04 23:24:38 +0000767 // Handle anything that needs to be done on a per-unit basis after
768 // all other generation.
David Blaikie1998a2e2014-11-01 01:11:19 +0000769 for (const auto &P : CUMap) {
770 auto &TheCU = *P.second;
Alexey Bataevd4dd7212018-08-01 19:38:20 +0000771 if (TheCU.getCUNode()->isDebugDirectivesOnly())
772 continue;
Eric Christopher60eb7692013-08-12 20:27:48 +0000773 // Emit DW_AT_containing_type attribute to connect types with their
774 // vtable holding type.
David Blaikie1998a2e2014-11-01 01:11:19 +0000775 TheCU.constructContainingTypeDIEs();
Eric Christopher60eb7692013-08-12 20:27:48 +0000776
Eric Christopher46e23432013-12-20 04:16:18 +0000777 // Add CU specific attributes if we need to add any.
David Blaikie1998a2e2014-11-01 01:11:19 +0000778 // If we're splitting the dwarf out now that we've got the entire
779 // CU then add the dwo id to it.
780 auto *SkCU = TheCU.getSkeleton();
781 if (useSplitDwarf()) {
782 // Emit a unique identifier for this CU.
Mehdi Amini96ab48f2017-05-29 06:32:34 +0000783 uint64_t ID =
784 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
Paul Robinson543c0e12018-05-22 17:27:31 +0000785 if (getDwarfVersion() >= 5) {
786 TheCU.setDWOId(ID);
787 SkCU->setDWOId(ID);
788 } else {
789 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
790 dwarf::DW_FORM_data8, ID);
791 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
792 dwarf::DW_FORM_data8, ID);
793 }
David Blaikie1998a2e2014-11-01 01:11:19 +0000794 // We don't keep track of which addresses are used in which CU so this
795 // is a bit pessimistic under LTO.
Rafael Espindola063d7252015-03-10 16:58:10 +0000796 if (!AddrPool.isEmpty()) {
797 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
David Blaikie1998a2e2014-11-01 01:11:19 +0000798 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
Rafael Espindola063d7252015-03-10 16:58:10 +0000799 Sym, Sym);
800 }
Wolfgang Piebfcf38102018-07-12 18:18:21 +0000801 if (getDwarfVersion() < 5 && !SkCU->getRangeLists().empty()) {
Rafael Espindola063d7252015-03-10 16:58:10 +0000802 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
David Blaikie1998a2e2014-11-01 01:11:19 +0000803 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
Rafael Espindola063d7252015-03-10 16:58:10 +0000804 Sym, Sym);
805 }
David Blaikie1998a2e2014-11-01 01:11:19 +0000806 }
Eric Christopherd8667202013-12-30 17:22:27 +0000807
David Blaikie1998a2e2014-11-01 01:11:19 +0000808 // If we have code split among multiple sections or non-contiguous
809 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
810 // remain in the .o file, otherwise add a DW_AT_low_pc.
811 // FIXME: We should use ranges allow reordering of code ala
812 // .subsections_via_symbols in mach-o. This would mean turning on
813 // ranges for all subprogram DIEs for mach-o.
David Blaikiea8be0a72014-11-01 01:15:24 +0000814 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
David Blaikie5b02a192014-11-03 23:10:59 +0000815 if (unsigned NumRanges = TheCU.getRanges().size()) {
Alexey Bataev858a7dd2018-03-20 20:21:38 +0000816 if (NumRanges > 1 && useRangesSection())
David Blaikie1998a2e2014-11-01 01:11:19 +0000817 // A DW_AT_low_pc attribute may also be specified in combination with
818 // DW_AT_ranges to specify the default base address for use in
819 // location lists (see Section 2.6.2) and range lists (see Section
820 // 2.17.3).
821 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
David Blaikie5b02a192014-11-03 23:10:59 +0000822 else
David Blaikie72d03ef2015-05-02 02:31:49 +0000823 U.setBaseAddress(TheCU.getRanges().front().getStart());
David Blaikie5b02a192014-11-03 23:10:59 +0000824 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
Eric Christopher60eb7692013-08-12 20:27:48 +0000825 }
Amjad Aboudd7cfb482016-01-07 14:28:20 +0000826
Wolfgang Pieb9ea65082018-07-26 22:48:52 +0000827 if (getDwarfVersion() >= 5 && !useSplitDwarf() &&
828 !U.getRangeLists().empty())
829 U.addRnglistsBase();
830
Amjad Aboudd7cfb482016-01-07 14:28:20 +0000831 auto *CUNode = cast<DICompileUnit>(P.first);
Amjad Aboud8bbce8a2016-02-01 14:09:41 +0000832 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
833 if (CUNode->getMacros())
834 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
835 U.getMacroLabelBegin(),
836 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
Eric Christopher60eb7692013-08-12 20:27:48 +0000837 }
838
Adrian Prantl833ad372017-07-26 18:48:32 +0000839 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
840 for (auto *CUNode : MMI->getModule()->debug_compile_units())
Adrian Prantl960e7662017-07-27 15:24:20 +0000841 if (CUNode->getDWOId())
Adrian Prantl833ad372017-07-26 18:48:32 +0000842 getOrCreateDwarfCompileUnit(CUNode);
843
Eric Christopher60eb7692013-08-12 20:27:48 +0000844 // Compute DIE offsets and sizes.
Eric Christopherc8a310e2012-12-10 23:34:43 +0000845 InfoHolder.computeSizeAndOffsets();
846 if (useSplitDwarf())
847 SkeletonHolder.computeSizeAndOffsets();
Eric Christopher960ac372012-11-22 00:59:49 +0000848}
849
Eric Christopheracdcbdb2012-11-27 22:43:45 +0000850// Emit all Dwarf sections that should come after the content.
Eric Christopher960ac372012-11-22 00:59:49 +0000851void DwarfDebug::endModule() {
Craig Toppere73658d2014-04-28 04:05:08 +0000852 assert(CurFn == nullptr);
853 assert(CurMI == nullptr);
Eric Christopher960ac372012-11-22 00:59:49 +0000854
David Blaikie0dc623c2014-10-24 17:53:38 +0000855 // If we aren't actually generating debug info (check beginModule -
856 // conditionalized on !DisableDebugInfoPrinting and the presence of the
857 // llvm.dbg.cu metadata node)
Rafael Espindolaf1a13f52015-03-11 00:51:37 +0000858 if (!MMI->hasDebugInfo())
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000859 return;
Eric Christopher960ac372012-11-22 00:59:49 +0000860
Eric Christopher960ac372012-11-22 00:59:49 +0000861 // Finalize the debug info for the module.
862 finalizeModuleInfo();
Bill Wendling2b128d72009-05-20 23:19:06 +0000863
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000864 emitDebugStr();
Eric Christopher9cd26af2013-09-20 23:22:52 +0000865
Rafael Espindola063d7252015-03-10 16:58:10 +0000866 if (useSplitDwarf())
867 emitDebugLocDWO();
868 else
869 // Emit info into a debug loc section.
870 emitDebugLoc();
871
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000872 // Corresponding abbreviations into a abbrev section.
873 emitAbbreviations();
Eric Christopher95198f502012-11-27 22:43:42 +0000874
Rafael Espindolaf1a13f52015-03-11 00:51:37 +0000875 // Emit all the DIEs into a debug info section.
876 emitDebugInfo();
877
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000878 // Emit info into a debug aranges section.
Eric Christopher02dbadb2014-02-14 01:26:55 +0000879 if (GenerateARangeSection)
880 emitDebugARanges();
Eric Christopher95198f502012-11-27 22:43:42 +0000881
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000882 // Emit info into a debug ranges section.
883 emitDebugRanges();
Eric Christopher95198f502012-11-27 22:43:42 +0000884
Amjad Aboudd7cfb482016-01-07 14:28:20 +0000885 // Emit info into a debug macinfo section.
886 emitDebugMacinfo();
887
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000888 if (useSplitDwarf()) {
889 emitDebugStrDWO();
Eric Christopher9c2ecd92012-11-30 23:59:06 +0000890 emitDebugInfoDWO();
Eric Christopher3c5a1912012-12-19 22:02:53 +0000891 emitDebugAbbrevDWO();
David Blaikie4a2f95f2014-03-18 01:17:26 +0000892 emitDebugLineDWO();
Victor Leschuk64e0c562018-08-01 05:48:06 +0000893 emitDebugAddr();
Rafael Espindola063d7252015-03-10 16:58:10 +0000894 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000895
Eric Christophera876b822012-08-23 07:32:06 +0000896 // Emit info into the dwarf accelerator table sections.
Pavel Labath6088c232018-04-04 14:42:14 +0000897 switch (getAccelTableKind()) {
898 case AccelTableKind::Apple:
Eric Christopher4996c702011-11-07 09:24:32 +0000899 emitAccelNames();
900 emitAccelObjC();
901 emitAccelNamespaces();
902 emitAccelTypes();
Pavel Labath6088c232018-04-04 14:42:14 +0000903 break;
904 case AccelTableKind::Dwarf:
905 emitAccelDebugNames();
906 break;
907 case AccelTableKind::None:
908 break;
909 case AccelTableKind::Default:
910 llvm_unreachable("Default should have already been resolved.");
Eric Christopher4996c702011-11-07 09:24:32 +0000911 }
Eric Christopher6a841382012-11-19 22:42:10 +0000912
Eric Christopher4b358182013-08-30 00:40:17 +0000913 // Emit the pubnames and pubtypes sections if requested.
Peter Collingbourneb52e2362017-09-12 21:50:41 +0000914 emitDebugPubSections();
Devang Patel04d2f2d2009-11-24 01:14:22 +0000915
Devang Pateld0701282010-08-02 17:32:15 +0000916 // clean up.
David Blaikie488393f2017-05-12 01:13:45 +0000917 // FIXME: AbstractVariables.clear();
Bill Wendling2b128d72009-05-20 23:19:06 +0000918}
919
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000920void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
921 const DINode *Node,
922 const MDNode *ScopeNode) {
923 if (CU.getExistingAbstractEntity(Node))
David Blaikie6f9e8672014-06-13 23:52:55 +0000924 return;
David Blaikie36408e72014-06-04 23:50:52 +0000925
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000926 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000927 cast<DILocalScope>(ScopeNode)));
David Blaikie36408e72014-06-04 23:50:52 +0000928}
929
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000930void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
931 const DINode *Node, const MDNode *ScopeNode) {
932 if (CU.getExistingAbstractEntity(Node))
David Blaikie6f9e8672014-06-13 23:52:55 +0000933 return;
David Blaikie36408e72014-06-04 23:50:52 +0000934
Duncan P. N. Exon Smith33af7a82015-03-30 23:21:21 +0000935 if (LexicalScope *Scope =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000936 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000937 CU.createAbstractEntity(Node, Scope);
David Blaikie36408e72014-06-04 23:50:52 +0000938}
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000939
Matthias Braunef331ef2016-11-30 23:48:50 +0000940// Collect variable information from side table maintained by MF.
941void DwarfDebug::collectVariableInfoFromMFTable(
David Blaikie488393f2017-05-12 01:13:45 +0000942 DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
Adrian Prantlbe662712017-07-25 23:32:59 +0000943 SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
Matthias Braunef331ef2016-11-30 23:48:50 +0000944 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
Benjamin Kramer2abfd6c72014-03-09 15:44:39 +0000945 if (!VI.Var)
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000946 continue;
Duncan P. N. Exon Smith78a95272015-04-16 22:12:59 +0000947 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
948 "Expected inlined-at fields to agree");
949
950 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +0000951 Processed.insert(Var);
Benjamin Kramer2abfd6c72014-03-09 15:44:39 +0000952 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
Jim Grosbacha8683bb2010-07-21 21:21:52 +0000953
Devang Patelcdb7d442009-11-10 23:20:04 +0000954 // If variable scope is not found then skip this variable.
Craig Topper353eda42014-04-24 06:44:33 +0000955 if (!Scope)
Devang Patelcdb7d442009-11-10 23:20:04 +0000956 continue;
Devang Patelf6eeaeb2009-11-10 23:06:00 +0000957
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000958 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000959 auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
Duncan P. N. Exon Smithe6cc5312015-06-21 16:50:43 +0000960 RegVar->initializeMMI(VI.Expr, VI.Slot);
Adrian Prantlbe662712017-07-25 23:32:59 +0000961 if (DbgVariable *DbgVar = MFVars.lookup(Var))
962 DbgVar->addMMIEntry(*RegVar);
963 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
964 MFVars.insert({Var, RegVar.get()});
Hsiangkai Wangccae2782018-08-14 13:50:59 +0000965 ConcreteEntities.push_back(std::move(RegVar));
Adrian Prantlbe662712017-07-25 23:32:59 +0000966 }
Devang Patel475d32a2009-10-06 01:26:37 +0000967 }
Devang Patel490c8ab2010-05-20 19:57:06 +0000968}
Devang Patela3e9c9c2010-03-15 18:33:46 +0000969
Eric Christopheracdcbdb2012-11-27 22:43:45 +0000970// Get .debug_loc entry for the instruction range starting at MI.
Adrian Prantle19e5ef2014-04-27 18:25:40 +0000971static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000972 const DIExpression *Expr = MI->getDebugExpression();
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000973 assert(MI->getNumOperands() == 4);
Adrian Prantl418d1d12013-07-09 20:28:37 +0000974 if (MI->getOperand(0).isReg()) {
Adrian Prantlbd6d2912017-08-02 17:19:13 +0000975 auto RegOp = MI->getOperand(0);
976 auto Op1 = MI->getOperand(1);
Adrian Prantl418d1d12013-07-09 20:28:37 +0000977 // If the second operand is an immediate, this is a
978 // register-indirect address.
Adrian Prantlbd6d2912017-08-02 17:19:13 +0000979 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
980 MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +0000981 return DebugLocEntry::Value(Expr, MLoc);
Devang Patel2442a892011-07-08 17:09:57 +0000982 }
983 if (MI->getOperand(0).isImm())
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +0000984 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
Devang Patel2442a892011-07-08 17:09:57 +0000985 if (MI->getOperand(0).isFPImm())
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +0000986 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
Devang Patel2442a892011-07-08 17:09:57 +0000987 if (MI->getOperand(0).isCImm())
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +0000988 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
Devang Patel2442a892011-07-08 17:09:57 +0000989
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000990 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
Devang Patel2442a892011-07-08 17:09:57 +0000991}
992
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000993/// If this and Next are describing different fragments of the same
Keno Fischerf8eb6a12016-01-16 01:11:33 +0000994/// variable, merge them by appending Next's values to the current
995/// list of values.
996/// Return true if the merge was successful.
997bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
998 if (Begin == Next.Begin) {
Keno Fischer6c1e47a2016-02-03 21:13:33 +0000999 auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
1000 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
Adrian Prantl941fa752016-12-05 18:04:47 +00001001 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001002 return false;
1003
Adrian Prantl941fa752016-12-05 18:04:47 +00001004 // We can only merge entries if none of the fragments overlap any others.
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001005 // In doing so, we can take advantage of the fact that both lists are
1006 // sorted.
1007 for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
1008 for (; j < Next.Values.size(); ++j) {
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001009 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp(
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001010 cast<DIExpression>(Next.Values[j].Expression));
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001011 if (res == 0) // The two expressions overlap, we can't merge.
1012 return false;
1013 // Values[i] is entirely before Next.Values[j],
1014 // so go back to the next entry of Values.
1015 else if (res == -1)
1016 break;
1017 // Next.Values[j] is entirely before Values[i], so go on to the
1018 // next entry of Next.Values.
1019 }
Keno Fischerf8eb6a12016-01-16 01:11:33 +00001020 }
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001021
1022 addValues(Next.Values);
1023 End = Next.End;
1024 return true;
Keno Fischerf8eb6a12016-01-16 01:11:33 +00001025 }
1026 return false;
1027}
1028
Adrian Prantlb1416832014-08-01 22:11:58 +00001029/// Build the location list for all DBG_VALUEs in the function that
1030/// describe the same variable. If the ranges of several independent
Adrian Prantl941fa752016-12-05 18:04:47 +00001031/// fragments of the same variable overlap partially, split them up and
Adrian Prantlb1416832014-08-01 22:11:58 +00001032/// combine the ranges. The resulting DebugLocEntries are will have
1033/// strict monotonically increasing begin addresses and will never
1034/// overlap.
1035//
1036// Input:
1037//
Adrian Prantl941fa752016-12-05 18:04:47 +00001038// Ranges History [var, loc, fragment ofs size]
1039// 0 | [x, (reg0, fragment 0, 32)]
1040// 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
Adrian Prantlb1416832014-08-01 22:11:58 +00001041// 2 | | ...
1042// 3 | [clobber reg0]
Adrian Prantl941fa752016-12-05 18:04:47 +00001043// 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
Eric Christopherffc5ff32015-02-17 20:02:28 +00001044// x.
Adrian Prantlb1416832014-08-01 22:11:58 +00001045//
1046// Output:
1047//
Adrian Prantl941fa752016-12-05 18:04:47 +00001048// [0-1] [x, (reg0, fragment 0, 32)]
1049// [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1050// [3-4] [x, (reg1, fragment 32, 32)]
1051// [4- ] [x, (mem, fragment 0, 64)]
David Blaikiee1a26a62014-08-05 23:14:16 +00001052void
1053DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1054 const DbgValueHistoryMap::InstrRanges &Ranges) {
Adrian Prantlcaaf0532014-08-11 21:05:57 +00001055 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
Adrian Prantlb1416832014-08-01 22:11:58 +00001056
1057 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1058 const MachineInstr *Begin = I->first;
1059 const MachineInstr *End = I->second;
1060 assert(Begin->isDebugValue() && "Invalid History entry");
1061
1062 // Check if a variable is inaccessible in this range.
Adrian Prantl5e1fa852014-08-12 21:55:58 +00001063 if (Begin->getNumOperands() > 1 &&
1064 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
Adrian Prantlb1416832014-08-01 22:11:58 +00001065 OpenRanges.clear();
1066 continue;
1067 }
1068
Adrian Prantl941fa752016-12-05 18:04:47 +00001069 // If this fragment overlaps with any open ranges, truncate them.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001070 const DIExpression *DIExpr = Begin->getDebugExpression();
David Majnemer0a16c222016-08-11 21:15:00 +00001071 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001072 return DIExpr->fragmentsOverlap(R.getExpression());
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001073 });
Adrian Prantlb1416832014-08-01 22:11:58 +00001074 OpenRanges.erase(Last, OpenRanges.end());
1075
1076 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1077 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1078
1079 const MCSymbol *EndLabel;
1080 if (End != nullptr)
1081 EndLabel = getLabelAfterInsn(End);
1082 else if (std::next(I) == Ranges.end())
Rafael Espindola07c03d32015-03-05 02:05:42 +00001083 EndLabel = Asm->getFunctionEnd();
Adrian Prantlb1416832014-08-01 22:11:58 +00001084 else
1085 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1086 assert(EndLabel && "Forgot label after instruction ending a range!");
1087
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001088 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
Adrian Prantlb1416832014-08-01 22:11:58 +00001089
1090 auto Value = getDebugLocValue(Begin);
David Blaikiee1a26a62014-08-05 23:14:16 +00001091 DebugLocEntry Loc(StartLabel, EndLabel, Value);
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001092 bool couldMerge = false;
1093
Adrian Prantl941fa752016-12-05 18:04:47 +00001094 // If this is a fragment, it may belong to the current DebugLocEntry.
1095 if (DIExpr->isFragment()) {
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001096 // Add this value to the list of open ranges.
Adrian Prantlcaaf0532014-08-11 21:05:57 +00001097 OpenRanges.push_back(Value);
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001098
Adrian Prantl941fa752016-12-05 18:04:47 +00001099 // Attempt to add the fragment to the last entry.
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001100 if (!DebugLoc.empty())
1101 if (DebugLoc.back().MergeValues(Loc))
1102 couldMerge = true;
1103 }
1104
1105 if (!couldMerge) {
1106 // Need to add a new DebugLocEntry. Add all values from still
Adrian Prantl941fa752016-12-05 18:04:47 +00001107 // valid non-overlapping fragments.
Adrian Prantl1c6f2ec2014-08-11 21:06:00 +00001108 if (OpenRanges.size())
1109 Loc.addValues(OpenRanges);
1110
Adrian Prantlb1416832014-08-01 22:11:58 +00001111 DebugLoc.push_back(std::move(Loc));
1112 }
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001113
1114 // Attempt to coalesce the ranges of two otherwise identical
1115 // DebugLocEntries.
1116 auto CurEntry = DebugLoc.rbegin();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001117 LLVM_DEBUG({
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001118 dbgs() << CurEntry->getValues().size() << " Values:\n";
Adrian Prantl6f8c1b62015-05-26 20:06:51 +00001119 for (auto &Value : CurEntry->getValues())
Adrian Prantldba58fb2016-02-29 22:28:22 +00001120 Value.dump();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001121 dbgs() << "-----\n";
1122 });
Adrian Prantl75707312015-05-26 20:06:48 +00001123
1124 auto PrevEntry = std::next(CurEntry);
1125 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1126 DebugLoc.pop_back();
Adrian Prantlb1416832014-08-01 22:11:58 +00001127 }
1128}
1129
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001130DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1131 LexicalScope &Scope,
1132 const DINode *Node,
1133 const DILocation *Location,
1134 const MCSymbol *Sym) {
1135 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1136 if (isa<const DILocalVariable>(Node)) {
1137 ConcreteEntities.push_back(
1138 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1139 Location));
1140 InfoHolder.addScopeVariable(&Scope,
1141 cast<DbgVariable>(ConcreteEntities.back().get()));
1142 } else if (isa<const DILabel>(Node)) {
1143 ConcreteEntities.push_back(
1144 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
1145 Location, Sym));
1146 InfoHolder.addScopeLabel(&Scope,
1147 cast<DbgLabel>(ConcreteEntities.back().get()));
1148 }
1149 return ConcreteEntities.back().get();
Duncan P. N. Exon Smithe6cc5312015-06-21 16:50:43 +00001150}
Adrian Prantlb1416832014-08-01 22:11:58 +00001151
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001152/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1153/// enclosing lexical scope. The check ensures there are no other instructions
1154/// in the same lexical scope preceding the DBG_VALUE and that its range is
1155/// either open or otherwise rolls off the end of the scope.
1156static bool validThroughout(LexicalScopes &LScopes,
1157 const MachineInstr *DbgValue,
1158 const MachineInstr *RangeEnd) {
1159 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1160 auto MBB = DbgValue->getParent();
1161 auto DL = DbgValue->getDebugLoc();
1162 auto *LScope = LScopes.findLexicalScope(DL);
1163 // Scope doesn't exist; this is a dead DBG_VALUE.
1164 if (!LScope)
Adrian Prantlfb2add22016-02-29 19:49:46 +00001165 return false;
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001166 auto &LSRange = LScope->getRanges();
1167 if (LSRange.size() == 0)
1168 return false;
1169
1170 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1171 const MachineInstr *LScopeBegin = LSRange.front().first;
1172 // Early exit if the lexical scope begins outside of the current block.
1173 if (LScopeBegin->getParent() != MBB)
1174 return false;
1175 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1176 for (++Pred; Pred != MBB->rend(); ++Pred) {
1177 if (Pred->getFlag(MachineInstr::FrameSetup))
1178 break;
1179 auto PredDL = Pred->getDebugLoc();
Adrian Prantl25422dc2017-06-20 21:08:52 +00001180 if (!PredDL || Pred->isMetaInstruction())
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001181 continue;
1182 // Check whether the instruction preceding the DBG_VALUE is in the same
1183 // (sub)scope as the DBG_VALUE.
Adrian Prantl25422dc2017-06-20 21:08:52 +00001184 if (DL->getScope() == PredDL->getScope())
1185 return false;
1186 auto *PredScope = LScopes.findLexicalScope(PredDL);
1187 if (!PredScope || LScope->dominates(PredScope))
Adrian Prantlfb2add22016-02-29 19:49:46 +00001188 return false;
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001189 }
1190
1191 // If the range of the DBG_VALUE is open-ended, report success.
1192 if (!RangeEnd)
1193 return true;
1194
1195 // Fail if there are instructions belonging to our scope in another block.
1196 const MachineInstr *LScopeEnd = LSRange.back().second;
1197 if (LScopeEnd->getParent() != MBB)
1198 return false;
1199
1200 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1201 // throughout the function. This is a hack, presumably for DWARF v2 and not
1202 // necessarily correct. It would be much better to use a dbg.declare instead
1203 // if we know the constant is live throughout the scope.
1204 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1205 return true;
1206
1207 return false;
Adrian Prantlfb2add22016-02-29 19:49:46 +00001208}
1209
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001210// Find variables for each lexical scope.
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001211void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1212 const DISubprogram *SP,
1213 DenseSet<InlinedVariable> &Processed) {
Eric Christopher270a12c2013-07-03 21:37:03 +00001214 // Grab the variable info that was squirreled away in the MMI side-table.
David Blaikie488393f2017-05-12 01:13:45 +00001215 collectVariableInfoFromMFTable(TheCU, Processed);
Devang Patel490c8ab2010-05-20 19:57:06 +00001216
Alexey Samsonov0436caa2014-04-30 23:02:40 +00001217 for (const auto &I : DbgValues) {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001218 InlinedVariable IV = I.first;
1219 if (Processed.count(IV))
Devang Patel490c8ab2010-05-20 19:57:06 +00001220 continue;
1221
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001222 // Instruction ranges, specifying where IV is accessible.
Alexey Samsonovbb2990d2014-05-27 23:09:50 +00001223 const auto &Ranges = I.second;
1224 if (Ranges.empty())
Jakob Stoklund Olesen9a624fa2011-03-26 02:19:36 +00001225 continue;
Devang Patel9fc11702010-05-25 23:40:22 +00001226
Craig Topper353eda42014-04-24 06:44:33 +00001227 LexicalScope *Scope = nullptr;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001228 if (const DILocation *IA = IV.second)
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001229 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
Duncan P. N. Exon Smithb4749372015-02-17 00:02:27 +00001230 else
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001231 Scope = LScopes.findLexicalScope(IV.first->getScope());
Devang Patel490c8ab2010-05-20 19:57:06 +00001232 // If variable scope is not found then skip this variable.
Devang Patelfbd6c452010-05-21 00:10:20 +00001233 if (!Scope)
Devang Patel490c8ab2010-05-20 19:57:06 +00001234 continue;
1235
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001236 Processed.insert(IV);
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001237 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1238 *Scope, IV.first, IV.second));
Duncan P. N. Exon Smithe6cc5312015-06-21 16:50:43 +00001239
Alexey Samsonovbb2990d2014-05-27 23:09:50 +00001240 const MachineInstr *MInsn = Ranges.front().first;
Jakob Stoklund Olesen9a624fa2011-03-26 02:19:36 +00001241 assert(MInsn->isDebugValue() && "History must begin with debug value");
Jakob Stoklund Olesen9a624fa2011-03-26 02:19:36 +00001242
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001243 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
Adrian Prantlfb2add22016-02-29 19:49:46 +00001244 if (Ranges.size() == 1 &&
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001245 validThroughout(LScopes, MInsn, Ranges.front().second)) {
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001246 RegVar->initializeDbgValue(MInsn);
Devang Patel9fc11702010-05-25 23:40:22 +00001247 continue;
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001248 }
Alexey Bataev2a03d422018-06-29 14:23:28 +00001249 // Do not emit location lists if .debug_loc secton is disabled.
1250 if (!useLocSection())
1251 continue;
Devang Patel9fc11702010-05-25 23:40:22 +00001252
Eric Christopher59cc0712013-01-28 17:33:26 +00001253 // Handle multiple DBG_VALUE instructions describing one variable.
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001254 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
Jakob Stoklund Olesen9c057ee2011-03-22 00:21:41 +00001255
Adrian Prantlb1416832014-08-01 22:11:58 +00001256 // Build the location list for this variable.
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001257 SmallVector<DebugLocEntry, 8> Entries;
1258 buildLocationList(Entries, Ranges);
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001259
Adrian Prantl693e8de2016-02-29 17:06:46 +00001260 // If the variable has a DIBasicType, extract it. Basic types cannot have
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001261 // unique identifiers, so don't bother resolving the type with the
1262 // identifier map.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001263 const DIBasicType *BT = dyn_cast<DIBasicType>(
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001264 static_cast<const Metadata *>(IV.first->getType()));
1265
Adrian Prantl92da14b2015-03-02 22:02:33 +00001266 // Finalize the entry by lowering it into a DWARF bytestream.
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001267 for (auto &Entry : Entries)
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001268 Entry.finalize(*Asm, List, BT);
Devang Patela3e9c9c2010-03-15 18:33:46 +00001269 }
Devang Patele0a94bf2010-05-14 21:01:35 +00001270
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001271 // For each InlinedLabel collected from DBG_LABEL instructions, convert to
1272 // DWARF-related DbgLabel.
1273 for (const auto &I : DbgLabels) {
1274 InlinedLabel IL = I.first;
1275 const MachineInstr *MI = I.second;
1276 if (MI == nullptr)
1277 continue;
1278
1279 LexicalScope *Scope = nullptr;
1280 // Get inlined DILocation if it is inlined label.
1281 if (const DILocation *IA = IL.second)
1282 Scope = LScopes.findInlinedScope(IL.first->getScope(), IA);
1283 else
1284 Scope = LScopes.findLexicalScope(IL.first->getScope());
1285 // If label scope is not found then skip this label.
1286 if (!Scope)
1287 continue;
1288
1289 /// At this point, the temporary label is created.
1290 /// Save the temporary label to DbgLabel entity to get the
1291 /// actually address when generating Dwarf DIE.
1292 MCSymbol *Sym = getLabelBeforeInsn(MI);
1293 createConcreteEntity(TheCU, *Scope, IL.first, IL.second, Sym);
1294 }
1295
1296 // Collect info for variables/labels that were optimized out.
Shiva Chen2c864552018-05-09 02:40:45 +00001297 for (const DINode *DN : SP->getRetainedNodes()) {
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001298 LexicalScope *Scope = nullptr;
Shiva Chen2c864552018-05-09 02:40:45 +00001299 if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001300 if (!Processed.insert(InlinedVariable(DV, nullptr)).second)
1301 continue;
1302 Scope = LScopes.findLexicalScope(DV->getScope());
1303 } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1304 Scope = LScopes.findLexicalScope(DL->getScope());
Shiva Chen2c864552018-05-09 02:40:45 +00001305 }
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001306
1307 if (Scope)
1308 createConcreteEntity(TheCU, *Scope, DN, nullptr);
Devang Patele0a94bf2010-05-14 21:01:35 +00001309 }
Devang Patel9fc11702010-05-25 23:40:22 +00001310}
Devang Patele0a94bf2010-05-14 21:01:35 +00001311
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001312// Process beginning of an instruction.
Devang Patelb5694e72010-10-26 17:49:02 +00001313void DwarfDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001314 DebugHandlerBase::beginInstruction(MI);
1315 assert(CurMI);
1316
Matthias Braunf1caa282017-12-15 22:22:58 +00001317 const auto *SP = MI->getMF()->getFunction().getSubprogram();
David Blaikie7f2b7172017-05-26 17:05:15 +00001318 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1319 return;
1320
Paul Robinson4fa7b57a2016-12-09 19:15:32 +00001321 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
Paul Robinsonee88ed62018-02-14 17:35:52 +00001322 // If the instruction is part of the function frame setup code, do not emit
1323 // any line record, as there is no correspondence with any user code.
1324 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
Paul Robinsonf428c9b2016-11-22 19:46:51 +00001325 return;
1326 const DebugLoc &DL = MI->getDebugLoc();
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001327 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1328 // the last line number actually emitted, to see if it was line 0.
1329 unsigned LastAsmLine =
1330 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
Paul Robinson96de8c72016-11-29 22:41:16 +00001331
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001332 if (DL == PrevInstLoc) {
1333 // If we have an ongoing unspecified location, nothing to do here.
1334 if (!DL)
1335 return;
1336 // We have an explicit location, same as the previous location.
1337 // But we might be coming back to it after a line 0 record.
1338 if (LastAsmLine == 0 && DL.getLine() != 0) {
1339 // Reinstate the source location but not marked as a statement.
1340 const MDNode *Scope = DL.getScope();
1341 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
Paul Robinson37a13dd2016-11-30 22:49:55 +00001342 }
1343 return;
1344 }
1345
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001346 if (!DL) {
1347 // We have an unspecified location, which might want to be line 0.
1348 // If we have already emitted a line-0 record, don't repeat it.
1349 if (LastAsmLine == 0)
1350 return;
1351 // If user said Don't Do That, don't do that.
1352 if (UnknownLocations == Disable)
1353 return;
1354 // See if we have a reason to emit a line-0 record now.
1355 // Reasons to emit a line-0 record include:
1356 // - User asked for it (UnknownLocations).
1357 // - Instruction has a label, so it's referenced from somewhere else,
1358 // possibly debug information; we want it to have a source location.
1359 // - Instruction is at the top of a block; we don't want to inherit the
1360 // location from the physically previous (maybe unrelated) block.
1361 if (UnknownLocations == Enable || PrevLabel ||
1362 (PrevInstBB && PrevInstBB != MI->getParent())) {
Paul Robinson8fec3da2016-12-14 00:27:35 +00001363 // Preserve the file and column numbers, if we can, to save space in
1364 // the encoded line table.
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001365 // Do not update PrevInstLoc, it remembers the last non-0 line.
Paul Robinson8fec3da2016-12-14 00:27:35 +00001366 const MDNode *Scope = nullptr;
1367 unsigned Column = 0;
1368 if (PrevInstLoc) {
1369 Scope = PrevInstLoc.getScope();
1370 Column = PrevInstLoc.getCol();
1371 }
1372 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001373 }
1374 return;
1375 }
1376
1377 // We have an explicit location, different from the previous location.
1378 // Don't repeat a line-0 record, but otherwise emit the new location.
1379 // (The new location might be an explicit line 0, which we do emit.)
Paul Robinson2dfb6882016-12-16 23:54:33 +00001380 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001381 return;
Paul Robinsonf428c9b2016-11-22 19:46:51 +00001382 unsigned Flags = 0;
Paul Robinsonf428c9b2016-11-22 19:46:51 +00001383 if (DL == PrologEndLoc) {
1384 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1385 PrologEndLoc = DebugLoc();
1386 }
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001387 // If the line changed, we call that a new statement; unless we went to
1388 // line 0 and came back, in which case it is not a new statement.
1389 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1390 if (DL.getLine() && DL.getLine() != OldLine)
Paul Robinsonf428c9b2016-11-22 19:46:51 +00001391 Flags |= DWARF2_FLAG_IS_STMT;
1392
1393 const MDNode *Scope = DL.getScope();
1394 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001395
1396 // If we're not at line 0, remember this location.
1397 if (DL.getLine())
1398 PrevInstLoc = DL;
Devang Patel75cc16c2009-10-01 20:31:14 +00001399}
1400
Alexey Samsonov8a86d6d2014-05-27 22:47:41 +00001401static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1402 // First known non-DBG_VALUE and non-frame setup location marks
1403 // the beginning of the function body.
1404 for (const auto &MBB : *MF)
1405 for (const auto &MI : MBB)
Adrian Prantlfb31da12017-05-22 20:47:09 +00001406 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Michael Kuperstein2b3c16c2015-10-08 07:48:49 +00001407 MI.getDebugLoc())
Alexey Samsonov8a86d6d2014-05-27 22:47:41 +00001408 return MI.getDebugLoc();
1409 return DebugLoc();
1410}
1411
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001412// Gather pre-function debug information. Assumes being called immediately
1413// after the function entry point has been emitted.
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001414void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanov1cd14442013-12-03 15:10:23 +00001415 CurFn = MF;
Eric Christopherfedfa442013-11-01 23:14:17 +00001416
Matthias Braunf1caa282017-12-15 22:22:58 +00001417 auto *SP = MF->getFunction().getSubprogram();
David Blaikie2c78f182017-05-25 23:11:28 +00001418 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
David Blaikie07963bd2017-05-26 18:52:56 +00001419 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
Adrian Prantl5992a722016-04-08 22:43:03 +00001420 return;
David Blaikie07963bd2017-05-26 18:52:56 +00001421
1422 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
David Blaikie2c78f182017-05-25 23:11:28 +00001423
1424 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1425 // belongs to so that we add to the correct per-cu line table in the
1426 // non-asm case.
Lang Hames9ff69c82015-04-24 19:11:51 +00001427 if (Asm->OutStreamer->hasRawTextSupport())
Rafael Espindolab4eec1d2014-02-05 18:00:21 +00001428 // Use a single line table if we are generating assembly.
Lang Hames9ff69c82015-04-24 19:11:51 +00001429 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
Manman Ren9d4c7352013-05-21 00:57:22 +00001430 else
David Blaikie07963bd2017-05-26 18:52:56 +00001431 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
Manman Ren4e042a62013-02-05 21:52:47 +00001432
Devang Patel34a66202011-05-11 19:22:19 +00001433 // Record beginning of function.
Alexey Samsonov8a86d6d2014-05-27 22:47:41 +00001434 PrologEndLoc = findPrologueEndLoc(MF);
David Blaikie2c78f182017-05-25 23:11:28 +00001435 if (PrologEndLoc) {
Saleem Abdulrasoolfc07c722015-01-24 20:19:45 +00001436 // We'd like to list the prologue as "not statements" but GDB behaves
1437 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
David Blaikie2c78f182017-05-25 23:11:28 +00001438 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
Duncan P. N. Exon Smithfd07a2a2015-03-30 21:32:28 +00001439 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
Devang Patel34a66202011-05-11 19:22:19 +00001440 }
Bill Wendling2b128d72009-05-20 23:19:06 +00001441}
1442
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001443void DwarfDebug::skippedNonDebugFunction() {
1444 // If we don't have a subprogram for this function then there will be a hole
1445 // in the range information. Keep note of this by setting the previously used
1446 // section to nullptr.
1447 PrevCU = nullptr;
1448 CurFn = nullptr;
1449}
1450
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001451// Gather and emit post-function debug information.
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001452void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001453 const DISubprogram *SP = MF->getFunction().getSubprogram();
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001454
David Blaikiee75f9632014-10-14 17:12:02 +00001455 assert(CurFn == MF &&
1456 "endFunction should be called with the same function as beginFunction");
Timur Iskhodzhanov1cd14442013-12-03 15:10:23 +00001457
Eric Christopher4287a492013-12-09 23:57:44 +00001458 // Set DwarfDwarfCompileUnitID in MCContext to default value.
Lang Hames9ff69c82015-04-24 19:11:51 +00001459 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
Eric Christopher6a841382012-11-19 22:42:10 +00001460
Devang Patel3acc70e2011-08-15 22:04:40 +00001461 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
David Blaikie3e3eb332016-12-15 23:17:52 +00001462 assert(!FnScope || SP == FnScope->getScopeNode());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001463 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
Alexey Bataevd4dd7212018-08-01 19:38:20 +00001464 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1465 PrevLabel = nullptr;
1466 CurFn = nullptr;
1467 return;
1468 }
David Blaikie263a0082014-10-23 00:06:27 +00001469
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001470 DenseSet<InlinedVariable> ProcessedVars;
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001471 collectEntityInfo(TheCU, SP, ProcessedVars);
Devang Patel3acc70e2011-08-15 22:04:40 +00001472
David Blaikie3a7ce252014-09-19 17:03:16 +00001473 // Add the range of this function to the list of ranges for the CU.
Rafael Espindola07c03d32015-03-05 02:05:42 +00001474 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
David Blaikie3a7ce252014-09-19 17:03:16 +00001475
1476 // Under -gmlt, skip building the subprogram if there are no inlined
Dehao Chen1ce8d6c2017-01-19 00:44:11 +00001477 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1478 // is still needed as we need its source location.
Dehao Chen0944a8c2017-02-01 22:45:09 +00001479 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
Dehao Chen1ce8d6c2017-01-19 00:44:11 +00001480 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
David Blaikiee1c79742014-09-30 21:28:32 +00001481 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
David Blaikie80e5b1e2014-10-24 17:57:34 +00001482 assert(InfoHolder.getScopeVariables().empty());
David Blaikie3a7ce252014-09-19 17:03:16 +00001483 PrevLabel = nullptr;
1484 CurFn = nullptr;
1485 return;
1486 }
1487
Adrian Prantl049d21c2014-10-13 20:44:58 +00001488#ifndef NDEBUG
1489 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1490#endif
Devang Patel7e623022011-08-10 20:55:27 +00001491 // Construct abstract scopes.
Benjamin Kramer15596c72014-03-07 19:09:39 +00001492 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001493 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
Shiva Chen2c864552018-05-09 02:40:45 +00001494 for (const DINode *DN : SP->getRetainedNodes()) {
1495 if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1496 // Collect info for variables that were optimized out.
1497 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1498 continue;
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001499 ensureAbstractEntityIsCreated(TheCU, DV, DV->getScope());
Shiva Chen2c864552018-05-09 02:40:45 +00001500 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001501 && "ensureAbstractEntityIsCreated inserted abstract scopes");
1502 } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1503 ensureAbstractEntityIsCreated(TheCU, DL, DL->getScope());
Shiva Chen2c864552018-05-09 02:40:45 +00001504 }
Devang Patel5c0f85c2010-06-25 22:07:34 +00001505 }
David Blaikie488393f2017-05-12 01:13:45 +00001506 constructAbstractSubprogramScopeDIE(TheCU, AScope);
Bill Wendling2b128d72009-05-20 23:19:06 +00001507 }
Eric Christopher6a841382012-11-19 22:42:10 +00001508
David Blaikie38b74bf2016-12-15 23:37:38 +00001509 ProcessedSPNodes.insert(SP);
David Blaikie3e3eb332016-12-15 23:17:52 +00001510 TheCU.constructSubprogramScopeDIE(SP, FnScope);
David Blaikie3a443c22014-11-04 22:12:25 +00001511 if (auto *SkelCU = TheCU.getSkeleton())
David Blaikiea01f2952016-08-24 18:29:49 +00001512 if (!LScopes.getAbstractScopesList().empty() &&
1513 TheCU.getCUNode()->getSplitDebugInlining())
David Blaikie3e3eb332016-12-15 23:17:52 +00001514 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
Devang Patel3acc70e2011-08-15 22:04:40 +00001515
Bill Wendling2b128d72009-05-20 23:19:06 +00001516 // Clear debug info
David Blaikie825bdd22014-05-21 22:41:17 +00001517 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1518 // DbgVariables except those that are also in AbstractVariables (since they
1519 // can be used cross-function)
David Blaikie80e5b1e2014-10-24 17:57:34 +00001520 InfoHolder.getScopeVariables().clear();
Hsiangkai Wangccae2782018-08-14 13:50:59 +00001521 InfoHolder.getScopeLabels().clear();
Craig Topper353eda42014-04-24 06:44:33 +00001522 PrevLabel = nullptr;
1523 CurFn = nullptr;
Bill Wendling2b128d72009-05-20 23:19:06 +00001524}
1525
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001526// Register a source line with debug info. Returns the unique label that was
1527// emitted and which provides correspondence to the source line list.
Devang Patel34a66202011-05-11 19:22:19 +00001528void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1529 unsigned Flags) {
Devang Patel2d9caf92009-11-25 17:36:49 +00001530 StringRef Fn;
Scott Linder16c7bda2018-02-23 23:01:06 +00001531 unsigned FileNo = 1;
Diego Novillo282450d2014-03-03 18:53:17 +00001532 unsigned Discriminator = 0;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001533 if (auto *Scope = cast_or_null<DIScope>(S)) {
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +00001534 Fn = Scope->getFilename();
Paul Robinsonbb921372017-09-07 22:15:44 +00001535 if (Line != 0 && getDwarfVersion() >= 4)
1536 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
Dehao Chen6e0c8442016-10-07 15:21:31 +00001537 Discriminator = LBF->getDiscriminator();
Dan Gohman50849c62010-05-05 23:41:32 +00001538
Lang Hames9ff69c82015-04-24 19:11:51 +00001539 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
Scott Linder16c7bda2018-02-23 23:01:06 +00001540 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
Paul Robinson612e89d2018-01-12 19:17:50 +00001541 .getOrCreateSourceID(Scope->getFile());
Dan Gohman50849c62010-05-05 23:41:32 +00001542 }
Scott Linder16c7bda2018-02-23 23:01:06 +00001543 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
Lang Hames9ff69c82015-04-24 19:11:51 +00001544 Discriminator, Fn);
Bill Wendling2b128d72009-05-20 23:19:06 +00001545}
1546
Bill Wendling806535f2009-05-20 23:22:40 +00001547//===----------------------------------------------------------------------===//
1548// Emit Methods
1549//===----------------------------------------------------------------------===//
1550
Eric Christopher9c2ecd92012-11-30 23:59:06 +00001551// Emit the debug info section.
1552void DwarfDebug::emitDebugInfo() {
Eric Christopherf8194852013-12-05 18:06:10 +00001553 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Rafael Espindola063d7252015-03-10 16:58:10 +00001554 Holder.emitUnits(/* UseOffsets */ false);
Eric Christopher9c2ecd92012-11-30 23:59:06 +00001555}
1556
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001557// Emit the abbreviation section.
Eric Christopher38371952012-11-20 23:30:11 +00001558void DwarfDebug::emitAbbreviations() {
Eric Christopherf8194852013-12-05 18:06:10 +00001559 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
David Blaikie0504cda2013-12-05 07:43:55 +00001560
1561 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
Eric Christopher3c5a1912012-12-19 22:02:53 +00001562}
Bill Wendling480ff322009-05-20 23:21:38 +00001563
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001564void DwarfDebug::emitStringOffsetsTableHeader() {
1565 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Pavel Labath7bfa5d62018-07-26 14:36:07 +00001566 Holder.getStringPool().emitStringOffsetsTableHeader(
1567 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1568 Holder.getStringOffsetsStartSym());
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001569}
1570
Jonas Devliegheree699dfa2018-01-29 14:52:34 +00001571template <typename AccelTableT>
1572void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001573 StringRef TableName) {
Lang Hames9ff69c82015-04-24 19:11:51 +00001574 Asm->OutStreamer->SwitchSection(Section);
Eric Christopher4996c702011-11-07 09:24:32 +00001575
1576 // Emit the full data.
Pavel Labatha7c457d2018-02-19 16:12:20 +00001577 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
David Blaikie6741bb02014-09-11 21:12:48 +00001578}
1579
Pavel Labath6088c232018-04-04 14:42:14 +00001580void DwarfDebug::emitAccelDebugNames() {
Pavel Labatheadfac82018-04-09 14:38:53 +00001581 // Don't emit anything if we have no compilation units to index.
1582 if (getUnits().empty())
1583 return;
1584
Pavel Labath6088c232018-04-04 14:42:14 +00001585 Asm->OutStreamer->SwitchSection(
1586 Asm->getObjFileLowering().getDwarfDebugNamesSection());
1587 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1588}
1589
David Blaikie6741bb02014-09-11 21:12:48 +00001590// Emit visible names into a hashed accelerator table section.
1591void DwarfDebug::emitAccelNames() {
1592 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001593 "Names");
Eric Christopher4996c702011-11-07 09:24:32 +00001594}
1595
Eric Christopher48fef592012-12-20 21:58:40 +00001596// Emit objective C classes and categories into a hashed accelerator table
1597// section.
Eric Christopher4996c702011-11-07 09:24:32 +00001598void DwarfDebug::emitAccelObjC() {
David Blaikie6741bb02014-09-11 21:12:48 +00001599 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001600 "ObjC");
Eric Christopher4996c702011-11-07 09:24:32 +00001601}
1602
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001603// Emit namespace dies into a hashed accelerator table.
Eric Christopher4996c702011-11-07 09:24:32 +00001604void DwarfDebug::emitAccelNamespaces() {
David Blaikie6741bb02014-09-11 21:12:48 +00001605 emitAccel(AccelNamespace,
1606 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001607 "namespac");
Eric Christopher4996c702011-11-07 09:24:32 +00001608}
1609
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001610// Emit type dies into a hashed accelerator table.
Eric Christopher4996c702011-11-07 09:24:32 +00001611void DwarfDebug::emitAccelTypes() {
David Blaikie6741bb02014-09-11 21:12:48 +00001612 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001613 "types");
Eric Christopher4996c702011-11-07 09:24:32 +00001614}
1615
Eric Christopherdd1a0122013-09-13 00:35:05 +00001616// Public name handling.
1617// The format for the various pubnames:
1618//
1619// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1620// for the DIE that is named.
1621//
1622// gnu pubnames - offset/index value/name tuples where the offset is the offset
1623// into the CU and the index value is computed according to the type of value
1624// for the DIE that is named.
1625//
1626// For type units the offset is the offset of the skeleton DIE. For split dwarf
1627// it's the offset within the debug_info/debug_types dwo section, however, the
1628// reference in the pubname header doesn't change.
1629
1630/// computeIndexValue - Compute the gdb index value for the DIE and CU.
Eric Christophera5a79422013-12-09 23:32:48 +00001631static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
Eric Christopher0fe676a2013-11-21 00:48:22 +00001632 const DIE *Die) {
David Blaikiea0e3c752017-02-03 00:44:18 +00001633 // Entities that ended up only in a Type Unit reference the CU instead (since
1634 // the pub entry has offsets within the CU there's no real offset that can be
1635 // provided anyway). As it happens all such entities (namespaces and types,
1636 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1637 // not to be true it would be necessary to persist this information from the
1638 // point at which the entry is added to the index data structure - since by
1639 // the time the index is built from that, the original type/namespace DIE in a
1640 // type unit has already been destroyed so it can't be queried for properties
1641 // like tag, etc.
1642 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1643 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1644 dwarf::GIEL_EXTERNAL);
Eric Christopherd2b497b2013-10-16 01:37:49 +00001645 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1646
1647 // We could have a specification DIE that has our most of our knowledge,
1648 // look for that now.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001649 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1650 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
David Blaikie8dbcc3f2014-04-25 19:33:43 +00001651 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
Eric Christopherd2b497b2013-10-16 01:37:49 +00001652 Linkage = dwarf::GIEL_EXTERNAL;
1653 } else if (Die->findAttribute(dwarf::DW_AT_external))
1654 Linkage = dwarf::GIEL_EXTERNAL;
Eric Christopherdd1a0122013-09-13 00:35:05 +00001655
1656 switch (Die->getTag()) {
1657 case dwarf::DW_TAG_class_type:
1658 case dwarf::DW_TAG_structure_type:
1659 case dwarf::DW_TAG_union_type:
1660 case dwarf::DW_TAG_enumeration_type:
Eric Christopher261d2342013-09-23 20:55:35 +00001661 return dwarf::PubIndexEntryDescriptor(
1662 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1663 ? dwarf::GIEL_STATIC
1664 : dwarf::GIEL_EXTERNAL);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001665 case dwarf::DW_TAG_typedef:
1666 case dwarf::DW_TAG_base_type:
1667 case dwarf::DW_TAG_subrange_type:
David Blaikie8dec4072013-09-19 20:40:26 +00001668 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001669 case dwarf::DW_TAG_namespace:
David Blaikie8dec4072013-09-19 20:40:26 +00001670 return dwarf::GIEK_TYPE;
Eric Christopherdd1a0122013-09-13 00:35:05 +00001671 case dwarf::DW_TAG_subprogram:
Eric Christopherccac5c42013-09-23 22:59:14 +00001672 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001673 case dwarf::DW_TAG_variable:
Eric Christopherccac5c42013-09-23 22:59:14 +00001674 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001675 case dwarf::DW_TAG_enumerator:
David Blaikie8dec4072013-09-19 20:40:26 +00001676 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1677 dwarf::GIEL_STATIC);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001678 default:
David Blaikie8dec4072013-09-19 20:40:26 +00001679 return dwarf::GIEK_NONE;
Eric Christopherdd1a0122013-09-13 00:35:05 +00001680 }
Eric Christopherdd1a0122013-09-13 00:35:05 +00001681}
1682
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001683/// emitDebugPubSections - Emit visible names and types into debug pubnames and
1684/// pubtypes sections.
1685void DwarfDebug::emitDebugPubSections() {
David Blaikiec3d9e9e2014-03-06 01:42:00 +00001686 for (const auto &NU : CUMap) {
1687 DwarfCompileUnit *TheU = NU.second;
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001688 if (!TheU->hasDwarfPubSections())
David Blaikiece2f1cb2014-03-11 23:35:06 +00001689 continue;
1690
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001691 bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
Krzysztof Parzyszek228daa62013-02-12 18:00:14 +00001692
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001693 Asm->OutStreamer->SwitchSection(
1694 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1695 : Asm->getObjFileLowering().getDwarfPubNamesSection());
1696 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
Krzysztof Parzyszek228daa62013-02-12 18:00:14 +00001697
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001698 Asm->OutStreamer->SwitchSection(
1699 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1700 : Asm->getObjFileLowering().getDwarfPubTypesSection());
1701 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
Krzysztof Parzyszek228daa62013-02-12 18:00:14 +00001702 }
1703}
1704
Alexey Bataevbff36082018-03-23 13:35:54 +00001705void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1706 if (useSectionsAsReferences())
1707 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
1708 CU.getDebugSectionOffset());
1709 else
1710 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
1711}
1712
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001713void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1714 DwarfCompileUnit *TheU,
1715 const StringMap<const DIE *> &Globals) {
1716 if (auto *Skeleton = TheU->getSkeleton())
1717 TheU = Skeleton;
Eric Christopher8b3737f2013-09-13 00:34:58 +00001718
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001719 // Emit the header.
1720 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1721 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1722 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1723 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1724
1725 Asm->OutStreamer->EmitLabel(BeginLabel);
1726
1727 Asm->OutStreamer->AddComment("DWARF Version");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001728 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001729
1730 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
Alexey Bataevbff36082018-03-23 13:35:54 +00001731 emitSectionReference(*TheU);
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001732
1733 Asm->OutStreamer->AddComment("Compilation Unit Length");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001734 Asm->emitInt32(TheU->getLength());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001735
1736 // Emit the pubnames for this compilation unit.
1737 for (const auto &GI : Globals) {
1738 const char *Name = GI.getKeyData();
1739 const DIE *Entity = GI.second;
1740
1741 Asm->OutStreamer->AddComment("DIE offset");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001742 Asm->emitInt32(Entity->getOffset());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001743
1744 if (GnuStyle) {
1745 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1746 Asm->OutStreamer->AddComment(
1747 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1748 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001749 Asm->emitInt8(Desc.toBits());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001750 }
1751
1752 Asm->OutStreamer->AddComment("External Name");
1753 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1754 }
1755
1756 Asm->OutStreamer->AddComment("End Mark");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001757 Asm->emitInt32(0);
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001758 Asm->OutStreamer->EmitLabel(EndLabel);
Devang Patel04d2f2d2009-11-24 01:14:22 +00001759}
1760
Amjad Aboudc0778412016-01-24 08:18:55 +00001761/// Emit null-terminated strings into a debug str section.
Eric Christopher3bf29fd2012-12-27 02:14:01 +00001762void DwarfDebug::emitDebugStr() {
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001763 MCSection *StringOffsetsSection = nullptr;
1764 if (useSegmentedStringOffsetsTable()) {
1765 emitStringOffsetsTableHeader();
1766 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1767 }
Eric Christopherf8194852013-12-05 18:06:10 +00001768 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001769 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1770 StringOffsetsSection, /* UseRelativeOffsets = */ true);
Eric Christopher3bf29fd2012-12-27 02:14:01 +00001771}
1772
Eric Christopher29e874d2014-03-07 22:40:37 +00001773void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001774 const DebugLocStream::Entry &Entry) {
1775 auto &&Comments = DebugLocs.getComments(Entry);
1776 auto Comment = Comments.begin();
1777 auto End = Comments.end();
1778 for (uint8_t Byte : DebugLocs.getBytes(Entry))
Adrian Prantl92da14b2015-03-02 22:02:33 +00001779 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
Adrian Prantlb1416832014-08-01 22:11:58 +00001780}
1781
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001782static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
Adrian Prantl92da14b2015-03-02 22:02:33 +00001783 const DebugLocEntry::Value &Value,
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001784 DwarfExpression &DwarfExpr) {
Adrian Prantl956484b2017-03-20 21:35:09 +00001785 auto *DIExpr = Value.getExpression();
1786 DIExpressionCursor ExprCursor(DIExpr);
1787 DwarfExpr.addFragmentOffset(DIExpr);
Adrian Prantlb1416832014-08-01 22:11:58 +00001788 // Regular entry.
Adrian Prantle19e5ef2014-04-27 18:25:40 +00001789 if (Value.isInt()) {
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001790 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1791 BT->getEncoding() == dwarf::DW_ATE_signed_char))
Adrian Prantla63b8e82017-03-16 17:42:45 +00001792 DwarfExpr.addSignedConstant(Value.getInt());
Adrian Prantl66f25952015-01-13 00:04:06 +00001793 else
Adrian Prantla63b8e82017-03-16 17:42:45 +00001794 DwarfExpr.addUnsignedConstant(Value.getInt());
Adrian Prantle19e5ef2014-04-27 18:25:40 +00001795 } else if (Value.isLocation()) {
Adrian Prantl956484b2017-03-20 21:35:09 +00001796 MachineLocation Location = Value.getLoc();
Adrian Prantlc12cee32017-04-19 23:42:25 +00001797 if (Location.isIndirect())
1798 DwarfExpr.setMemoryLocationKind();
Adrian Prantl2049c0d2017-08-02 15:22:17 +00001799 DIExpressionCursor Cursor(DIExpr);
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001800 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
Adrian Prantlc12cee32017-04-19 23:42:25 +00001801 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
Adrian Prantl956484b2017-03-20 21:35:09 +00001802 return;
1803 return DwarfExpr.addExpression(std::move(Cursor));
Adrian Prantl3e9c8872016-04-08 00:38:37 +00001804 } else if (Value.isConstantFP()) {
1805 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
Adrian Prantla63b8e82017-03-16 17:42:45 +00001806 DwarfExpr.addUnsignedConstant(RawBytes);
Eric Christopher29e874d2014-03-07 22:40:37 +00001807 }
Adrian Prantla63b8e82017-03-16 17:42:45 +00001808 DwarfExpr.addExpression(std::move(ExprCursor));
Eric Christopher29e874d2014-03-07 22:40:37 +00001809}
1810
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001811void DebugLocEntry::finalize(const AsmPrinter &AP,
1812 DebugLocStream::ListBuilder &List,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001813 const DIBasicType *BT) {
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001814 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1815 BufferByteStreamer Streamer = Entry.getStreamer();
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001816 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001817 const DebugLocEntry::Value &Value = Values[0];
Adrian Prantl941fa752016-12-05 18:04:47 +00001818 if (Value.isFragment()) {
1819 // Emit all fragments that belong to the same variable and range.
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00001820 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
Adrian Prantl941fa752016-12-05 18:04:47 +00001821 return P.isFragment();
1822 }) && "all values are expected to be fragments");
Adrian Prantl92da14b2015-03-02 22:02:33 +00001823 assert(std::is_sorted(Values.begin(), Values.end()) &&
Adrian Prantl941fa752016-12-05 18:04:47 +00001824 "fragments are expected to be sorted");
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00001825
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001826 for (auto Fragment : Values)
Petar Jovanovicd175aeb2018-06-28 04:50:40 +00001827 emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001828
Adrian Prantl92da14b2015-03-02 22:02:33 +00001829 } else {
Adrian Prantl941fa752016-12-05 18:04:47 +00001830 assert(Values.size() == 1 && "only fragments may have >1 value");
Petar Jovanovicd175aeb2018-06-28 04:50:40 +00001831 emitDebugLocValue(AP, BT, Value, DwarfExpr);
Adrian Prantl92da14b2015-03-02 22:02:33 +00001832 }
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001833 DwarfExpr.finalize();
Adrian Prantl92da14b2015-03-02 22:02:33 +00001834}
1835
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001836void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
Duncan P. N. Exon Smith653c1092015-05-06 19:11:20 +00001837 // Emit the size.
Lang Hames9ff69c82015-04-24 19:11:51 +00001838 Asm->OutStreamer->AddComment("Loc expr size");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001839 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
Duncan P. N. Exon Smith653c1092015-05-06 19:11:20 +00001840
David Blaikie0e84adc2014-04-01 16:17:41 +00001841 // Emit the entry.
1842 APByteStreamer Streamer(*Asm);
1843 emitDebugLocEntry(Streamer, Entry);
David Blaikie0e84adc2014-04-01 16:17:41 +00001844}
1845
Eric Christopher9046f942013-07-02 21:36:07 +00001846// Emit locations into the debug loc section.
Devang Patel930143b2009-11-21 02:48:08 +00001847void DwarfDebug::emitDebugLoc() {
David Blaikie07963bd2017-05-26 18:52:56 +00001848 if (DebugLocs.getLists().empty())
1849 return;
1850
Daniel Dunbarfd95b012011-03-16 22:16:39 +00001851 // Start the dwarf loc section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001852 Asm->OutStreamer->SwitchSection(
David Blaikie94c1d7f2014-04-02 01:50:20 +00001853 Asm->getObjFileLowering().getDwarfLocSection());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001854 unsigned char Size = Asm->MAI->getCodePointerSize();
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001855 for (const auto &List : DebugLocs.getLists()) {
Lang Hames9ff69c82015-04-24 19:11:51 +00001856 Asm->OutStreamer->EmitLabel(List.Label);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001857 const DwarfCompileUnit *CU = List.CU;
1858 for (const auto &Entry : DebugLocs.getEntries(List)) {
Eric Christopher384f3fe2014-03-20 19:16:16 +00001859 // Set up the range. This range is relative to the entry point of the
1860 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1861 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
David Blaikiece343492014-11-03 21:15:30 +00001862 if (auto *Base = CU->getBaseAddress()) {
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001863 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1864 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
Eric Christopher384f3fe2014-03-20 19:16:16 +00001865 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +00001866 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1867 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
Eric Christopher384f3fe2014-03-20 19:16:16 +00001868 }
David Blaikie94c1d7f2014-04-02 01:50:20 +00001869
David Blaikie0e84adc2014-04-01 16:17:41 +00001870 emitDebugLocEntryLocation(Entry);
Devang Patel9fc11702010-05-25 23:40:22 +00001871 }
Lang Hames9ff69c82015-04-24 19:11:51 +00001872 Asm->OutStreamer->EmitIntValue(0, Size);
1873 Asm->OutStreamer->EmitIntValue(0, Size);
David Blaikie94c1d7f2014-04-02 01:50:20 +00001874 }
1875}
1876
1877void DwarfDebug::emitDebugLocDWO() {
Lang Hames9ff69c82015-04-24 19:11:51 +00001878 Asm->OutStreamer->SwitchSection(
David Blaikie94c1d7f2014-04-02 01:50:20 +00001879 Asm->getObjFileLowering().getDwarfLocDWOSection());
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001880 for (const auto &List : DebugLocs.getLists()) {
Lang Hames9ff69c82015-04-24 19:11:51 +00001881 Asm->OutStreamer->EmitLabel(List.Label);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001882 for (const auto &Entry : DebugLocs.getEntries(List)) {
David Blaikie94c1d7f2014-04-02 01:50:20 +00001883 // Just always use start_length for now - at least that's one address
1884 // rather than two. We could get fancier and try to, say, reuse an
1885 // address we know we've emitted elsewhere (the start of the function?
1886 // The start of the CU or CU subrange that encloses this range?)
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001887 Asm->emitInt8(dwarf::DW_LLE_startx_length);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001888 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
David Blaikie94c1d7f2014-04-02 01:50:20 +00001889 Asm->EmitULEB128(idx);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001890 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
David Blaikie94c1d7f2014-04-02 01:50:20 +00001891
1892 emitDebugLocEntryLocation(Entry);
David Blaikie9c550ac2014-03-25 01:44:02 +00001893 }
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001894 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
Devang Patel9fc11702010-05-25 23:40:22 +00001895 }
Bill Wendling480ff322009-05-20 23:21:38 +00001896}
1897
Richard Mitton21101b32013-09-19 23:21:01 +00001898struct ArangeSpan {
1899 const MCSymbol *Start, *End;
1900};
1901
1902// Emit a debug aranges section, containing a CU lookup for any
1903// address we can tie back to a CU.
Eric Christopher7b30f2e42012-11-21 00:34:35 +00001904void DwarfDebug::emitDebugARanges() {
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00001905 // Provides a unique id per text section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001906 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
Richard Mitton21101b32013-09-19 23:21:01 +00001907
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00001908 // Filter labels by section.
1909 for (const SymbolCU &SCU : ArangeLabels) {
1910 if (SCU.Sym->isInSection()) {
1911 // Make a note of this symbol and it's section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001912 MCSection *Section = &SCU.Sym->getSection();
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00001913 if (!Section->getKind().isMetadata())
1914 SectionMap[Section].push_back(SCU);
1915 } else {
1916 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1917 // appear in the output. This sucks as we rely on sections to build
1918 // arange spans. We can do it without, but it's icky.
1919 SectionMap[nullptr].push_back(SCU);
1920 }
1921 }
Richard Mitton21101b32013-09-19 23:21:01 +00001922
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00001923 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1924
Rafael Espindola4f4ef152015-03-09 22:08:37 +00001925 for (auto &I : SectionMap) {
Rafael Espindola78d947b2016-05-20 00:38:28 +00001926 MCSection *Section = I.first;
Rafael Espindola4f4ef152015-03-09 22:08:37 +00001927 SmallVector<SymbolCU, 8> &List = I.second;
Rafael Espindola78d947b2016-05-20 00:38:28 +00001928 if (List.size() < 1)
Richard Mitton21101b32013-09-19 23:21:01 +00001929 continue;
1930
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00001931 // If we have no section (e.g. common), just write out
1932 // individual spans for each symbol.
1933 if (!Section) {
1934 for (const SymbolCU &Cur : List) {
1935 ArangeSpan Span;
1936 Span.Start = Cur.Sym;
1937 Span.End = nullptr;
Rafael Espindola78d947b2016-05-20 00:38:28 +00001938 assert(Cur.CU);
1939 Spans[Cur.CU].push_back(Span);
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00001940 }
1941 continue;
1942 }
1943
Richard Mitton21101b32013-09-19 23:21:01 +00001944 // Sort the symbols by offset within the section.
Mandeep Singh Grang46d02de2018-02-25 19:52:34 +00001945 std::stable_sort(
Rafael Espindola0a78f8c2016-05-19 23:17:37 +00001946 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1947 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1948 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
Benjamin Kramer571e2fe2014-03-07 19:41:22 +00001949
Rafael Espindola0a78f8c2016-05-19 23:17:37 +00001950 // Symbols with no order assigned should be placed at the end.
1951 // (e.g. section end labels)
1952 if (IA == 0)
1953 return false;
1954 if (IB == 0)
1955 return true;
1956 return IA < IB;
1957 });
Richard Mitton21101b32013-09-19 23:21:01 +00001958
Rafael Espindola78d947b2016-05-20 00:38:28 +00001959 // Insert a final terminator.
1960 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1961
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00001962 // Build spans between each label.
1963 const MCSymbol *StartSym = List[0].Sym;
1964 for (size_t n = 1, e = List.size(); n < e; n++) {
1965 const SymbolCU &Prev = List[n - 1];
1966 const SymbolCU &Cur = List[n];
Richard Mitton21101b32013-09-19 23:21:01 +00001967
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00001968 // Try and build the longest span we can within the same CU.
1969 if (Cur.CU != Prev.CU) {
1970 ArangeSpan Span;
1971 Span.Start = StartSym;
1972 Span.End = Cur.Sym;
Rafael Espindola78d947b2016-05-20 00:38:28 +00001973 assert(Prev.CU);
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00001974 Spans[Prev.CU].push_back(Span);
1975 StartSym = Cur.Sym;
Richard Mitton21101b32013-09-19 23:21:01 +00001976 }
1977 }
1978 }
1979
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00001980 // Start the dwarf aranges section.
Lang Hames9ff69c82015-04-24 19:11:51 +00001981 Asm->OutStreamer->SwitchSection(
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00001982 Asm->getObjFileLowering().getDwarfARangesSection());
1983
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001984 unsigned PtrSize = Asm->MAI->getCodePointerSize();
Richard Mitton21101b32013-09-19 23:21:01 +00001985
1986 // Build a list of CUs used.
Eric Christopher4287a492013-12-09 23:57:44 +00001987 std::vector<DwarfCompileUnit *> CUs;
Benjamin Kramer15596c72014-03-07 19:09:39 +00001988 for (const auto &it : Spans) {
1989 DwarfCompileUnit *CU = it.first;
Richard Mitton21101b32013-09-19 23:21:01 +00001990 CUs.push_back(CU);
1991 }
1992
1993 // Sort the CU list (again, to ensure consistent output order).
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +00001994 llvm::sort(CUs.begin(), CUs.end(),
1995 [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1996 return A->getUniqueID() < B->getUniqueID();
1997 });
Richard Mitton21101b32013-09-19 23:21:01 +00001998
1999 // Emit an arange table for each CU we used.
Benjamin Kramer15596c72014-03-07 19:09:39 +00002000 for (DwarfCompileUnit *CU : CUs) {
Richard Mitton21101b32013-09-19 23:21:01 +00002001 std::vector<ArangeSpan> &List = Spans[CU];
2002
David Blaikie27e35f22014-11-02 01:21:43 +00002003 // Describe the skeleton CU's offset and length, not the dwo file's.
2004 if (auto *Skel = CU->getSkeleton())
2005 CU = Skel;
2006
Richard Mitton21101b32013-09-19 23:21:01 +00002007 // Emit size of content not including length itself.
Eric Christopherb4bef6d2013-11-19 09:04:36 +00002008 unsigned ContentSize =
2009 sizeof(int16_t) + // DWARF ARange version number
2010 sizeof(int32_t) + // Offset of CU in the .debug_info section
2011 sizeof(int8_t) + // Pointer Size (in bytes)
2012 sizeof(int8_t); // Segment Size (in bytes)
Richard Mitton21101b32013-09-19 23:21:01 +00002013
2014 unsigned TupleSize = PtrSize * 2;
2015
2016 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
Benjamin Kramer8a68ab32014-01-07 19:28:14 +00002017 unsigned Padding =
2018 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
Richard Mitton21101b32013-09-19 23:21:01 +00002019
2020 ContentSize += Padding;
2021 ContentSize += (List.size() + 1) * TupleSize;
2022
2023 // For each compile unit, write the list of spans it covers.
Lang Hames9ff69c82015-04-24 19:11:51 +00002024 Asm->OutStreamer->AddComment("Length of ARange Set");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002025 Asm->emitInt32(ContentSize);
Lang Hames9ff69c82015-04-24 19:11:51 +00002026 Asm->OutStreamer->AddComment("DWARF Arange version number");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002027 Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
Lang Hames9ff69c82015-04-24 19:11:51 +00002028 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
Alexey Bataevbff36082018-03-23 13:35:54 +00002029 emitSectionReference(*CU);
Lang Hames9ff69c82015-04-24 19:11:51 +00002030 Asm->OutStreamer->AddComment("Address Size (in bytes)");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002031 Asm->emitInt8(PtrSize);
Lang Hames9ff69c82015-04-24 19:11:51 +00002032 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002033 Asm->emitInt8(0);
Richard Mitton21101b32013-09-19 23:21:01 +00002034
Petr Hosekfaef3202016-06-01 01:59:58 +00002035 Asm->OutStreamer->emitFill(Padding, 0xff);
Richard Mitton21101b32013-09-19 23:21:01 +00002036
Benjamin Kramer15596c72014-03-07 19:09:39 +00002037 for (const ArangeSpan &Span : List) {
Richard Mitton21101b32013-09-19 23:21:01 +00002038 Asm->EmitLabelReference(Span.Start, PtrSize);
2039
2040 // Calculate the size as being from the span start to it's end.
Richard Mitton089ed892013-09-23 17:56:20 +00002041 if (Span.End) {
Richard Mitton21101b32013-09-19 23:21:01 +00002042 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
Richard Mitton089ed892013-09-23 17:56:20 +00002043 } else {
2044 // For symbols without an end marker (e.g. common), we
2045 // write a single arange entry containing just that one symbol.
2046 uint64_t Size = SymSize[Span.Start];
2047 if (Size == 0)
2048 Size = 1;
2049
Lang Hames9ff69c82015-04-24 19:11:51 +00002050 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
Richard Mitton089ed892013-09-23 17:56:20 +00002051 }
Richard Mitton21101b32013-09-19 23:21:01 +00002052 }
2053
Lang Hames9ff69c82015-04-24 19:11:51 +00002054 Asm->OutStreamer->AddComment("ARange terminator");
2055 Asm->OutStreamer->EmitIntValue(0, PtrSize);
2056 Asm->OutStreamer->EmitIntValue(0, PtrSize);
Richard Mitton21101b32013-09-19 23:21:01 +00002057 }
Bill Wendling480ff322009-05-20 23:21:38 +00002058}
2059
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002060/// Emit a single range list. We handle both DWARF v5 and earlier.
Wolfgang Piebe194f732018-07-10 00:10:11 +00002061static void emitRangeList(AsmPrinter *Asm, DwarfCompileUnit *CU,
2062 const RangeSpanList &List) {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002063
2064 auto DwarfVersion = CU->getDwarfVersion();
Wolfgang Piebe194f732018-07-10 00:10:11 +00002065 // Emit our symbol so we can find the beginning of the range.
2066 Asm->OutStreamer->EmitLabel(List.getSym());
2067 // Gather all the ranges that apply to the same section so they can share
2068 // a base address entry.
2069 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges;
2070 // Size for our labels.
2071 auto Size = Asm->MAI->getCodePointerSize();
2072
2073 for (const RangeSpan &Range : List.getRanges())
2074 SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
2075
2076 auto *CUBase = CU->getBaseAddress();
2077 bool BaseIsSet = false;
2078 for (const auto &P : SectionRanges) {
2079 // Don't bother with a base address entry if there's only one range in
2080 // this section in this range list - for example ranges for a CU will
2081 // usually consist of single regions from each of many sections
2082 // (-ffunction-sections, or just C++ inline functions) except under LTO
2083 // or optnone where there may be holes in a single CU's section
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002084 // contributions.
Wolfgang Piebe194f732018-07-10 00:10:11 +00002085 auto *Base = CUBase;
David Blaikied6614052018-07-18 18:04:42 +00002086 if (!Base && P.second.size() > 1 &&
2087 (UseDwarfRangesBaseAddressSpecifier || DwarfVersion >= 5)) {
Wolfgang Piebe194f732018-07-10 00:10:11 +00002088 BaseIsSet = true;
2089 // FIXME/use care: This may not be a useful base address if it's not
2090 // the lowest address/range in this object.
2091 Base = P.second.front()->getStart();
David Blaikied6614052018-07-18 18:04:42 +00002092 if (DwarfVersion >= 5) {
2093 Asm->OutStreamer->AddComment("DW_RLE_base_address");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002094 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_address, 1);
David Blaikied6614052018-07-18 18:04:42 +00002095 } else
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002096 Asm->OutStreamer->EmitIntValue(-1, Size);
David Blaikied6614052018-07-18 18:04:42 +00002097 Asm->OutStreamer->AddComment(" base address");
Wolfgang Piebe194f732018-07-10 00:10:11 +00002098 Asm->OutStreamer->EmitSymbolValue(Base, Size);
David Blaikied6614052018-07-18 18:04:42 +00002099 } else if (BaseIsSet && DwarfVersion < 5) {
Wolfgang Piebe194f732018-07-10 00:10:11 +00002100 BaseIsSet = false;
David Blaikied6614052018-07-18 18:04:42 +00002101 assert(!Base);
2102 Asm->OutStreamer->EmitIntValue(-1, Size);
Wolfgang Piebe194f732018-07-10 00:10:11 +00002103 Asm->OutStreamer->EmitIntValue(0, Size);
2104 }
2105
2106 for (const auto *RS : P.second) {
2107 const MCSymbol *Begin = RS->getStart();
2108 const MCSymbol *End = RS->getEnd();
2109 assert(Begin && "Range without a begin symbol?");
2110 assert(End && "Range without an end symbol?");
2111 if (Base) {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002112 if (DwarfVersion >= 5) {
2113 // Emit DW_RLE_offset_pair when we have a base.
David Blaikied6614052018-07-18 18:04:42 +00002114 Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002115 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
David Blaikied6614052018-07-18 18:04:42 +00002116 Asm->OutStreamer->AddComment(" starting offset");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002117 Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
David Blaikied6614052018-07-18 18:04:42 +00002118 Asm->OutStreamer->AddComment(" ending offset");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002119 Asm->EmitLabelDifferenceAsULEB128(End, Base);
2120 } else {
2121 Asm->EmitLabelDifference(Begin, Base, Size);
2122 Asm->EmitLabelDifference(End, Base, Size);
2123 }
2124 } else if (DwarfVersion >= 5) {
David Blaikied6614052018-07-18 18:04:42 +00002125 Asm->OutStreamer->AddComment("DW_RLE_start_length");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002126 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_start_length, 1);
David Blaikied6614052018-07-18 18:04:42 +00002127 Asm->OutStreamer->AddComment(" start");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002128 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
David Blaikied6614052018-07-18 18:04:42 +00002129 Asm->OutStreamer->AddComment(" length");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002130 Asm->EmitLabelDifferenceAsULEB128(End, Begin);
Wolfgang Piebe194f732018-07-10 00:10:11 +00002131 } else {
2132 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2133 Asm->OutStreamer->EmitSymbolValue(End, Size);
2134 }
2135 }
2136 }
David Blaikied6614052018-07-18 18:04:42 +00002137 if (DwarfVersion >= 5) {
2138 Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002139 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
David Blaikied6614052018-07-18 18:04:42 +00002140 } else {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002141 // Terminate the list with two 0 values.
2142 Asm->OutStreamer->EmitIntValue(0, Size);
2143 Asm->OutStreamer->EmitIntValue(0, Size);
2144 }
Wolfgang Piebe194f732018-07-10 00:10:11 +00002145}
2146
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002147// Emit the header of a DWARF 5 range list table. Returns the symbol that
2148// designates the end of the table for the caller to emit when the table is
2149// complete.
2150static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm, DwarfFile &Holder) {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002151 // The length is described by a starting label right after the length field
2152 // and an end label.
2153 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2154 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2155 // Build the range table header, which starts with the length field.
2156 Asm->EmitLabelDifference(TableEnd, TableStart, 4);
2157 Asm->OutStreamer->EmitLabel(TableStart);
2158 // Version number (DWARF v5 and later).
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002159 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002160 // Address size.
2161 Asm->emitInt8(Asm->MAI->getCodePointerSize());
2162 // Segment selector size.
2163 Asm->emitInt8(0);
2164
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002165 MCSymbol *RnglistTableBaseSym = Holder.getRnglistsTableBaseSym();
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002166
2167 // FIXME: Generate the offsets table and use DW_FORM_rnglistx with the
2168 // DW_AT_ranges attribute. Until then set the number of offsets to 0.
2169 Asm->emitInt32(0);
2170 Asm->OutStreamer->EmitLabel(RnglistTableBaseSym);
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002171 return TableEnd;
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002172}
2173
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002174/// Emit address ranges into the .debug_ranges section or into the DWARF v5
2175/// .debug_rnglists section.
Devang Patel930143b2009-11-21 02:48:08 +00002176void DwarfDebug::emitDebugRanges() {
David Blaikie07963bd2017-05-26 18:52:56 +00002177 if (CUMap.empty())
2178 return;
2179
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002180 auto NoRangesPresent = [this]() {
2181 return llvm::all_of(
2182 CUMap, [](const decltype(CUMap)::const_iterator::value_type &Pair) {
2183 return Pair.second->getRangeLists().empty();
2184 });
2185 };
2186
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002187 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2188 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2189 })) {
2190 assert(NoRangesPresent() && "No debug ranges expected.");
2191 return;
2192 }
2193
Alexey Bataev858a7dd2018-03-20 20:21:38 +00002194 if (!useRangesSection()) {
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002195 assert(NoRangesPresent() && "No debug ranges expected.");
Alexey Bataev858a7dd2018-03-20 20:21:38 +00002196 return;
2197 }
2198
Wolfgang Piebbaf94f82018-07-31 20:56:32 +00002199 if (NoRangesPresent())
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002200 return;
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002201
Bill Wendling480ff322009-05-20 23:21:38 +00002202 // Start the dwarf ranges section.
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002203 MCSymbol *TableEnd = nullptr;
2204 if (getDwarfVersion() >= 5) {
2205 Asm->OutStreamer->SwitchSection(
2206 Asm->getObjFileLowering().getDwarfRnglistsSection());
2207 TableEnd = emitRnglistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder
2208 : InfoHolder);
2209 } else
2210 Asm->OutStreamer->SwitchSection(
2211 Asm->getObjFileLowering().getDwarfRangesSection());
Eric Christopher4751d702013-11-23 00:05:29 +00002212
Eric Christopher0f63d062013-12-03 00:45:45 +00002213 // Grab the specific ranges for the compile units in the module.
Benjamin Kramer15596c72014-03-07 19:09:39 +00002214 for (const auto &I : CUMap) {
2215 DwarfCompileUnit *TheCU = I.second;
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002216 if (TheCU->getCUNode()->isDebugDirectivesOnly())
2217 continue;
Eric Christopher0f63d062013-12-03 00:45:45 +00002218
David Blaikie3a443c22014-11-04 22:12:25 +00002219 if (auto *Skel = TheCU->getSkeleton())
2220 TheCU = Skel;
2221
Eric Christopher0f63d062013-12-03 00:45:45 +00002222 // Iterate over the misc ranges for the compile units in the module.
Wolfgang Piebe194f732018-07-10 00:10:11 +00002223 for (const RangeSpanList &List : TheCU->getRangeLists())
2224 emitRangeList(Asm, TheCU, List);
Devang Patel12563b32010-04-16 23:33:45 +00002225 }
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002226
2227 if (TableEnd)
2228 Asm->OutStreamer->EmitLabel(TableEnd);
Bill Wendling480ff322009-05-20 23:21:38 +00002229}
2230
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002231void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002232 for (auto *MN : Nodes) {
2233 if (auto *M = dyn_cast<DIMacro>(MN))
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002234 emitMacro(*M);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002235 else if (auto *F = dyn_cast<DIMacroFile>(MN))
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002236 emitMacroFile(*F, U);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002237 else
2238 llvm_unreachable("Unexpected DI type!");
2239 }
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002240}
2241
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002242void DwarfDebug::emitMacro(DIMacro &M) {
2243 Asm->EmitULEB128(M.getMacinfoType());
2244 Asm->EmitULEB128(M.getLine());
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002245 StringRef Name = M.getName();
2246 StringRef Value = M.getValue();
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002247 Asm->OutStreamer->EmitBytes(Name);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002248 if (!Value.empty()) {
2249 // There should be one space between macro name and macro value.
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002250 Asm->emitInt8(' ');
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002251 Asm->OutStreamer->EmitBytes(Value);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002252 }
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002253 Asm->emitInt8('\0');
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002254}
2255
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002256void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002257 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002258 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2259 Asm->EmitULEB128(F.getLine());
Paul Robinson612e89d2018-01-12 19:17:50 +00002260 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002261 handleMacroNodes(F.getElements(), U);
2262 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002263}
2264
Amjad Aboudc0778412016-01-24 08:18:55 +00002265/// Emit macros into a debug macinfo section.
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002266void DwarfDebug::emitDebugMacinfo() {
David Blaikie07963bd2017-05-26 18:52:56 +00002267 if (CUMap.empty())
2268 return;
2269
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002270 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2271 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2272 }))
2273 return;
2274
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002275 // Start the dwarf macinfo section.
2276 Asm->OutStreamer->SwitchSection(
2277 Asm->getObjFileLowering().getDwarfMacinfoSection());
2278
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002279 for (const auto &P : CUMap) {
2280 auto &TheCU = *P.second;
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002281 if (TheCU.getCUNode()->isDebugDirectivesOnly())
2282 continue;
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002283 auto *SkCU = TheCU.getSkeleton();
2284 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2285 auto *CUNode = cast<DICompileUnit>(P.first);
Alexey Bataevbd7869442018-02-22 16:20:30 +00002286 DIMacroNodeArray Macros = CUNode->getMacros();
2287 if (!Macros.empty()) {
2288 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2289 handleMacroNodes(Macros, U);
2290 }
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002291 }
2292 Asm->OutStreamer->AddComment("End Of Macro List Mark");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002293 Asm->emitInt8(0);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002294}
2295
Eric Christopherd692c1d2012-12-11 19:42:09 +00002296// DWARF5 Experimental Separate Dwarf emitters.
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002297
David Blaikie65a74662014-04-25 18:26:14 +00002298void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002299 std::unique_ptr<DwarfCompileUnit> NewU) {
David Blaikiecafd9622014-11-02 08:51:37 +00002300 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
David Blaikie96b1ed52017-04-21 23:35:26 +00002301 Asm->TM.Options.MCOptions.SplitDwarfFile);
David Blaikie38fe6342014-01-09 04:28:46 +00002302
David Blaikie38fe6342014-01-09 04:28:46 +00002303 if (!CompilationDir.empty())
David Blaikiecafd9622014-11-02 08:51:37 +00002304 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
David Blaikie38fe6342014-01-09 04:28:46 +00002305
David Blaikief9b6a552014-04-22 22:39:41 +00002306 addGnuPubAttributes(*NewU, Die);
David Blaikie38fe6342014-01-09 04:28:46 +00002307
David Blaikief9b6a552014-04-22 22:39:41 +00002308 SkeletonHolder.addUnit(std::move(NewU));
David Blaikie38fe6342014-01-09 04:28:46 +00002309}
2310
David Blaikief9b6a552014-04-22 22:39:41 +00002311DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002312
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00002313 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
David Blaikiebd579052014-04-28 21:14:27 +00002314 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
David Blaikief9b6a552014-04-22 22:39:41 +00002315 DwarfCompileUnit &NewCU = *OwnedUnit;
Greg Clayton35630c32016-12-01 18:56:29 +00002316 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
Eric Christopher4c7765f2013-01-17 03:00:04 +00002317
Rafael Espindola063d7252015-03-10 16:58:10 +00002318 NewCU.initStmtList();
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002319
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002320 if (useSegmentedStringOffsetsTable())
2321 NewCU.addStringOffsetsStart();
2322
David Blaikie92a2f8a2014-04-28 21:04:29 +00002323 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
Eric Christopherc8a310e2012-12-10 23:34:43 +00002324
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002325 return NewCU;
2326}
2327
Eric Christopherd692c1d2012-12-11 19:42:09 +00002328// Emit the .debug_info.dwo section for separated dwarf. This contains the
2329// compile units that would normally be in debug_info.
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002330void DwarfDebug::emitDebugInfoDWO() {
Eric Christophercdf218d2012-12-10 19:51:21 +00002331 assert(useSplitDwarf() && "No split dwarf debug info?");
Rafael Espindola063d7252015-03-10 16:58:10 +00002332 // Don't emit relocations into the dwo file.
2333 InfoHolder.emitUnits(/* UseOffsets */ true);
Eric Christopher3c5a1912012-12-19 22:02:53 +00002334}
2335
2336// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2337// abbreviations for the .debug_info.dwo section.
2338void DwarfDebug::emitDebugAbbrevDWO() {
2339 assert(useSplitDwarf() && "No split dwarf?");
David Blaikie0504cda2013-12-05 07:43:55 +00002340 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002341}
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002342
David Blaikie4a2f95f2014-03-18 01:17:26 +00002343void DwarfDebug::emitDebugLineDWO() {
2344 assert(useSplitDwarf() && "No split dwarf?");
Paul Robinson7cb26ad2018-03-27 21:28:59 +00002345 SplitTypeUnitFileTable.Emit(
2346 *Asm->OutStreamer, MCDwarfLineTableParams(),
David Blaikie4a2f95f2014-03-18 01:17:26 +00002347 Asm->getObjFileLowering().getDwarfLineDWOSection());
David Blaikie4a2f95f2014-03-18 01:17:26 +00002348}
2349
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002350void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2351 assert(useSplitDwarf() && "No split dwarf?");
Pavel Labath7bfa5d62018-07-26 14:36:07 +00002352 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2353 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2354 InfoHolder.getStringOffsetsStartSym());
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002355}
2356
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002357// Emit the .debug_str.dwo section for separated dwarf. This contains the
2358// string section and is identical in format to traditional .debug_str
2359// sections.
2360void DwarfDebug::emitDebugStrDWO() {
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002361 if (useSegmentedStringOffsetsTable())
2362 emitStringOffsetsTableHeaderDWO();
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002363 assert(useSplitDwarf() && "No split dwarf?");
Rafael Espindola0709a7b2015-05-21 19:20:38 +00002364 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
Eric Christopher2cbd5762013-01-07 19:32:41 +00002365 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002366 OffSec, /* UseRelativeOffsets = */ false);
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002367}
David Blaikie409dd9c2013-11-19 23:08:21 +00002368
Victor Leschuk64e0c562018-08-01 05:48:06 +00002369// Emit DWO addresses.
2370void DwarfDebug::emitDebugAddr() {
2371 assert(useSplitDwarf() && "No split dwarf?");
2372 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2373}
2374
David Blaikie47f4b822014-03-19 00:11:28 +00002375MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2376 if (!useSplitDwarf())
2377 return nullptr;
Paul Robinsonb271f312018-03-29 17:16:41 +00002378 const DICompileUnit *DIUnit = CU.getCUNode();
2379 SplitTypeUnitFileTable.maybeSetRootFile(
2380 DIUnit->getDirectory(), DIUnit->getFilename(),
2381 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
David Blaikie47f4b822014-03-19 00:11:28 +00002382 return &SplitTypeUnitFileTable;
2383}
2384
Adrian Prantlee5feaf2015-07-15 17:01:41 +00002385uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
David Blaikief3de2ab2014-04-26 16:26:41 +00002386 MD5 Hash;
2387 Hash.update(Identifier);
2388 // ... take the least significant 8 bytes and return those. Our MD5
Zachary Turner82a0c972017-03-20 23:33:18 +00002389 // implementation always returns its results in little endian, so we actually
2390 // need the "high" word.
David Blaikief3de2ab2014-04-26 16:26:41 +00002391 MD5::MD5Result Result;
2392 Hash.final(Result);
Zachary Turner82a0c972017-03-20 23:33:18 +00002393 return Result.high();
David Blaikief3de2ab2014-04-26 16:26:41 +00002394}
2395
David Blaikie15632ae2014-02-12 00:31:30 +00002396void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
David Blaikie65a74662014-04-25 18:26:14 +00002397 StringRef Identifier, DIE &RefDie,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002398 const DICompositeType *CTy) {
David Blaikiee12b49a2014-04-26 17:27:38 +00002399 // Fast path if we're building some type units and one has already used the
2400 // address pool we know we're going to throw away all this work anyway, so
2401 // don't bother building dependent types.
2402 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2403 return;
2404
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002405 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2406 if (!Ins.second) {
2407 CU.addDIETypeSignature(RefDie, Ins.first->second);
Chandler Carruthb587ab62014-01-20 08:07:07 +00002408 return;
David Blaikie409dd9c2013-11-19 23:08:21 +00002409 }
2410
David Blaikiee12b49a2014-04-26 17:27:38 +00002411 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2412 AddrPool.resetUsedFlag();
2413
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00002414 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2415 getDwoLineTable(CU));
David Blaikief9b6a552014-04-22 22:39:41 +00002416 DwarfTypeUnit &NewTU = *OwnedUnit;
David Blaikie92a2f8a2014-04-28 21:04:29 +00002417 DIE &UnitDie = NewTU.getUnitDie();
David Majnemer0a16c222016-08-11 21:15:00 +00002418 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
Chandler Carruthb587ab62014-01-20 08:07:07 +00002419
David Blaikie92a2f8a2014-04-28 21:04:29 +00002420 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
David Blaikie637cac42014-04-22 23:09:36 +00002421 CU.getLanguage());
Chandler Carruthb587ab62014-01-20 08:07:07 +00002422
David Blaikief3de2ab2014-04-26 16:26:41 +00002423 uint64_t Signature = makeTypeSignature(Identifier);
David Blaikief9b6a552014-04-22 22:39:41 +00002424 NewTU.setTypeSignature(Signature);
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002425 Ins.first->second = Signature;
David Blaikief3de2ab2014-04-26 16:26:41 +00002426
David Blaikie29459ae2014-07-25 17:11:58 +00002427 if (useSplitDwarf())
Greg Clayton35630c32016-12-01 18:56:29 +00002428 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
David Blaikie29459ae2014-07-25 17:11:58 +00002429 else {
Greg Clayton35630c32016-12-01 18:56:29 +00002430 NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
Paul Robinson7cb26ad2018-03-27 21:28:59 +00002431 // Non-split type units reuse the compile unit's line table.
2432 CU.applyStmtList(UnitDie);
David Blaikie29459ae2014-07-25 17:11:58 +00002433 }
Chandler Carruthb587ab62014-01-20 08:07:07 +00002434
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002435 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2436 // units.
2437 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2438 NewTU.addStringOffsetsStart();
2439
David Blaikief3de2ab2014-04-26 16:26:41 +00002440 NewTU.setType(NewTU.createTypeDIE(CTy));
2441
David Blaikiee12b49a2014-04-26 17:27:38 +00002442 if (TopLevelType) {
2443 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2444 TypeUnitsUnderConstruction.clear();
2445
2446 // Types referencing entries in the address table cannot be placed in type
2447 // units.
2448 if (AddrPool.hasBeenUsed()) {
2449
2450 // Remove all the types built while building this type.
2451 // This is pessimistic as some of these types might not be dependent on
2452 // the type that used an address.
2453 for (const auto &TU : TypeUnitsToAdd)
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002454 TypeSignatures.erase(TU.second);
David Blaikiee12b49a2014-04-26 17:27:38 +00002455
2456 // Construct this type in the CU directly.
2457 // This is inefficient because all the dependent types will be rebuilt
2458 // from scratch, including building them in type units, discovering that
2459 // they depend on addresses, throwing them out and rebuilding them.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002460 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
David Blaikiee12b49a2014-04-26 17:27:38 +00002461 return;
2462 }
2463
2464 // If the type wasn't dependent on fission addresses, finish adding the type
2465 // and all its dependent types.
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002466 for (auto &TU : TypeUnitsToAdd) {
2467 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2468 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2469 }
David Blaikiee12b49a2014-04-26 17:27:38 +00002470 }
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002471 CU.addDIETypeSignature(RefDie, Signature);
David Blaikie409dd9c2013-11-19 23:08:21 +00002472}
David Blaikie4bd13b72014-03-07 18:49:45 +00002473
Pavel Labath7f7e6062018-07-20 15:24:13 +00002474// Add the Name along with its companion DIE to the appropriate accelerator
2475// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
2476// AccelTableKind::Apple, we use the table we got as an argument). If
2477// accelerator tables are disabled, this function does nothing.
2478template <typename DataT>
2479void DwarfDebug::addAccelNameImpl(AccelTable<DataT> &AppleAccel, StringRef Name,
2480 const DIE &Die) {
2481 if (getAccelTableKind() == AccelTableKind::None)
2482 return;
Pavel Labath3fb39c72018-04-18 12:11:59 +00002483
2484 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Pavel Labath2f088112018-08-07 09:54:52 +00002485 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
Pavel Labath3fb39c72018-04-18 12:11:59 +00002486
Pavel Labath6088c232018-04-04 14:42:14 +00002487 switch (getAccelTableKind()) {
2488 case AccelTableKind::Apple:
Pavel Labath7f7e6062018-07-20 15:24:13 +00002489 AppleAccel.addName(Ref, Die);
Pavel Labath6088c232018-04-04 14:42:14 +00002490 break;
2491 case AccelTableKind::Dwarf:
Pavel Labath7f7e6062018-07-20 15:24:13 +00002492 AccelDebugNames.addName(Ref, Die);
Pavel Labath6088c232018-04-04 14:42:14 +00002493 break;
Pavel Labath6088c232018-04-04 14:42:14 +00002494 case AccelTableKind::Default:
2495 llvm_unreachable("Default should have already been resolved.");
Pavel Labath7f7e6062018-07-20 15:24:13 +00002496 case AccelTableKind::None:
2497 llvm_unreachable("None handled above");
Pavel Labath6088c232018-04-04 14:42:14 +00002498 }
David Blaikie2406a0622014-04-23 23:37:35 +00002499}
David Blaikie0ee82b92014-04-24 00:53:32 +00002500
Pavel Labath7f7e6062018-07-20 15:24:13 +00002501void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2502 addAccelNameImpl(AccelNames, Name, Die);
2503}
2504
David Blaikieb0b3fcf2014-04-25 18:52:29 +00002505void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
Pavel Labath7f7e6062018-07-20 15:24:13 +00002506 // ObjC names go only into the Apple accelerator tables.
2507 if (getAccelTableKind() == AccelTableKind::Apple)
2508 addAccelNameImpl(AccelObjC, Name, Die);
David Blaikie0ee82b92014-04-24 00:53:32 +00002509}
David Blaikieecf04152014-04-24 01:02:42 +00002510
David Blaikieb0b3fcf2014-04-25 18:52:29 +00002511void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
Pavel Labath7f7e6062018-07-20 15:24:13 +00002512 addAccelNameImpl(AccelNamespace, Name, Die);
David Blaikieecf04152014-04-24 01:02:42 +00002513}
David Blaikie18d33752014-04-24 01:23:49 +00002514
David Blaikieb0b3fcf2014-04-25 18:52:29 +00002515void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
Pavel Labath7f7e6062018-07-20 15:24:13 +00002516 addAccelNameImpl(AccelTypes, Name, Die);
David Blaikie18d33752014-04-24 01:23:49 +00002517}
Greg Claytone6543972016-11-23 23:30:37 +00002518
2519uint16_t DwarfDebug::getDwarfVersion() const {
2520 return Asm->OutStreamer->getContext().getDwarfVersion();
2521}