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