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)
1152 return;
1153
1154 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1155 M->debug_compile_units_end());
1156 if (NumDebugCUs == 0)
1157 return;
1158
1159 assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1160 SingleCU = NumDebugCUs == 1;
1162 GVMap;
1163 for (const GlobalVariable &Global : M->globals()) {
1165 Global.getDebugInfo(GVs);
1166 for (auto *GVE : GVs)
1167 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1168 }
1169
1170 // Create the symbol that designates the start of the unit's contribution
1171 // to the string offsets table. In a split DWARF scenario, only the skeleton
1172 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1174 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1175 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1176
1177
1178 // Create the symbols that designates the start of the DWARF v5 range list
1179 // and locations list tables. They are located past the table headers.
1180 if (getDwarfVersion() >= 5) {
1181 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1183 Asm->createTempSymbol("rnglists_table_base"));
1184
1185 if (useSplitDwarf())
1186 InfoHolder.setRnglistsTableBaseSym(
1187 Asm->createTempSymbol("rnglists_dwo_table_base"));
1188 }
1189
1190 // Create the symbol that points to the first entry following the debug
1191 // address table (.debug_addr) header.
1192 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1193 DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1194
1195 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1196 if (CUNode->getImportedEntities().empty() &&
1197 CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1198 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1199 continue;
1200
1201 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1202
1203 // Global Variables.
1204 for (auto *GVE : CUNode->getGlobalVariables()) {
1205 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1206 // already know about the variable and it isn't adding a constant
1207 // expression.
1208 auto &GVMapEntry = GVMap[GVE->getVariable()];
1209 auto *Expr = GVE->getExpression();
1210 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1211 GVMapEntry.push_back({nullptr, Expr});
1212 }
1213
1215 for (auto *GVE : CUNode->getGlobalVariables()) {
1216 DIGlobalVariable *GV = GVE->getVariable();
1217 if (Processed.insert(GV).second)
1218 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1219 }
1220
1221 for (auto *Ty : CUNode->getEnumTypes())
1222 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1223
1224 for (auto *Ty : CUNode->getRetainedTypes()) {
1225 // The retained types array by design contains pointers to
1226 // MDNodes rather than DIRefs. Unique them here.
1227 if (DIType *RT = dyn_cast<DIType>(Ty))
1228 // There is no point in force-emitting a forward declaration.
1229 CU.getOrCreateTypeDIE(RT);
1230 }
1231 }
1232}
1233
1234void DwarfDebug::finishEntityDefinitions() {
1235 for (const auto &Entity : ConcreteEntities) {
1236 DIE *Die = Entity->getDIE();
1237 assert(Die);
1238 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1239 // in the ConcreteEntities list, rather than looking it up again here.
1240 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1241 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1242 assert(Unit);
1243 Unit->finishEntityDefinition(Entity.get());
1244 }
1245}
1246
1247void DwarfDebug::finishSubprogramDefinitions() {
1248 for (const DISubprogram *SP : ProcessedSPNodes) {
1249 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1250 forBothCUs(
1251 getOrCreateDwarfCompileUnit(SP->getUnit()),
1252 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1253 }
1254}
1255
1256void DwarfDebug::finalizeModuleInfo() {
1258
1259 finishSubprogramDefinitions();
1260
1261 finishEntityDefinitions();
1262
1263 bool HasEmittedSplitCU = false;
1264
1265 // Handle anything that needs to be done on a per-unit basis after
1266 // all other generation.
1267 for (const auto &P : CUMap) {
1268 auto &TheCU = *P.second;
1269 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1270 continue;
1271 // Emit DW_AT_containing_type attribute to connect types with their
1272 // vtable holding type.
1273 TheCU.constructContainingTypeDIEs();
1274
1275 // Add CU specific attributes if we need to add any.
1276 // If we're splitting the dwarf out now that we've got the entire
1277 // CU then add the dwo id to it.
1278 auto *SkCU = TheCU.getSkeleton();
1279
1280 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1281
1282 if (HasSplitUnit) {
1283 (void)HasEmittedSplitCU;
1284 assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
1285 "Multiple CUs emitted into a single dwo file");
1286 HasEmittedSplitCU = true;
1287 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1288 ? dwarf::DW_AT_dwo_name
1289 : dwarf::DW_AT_GNU_dwo_name;
1290 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1292 TheCU.addString(TheCU.getUnitDie(), attrDWOName, DWOName);
1293 SkCU->addString(SkCU->getUnitDie(), attrDWOName, DWOName);
1294 // Emit a unique identifier for this CU. Include the DWO file name in the
1295 // hash to avoid the case where two (almost) empty compile units have the
1296 // same contents. This can happen if link-time optimization removes nearly
1297 // all (unused) code from a CU.
1298 uint64_t ID =
1299 DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1300 if (getDwarfVersion() >= 5) {
1301 TheCU.setDWOId(ID);
1302 SkCU->setDWOId(ID);
1303 } else {
1304 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1305 dwarf::DW_FORM_data8, ID);
1306 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1307 dwarf::DW_FORM_data8, ID);
1308 }
1309
1310 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1312 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1313 Sym, Sym);
1314 }
1315 } else if (SkCU) {
1316 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1317 }
1318
1319 // If we have code split among multiple sections or non-contiguous
1320 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1321 // remain in the .o file, otherwise add a DW_AT_low_pc.
1322 // FIXME: We should use ranges allow reordering of code ala
1323 // .subsections_via_symbols in mach-o. This would mean turning on
1324 // ranges for all subprogram DIEs for mach-o.
1325 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1326
1327 if (unsigned NumRanges = TheCU.getRanges().size()) {
1328 if (NumRanges > 1 && useRangesSection())
1329 // A DW_AT_low_pc attribute may also be specified in combination with
1330 // DW_AT_ranges to specify the default base address for use in
1331 // location lists (see Section 2.6.2) and range lists (see Section
1332 // 2.17.3).
1333 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1334 else
1335 U.setBaseAddress(TheCU.getRanges().front().Begin);
1336 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1337 }
1338
1339 // We don't keep track of which addresses are used in which CU so this
1340 // is a bit pessimistic under LTO.
1341 if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1342 U.addAddrTableBase();
1343
1344 if (getDwarfVersion() >= 5) {
1345 if (U.hasRangeLists())
1346 U.addRnglistsBase();
1347
1348 if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
1349 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1350 DebugLocs.getSym(),
1352 }
1353 }
1354
1355 auto *CUNode = cast<DICompileUnit>(P.first);
1356 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1357 // attribute.
1358 if (CUNode->getMacros()) {
1359 if (UseDebugMacroSection) {
1360 if (useSplitDwarf())
1361 TheCU.addSectionDelta(
1362 TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
1364 else {
1365 dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1366 ? dwarf::DW_AT_macros
1367 : dwarf::DW_AT_GNU_macros;
1368 U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
1370 }
1371 } else {
1372 if (useSplitDwarf())
1373 TheCU.addSectionDelta(
1374 TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1375 U.getMacroLabelBegin(),
1377 else
1378 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1379 U.getMacroLabelBegin(),
1381 }
1382 }
1383 }
1384
1385 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1386 for (auto *CUNode : MMI->getModule()->debug_compile_units())
1387 if (CUNode->getDWOId())
1388 getOrCreateDwarfCompileUnit(CUNode);
1389
1390 // Compute DIE offsets and sizes.
1391 InfoHolder.computeSizeAndOffsets();
1392 if (useSplitDwarf())
1393 SkeletonHolder.computeSizeAndOffsets();
1394
1395 // Now that offsets are computed, can replace DIEs in debug_names Entry with
1396 // an actual offset.
1397 AccelDebugNames.convertDieToOffset();
1398}
1399
1400// Emit all Dwarf sections that should come after the content.
1402 // Terminate the pending line table.
1403 if (PrevCU)
1404 terminateLineTable(PrevCU);
1405 PrevCU = nullptr;
1406 assert(CurFn == nullptr);
1407 assert(CurMI == nullptr);
1408
1409 for (const auto &P : CUMap) {
1410 const auto *CUNode = cast<DICompileUnit>(P.first);
1411 DwarfCompileUnit *CU = &*P.second;
1412
1413 // Emit imported entities.
1414 for (auto *IE : CUNode->getImportedEntities()) {
1415 assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
1416 "Unexpected function-local entity in 'imports' CU field.");
1417 CU->getOrCreateImportedEntityDIE(IE);
1418 }
1419 for (const auto *D : CU->getDeferredLocalDecls()) {
1420 if (auto *IE = dyn_cast<DIImportedEntity>(D))
1421 CU->getOrCreateImportedEntityDIE(IE);
1422 else
1423 llvm_unreachable("Unexpected local retained node!");
1424 }
1425
1426 // Emit base types.
1427 CU->createBaseTypeDIEs();
1428 }
1429
1430 // If we aren't actually generating debug info (check beginModule -
1431 // conditionalized on the presence of the llvm.dbg.cu metadata node)
1432 if (!Asm || !Asm->hasDebugInfo())
1433 return;
1434
1435 // Finalize the debug info for the module.
1436 finalizeModuleInfo();
1437
1438 if (useSplitDwarf())
1439 // Emit debug_loc.dwo/debug_loclists.dwo section.
1440 emitDebugLocDWO();
1441 else
1442 // Emit debug_loc/debug_loclists section.
1443 emitDebugLoc();
1444
1445 // Corresponding abbreviations into a abbrev section.
1446 emitAbbreviations();
1447
1448 // Emit all the DIEs into a debug info section.
1449 emitDebugInfo();
1450
1451 // Emit info into a debug aranges section.
1452 if (UseARangesSection)
1453 emitDebugARanges();
1454
1455 // Emit info into a debug ranges section.
1456 emitDebugRanges();
1457
1458 if (useSplitDwarf())
1459 // Emit info into a debug macinfo.dwo section.
1460 emitDebugMacinfoDWO();
1461 else
1462 // Emit info into a debug macinfo/macro section.
1463 emitDebugMacinfo();
1464
1465 emitDebugStr();
1466
1467 if (useSplitDwarf()) {
1468 emitDebugStrDWO();
1469 emitDebugInfoDWO();
1470 emitDebugAbbrevDWO();
1471 emitDebugLineDWO();
1472 emitDebugRangesDWO();
1473 }
1474
1475 emitDebugAddr();
1476
1477 // Emit info into the dwarf accelerator table sections.
1478 switch (getAccelTableKind()) {
1480 emitAccelNames();
1481 emitAccelObjC();
1482 emitAccelNamespaces();
1483 emitAccelTypes();
1484 break;
1486 emitAccelDebugNames();
1487 break;
1489 break;
1491 llvm_unreachable("Default should have already been resolved.");
1492 }
1493
1494 // Emit the pubnames and pubtypes sections if requested.
1495 emitDebugPubSections();
1496
1497 // clean up.
1498 // FIXME: AbstractVariables.clear();
1499}
1500
1501void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1502 const DINode *Node, const MDNode *ScopeNode) {
1503 if (CU.getExistingAbstractEntity(Node))
1504 return;
1505
1506 if (LexicalScope *Scope =
1507 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1508 CU.createAbstractEntity(Node, Scope);
1509}
1510
1512 const DIScope *S;
1513 if (const auto *LV = dyn_cast<DILocalVariable>(N))
1514 S = LV->getScope();
1515 else if (const auto *L = dyn_cast<DILabel>(N))
1516 S = L->getScope();
1517 else if (const auto *IE = dyn_cast<DIImportedEntity>(N))
1518 S = IE->getScope();
1519 else
1520 llvm_unreachable("Unexpected retained node!");
1521
1522 // Ensure the scope is not a DILexicalBlockFile.
1523 return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();
1524}
1525
1526// Collect variable information from side table maintained by MF.
1527void DwarfDebug::collectVariableInfoFromMFTable(
1528 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1530 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1531 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1532 if (!VI.Var)
1533 continue;
1534 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1535 "Expected inlined-at fields to agree");
1536
1537 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1538 Processed.insert(Var);
1540
1541 // If variable scope is not found then skip this variable.
1542 if (!Scope) {
1543 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1544 << ", no variable scope found\n");
1545 continue;
1546 }
1547
1548 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1549
1550 // If we have already seen information for this variable, add to what we
1551 // already know.
1552 if (DbgVariable *PreviousLoc = MFVars.lookup(Var)) {
1553 auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
1554 auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
1555 // Previous and new locations are both stack slots (MMI).
1556 if (PreviousMMI && VI.inStackSlot())
1557 PreviousMMI->addFrameIndexExpr(VI.Expr, VI.getStackSlot());
1558 // Previous and new locations are both entry values.
1559 else if (PreviousEntryValue && VI.inEntryValueRegister())
1560 PreviousEntryValue->addExpr(VI.getEntryValueRegister(), *VI.Expr);
1561 else {
1562 // Locations differ, this should (rarely) happen in optimized async
1563 // coroutines.
1564 // Prefer whichever location has an EntryValue.
1565 if (PreviousLoc->holds<Loc::MMI>())
1566 PreviousLoc->emplace<Loc::EntryValue>(VI.getEntryValueRegister(),
1567 *VI.Expr);
1568 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1569 << ", conflicting fragment location types\n");
1570 }
1571 continue;
1572 }
1573
1574 auto RegVar = std::make_unique<DbgVariable>(
1575 cast<DILocalVariable>(Var.first), Var.second);
1576 if (VI.inStackSlot())
1577 RegVar->emplace<Loc::MMI>(VI.Expr, VI.getStackSlot());
1578 else
1579 RegVar->emplace<Loc::EntryValue>(VI.getEntryValueRegister(), *VI.Expr);
1580 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1581 << "\n");
1582 InfoHolder.addScopeVariable(Scope, RegVar.get());
1583 MFVars.insert({Var, RegVar.get()});
1584 ConcreteEntities.push_back(std::move(RegVar));
1585 }
1586}
1587
1588/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1589/// enclosing lexical scope. The check ensures there are no other instructions
1590/// in the same lexical scope preceding the DBG_VALUE and that its range is
1591/// either open or otherwise rolls off the end of the scope.
1592static bool validThroughout(LexicalScopes &LScopes,
1593 const MachineInstr *DbgValue,
1594 const MachineInstr *RangeEnd,
1595 const InstructionOrdering &Ordering) {
1596 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1597 auto MBB = DbgValue->getParent();
1598 auto DL = DbgValue->getDebugLoc();
1599 auto *LScope = LScopes.findLexicalScope(DL);
1600 // Scope doesn't exist; this is a dead DBG_VALUE.
1601 if (!LScope)
1602 return false;
1603 auto &LSRange = LScope->getRanges();
1604 if (LSRange.size() == 0)
1605 return false;
1606
1607 const MachineInstr *LScopeBegin = LSRange.front().first;
1608 // If the scope starts before the DBG_VALUE then we may have a negative
1609 // result. Otherwise the location is live coming into the scope and we
1610 // can skip the following checks.
1611 if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1612 // Exit if the lexical scope begins outside of the current block.
1613 if (LScopeBegin->getParent() != MBB)
1614 return false;
1615
1617 for (++Pred; Pred != MBB->rend(); ++Pred) {
1618 if (Pred->getFlag(MachineInstr::FrameSetup))
1619 break;
1620 auto PredDL = Pred->getDebugLoc();
1621 if (!PredDL || Pred->isMetaInstruction())
1622 continue;
1623 // Check whether the instruction preceding the DBG_VALUE is in the same
1624 // (sub)scope as the DBG_VALUE.
1625 if (DL->getScope() == PredDL->getScope())
1626 return false;
1627 auto *PredScope = LScopes.findLexicalScope(PredDL);
1628 if (!PredScope || LScope->dominates(PredScope))
1629 return false;
1630 }
1631 }
1632
1633 // If the range of the DBG_VALUE is open-ended, report success.
1634 if (!RangeEnd)
1635 return true;
1636
1637 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1638 // throughout the function. This is a hack, presumably for DWARF v2 and not
1639 // necessarily correct. It would be much better to use a dbg.declare instead
1640 // if we know the constant is live throughout the scope.
1641 if (MBB->pred_empty() &&
1642 all_of(DbgValue->debug_operands(),
1643 [](const MachineOperand &Op) { return Op.isImm(); }))
1644 return true;
1645
1646 // Test if the location terminates before the end of the scope.
1647 const MachineInstr *LScopeEnd = LSRange.back().second;
1648 if (Ordering.isBefore(RangeEnd, LScopeEnd))
1649 return false;
1650
1651 // There's a single location which starts at the scope start, and ends at or
1652 // after the scope end.
1653 return true;
1654}
1655
1656/// Build the location list for all DBG_VALUEs in the function that
1657/// describe the same variable. The resulting DebugLocEntries will have
1658/// strict monotonically increasing begin addresses and will never
1659/// overlap. If the resulting list has only one entry that is valid
1660/// throughout variable's scope return true.
1661//
1662// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1663// different kinds of history map entries. One thing to be aware of is that if
1664// a debug value is ended by another entry (rather than being valid until the
1665// end of the function), that entry's instruction may or may not be included in
1666// the range, depending on if the entry is a clobbering entry (it has an
1667// instruction that clobbers one or more preceding locations), or if it is an
1668// (overlapping) debug value entry. This distinction can be seen in the example
1669// below. The first debug value is ended by the clobbering entry 2, and the
1670// second and third debug values are ended by the overlapping debug value entry
1671// 4.
1672//
1673// Input:
1674//
1675// History map entries [type, end index, mi]
1676//
1677// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1678// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1679// 2 | | [Clobber, $reg0 = [...], -, -]
1680// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1681// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1682//
1683// Output [start, end) [Value...]:
1684//
1685// [0-1) [(reg0, fragment 0, 32)]
1686// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1687// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1688// [4-) [(@g, fragment 0, 96)]
1689bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1690 const DbgValueHistoryMap::Entries &Entries) {
1691 using OpenRange =
1692 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1693 SmallVector<OpenRange, 4> OpenRanges;
1694 bool isSafeForSingleLocation = true;
1695 const MachineInstr *StartDebugMI = nullptr;
1696 const MachineInstr *EndMI = nullptr;
1697
1698 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1699 const MachineInstr *Instr = EI->getInstr();
1700
1701 // Remove all values that are no longer live.
1702 size_t Index = std::distance(EB, EI);
1703 erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1704
1705 // If we are dealing with a clobbering entry, this iteration will result in
1706 // a location list entry starting after the clobbering instruction.
1707 const MCSymbol *StartLabel =
1708 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1709 assert(StartLabel &&
1710 "Forgot label before/after instruction starting a range!");
1711
1712 const MCSymbol *EndLabel;
1713 if (std::next(EI) == Entries.end()) {
1714 const MachineBasicBlock &EndMBB = Asm->MF->back();
1715 EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionID()].EndLabel;
1716 if (EI->isClobber())
1717 EndMI = EI->getInstr();
1718 }
1719 else if (std::next(EI)->isClobber())
1720 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1721 else
1722 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1723 assert(EndLabel && "Forgot label after instruction ending a range!");
1724
1725 if (EI->isDbgValue())
1726 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1727
1728 // If this history map entry has a debug value, add that to the list of
1729 // open ranges and check if its location is valid for a single value
1730 // location.
1731 if (EI->isDbgValue()) {
1732 // Do not add undef debug values, as they are redundant information in
1733 // the location list entries. An undef debug results in an empty location
1734 // description. If there are any non-undef fragments then padding pieces
1735 // with empty location descriptions will automatically be inserted, and if
1736 // all fragments are undef then the whole location list entry is
1737 // redundant.
1738 if (!Instr->isUndefDebugValue()) {
1739 auto Value = getDebugLocValue(Instr);
1740 OpenRanges.emplace_back(EI->getEndIndex(), Value);
1741
1742 // TODO: Add support for single value fragment locations.
1743 if (Instr->getDebugExpression()->isFragment())
1744 isSafeForSingleLocation = false;
1745
1746 if (!StartDebugMI)
1747 StartDebugMI = Instr;
1748 } else {
1749 isSafeForSingleLocation = false;
1750 }
1751 }
1752
1753 // Location list entries with empty location descriptions are redundant
1754 // information in DWARF, so do not emit those.
1755 if (OpenRanges.empty())
1756 continue;
1757
1758 // Omit entries with empty ranges as they do not have any effect in DWARF.
1759 if (StartLabel == EndLabel) {
1760 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1761 continue;
1762 }
1763
1765 for (auto &R : OpenRanges)
1766 Values.push_back(R.second);
1767
1768 // With Basic block sections, it is posssible that the StartLabel and the
1769 // Instr are not in the same section. This happens when the StartLabel is
1770 // the function begin label and the dbg value appears in a basic block
1771 // that is not the entry. In this case, the range needs to be split to
1772 // span each individual section in the range from StartLabel to EndLabel.
1773 if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1774 !Instr->getParent()->sameSection(&Asm->MF->front())) {
1775 const MCSymbol *BeginSectionLabel = StartLabel;
1776
1777 for (const MachineBasicBlock &MBB : *Asm->MF) {
1778 if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
1779 BeginSectionLabel = MBB.getSymbol();
1780
1781 if (MBB.sameSection(Instr->getParent())) {
1782 DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
1783 break;
1784 }
1785 if (MBB.isEndSection())
1786 DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
1787 }
1788 } else {
1789 DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1790 }
1791
1792 // Attempt to coalesce the ranges of two otherwise identical
1793 // DebugLocEntries.
1794 auto CurEntry = DebugLoc.rbegin();
1795 LLVM_DEBUG({
1796 dbgs() << CurEntry->getValues().size() << " Values:\n";
1797 for (auto &Value : CurEntry->getValues())
1798 Value.dump();
1799 dbgs() << "-----\n";
1800 });
1801
1802 auto PrevEntry = std::next(CurEntry);
1803 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1804 DebugLoc.pop_back();
1805 }
1806
1807 if (!isSafeForSingleLocation ||
1808 !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
1809 return false;
1810
1811 if (DebugLoc.size() == 1)
1812 return true;
1813
1814 if (!Asm->MF->hasBBSections())
1815 return false;
1816
1817 // Check here to see if loclist can be merged into a single range. If not,
1818 // we must keep the split loclists per section. This does exactly what
1819 // MergeRanges does without sections. We don't actually merge the ranges
1820 // as the split ranges must be kept intact if this cannot be collapsed
1821 // into a single range.
1822 const MachineBasicBlock *RangeMBB = nullptr;
1823 if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1824 RangeMBB = &Asm->MF->front();
1825 else
1826 RangeMBB = Entries.begin()->getInstr()->getParent();
1827 auto *CurEntry = DebugLoc.begin();
1828 auto *NextEntry = std::next(CurEntry);
1829 while (NextEntry != DebugLoc.end()) {
1830 // Get the last machine basic block of this section.
1831 while (!RangeMBB->isEndSection())
1832 RangeMBB = RangeMBB->getNextNode();
1833 if (!RangeMBB->getNextNode())
1834 return false;
1835 // CurEntry should end the current section and NextEntry should start
1836 // the next section and the Values must match for these two ranges to be
1837 // merged.
1838 if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
1839 NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
1840 CurEntry->getValues() != NextEntry->getValues())
1841 return false;
1842 RangeMBB = RangeMBB->getNextNode();
1843 CurEntry = NextEntry;
1844 NextEntry = std::next(CurEntry);
1845 }
1846 return true;
1847}
1848
1849DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1850 LexicalScope &Scope,
1851 const DINode *Node,
1852 const DILocation *Location,
1853 const MCSymbol *Sym) {
1854 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1855 if (isa<const DILocalVariable>(Node)) {
1856 ConcreteEntities.push_back(
1857 std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1858 Location));
1859 InfoHolder.addScopeVariable(&Scope,
1860 cast<DbgVariable>(ConcreteEntities.back().get()));
1861 } else if (isa<const DILabel>(Node)) {
1862 ConcreteEntities.push_back(
1863 std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1864 Location, Sym));
1865 InfoHolder.addScopeLabel(&Scope,
1866 cast<DbgLabel>(ConcreteEntities.back().get()));
1867 }
1868 return ConcreteEntities.back().get();
1869}
1870
1871// Find variables for each lexical scope.
1872void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1873 const DISubprogram *SP,
1874 DenseSet<InlinedEntity> &Processed) {
1875 // Grab the variable info that was squirreled away in the MMI side-table.
1876 collectVariableInfoFromMFTable(TheCU, Processed);
1877
1878 for (const auto &I : DbgValues) {
1879 InlinedEntity IV = I.first;
1880 if (Processed.count(IV))
1881 continue;
1882
1883 // Instruction ranges, specifying where IV is accessible.
1884 const auto &HistoryMapEntries = I.second;
1885
1886 // Try to find any non-empty variable location. Do not create a concrete
1887 // entity if there are no locations.
1888 if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
1889 continue;
1890
1891 LexicalScope *Scope = nullptr;
1892 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1893 if (const DILocation *IA = IV.second)
1894 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1895 else
1896 Scope = LScopes.findLexicalScope(LocalVar->getScope());
1897 // If variable scope is not found then skip this variable.
1898 if (!Scope)
1899 continue;
1900
1901 Processed.insert(IV);
1902 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1903 *Scope, LocalVar, IV.second));
1904
1905 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1906 assert(MInsn->isDebugValue() && "History must begin with debug value");
1907
1908 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1909 // If the history map contains a single debug value, there may be an
1910 // additional entry which clobbers the debug value.
1911 size_t HistSize = HistoryMapEntries.size();
1912 bool SingleValueWithClobber =
1913 HistSize == 2 && HistoryMapEntries[1].isClobber();
1914 if (HistSize == 1 || SingleValueWithClobber) {
1915 const auto *End =
1916 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1917 if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
1918 RegVar->emplace<Loc::Single>(MInsn);
1919 continue;
1920 }
1921 }
1922
1923 // Do not emit location lists if .debug_loc secton is disabled.
1924 if (!useLocSection())
1925 continue;
1926
1927 // Handle multiple DBG_VALUE instructions describing one variable.
1928 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);
1929
1930 // Build the location list for this variable.
1932 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1933
1934 // Check whether buildLocationList managed to merge all locations to one
1935 // that is valid throughout the variable's scope. If so, produce single
1936 // value location.
1937 if (isValidSingleLocation) {
1938 RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);
1939 continue;
1940 }
1941
1942 // If the variable has a DIBasicType, extract it. Basic types cannot have
1943 // unique identifiers, so don't bother resolving the type with the
1944 // identifier map.
1945 const DIBasicType *BT = dyn_cast<DIBasicType>(
1946 static_cast<const Metadata *>(LocalVar->getType()));
1947
1948 // Finalize the entry by lowering it into a DWARF bytestream.
1949 for (auto &Entry : Entries)
1950 Entry.finalize(*Asm, List, BT, TheCU);
1951 }
1952
1953 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1954 // DWARF-related DbgLabel.
1955 for (const auto &I : DbgLabels) {
1956 InlinedEntity IL = I.first;
1957 const MachineInstr *MI = I.second;
1958 if (MI == nullptr)
1959 continue;
1960
1961 LexicalScope *Scope = nullptr;
1962 const DILabel *Label = cast<DILabel>(IL.first);
1963 // The scope could have an extra lexical block file.
1964 const DILocalScope *LocalScope =
1965 Label->getScope()->getNonLexicalBlockFileScope();
1966 // Get inlined DILocation if it is inlined label.
1967 if (const DILocation *IA = IL.second)
1968 Scope = LScopes.findInlinedScope(LocalScope, IA);
1969 else
1970 Scope = LScopes.findLexicalScope(LocalScope);
1971 // If label scope is not found then skip this label.
1972 if (!Scope)
1973 continue;
1974
1975 Processed.insert(IL);
1976 /// At this point, the temporary label is created.
1977 /// Save the temporary label to DbgLabel entity to get the
1978 /// actually address when generating Dwarf DIE.
1980 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1981 }
1982
1983 // Collect info for retained nodes.
1984 for (const DINode *DN : SP->getRetainedNodes()) {
1985 const auto *LS = getRetainedNodeScope(DN);
1986 if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
1987 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1988 continue;
1990 if (LexS)
1991 createConcreteEntity(TheCU, *LexS, DN, nullptr);
1992 } else {
1993 LocalDeclsPerLS[LS].insert(DN);
1994 }
1995 }
1996}
1997
1998// Process beginning of an instruction.
2000 const MachineFunction &MF = *MI->getMF();
2001 const auto *SP = MF.getFunction().getSubprogram();
2002 bool NoDebug =
2003 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
2004
2005 // Delay slot support check.
2006 auto delaySlotSupported = [](const MachineInstr &MI) {
2007 if (!MI.isBundledWithSucc())
2008 return false;
2009 auto Suc = std::next(MI.getIterator());
2010 (void)Suc;
2011 // Ensure that delay slot instruction is successor of the call instruction.
2012 // Ex. CALL_INSTRUCTION {
2013 // DELAY_SLOT_INSTRUCTION }
2014 assert(Suc->isBundledWithPred() &&
2015 "Call bundle instructions are out of order");
2016 return true;
2017 };
2018
2019 // When describing calls, we need a label for the call instruction.
2020 if (!NoDebug && SP->areAllCallsDescribed() &&
2021 MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
2022 (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
2024 bool IsTail = TII->isTailCall(*MI);
2025 // For tail calls, we need the address of the branch instruction for
2026 // DW_AT_call_pc.
2027 if (IsTail)
2029 // For non-tail calls, we need the return address for the call for
2030 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
2031 // tail calls as well.
2033 }
2034
2036 if (!CurMI)
2037 return;
2038
2039 if (NoDebug)
2040 return;
2041
2042 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2043 // If the instruction is part of the function frame setup code, do not emit
2044 // any line record, as there is no correspondence with any user code.
2045 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
2046 return;
2047 const DebugLoc &DL = MI->getDebugLoc();
2048 unsigned Flags = 0;
2049
2050 if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
2051 const MachineBasicBlock *MBB = MI->getParent();
2052 if (MBB && (MBB != EpilogBeginBlock)) {
2053 // First time FrameDestroy has been seen in this basic block
2056 }
2057 }
2058
2059 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2060 // the last line number actually emitted, to see if it was line 0.
2061 unsigned LastAsmLine =
2062 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2063
2064 bool PrevInstInSameSection =
2065 (!PrevInstBB ||
2066 PrevInstBB->getSectionID() == MI->getParent()->getSectionID());
2067 if (DL == PrevInstLoc && PrevInstInSameSection) {
2068 // If we have an ongoing unspecified location, nothing to do here.
2069 if (!DL)
2070 return;
2071 // We have an explicit location, same as the previous location.
2072 // But we might be coming back to it after a line 0 record.
2073 if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
2074 // Reinstate the source location but not marked as a statement.
2075 const MDNode *Scope = DL.getScope();
2076 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2077 }
2078 return;
2079 }
2080
2081 if (!DL) {
2082 // We have an unspecified location, which might want to be line 0.
2083 // If we have already emitted a line-0 record, don't repeat it.
2084 if (LastAsmLine == 0)
2085 return;
2086 // If user said Don't Do That, don't do that.
2088 return;
2089 // See if we have a reason to emit a line-0 record now.
2090 // Reasons to emit a line-0 record include:
2091 // - User asked for it (UnknownLocations).
2092 // - Instruction has a label, so it's referenced from somewhere else,
2093 // possibly debug information; we want it to have a source location.
2094 // - Instruction is at the top of a block; we don't want to inherit the
2095 // location from the physically previous (maybe unrelated) block.
2096 if (UnknownLocations == Enable || PrevLabel ||
2097 (PrevInstBB && PrevInstBB != MI->getParent())) {
2098 // Preserve the file and column numbers, if we can, to save space in
2099 // the encoded line table.
2100 // Do not update PrevInstLoc, it remembers the last non-0 line.
2101 const MDNode *Scope = nullptr;
2102 unsigned Column = 0;
2103 if (PrevInstLoc) {
2104 Scope = PrevInstLoc.getScope();
2105 Column = PrevInstLoc.getCol();
2106 }
2107 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
2108 }
2109 return;
2110 }
2111
2112 // We have an explicit location, different from the previous location.
2113 // Don't repeat a line-0 record, but otherwise emit the new location.
2114 // (The new location might be an explicit line 0, which we do emit.)
2115 if (DL.getLine() == 0 && LastAsmLine == 0)
2116 return;
2117 if (DL == PrologEndLoc) {
2120 }
2121 // If the line changed, we call that a new statement; unless we went to
2122 // line 0 and came back, in which case it is not a new statement.
2123 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2124 if (DL.getLine() && DL.getLine() != OldLine)
2125 Flags |= DWARF2_FLAG_IS_STMT;
2126
2127 const MDNode *Scope = DL.getScope();
2128 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2129
2130 // If we're not at line 0, remember this location.
2131 if (DL.getLine())
2132 PrevInstLoc = DL;
2133}
2134
2135static std::pair<DebugLoc, bool> findPrologueEndLoc(const MachineFunction *MF) {
2136 // First known non-DBG_VALUE and non-frame setup location marks
2137 // the beginning of the function body.
2138 DebugLoc LineZeroLoc;
2139 const Function &F = MF->getFunction();
2140
2141 // Some instructions may be inserted into prologue after this function. Must
2142 // keep prologue for these cases.
2143 bool IsEmptyPrologue =
2144 !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2145 for (const auto &MBB : *MF) {
2146 for (const auto &MI : MBB) {
2147 if (!MI.isMetaInstruction()) {
2148 if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {
2149 // Scan forward to try to find a non-zero line number. The
2150 // prologue_end marks the first breakpoint in the function after the
2151 // frame setup, and a compiler-generated line 0 location is not a
2152 // meaningful breakpoint. If none is found, return the first
2153 // location after the frame setup.
2154 if (MI.getDebugLoc().getLine())
2155 return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);
2156
2157 LineZeroLoc = MI.getDebugLoc();
2158 }
2159 IsEmptyPrologue = false;
2160 }
2161 }
2162 }
2163 return std::make_pair(LineZeroLoc, IsEmptyPrologue);
2164}
2165
2166/// Register a source line with debug info. Returns the unique label that was
2167/// emitted and which provides correspondence to the source line list.
2168static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2169 const MDNode *S, unsigned Flags, unsigned CUID,
2170 uint16_t DwarfVersion,
2171 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2172 StringRef Fn;
2173 unsigned FileNo = 1;
2174 unsigned Discriminator = 0;
2175 if (auto *Scope = cast_or_null<DIScope>(S)) {
2176 Fn = Scope->getFilename();
2177 if (Line != 0 && DwarfVersion >= 4)
2178 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2179 Discriminator = LBF->getDiscriminator();
2180
2181 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2182 .getOrCreateSourceID(Scope->getFile());
2183 }
2184 Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2185 Discriminator, Fn);
2186}
2187
2189 unsigned CUID) {
2190 std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);
2191 DebugLoc PrologEndLoc = PrologEnd.first;
2192 bool IsEmptyPrologue = PrologEnd.second;
2193
2194 // Get beginning of function.
2195 if (PrologEndLoc) {
2196 // If the prolog is empty, no need to generate scope line for the proc.
2197 if (IsEmptyPrologue)
2198 return PrologEndLoc;
2199
2200 // Ensure the compile unit is created if the function is called before
2201 // beginFunction().
2202 (void)getOrCreateDwarfCompileUnit(
2203 MF.getFunction().getSubprogram()->getUnit());
2204 // We'd like to list the prologue as "not statements" but GDB behaves
2205 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2206 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
2207 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
2208 CUID, getDwarfVersion(), getUnits());
2209 return PrologEndLoc;
2210 }
2211 return DebugLoc();
2212}
2213
2214// Gather pre-function debug information. Assumes being called immediately
2215// after the function entry point has been emitted.
2217 CurFn = MF;
2218
2219 auto *SP = MF->getFunction().getSubprogram();
2221 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2222 return;
2223
2224 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2225
2226 Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2228
2229 // Record beginning of function.
2231 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2232}
2233
2234unsigned
2236 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2237 // belongs to so that we add to the correct per-cu line table in the
2238 // non-asm case.
2239 if (Asm->OutStreamer->hasRawTextSupport())
2240 // Use a single line table if we are generating assembly.
2241 return 0;
2242 else
2243 return CU.getUniqueID();
2244}
2245
2247 const auto &CURanges = CU->getRanges();
2248 auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2250 // Add the last range label for the given CU.
2251 LineTable.getMCLineSections().addEndEntry(
2252 const_cast<MCSymbol *>(CURanges.back().End));
2253}
2254
2256 // If we don't have a subprogram for this function then there will be a hole
2257 // in the range information. Keep note of this by setting the previously used
2258 // section to nullptr.
2259 // Terminate the pending line table.
2260 if (PrevCU)
2261 terminateLineTable(PrevCU);
2262 PrevCU = nullptr;
2263 CurFn = nullptr;
2264}
2265
2266// Gather and emit post-function debug information.
2268 const DISubprogram *SP = MF->getFunction().getSubprogram();
2269
2270 assert(CurFn == MF &&
2271 "endFunction should be called with the same function as beginFunction");
2272
2273 // Set DwarfDwarfCompileUnitID in MCContext to default value.
2274 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2275
2277 assert(!FnScope || SP == FnScope->getScopeNode());
2278 DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(SP->getUnit());
2279 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2280 PrevLabel = nullptr;
2281 CurFn = nullptr;
2282 return;
2283 }
2284
2285 DenseSet<InlinedEntity> Processed;
2286 collectEntityInfo(TheCU, SP, Processed);
2287
2288 // Add the range of this function to the list of ranges for the CU.
2289 // With basic block sections, add ranges for all basic block sections.
2290 for (const auto &R : Asm->MBBSectionRanges)
2291 TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
2292
2293 // Under -gmlt, skip building the subprogram if there are no inlined
2294 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2295 // is still needed as we need its source location.
2296 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2298 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2299 for (const auto &R : Asm->MBBSectionRanges)
2300 addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
2301
2302 assert(InfoHolder.getScopeVariables().empty());
2303 PrevLabel = nullptr;
2304 CurFn = nullptr;
2305 return;
2306 }
2307
2308#ifndef NDEBUG
2309 size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();
2310#endif
2311 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2312 const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2313 for (const DINode *DN : SP->getRetainedNodes()) {
2314 const auto *LS = getRetainedNodeScope(DN);
2315 // Ensure LexicalScope is created for the scope of this node.
2316 auto *LexS = LScopes.getOrCreateAbstractScope(LS);
2317 assert(LexS && "Expected the LexicalScope to be created.");
2318 if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
2319 // Collect info for variables/labels that were optimized out.
2320 if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||
2321 TheCU.getExistingAbstractEntity(DN))
2322 continue;
2323 TheCU.createAbstractEntity(DN, LexS);
2324 } else {
2325 // Remember the node if this is a local declarations.
2326 LocalDeclsPerLS[LS].insert(DN);
2327 }
2328 assert(
2329 LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
2330 "getOrCreateAbstractScope() inserted an abstract subprogram scope");
2331 }
2332 constructAbstractSubprogramScopeDIE(TheCU, AScope);
2333 }
2334
2335 ProcessedSPNodes.insert(SP);
2336 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2337 if (auto *SkelCU = TheCU.getSkeleton())
2338 if (!LScopes.getAbstractScopesList().empty() &&
2340 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2341
2342 // Construct call site entries.
2343 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2344
2345 // Clear debug info
2346 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2347 // DbgVariables except those that are also in AbstractVariables (since they
2348 // can be used cross-function)
2349 InfoHolder.getScopeVariables().clear();
2350 InfoHolder.getScopeLabels().clear();
2351 LocalDeclsPerLS.clear();
2352 PrevLabel = nullptr;
2353 CurFn = nullptr;
2354}
2355
2356// Register a source line with debug info. Returns the unique label that was
2357// emitted and which provides correspondence to the source line list.
2358void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2359 unsigned Flags) {
2360 ::recordSourceLine(*Asm, Line, Col, S, Flags,
2361 Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2362 getDwarfVersion(), getUnits());
2363}
2364
2365//===----------------------------------------------------------------------===//
2366// Emit Methods
2367//===----------------------------------------------------------------------===//
2368
2369// Emit the debug info section.
2370void DwarfDebug::emitDebugInfo() {
2371 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2372 Holder.emitUnits(/* UseOffsets */ false);
2373}
2374
2375// Emit the abbreviation section.
2376void DwarfDebug::emitAbbreviations() {
2377 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2378
2380}
2381
2382void DwarfDebug::emitStringOffsetsTableHeader() {
2383 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2386 Holder.getStringOffsetsStartSym());
2387}
2388
2389template <typename AccelTableT>
2390void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2391 StringRef TableName) {
2392 Asm->OutStreamer->switchSection(Section);
2393
2394 // Emit the full data.
2395 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2396}
2397
2398void DwarfDebug::emitAccelDebugNames() {
2399 // Don't emit anything if we have no compilation units to index.
2400 if (getUnits().empty())
2401 return;
2402
2403 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2404}
2405
2406// Emit visible names into a hashed accelerator table section.
2407void DwarfDebug::emitAccelNames() {
2408 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2409 "Names");
2410}
2411
2412// Emit objective C classes and categories into a hashed accelerator table
2413// section.
2414void DwarfDebug::emitAccelObjC() {
2415 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2416 "ObjC");
2417}
2418
2419// Emit namespace dies into a hashed accelerator table.
2420void DwarfDebug::emitAccelNamespaces() {
2421 emitAccel(AccelNamespace,
2423 "namespac");
2424}
2425
2426// Emit type dies into a hashed accelerator table.
2427void DwarfDebug::emitAccelTypes() {
2428 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2429 "types");
2430}
2431
2432// Public name handling.
2433// The format for the various pubnames:
2434//
2435// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2436// for the DIE that is named.
2437//
2438// gnu pubnames - offset/index value/name tuples where the offset is the offset
2439// into the CU and the index value is computed according to the type of value
2440// for the DIE that is named.
2441//
2442// For type units the offset is the offset of the skeleton DIE. For split dwarf
2443// it's the offset within the debug_info/debug_types dwo section, however, the
2444// reference in the pubname header doesn't change.
2445
2446/// computeIndexValue - Compute the gdb index value for the DIE and CU.
2448 const DIE *Die) {
2449 // Entities that ended up only in a Type Unit reference the CU instead (since
2450 // the pub entry has offsets within the CU there's no real offset that can be
2451 // provided anyway). As it happens all such entities (namespaces and types,
2452 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2453 // not to be true it would be necessary to persist this information from the
2454 // point at which the entry is added to the index data structure - since by
2455 // the time the index is built from that, the original type/namespace DIE in a
2456 // type unit has already been destroyed so it can't be queried for properties
2457 // like tag, etc.
2458 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2462
2463 // We could have a specification DIE that has our most of our knowledge,
2464 // look for that now.
2465 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2466 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2467 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2468 Linkage = dwarf::GIEL_EXTERNAL;
2469 } else if (Die->findAttribute(dwarf::DW_AT_external))
2470 Linkage = dwarf::GIEL_EXTERNAL;
2471
2472 switch (Die->getTag()) {
2473 case dwarf::DW_TAG_class_type:
2474 case dwarf::DW_TAG_structure_type:
2475 case dwarf::DW_TAG_union_type:
2476 case dwarf::DW_TAG_enumeration_type:
2482 case dwarf::DW_TAG_typedef:
2483 case dwarf::DW_TAG_base_type:
2484 case dwarf::DW_TAG_subrange_type:
2485 case dwarf::DW_TAG_template_alias:
2487 case dwarf::DW_TAG_namespace:
2488 return dwarf::GIEK_TYPE;
2489 case dwarf::DW_TAG_subprogram:
2491 case dwarf::DW_TAG_variable:
2493 case dwarf::DW_TAG_enumerator:
2496 default:
2497 return dwarf::GIEK_NONE;
2498 }
2499}
2500
2501/// emitDebugPubSections - Emit visible names and types into debug pubnames and
2502/// pubtypes sections.
2503void DwarfDebug::emitDebugPubSections() {
2504 for (const auto &NU : CUMap) {
2505 DwarfCompileUnit *TheU = NU.second;
2506 if (!TheU->hasDwarfPubSections())
2507 continue;
2508
2509 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2511
2512 Asm->OutStreamer->switchSection(
2515 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2516
2517 Asm->OutStreamer->switchSection(
2520 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2521 }
2522}
2523
2524void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2526 Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2527 CU.getDebugSectionOffset());
2528 else
2529 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2530}
2531
2532void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2533 DwarfCompileUnit *TheU,
2534 const StringMap<const DIE *> &Globals) {
2535 if (auto *Skeleton = TheU->getSkeleton())
2536 TheU = Skeleton;
2537
2538 // Emit the header.
2539 MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
2540 "pub" + Name, "Length of Public " + Name + " Info");
2541
2542 Asm->OutStreamer->AddComment("DWARF Version");
2544
2545 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2546 emitSectionReference(*TheU);
2547
2548 Asm->OutStreamer->AddComment("Compilation Unit Length");
2550
2551 // Emit the pubnames for this compilation unit.
2553 for (const auto &GI : Globals)
2554 Vec.emplace_back(GI.first(), GI.second);
2555 llvm::sort(Vec, [](auto &A, auto &B) {
2556 return A.second->getOffset() < B.second->getOffset();
2557 });
2558 for (const auto &[Name, Entity] : Vec) {
2559 Asm->OutStreamer->AddComment("DIE offset");
2560 Asm->emitDwarfLengthOrOffset(Entity->getOffset());
2561
2562 if (GnuStyle) {
2564 Asm->OutStreamer->AddComment(
2565 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2566 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2567 Asm->emitInt8(Desc.toBits());
2568 }
2569
2570 Asm->OutStreamer->AddComment("External Name");
2571 Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));
2572 }
2573
2574 Asm->OutStreamer->AddComment("End Mark");
2576 Asm->OutStreamer->emitLabel(EndLabel);
2577}
2578
2579/// Emit null-terminated strings into a debug str section.
2580void DwarfDebug::emitDebugStr() {
2581 MCSection *StringOffsetsSection = nullptr;
2583 emitStringOffsetsTableHeader();
2584 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2585 }
2586 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2588 StringOffsetsSection, /* UseRelativeOffsets = */ true);
2589}
2590
2592 const DebugLocStream::Entry &Entry,
2593 const DwarfCompileUnit *CU) {
2594 auto &&Comments = DebugLocs.getComments(Entry);
2595 auto Comment = Comments.begin();
2596 auto End = Comments.end();
2597
2598 // The expressions are inserted into a byte stream rather early (see
2599 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2600 // need to reference a base_type DIE the offset of that DIE is not yet known.
2601 // To deal with this we instead insert a placeholder early and then extract
2602 // it here and replace it with the real reference.
2603 unsigned PtrSize = Asm->MAI->getCodePointerSize();
2604 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2605 DebugLocs.getBytes(Entry).size()),
2606 Asm->getDataLayout().isLittleEndian(), PtrSize);
2608
2609 using Encoding = DWARFExpression::Operation::Encoding;
2610 uint64_t Offset = 0;
2611 for (const auto &Op : Expr) {
2612 assert(Op.getCode() != dwarf::DW_OP_const_type &&
2613 "3 operand ops not yet supported");
2614 assert(!Op.getSubCode() && "SubOps not yet supported");
2615 Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2616 Offset++;
2617 for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
2618 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2619 unsigned Length =
2620 Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
2621 // Make sure comments stay aligned.
2622 for (unsigned J = 0; J < Length; ++J)
2623 if (Comment != End)
2624 Comment++;
2625 } else {
2626 for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2627 Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2628 }
2630 }
2632 }
2633}
2634
2636 const DbgValueLoc &Value,
2637 DwarfExpression &DwarfExpr) {
2638 auto *DIExpr = Value.getExpression();
2639 DIExpressionCursor ExprCursor(DIExpr);
2640 DwarfExpr.addFragmentOffset(DIExpr);
2641
2642 // If the DIExpr is an Entry Value, we want to follow the same code path
2643 // regardless of whether the DBG_VALUE is variadic or not.
2644 if (DIExpr && DIExpr->isEntryValue()) {
2645 // Entry values can only be a single register with no additional DIExpr,
2646 // so just add it directly.
2647 assert(Value.getLocEntries().size() == 1);
2648 assert(Value.getLocEntries()[0].isLocation());
2649 MachineLocation Location = Value.getLocEntries()[0].getLoc();
2650 DwarfExpr.setLocation(Location, DIExpr);
2651
2652 DwarfExpr.beginEntryValueExpression(ExprCursor);
2653
2655 if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
2656 return;
2657 return DwarfExpr.addExpression(std::move(ExprCursor));
2658 }
2659
2660 // Regular entry.
2661 auto EmitValueLocEntry = [&DwarfExpr, &BT,
2662 &AP](const DbgValueLocEntry &Entry,
2663 DIExpressionCursor &Cursor) -> bool {
2664 if (Entry.isInt()) {
2665 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2666 BT->getEncoding() == dwarf::DW_ATE_signed_char))
2667 DwarfExpr.addSignedConstant(Entry.getInt());
2668 else
2669 DwarfExpr.addUnsignedConstant(Entry.getInt());
2670 } else if (Entry.isLocation()) {
2671 MachineLocation Location = Entry.getLoc();
2672 if (Location.isIndirect())
2673 DwarfExpr.setMemoryLocationKind();
2674
2676 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2677 return false;
2678 } else if (Entry.isTargetIndexLocation()) {
2679 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
2680 // TODO TargetIndexLocation is a target-independent. Currently only the
2681 // WebAssembly-specific encoding is supported.
2683 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2684 } else if (Entry.isConstantFP()) {
2685 if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2686 !Cursor) {
2687 DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2688 } else if (Entry.getConstantFP()
2689 ->getValueAPF()
2690 .bitcastToAPInt()
2691 .getBitWidth() <= 64 /*bits*/) {
2692 DwarfExpr.addUnsignedConstant(
2693 Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2694 } else {
2695 LLVM_DEBUG(
2696 dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
2697 << Entry.getConstantFP()
2698 ->getValueAPF()
2699 .bitcastToAPInt()
2700 .getBitWidth()
2701 << " bits\n");
2702 return false;
2703 }
2704 }
2705 return true;
2706 };
2707
2708 if (!Value.isVariadic()) {
2709 if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
2710 return;
2711 DwarfExpr.addExpression(std::move(ExprCursor));
2712 return;
2713 }
2714
2715 // If any of the location entries are registers with the value 0, then the
2716 // location is undefined.
2717 if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
2718 return Entry.isLocation() && !Entry.getLoc().getReg();
2719 }))
2720 return;
2721
2722 DwarfExpr.addExpression(
2723 std::move(ExprCursor),
2724 [EmitValueLocEntry, &Value](unsigned Idx,
2725 DIExpressionCursor &Cursor) -> bool {
2726 return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
2727 });
2728}
2729
2732 const DIBasicType *BT,
2733 DwarfCompileUnit &TheCU) {
2734 assert(!Values.empty() &&
2735 "location list entries without values are redundant");
2736 assert(Begin != End && "unexpected location list entry with empty range");
2737 DebugLocStream::EntryBuilder Entry(List, Begin, End);
2738 BufferByteStreamer Streamer = Entry.getStreamer();
2739 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2740 const DbgValueLoc &Value = Values[0];
2741 if (Value.isFragment()) {
2742 // Emit all fragments that belong to the same variable and range.
2743 assert(llvm::all_of(Values, [](DbgValueLoc P) {
2744 return P.isFragment();
2745 }) && "all values are expected to be fragments");
2746 assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
2747
2748 for (const auto &Fragment : Values)
2749 DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2750
2751 } else {
2752 assert(Values.size() == 1 && "only fragments may have >1 value");
2753 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2754 }
2755 DwarfExpr.finalize();
2756 if (DwarfExpr.TagOffset)
2757 List.setTagOffset(*DwarfExpr.TagOffset);
2758}
2759
2761 const DwarfCompileUnit *CU) {
2762 // Emit the size.
2763 Asm->OutStreamer->AddComment("Loc expr size");
2764 if (getDwarfVersion() >= 5)
2765 Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2766 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2767 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2768 else {
2769 // The entry is too big to fit into 16 bit, drop it as there is nothing we
2770 // can do.
2771 Asm->emitInt16(0);
2772 return;
2773 }
2774 // Emit the entry.
2775 APByteStreamer Streamer(*Asm);
2776 emitDebugLocEntry(Streamer, Entry, CU);
2777}
2778
2779// Emit the header of a DWARF 5 range list table list table. Returns the symbol
2780// that designates the end of the table for the caller to emit when the table is
2781// complete.
2783 const DwarfFile &Holder) {
2784 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2785
2786 Asm->OutStreamer->AddComment("Offset entry count");
2787 Asm->emitInt32(Holder.getRangeLists().size());
2788 Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2789
2790 for (const RangeSpanList &List : Holder.getRangeLists())
2791 Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2792 Asm->getDwarfOffsetByteSize());
2793
2794 return TableEnd;
2795}
2796
2797// Emit the header of a DWARF 5 locations list table. Returns the symbol that
2798// designates the end of the table for the caller to emit when the table is
2799// complete.
2801 const DwarfDebug &DD) {
2802 MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2803
2804 const auto &DebugLocs = DD.getDebugLocs();
2805
2806 Asm->OutStreamer->AddComment("Offset entry count");
2807 Asm->emitInt32(DebugLocs.getLists().size());
2808 Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2809
2810 for (const auto &List : DebugLocs.getLists())
2811 Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2812 Asm->getDwarfOffsetByteSize());
2813
2814 return TableEnd;
2815}
2816
2817template <typename Ranges, typename PayloadEmitter>
2818static void emitRangeList(
2819 DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2820 const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2821 unsigned StartxLength, unsigned EndOfList,
2822 StringRef (*StringifyEnum)(unsigned),
2823 bool ShouldUseBaseAddress,
2824 PayloadEmitter EmitPayload) {
2825
2826 auto Size = Asm->MAI->getCodePointerSize();
2827 bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2828
2829 // Emit our symbol so we can find the beginning of the range.
2830 Asm->OutStreamer->emitLabel(Sym);
2831
2832 // Gather all the ranges that apply to the same section so they can share
2833 // a base address entry.
2834 MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2835
2836 for (const auto &Range : R)
2837 SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2838
2839 const MCSymbol *CUBase = CU.getBaseAddress();
2840 bool BaseIsSet = false;
2841 for (const auto &P : SectionRanges) {
2842 auto *Base = CUBase;
2843 if (!Base && ShouldUseBaseAddress) {
2844 const MCSymbol *Begin = P.second.front()->Begin;
2845 const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2846 if (!UseDwarf5) {
2847 Base = NewBase;
2848 BaseIsSet = true;
2849 Asm->OutStreamer->emitIntValue(-1, Size);
2850 Asm->OutStreamer->AddComment(" base address");
2851 Asm->OutStreamer->emitSymbolValue(Base, Size);
2852 } else if (NewBase != Begin || P.second.size() > 1) {
2853 // Only use a base address if
2854 // * the existing pool address doesn't match (NewBase != Begin)
2855 // * or, there's more than one entry to share the base address
2856 Base = NewBase;
2857 BaseIsSet = true;
2858 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2859 Asm->emitInt8(BaseAddressx);
2860 Asm->OutStreamer->AddComment(" base address index");
2861 Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
2862 }
2863 } else if (BaseIsSet && !UseDwarf5) {
2864 BaseIsSet = false;
2865 assert(!Base);
2866 Asm->OutStreamer->emitIntValue(-1, Size);
2867 Asm->OutStreamer->emitIntValue(0, Size);
2868 }
2869
2870 for (const auto *RS : P.second) {
2871 const MCSymbol *Begin = RS->Begin;
2872 const MCSymbol *End = RS->End;
2873 assert(Begin && "Range without a begin symbol?");
2874 assert(End && "Range without an end symbol?");
2875 if (Base) {
2876 if (UseDwarf5) {
2877 // Emit offset_pair when we have a base.
2878 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2879 Asm->emitInt8(OffsetPair);
2880 Asm->OutStreamer->AddComment(" starting offset");
2881 Asm->emitLabelDifferenceAsULEB128(Begin, Base);
2882 Asm->OutStreamer->AddComment(" ending offset");
2883 Asm->emitLabelDifferenceAsULEB128(End, Base);
2884 } else {
2885 Asm->emitLabelDifference(Begin, Base, Size);
2886 Asm->emitLabelDifference(End, Base, Size);
2887 }
2888 } else if (UseDwarf5) {
2889 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2890 Asm->emitInt8(StartxLength);
2891 Asm->OutStreamer->AddComment(" start index");
2892 Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
2893 Asm->OutStreamer->AddComment(" length");
2894 Asm->emitLabelDifferenceAsULEB128(End, Begin);
2895 } else {
2896 Asm->OutStreamer->emitSymbolValue(Begin, Size);
2897 Asm->OutStreamer->emitSymbolValue(End, Size);
2898 }
2899 EmitPayload(*RS);
2900 }
2901 }
2902
2903 if (UseDwarf5) {
2904 Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2905 Asm->emitInt8(EndOfList);
2906 } else {
2907 // Terminate the list with two 0 values.
2908 Asm->OutStreamer->emitIntValue(0, Size);
2909 Asm->OutStreamer->emitIntValue(0, Size);
2910 }
2911}
2912
2913// Handles emission of both debug_loclist / debug_loclist.dwo
2915 emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2916 *List.CU, dwarf::DW_LLE_base_addressx,
2917 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2918 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2919 /* ShouldUseBaseAddress */ true,
2920 [&](const DebugLocStream::Entry &E) {
2921 DD.emitDebugLocEntryLocation(E, List.CU);
2922 });
2923}
2924
2925void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2926 if (DebugLocs.getLists().empty())
2927 return;
2928
2929 Asm->OutStreamer->switchSection(Sec);
2930
2931 MCSymbol *TableEnd = nullptr;
2932 if (getDwarfVersion() >= 5)
2933 TableEnd = emitLoclistsTableHeader(Asm, *this);
2934
2935 for (const auto &List : DebugLocs.getLists())
2936 emitLocList(*this, Asm, List);
2937
2938 if (TableEnd)
2939 Asm->OutStreamer->emitLabel(TableEnd);
2940}
2941
2942// Emit locations into the .debug_loc/.debug_loclists section.
2943void DwarfDebug::emitDebugLoc() {
2944 emitDebugLocImpl(
2945 getDwarfVersion() >= 5
2948}
2949
2950// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2951void DwarfDebug::emitDebugLocDWO() {
2952 if (getDwarfVersion() >= 5) {
2953 emitDebugLocImpl(
2955
2956 return;
2957 }
2958
2959 for (const auto &List : DebugLocs.getLists()) {
2960 Asm->OutStreamer->switchSection(
2962 Asm->OutStreamer->emitLabel(List.Label);
2963
2964 for (const auto &Entry : DebugLocs.getEntries(List)) {
2965 // GDB only supports startx_length in pre-standard split-DWARF.
2966 // (in v5 standard loclists, it currently* /only/ supports base_address +
2967 // offset_pair, so the implementations can't really share much since they
2968 // need to use different representations)
2969 // * as of October 2018, at least
2970 //
2971 // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2972 // addresses in the address pool to minimize object size/relocations.
2973 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2974 unsigned idx = AddrPool.getIndex(Entry.Begin);
2975 Asm->emitULEB128(idx);
2976 // Also the pre-standard encoding is slightly different, emitting this as
2977 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2978 Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2980 }
2981 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2982 }
2983}
2984
2986 const MCSymbol *Start, *End;
2987};
2988
2989// Emit a debug aranges section, containing a CU lookup for any
2990// address we can tie back to a CU.
2991void DwarfDebug::emitDebugARanges() {
2992 if (ArangeLabels.empty())
2993 return;
2994
2995 // Provides a unique id per text section.
2997
2998 // Filter labels by section.
2999 for (const SymbolCU &SCU : ArangeLabels) {
3000 if (SCU.Sym->isInSection()) {
3001 // Make a note of this symbol and it's section.
3002 MCSection *Section = &SCU.Sym->getSection();
3003 SectionMap[Section].push_back(SCU);
3004 } else {
3005 // Some symbols (e.g. common/bss on mach-o) can have no section but still
3006 // appear in the output. This sucks as we rely on sections to build
3007 // arange spans. We can do it without, but it's icky.
3008 SectionMap[nullptr].push_back(SCU);
3009 }
3010 }
3011
3013
3014 for (auto &I : SectionMap) {
3015 MCSection *Section = I.first;
3017 assert(!List.empty());
3018
3019 // If we have no section (e.g. common), just write out
3020 // individual spans for each symbol.
3021 if (!Section) {
3022 for (const SymbolCU &Cur : List) {
3023 ArangeSpan Span;
3024 Span.Start = Cur.Sym;
3025 Span.End = nullptr;
3026 assert(Cur.CU);
3027 Spans[Cur.CU].push_back(Span);
3028 }
3029 continue;
3030 }
3031
3032 // Insert a final terminator.
3033 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
3034
3035 // Build spans between each label.
3036 const MCSymbol *StartSym = List[0].Sym;
3037 for (size_t n = 1, e = List.size(); n < e; n++) {
3038 const SymbolCU &Prev = List[n - 1];
3039 const SymbolCU &Cur = List[n];
3040
3041 // Try and build the longest span we can within the same CU.
3042 if (Cur.CU != Prev.CU) {
3043 ArangeSpan Span;
3044 Span.Start = StartSym;
3045 Span.End = Cur.Sym;
3046 assert(Prev.CU);
3047 Spans[Prev.CU].push_back(Span);
3048 StartSym = Cur.Sym;
3049 }
3050 }
3051 }
3052
3053 // Start the dwarf aranges section.
3054 Asm->OutStreamer->switchSection(
3056
3057 unsigned PtrSize = Asm->MAI->getCodePointerSize();
3058
3059 // Build a list of CUs used.
3060 std::vector<DwarfCompileUnit *> CUs;
3061 for (const auto &it : Spans) {
3062 DwarfCompileUnit *CU = it.first;
3063 CUs.push_back(CU);
3064 }
3065
3066 // Sort the CU list (again, to ensure consistent output order).
3067 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
3068 return A->getUniqueID() < B->getUniqueID();
3069 });
3070
3071 // Emit an arange table for each CU we used.
3072 for (DwarfCompileUnit *CU : CUs) {
3073 std::vector<ArangeSpan> &List = Spans[CU];
3074
3075 // Describe the skeleton CU's offset and length, not the dwo file's.
3076 if (auto *Skel = CU->getSkeleton())
3077 CU = Skel;
3078
3079 // Emit size of content not including length itself.
3080 unsigned ContentSize =
3081 sizeof(int16_t) + // DWARF ARange version number
3082 Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3083 // section
3084 sizeof(int8_t) + // Pointer Size (in bytes)
3085 sizeof(int8_t); // Segment Size (in bytes)
3086
3087 unsigned TupleSize = PtrSize * 2;
3088
3089 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3090 unsigned Padding = offsetToAlignment(
3091 Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
3092
3093 ContentSize += Padding;
3094 ContentSize += (List.size() + 1) * TupleSize;
3095
3096 // For each compile unit, write the list of spans it covers.
3097 Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
3098 Asm->OutStreamer->AddComment("DWARF Arange version number");
3100 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
3101 emitSectionReference(*CU);
3102 Asm->OutStreamer->AddComment("Address Size (in bytes)");
3103 Asm->emitInt8(PtrSize);
3104 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
3105 Asm->emitInt8(0);
3106
3107 Asm->OutStreamer->emitFill(Padding, 0xff);
3108
3109 for (const ArangeSpan &Span : List) {
3110 Asm->emitLabelReference(Span.Start, PtrSize);
3111
3112 // Calculate the size as being from the span start to its end.
3113 //
3114 // If the size is zero, then round it up to one byte. The DWARF
3115 // specification requires that entries in this table have nonzero
3116 // lengths.
3117 auto SizeRef = SymSize.find(Span.Start);
3118 if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3119 Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
3120 } else {
3121 // For symbols without an end marker (e.g. common), we
3122 // write a single arange entry containing just that one symbol.
3123 uint64_t Size;
3124 if (SizeRef == SymSize.end() || SizeRef->second == 0)
3125 Size = 1;
3126 else
3127 Size = SizeRef->second;
3128
3129 Asm->OutStreamer->emitIntValue(Size, PtrSize);
3130 }
3131 }
3132
3133 Asm->OutStreamer->AddComment("ARange terminator");
3134 Asm->OutStreamer->emitIntValue(0, PtrSize);
3135 Asm->OutStreamer->emitIntValue(0, PtrSize);
3136 }
3137}
3138
3139/// Emit a single range list. We handle both DWARF v5 and earlier.
3141 const RangeSpanList &List) {
3142 emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
3143 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
3144 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
3146 List.CU->getCUNode()->getRangesBaseAddress() ||
3147 DD.getDwarfVersion() >= 5,
3148 [](auto) {});
3149}
3150
3151void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3152 if (Holder.getRangeLists().empty())
3153 return;
3154
3156 assert(!CUMap.empty());
3157 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3158 return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3159 }));
3160
3161 Asm->OutStreamer->switchSection(Section);
3162
3163 MCSymbol *TableEnd = nullptr;
3164 if (getDwarfVersion() >= 5)
3165 TableEnd = emitRnglistsTableHeader(Asm, Holder);
3166
3167 for (const RangeSpanList &List : Holder.getRangeLists())
3168 emitRangeList(*this, Asm, List);
3169
3170 if (TableEnd)
3171 Asm->OutStreamer->emitLabel(TableEnd);
3172}
3173
3174/// Emit address ranges into the .debug_ranges section or into the DWARF v5
3175/// .debug_rnglists section.
3176void DwarfDebug::emitDebugRanges() {
3177 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3178
3179 emitDebugRangesImpl(Holder,
3180 getDwarfVersion() >= 5
3183}
3184
3185void DwarfDebug::emitDebugRangesDWO() {
3186 emitDebugRangesImpl(InfoHolder,
3188}
3189
3190/// Emit the header of a DWARF 5 macro section, or the GNU extension for
3191/// DWARF 4.
3192static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3193 const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
3194 enum HeaderFlagMask {
3195#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3196#include "llvm/BinaryFormat/Dwarf.def"
3197 };
3198 Asm->OutStreamer->AddComment("Macro information version");
3199 Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3200 // We emit the line offset flag unconditionally here, since line offset should
3201 // be mostly present.
3202 if (Asm->isDwarf64()) {
3203 Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3204 Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3205 } else {
3206 Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3207 Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3208 }
3209 Asm->OutStreamer->AddComment("debug_line_offset");
3210 if (DD.useSplitDwarf())
3211 Asm->emitDwarfLengthOrOffset(0);
3212 else
3213 Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
3214}
3215
3216void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3217 for (auto *MN : Nodes) {
3218 if (auto *M = dyn_cast<DIMacro>(MN))
3219 emitMacro(*M);
3220 else if (auto *F = dyn_cast<DIMacroFile>(MN))
3221 emitMacroFile(*F, U);
3222 else
3223 llvm_unreachable("Unexpected DI type!");
3224 }
3225}
3226
3227void DwarfDebug::emitMacro(DIMacro &M) {
3228 StringRef Name = M.getName();
3229 StringRef Value = M.getValue();
3230
3231 // There should be one space between the macro name and the macro value in
3232 // define entries. In undef entries, only the macro name is emitted.
3233 std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3234
3235 if (UseDebugMacroSection) {
3236 if (getDwarfVersion() >= 5) {
3237 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3238 ? dwarf::DW_MACRO_define_strx
3239 : dwarf::DW_MACRO_undef_strx;
3240 Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
3242 Asm->OutStreamer->AddComment("Line Number");
3243 Asm->emitULEB128(M.getLine());
3244 Asm->OutStreamer->AddComment("Macro String");
3246 InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3247 } else {
3248 unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3249 ? dwarf::DW_MACRO_GNU_define_indirect
3250 : dwarf::DW_MACRO_GNU_undef_indirect;
3253 Asm->OutStreamer->AddComment("Line Number");
3254 Asm->emitULEB128(M.getLine());
3255 Asm->OutStreamer->AddComment("Macro String");
3257 InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3258 }
3259 } else {
3260 Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
3261 Asm->emitULEB128(M.getMacinfoType());
3262 Asm->OutStreamer->AddComment("Line Number");
3263 Asm->emitULEB128(M.getLine());
3264 Asm->OutStreamer->AddComment("Macro String");
3265 Asm->OutStreamer->emitBytes(Str);
3266 Asm->emitInt8('\0');
3267 }
3268}
3269
3270void DwarfDebug::emitMacroFileImpl(
3271 DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3272 StringRef (*MacroFormToString)(unsigned Form)) {
3273
3274 Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3275 Asm->emitULEB128(StartFile);
3276 Asm->OutStreamer->AddComment("Line Number");
3277 Asm->emitULEB128(MF.getLine());
3278 Asm->OutStreamer->AddComment("File Number");
3279 DIFile &F = *MF.getFile();
3280 if (useSplitDwarf())
3281 Asm->emitULEB128(getDwoLineTable(U)->getFile(
3282 F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3283 Asm->OutContext.getDwarfVersion(), F.getSource()));
3284 else
3285 Asm->emitULEB128(U.getOrCreateSourceID(&F));
3286 handleMacroNodes(MF.getElements(), U);
3287 Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
3288 Asm->emitULEB128(EndFile);
3289}
3290
3291void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3292 // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3293 // so for readibility/uniformity, We are explicitly emitting those.
3294 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3295 if (UseDebugMacroSection)
3296 emitMacroFileImpl(
3297 F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3299 else
3300 emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
3302}
3303
3304void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3305 for (const auto &P : CUMap) {
3306 auto &TheCU = *P.second;
3307 auto *SkCU = TheCU.getSkeleton();
3308 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3309 auto *CUNode = cast<DICompileUnit>(P.first);
3310 DIMacroNodeArray Macros = CUNode->getMacros();
3311 if (Macros.empty())
3312 continue;
3313 Asm->OutStreamer->switchSection(Section);
3314 Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3315 if (UseDebugMacroSection)
3316 emitMacroHeader(Asm, *this, U, getDwarfVersion());
3317 handleMacroNodes(Macros, U);
3318 Asm->OutStreamer->AddComment("End Of Macro List Mark");
3319 Asm->emitInt8(0);
3320 }
3321}
3322
3323/// Emit macros into a debug macinfo/macro section.
3324void DwarfDebug::emitDebugMacinfo() {
3325 auto &ObjLower = Asm->getObjFileLowering();
3326 emitDebugMacinfoImpl(UseDebugMacroSection
3327 ? ObjLower.getDwarfMacroSection()
3328 : ObjLower.getDwarfMacinfoSection());
3329}
3330
3331void DwarfDebug::emitDebugMacinfoDWO() {
3332 auto &ObjLower = Asm->getObjFileLowering();
3333 emitDebugMacinfoImpl(UseDebugMacroSection
3334 ? ObjLower.getDwarfMacroDWOSection()
3335 : ObjLower.getDwarfMacinfoDWOSection());
3336}
3337
3338// DWARF5 Experimental Separate Dwarf emitters.
3339
3340void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
3341 std::unique_ptr<DwarfCompileUnit> NewU) {
3342
3343 if (!CompilationDir.empty())
3344 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3345 addGnuPubAttributes(*NewU, Die);
3346
3347 SkeletonHolder.addUnit(std::move(NewU));
3348}
3349
3350DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3351
3352 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3353 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3355 DwarfCompileUnit &NewCU = *OwnedUnit;
3357
3358 NewCU.initStmtList();
3359
3361 NewCU.addStringOffsetsStart();
3362
3363 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
3364
3365 return NewCU;
3366}
3367
3368// Emit the .debug_info.dwo section for separated dwarf. This contains the
3369// compile units that would normally be in debug_info.
3370void DwarfDebug::emitDebugInfoDWO() {
3371 assert(useSplitDwarf() && "No split dwarf debug info?");
3372 // Don't emit relocations into the dwo file.
3373 InfoHolder.emitUnits(/* UseOffsets */ true);
3374}
3375
3376// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3377// abbreviations for the .debug_info.dwo section.
3378void DwarfDebug::emitDebugAbbrevDWO() {
3379 assert(useSplitDwarf() && "No split dwarf?");
3381}
3382
3383void DwarfDebug::emitDebugLineDWO() {
3384 assert(useSplitDwarf() && "No split dwarf?");
3385 SplitTypeUnitFileTable.Emit(
3388}
3389
3390void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3391 assert(useSplitDwarf() && "No split dwarf?");
3394 InfoHolder.getStringOffsetsStartSym());
3395}
3396
3397// Emit the .debug_str.dwo section for separated dwarf. This contains the
3398// string section and is identical in format to traditional .debug_str
3399// sections.
3400void DwarfDebug::emitDebugStrDWO() {
3402 emitStringOffsetsTableHeaderDWO();
3403 assert(useSplitDwarf() && "No split dwarf?");
3406 OffSec, /* UseRelativeOffsets = */ false);
3407}
3408
3409// Emit address pool.
3410void DwarfDebug::emitDebugAddr() {
3412}
3413
3414MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
3415 if (!useSplitDwarf())
3416 return nullptr;
3417 const DICompileUnit *DIUnit = CU.getCUNode();
3418 SplitTypeUnitFileTable.maybeSetRootFile(
3419 DIUnit->getDirectory(), DIUnit->getFilename(),
3420 getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
3421 return &SplitTypeUnitFileTable;
3422}
3423
3425 MD5 Hash;
3426 Hash.update(Identifier);
3427 // ... take the least significant 8 bytes and return those. Our MD5
3428 // implementation always returns its results in little endian, so we actually
3429 // need the "high" word.
3430 MD5::MD5Result Result;
3431 Hash.final(Result);
3432 return Result.high();
3433}
3434
3436 StringRef Identifier, DIE &RefDie,
3437 const DICompositeType *CTy) {
3438 // Fast path if we're building some type units and one has already used the
3439 // address pool we know we're going to throw away all this work anyway, so
3440 // don't bother building dependent types.
3441 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3442 return;
3443
3444 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3445 if (!Ins.second) {
3446 CU.addDIETypeSignature(RefDie, Ins.first->second);
3447 return;
3448 }
3449
3451 bool TopLevelType = TypeUnitsUnderConstruction.empty();
3452 AddrPool.resetUsedFlag();
3453
3454 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
3455 CU, Asm, this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(CU));
3456 DwarfTypeUnit &NewTU = *OwnedUnit;
3457 DIE &UnitDie = NewTU.getUnitDie();
3458 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3459
3460 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3461 CU.getLanguage());
3462
3463 uint64_t Signature = makeTypeSignature(Identifier);
3464 NewTU.setTypeSignature(Signature);
3465 Ins.first->second = Signature;
3466
3467 if (useSplitDwarf()) {
3468 // Although multiple type units can have the same signature, they are not
3469 // guranteed to be bit identical. When LLDB uses .debug_names it needs to
3470 // know from which CU a type unit came from. These two attrbutes help it to
3471 // figure that out.
3472 if (getDwarfVersion() >= 5) {
3473 if (!CompilationDir.empty())
3474 NewTU.addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
3475 NewTU.addString(UnitDie, dwarf::DW_AT_dwo_name,
3477 }
3478 MCSection *Section =
3479 getDwarfVersion() <= 4
3482 NewTU.setSection(Section);
3483 } else {
3484 MCSection *Section =
3485 getDwarfVersion() <= 4
3488 NewTU.setSection(Section);
3489 // Non-split type units reuse the compile unit's line table.
3490 CU.applyStmtList(UnitDie);
3491 }
3492
3493 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3494 // units.
3496 NewTU.addStringOffsetsStart();
3497
3498 NewTU.setType(NewTU.createTypeDIE(CTy));
3499
3500 if (TopLevelType) {
3501 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3502 TypeUnitsUnderConstruction.clear();
3503
3504 // Types referencing entries in the address table cannot be placed in type
3505 // units.
3506 if (AddrPool.hasBeenUsed()) {
3507 AccelTypeUnitsDebugNames.clear();
3508 // Remove all the types built while building this type.
3509 // This is pessimistic as some of these types might not be dependent on
3510 // the type that used an address.
3511 for (const auto &TU : TypeUnitsToAdd)
3512 TypeSignatures.erase(TU.second);
3513
3514 // Construct this type in the CU directly.
3515 // This is inefficient because all the dependent types will be rebuilt
3516 // from scratch, including building them in type units, discovering that
3517 // they depend on addresses, throwing them out and rebuilding them.
3519 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3520 return;
3521 }
3522
3523 // If the type wasn't dependent on fission addresses, finish adding the type
3524 // and all its dependent types.
3525 for (auto &TU : TypeUnitsToAdd) {
3526 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3527 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3528 if (getDwarfVersion() >= 5 &&
3530 if (useSplitDwarf())
3531 AccelDebugNames.addTypeUnitSignature(*TU.first);
3532 else
3533 AccelDebugNames.addTypeUnitSymbol(*TU.first);
3534 }
3535 }
3536 AccelTypeUnitsDebugNames.convertDieToOffset();
3537 AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);
3538 AccelTypeUnitsDebugNames.clear();
3540 }
3541 CU.addDIETypeSignature(RefDie, Signature);
3542}
3543
3544// Add the Name along with its companion DIE to the appropriate accelerator
3545// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3546// AccelTableKind::Apple, we use the table we got as an argument). If
3547// accelerator tables are disabled, this function does nothing.
3548template <typename DataT>
3549void DwarfDebug::addAccelNameImpl(
3550 const DwarfUnit &Unit,
3551 const DICompileUnit::DebugNameTableKind NameTableKind,
3552 AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {
3554 Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())
3555 return;
3556
3560 return;
3561
3562 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3564
3565 switch (getAccelTableKind()) {
3567 AppleAccel.addName(Ref, Die);
3568 break;
3569 case AccelTableKind::Dwarf: {
3571 assert(((&Current == &AccelTypeUnitsDebugNames) ||
3572 ((&Current == &AccelDebugNames) &&
3573 (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
3574 "Kind is CU but TU is being processed.");
3575 assert(((&Current == &AccelDebugNames) ||
3576 ((&Current == &AccelTypeUnitsDebugNames) &&
3577 (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
3578 "Kind is TU but CU is being processed.");
3579 // The type unit can be discarded, so need to add references to final
3580 // acceleration table once we know it's complete and we emit it.
3581 Current.addName(Ref, Die, Unit.getUniqueID(),
3582 Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
3583 break;
3584 }
3586 llvm_unreachable("Default should have already been resolved.");
3588 llvm_unreachable("None handled above");
3589 }
3590}
3591
3593 const DwarfUnit &Unit,
3595 const DIE &Die) {
3596 addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);
3597}
3598
3600 const DwarfUnit &Unit,
3602 const DIE &Die) {
3603 // ObjC names go only into the Apple accelerator tables.
3605 addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);
3606}
3607
3609 const DwarfUnit &Unit,
3611 const DIE &Die) {
3612 addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);
3613}
3614
3616 const DwarfUnit &Unit,
3618 const DIE &Die, char Flags) {
3619 addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);
3620}
3621
3623 return Asm->OutStreamer->getContext().getDwarfVersion();
3624}
3625
3627 if (Asm->getDwarfVersion() >= 4)
3628 return dwarf::Form::DW_FORM_sec_offset;
3629 assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
3630 "DWARF64 is not defined prior DWARFv3");
3631 return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3632 : dwarf::Form::DW_FORM_data4;
3633}
3634
3636 return SectionLabels.lookup(S);
3637}
3638
3640 if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
3641 if (useSplitDwarf() || getDwarfVersion() >= 5)
3642 AddrPool.getIndex(S);
3643}
3644
3645std::optional<MD5::MD5Result>
3647 assert(File);
3648 if (getDwarfVersion() < 5)
3649 return std::nullopt;
3650 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3651 if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3652 return std::nullopt;
3653
3654 // Convert the string checksum to an MD5Result for the streamer.
3655 // The verifier validates the checksum so we assume it's okay.
3656 // An MD5 checksum is 16 bytes.
3657 std::string ChecksumString = fromHex(Checksum->Value);
3658 MD5::MD5Result CKMem;
3659 std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3660 return CKMem;
3661}
3662
3664 if (MinimizeAddr == MinimizeAddrInV5::Ranges)
3665 return true;
3666 if (MinimizeAddr != MinimizeAddrInV5::Default)
3667 return false;
3668 if (useSplitDwarf())
3669 return true;
3670 return false;
3671}
3672
3674 if (MBB.getAlignment() == Align(1))
3675 return;
3676
3677 auto *SP = MBB.getParent()->getFunction().getSubprogram();
3678 bool NoDebug =
3679 !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
3680
3681 if (NoDebug)
3682 return;
3683
3684 auto PrevLoc = Asm->OutStreamer->getContext().getCurrentDwarfLoc();
3685 Asm->OutStreamer->emitDwarfLocDirective(
3686 PrevLoc.getFileNum(), 0, PrevLoc.getColumn(), 0, 0, 0, StringRef());
3688 Asm->OutStreamer->getCurrentSectionOnly());
3689}
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(PassOpts->AAPipeline)
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:166
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:237
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:266
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.
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition: AsmPrinter.h:437
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:692
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:195
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:194
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:211
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:820
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:824
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:933
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:755
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:806
void skippedNonDebugFunction() override
void addArangeLabel(SymbolCU SCU)
Add a label so that arange data can be generated for it.
Definition: DwarfDebug.h:745
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
AddressPool & getAddressPool()
Definition: DwarfDebug.h:867
DWARF5AccelTable & getCurrentDWARF5AccelTable()
Returns either CU or TU DWARF5AccelTable.
Definition: DwarfDebug.h:943
bool useSectionsAsReferences() const
Returns whether to use sections as labels rather than temp symbols.
Definition: DwarfDebug.h:788
const DebugLocStream & getDebugLocs() const
Returns the entries for the .debug_loc section.
Definition: DwarfDebug.h:851
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:812
bool useLocSection() const
Returns whether .debug_loc section should be emitted.
Definition: DwarfDebug.h:793
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:769
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)
void beginCodeAlignment(const MachineBasicBlock &MBB) override
Process beginning of code alignment.
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:801
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:1837
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:380
bool isTailCall(const MachineInstr &MI) const override
Record instruction ordering so we can query their relative positions within a function.
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:518
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
static void make(MCStreamer *MCOS, MCSection *Section)
Definition: MCDwarf.cpp:95
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:135
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:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
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.
const MachineFunction * getParent() const
Return the MachineFunction containing 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.
Align getAlignment() const
Return alignment of the basic block.
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
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:867
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition: Module.cpp:550
bool isDwarf64() const
Returns the DWARF format by checking module flags.
Definition: Module.cpp:557
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:1021
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:5266
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:913
bool tuneForDBX() const
Definition: DwarfDebug.h:914
bool tuneForGDB() const
Definition: DwarfDebug.h:911
bool tuneForLLDB() const
Definition: DwarfDebug.h:912
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:826
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 tuples (A, B,...
Definition: STLExtras.h:2431
auto unique(Range &&R, Predicate P)
Definition: STLExtras.h:2038
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:2090
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:1909
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:2082
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