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