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