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