Thanks to visit codestin.com
Credit goes to llvm.org

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