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