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