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