1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains support for writing dwarf debug info into asm files.
11 //===----------------------------------------------------------------------===//
13 #include "DwarfDebug.h"
14 #include "ByteStreamer.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"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DIE.h"
25 #include "llvm/CodeGen/LexicalScopes.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/TargetInstrInfo.h"
31 #include "llvm/CodeGen/TargetLowering.h"
32 #include "llvm/CodeGen/TargetRegisterInfo.h"
33 #include "llvm/CodeGen/TargetSubtargetInfo.h"
34 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
35 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalVariable.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"
45 #include "llvm/MC/MCTargetOptions.h"
46 #include "llvm/MC/MachineLocation.h"
47 #include "llvm/MC/SectionKind.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MD5.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/Timer.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetLoweringObjectFile.h"
58 #include "llvm/Target/TargetMachine.h"
66 #define DEBUG_TYPE "dwarfdebug"
68 STATISTIC(NumCSParams
, "Number of dbg call site params created");
70 static cl::opt
<bool> UseDwarfRangesBaseAddressSpecifier(
71 "use-dwarf-ranges-base-address-specifier", cl::Hidden
,
72 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
74 static cl::opt
<bool> GenerateARangeSection("generate-arange-section",
76 cl::desc("Generate dwarf aranges"),
80 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden
,
81 cl::desc("Generate DWARF4 type units."),
84 static cl::opt
<bool> SplitDwarfCrossCuReferences(
85 "split-dwarf-cross-cu-references", cl::Hidden
,
86 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
88 enum DefaultOnOff
{ Default
, Enable
, Disable
};
90 static cl::opt
<DefaultOnOff
> UnknownLocations(
91 "use-unknown-locations", cl::Hidden
,
92 cl::desc("Make an absence of debug location information explicit."),
93 cl::values(clEnumVal(Default
, "At top of block or after label"),
94 clEnumVal(Enable
, "In all cases"), clEnumVal(Disable
, "Never")),
97 static cl::opt
<AccelTableKind
> AccelTables(
98 "accel-tables", cl::Hidden
, cl::desc("Output dwarf accelerator tables."),
99 cl::values(clEnumValN(AccelTableKind::Default
, "Default",
100 "Default for platform"),
101 clEnumValN(AccelTableKind::None
, "Disable", "Disabled."),
102 clEnumValN(AccelTableKind::Apple
, "Apple", "Apple"),
103 clEnumValN(AccelTableKind::Dwarf
, "Dwarf", "DWARF")),
104 cl::init(AccelTableKind::Default
));
106 static cl::opt
<DefaultOnOff
>
107 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden
,
108 cl::desc("Use inlined strings rather than string section."),
109 cl::values(clEnumVal(Default
, "Default for platform"),
110 clEnumVal(Enable
, "Enabled"),
111 clEnumVal(Disable
, "Disabled")),
115 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden
,
116 cl::desc("Disable emission .debug_ranges section."),
119 static cl::opt
<DefaultOnOff
> DwarfSectionsAsReferences(
120 "dwarf-sections-as-references", cl::Hidden
,
121 cl::desc("Use sections+offset as references rather than labels."),
122 cl::values(clEnumVal(Default
, "Default for platform"),
123 clEnumVal(Enable
, "Enabled"), clEnumVal(Disable
, "Disabled")),
127 UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden
,
128 cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
131 static cl::opt
<DefaultOnOff
> DwarfOpConvert(
132 "dwarf-op-convert", cl::Hidden
,
133 cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
134 cl::values(clEnumVal(Default
, "Default for platform"),
135 clEnumVal(Enable
, "Enabled"), clEnumVal(Disable
, "Disabled")),
138 enum LinkageNameOption
{
144 static cl::opt
<LinkageNameOption
>
145 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden
,
146 cl::desc("Which DWARF linkage-name attributes to emit."),
147 cl::values(clEnumValN(DefaultLinkageNames
, "Default",
148 "Default for platform"),
149 clEnumValN(AllLinkageNames
, "All", "All"),
150 clEnumValN(AbstractLinkageNames
, "Abstract",
151 "Abstract subprograms")),
152 cl::init(DefaultLinkageNames
));
154 static cl::opt
<DwarfDebug::MinimizeAddrInV5
> MinimizeAddrInV5Option(
155 "minimize-addr-in-v5", cl::Hidden
,
156 cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
157 "address pool entry sharing to reduce relocations/object size"),
158 cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default
, "Default",
159 "Default address minimization strategy"),
160 clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges
, "Ranges",
161 "Use rnglists for contiguous ranges if that allows "
162 "using a pre-existing base address"),
163 clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions
,
165 "Use exprloc addrx+offset expressions for any "
166 "address with a prior base address"),
167 clEnumValN(DwarfDebug::MinimizeAddrInV5::Form
, "Form",
168 "Use addrx+offset extension form for any address "
169 "with a prior base address"),
170 clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled
, "Disabled",
172 cl::init(DwarfDebug::MinimizeAddrInV5::Default
));
174 static constexpr unsigned ULEB128PadSize
= 4;
176 void DebugLocDwarfExpression::emitOp(uint8_t Op
, const char *Comment
) {
177 getActiveStreamer().emitInt8(
178 Op
, Comment
? Twine(Comment
) + " " + dwarf::OperationEncodingString(Op
)
179 : dwarf::OperationEncodingString(Op
));
182 void DebugLocDwarfExpression::emitSigned(int64_t Value
) {
183 getActiveStreamer().emitSLEB128(Value
, Twine(Value
));
186 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value
) {
187 getActiveStreamer().emitULEB128(Value
, Twine(Value
));
190 void DebugLocDwarfExpression::emitData1(uint8_t Value
) {
191 getActiveStreamer().emitInt8(Value
, Twine(Value
));
194 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx
) {
195 assert(Idx
< (1ULL << (ULEB128PadSize
* 7)) && "Idx wont fit");
196 getActiveStreamer().emitULEB128(Idx
, Twine(Idx
), ULEB128PadSize
);
199 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo
&TRI
,
200 llvm::Register MachineReg
) {
201 // This information is not available while emitting .debug_loc entries.
205 void DebugLocDwarfExpression::enableTemporaryBuffer() {
206 assert(!IsBuffering
&& "Already buffering?");
208 TmpBuf
= std::make_unique
<TempBuffer
>(OutBS
.GenerateComments
);
212 void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering
= false; }
214 unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
215 return TmpBuf
? TmpBuf
->Bytes
.size() : 0;
218 void DebugLocDwarfExpression::commitTemporaryBuffer() {
221 for (auto Byte
: enumerate(TmpBuf
->Bytes
)) {
222 const char *Comment
= (Byte
.index() < TmpBuf
->Comments
.size())
223 ? TmpBuf
->Comments
[Byte
.index()].c_str()
225 OutBS
.emitInt8(Byte
.value(), Comment
);
227 TmpBuf
->Bytes
.clear();
228 TmpBuf
->Comments
.clear();
231 const DIType
*DbgVariable::getType() const {
232 return getVariable()->getType();
235 /// Get .debug_loc entry for the instruction range starting at MI.
236 static DbgValueLoc
getDebugLocValue(const MachineInstr
*MI
) {
237 const DIExpression
*Expr
= MI
->getDebugExpression();
238 const bool IsVariadic
= MI
->isDebugValueList();
239 assert(MI
->getNumOperands() >= 3);
240 SmallVector
<DbgValueLocEntry
, 4> DbgValueLocEntries
;
241 for (const MachineOperand
&Op
: MI
->debug_operands()) {
243 MachineLocation
MLoc(Op
.getReg(),
244 MI
->isNonListDebugValue() && MI
->isDebugOffsetImm());
245 DbgValueLocEntries
.push_back(DbgValueLocEntry(MLoc
));
246 } else if (Op
.isTargetIndex()) {
247 DbgValueLocEntries
.push_back(
248 DbgValueLocEntry(TargetIndexLocation(Op
.getIndex(), Op
.getOffset())));
249 } else if (Op
.isImm())
250 DbgValueLocEntries
.push_back(DbgValueLocEntry(Op
.getImm()));
251 else if (Op
.isFPImm())
252 DbgValueLocEntries
.push_back(DbgValueLocEntry(Op
.getFPImm()));
253 else if (Op
.isCImm())
254 DbgValueLocEntries
.push_back(DbgValueLocEntry(Op
.getCImm()));
256 llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
258 return DbgValueLoc(Expr
, DbgValueLocEntries
, IsVariadic
);
261 void DbgVariable::initializeDbgValue(const MachineInstr
*DbgValue
) {
262 assert(FrameIndexExprs
.empty() && "Already initialized?");
263 assert(!ValueLoc
.get() && "Already initialized?");
265 assert(getVariable() == DbgValue
->getDebugVariable() && "Wrong variable");
266 assert(getInlinedAt() == DbgValue
->getDebugLoc()->getInlinedAt() &&
269 ValueLoc
= std::make_unique
<DbgValueLoc
>(getDebugLocValue(DbgValue
));
270 if (auto *E
= DbgValue
->getDebugExpression())
271 if (E
->getNumElements())
272 FrameIndexExprs
.push_back({0, E
});
275 ArrayRef
<DbgVariable::FrameIndexExpr
> DbgVariable::getFrameIndexExprs() const {
276 if (FrameIndexExprs
.size() == 1)
277 return FrameIndexExprs
;
279 assert(llvm::all_of(FrameIndexExprs
,
280 [](const FrameIndexExpr
&A
) {
281 return A
.Expr
->isFragment();
283 "multiple FI expressions without DW_OP_LLVM_fragment");
284 llvm::sort(FrameIndexExprs
,
285 [](const FrameIndexExpr
&A
, const FrameIndexExpr
&B
) -> bool {
286 return A
.Expr
->getFragmentInfo()->OffsetInBits
<
287 B
.Expr
->getFragmentInfo()->OffsetInBits
;
290 return FrameIndexExprs
;
293 void DbgVariable::addMMIEntry(const DbgVariable
&V
) {
294 assert(DebugLocListIndex
== ~0U && !ValueLoc
.get() && "not an MMI entry");
295 assert(V
.DebugLocListIndex
== ~0U && !V
.ValueLoc
.get() && "not an MMI entry");
296 assert(V
.getVariable() == getVariable() && "conflicting variable");
297 assert(V
.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
299 assert(!FrameIndexExprs
.empty() && "Expected an MMI entry");
300 assert(!V
.FrameIndexExprs
.empty() && "Expected an MMI entry");
302 // FIXME: This logic should not be necessary anymore, as we now have proper
303 // deduplication. However, without it, we currently run into the assertion
304 // below, which means that we are likely dealing with broken input, i.e. two
305 // non-fragment entries for the same variable at different frame indices.
306 if (FrameIndexExprs
.size()) {
307 auto *Expr
= FrameIndexExprs
.back().Expr
;
308 if (!Expr
|| !Expr
->isFragment())
312 for (const auto &FIE
: V
.FrameIndexExprs
)
313 // Ignore duplicate entries.
314 if (llvm::none_of(FrameIndexExprs
, [&](const FrameIndexExpr
&Other
) {
315 return FIE
.FI
== Other
.FI
&& FIE
.Expr
== Other
.Expr
;
317 FrameIndexExprs
.push_back(FIE
);
319 assert((FrameIndexExprs
.size() == 1 ||
320 llvm::all_of(FrameIndexExprs
,
321 [](FrameIndexExpr
&FIE
) {
322 return FIE
.Expr
&& FIE
.Expr
->isFragment();
324 "conflicting locations for variable");
327 static AccelTableKind
computeAccelTableKind(unsigned DwarfVersion
,
328 bool GenerateTypeUnits
,
331 // Honor an explicit request.
332 if (AccelTables
!= AccelTableKind::Default
)
335 // Accelerator tables with type units are currently not supported.
336 if (GenerateTypeUnits
)
337 return AccelTableKind::None
;
339 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
340 // always implies debug_names. For lower standard versions we use apple
341 // accelerator tables on apple platforms and debug_names elsewhere.
342 if (DwarfVersion
>= 5)
343 return AccelTableKind::Dwarf
;
344 if (Tuning
== DebuggerKind::LLDB
)
345 return TT
.isOSBinFormatMachO() ? AccelTableKind::Apple
346 : AccelTableKind::Dwarf
;
347 return AccelTableKind::None
;
350 DwarfDebug::DwarfDebug(AsmPrinter
*A
)
351 : DebugHandlerBase(A
), DebugLocs(A
->OutStreamer
->isVerboseAsm()),
352 InfoHolder(A
, "info_string", DIEValueAllocator
),
353 SkeletonHolder(A
, "skel_string", DIEValueAllocator
),
354 IsDarwin(A
->TM
.getTargetTriple().isOSDarwin()) {
355 const Triple
&TT
= Asm
->TM
.getTargetTriple();
357 // Make sure we know our "debugger tuning". The target option takes
358 // precedence; fall back to triple-based defaults.
359 if (Asm
->TM
.Options
.DebuggerTuning
!= DebuggerKind::Default
)
360 DebuggerTuning
= Asm
->TM
.Options
.DebuggerTuning
;
362 DebuggerTuning
= DebuggerKind::LLDB
;
363 else if (TT
.isPS4CPU())
364 DebuggerTuning
= DebuggerKind::SCE
;
365 else if (TT
.isOSAIX())
366 DebuggerTuning
= DebuggerKind::DBX
;
368 DebuggerTuning
= DebuggerKind::GDB
;
370 if (DwarfInlinedStrings
== Default
)
371 UseInlineStrings
= TT
.isNVPTX() || tuneForDBX();
373 UseInlineStrings
= DwarfInlinedStrings
== Enable
;
375 UseLocSection
= !TT
.isNVPTX();
377 HasAppleExtensionAttributes
= tuneForLLDB();
379 // Handle split DWARF.
380 HasSplitDwarf
= !Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
.empty();
382 // SCE defaults to linkage names only for abstract subprograms.
383 if (DwarfLinkageNames
== DefaultLinkageNames
)
384 UseAllLinkageNames
= !tuneForSCE();
386 UseAllLinkageNames
= DwarfLinkageNames
== AllLinkageNames
;
388 unsigned DwarfVersionNumber
= Asm
->TM
.Options
.MCOptions
.DwarfVersion
;
389 unsigned DwarfVersion
= DwarfVersionNumber
? DwarfVersionNumber
390 : MMI
->getModule()->getDwarfVersion();
391 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
393 TT
.isNVPTX() ? 2 : (DwarfVersion
? DwarfVersion
: dwarf::DWARF_VERSION
);
395 bool Dwarf64
= DwarfVersion
>= 3 && // DWARF64 was introduced in DWARFv3.
396 TT
.isArch64Bit(); // DWARF64 requires 64-bit relocations.
399 // 1: For ELF when requested.
400 // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
401 // according to the DWARF64 format for 64-bit assembly, so we must use
402 // DWARF64 in the compiler too for 64-bit mode.
404 ((Asm
->TM
.Options
.MCOptions
.Dwarf64
|| MMI
->getModule()->isDwarf64()) &&
405 TT
.isOSBinFormatELF()) ||
406 TT
.isOSBinFormatXCOFF();
408 if (!Dwarf64
&& TT
.isArch64Bit() && TT
.isOSBinFormatXCOFF())
409 report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
411 UseRangesSection
= !NoDwarfRangesSection
&& !TT
.isNVPTX();
413 // Use sections as references. Force for NVPTX.
414 if (DwarfSectionsAsReferences
== Default
)
415 UseSectionsAsReferences
= TT
.isNVPTX();
417 UseSectionsAsReferences
= DwarfSectionsAsReferences
== Enable
;
419 // Don't generate type units for unsupported object file formats.
420 GenerateTypeUnits
= (A
->TM
.getTargetTriple().isOSBinFormatELF() ||
421 A
->TM
.getTargetTriple().isOSBinFormatWasm()) &&
422 GenerateDwarfTypeUnits
;
424 TheAccelTableKind
= computeAccelTableKind(
425 DwarfVersion
, GenerateTypeUnits
, DebuggerTuning
, A
->TM
.getTargetTriple());
427 // Work around a GDB bug. GDB doesn't support the standard opcode;
428 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
429 // is defined as of DWARF 3.
430 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
431 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
432 UseGNUTLSOpcode
= tuneForGDB() || DwarfVersion
< 3;
434 // GDB does not fully support the DWARF 4 representation for bitfields.
435 UseDWARF2Bitfields
= (DwarfVersion
< 4) || tuneForGDB();
437 // The DWARF v5 string offsets table has - possibly shared - contributions
438 // from each compile and type unit each preceded by a header. The string
439 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
440 // a monolithic string offsets table without any header.
441 UseSegmentedStringOffsetsTable
= DwarfVersion
>= 5;
443 // Emit call-site-param debug info for GDB and LLDB, if the target supports
444 // the debug entry values feature. It can also be enabled explicitly.
445 EmitDebugEntryValues
= Asm
->TM
.Options
.ShouldEmitDebugEntryValues();
447 // It is unclear if the GCC .debug_macro extension is well-specified
448 // for split DWARF. For now, do not allow LLVM to emit it.
449 UseDebugMacroSection
=
450 DwarfVersion
>= 5 || (UseGNUDebugMacro
&& !useSplitDwarf());
451 if (DwarfOpConvert
== Default
)
452 EnableOpConvert
= !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT
.isOSBinFormatMachO()));
454 EnableOpConvert
= (DwarfOpConvert
== Enable
);
456 // Split DWARF would benefit object size significantly by trading reductions
457 // in address pool usage for slightly increased range list encodings.
458 if (DwarfVersion
>= 5) {
459 MinimizeAddr
= MinimizeAddrInV5Option
;
460 // FIXME: In the future, enable this by default for Split DWARF where the
461 // tradeoff is more pronounced due to being able to offload the range
462 // lists to the dwo file and shrink object files/reduce relocations there.
463 if (MinimizeAddr
== MinimizeAddrInV5::Default
)
464 MinimizeAddr
= MinimizeAddrInV5::Disabled
;
467 Asm
->OutStreamer
->getContext().setDwarfVersion(DwarfVersion
);
468 Asm
->OutStreamer
->getContext().setDwarfFormat(Dwarf64
? dwarf::DWARF64
472 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
473 DwarfDebug::~DwarfDebug() = default;
475 static bool isObjCClass(StringRef Name
) {
476 return Name
.startswith("+") || Name
.startswith("-");
479 static bool hasObjCCategory(StringRef Name
) {
480 if (!isObjCClass(Name
))
483 return Name
.contains(") ");
486 static void getObjCClassCategory(StringRef In
, StringRef
&Class
,
487 StringRef
&Category
) {
488 if (!hasObjCCategory(In
)) {
489 Class
= In
.slice(In
.find('[') + 1, In
.find(' '));
494 Class
= In
.slice(In
.find('[') + 1, In
.find('('));
495 Category
= In
.slice(In
.find('[') + 1, In
.find(' '));
498 static StringRef
getObjCMethodName(StringRef In
) {
499 return In
.slice(In
.find(' ') + 1, In
.find(']'));
502 // Add the various names to the Dwarf accelerator table names.
503 void DwarfDebug::addSubprogramNames(const DICompileUnit
&CU
,
504 const DISubprogram
*SP
, DIE
&Die
) {
505 if (getAccelTableKind() != AccelTableKind::Apple
&&
506 CU
.getNameTableKind() == DICompileUnit::DebugNameTableKind::None
)
509 if (!SP
->isDefinition())
512 if (SP
->getName() != "")
513 addAccelName(CU
, SP
->getName(), Die
);
515 // If the linkage name is different than the name, go ahead and output that as
516 // well into the name table. Only do that if we are going to actually emit
518 if (SP
->getLinkageName() != "" && SP
->getName() != SP
->getLinkageName() &&
519 (useAllLinkageNames() || InfoHolder
.getAbstractSPDies().lookup(SP
)))
520 addAccelName(CU
, SP
->getLinkageName(), Die
);
522 // If this is an Objective-C selector name add it to the ObjC accelerator
524 if (isObjCClass(SP
->getName())) {
525 StringRef Class
, Category
;
526 getObjCClassCategory(SP
->getName(), Class
, Category
);
527 addAccelObjC(CU
, Class
, Die
);
529 addAccelObjC(CU
, Category
, Die
);
530 // Also add the base method name to the name table.
531 addAccelName(CU
, getObjCMethodName(SP
->getName()), Die
);
535 /// Check whether we should create a DIE for the given Scope, return true
536 /// if we don't create a DIE (the corresponding DIE is null).
537 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope
*Scope
) {
538 if (Scope
->isAbstractScope())
541 // We don't create a DIE if there is no Range.
542 const SmallVectorImpl
<InsnRange
> &Ranges
= Scope
->getRanges();
546 if (Ranges
.size() > 1)
549 // We don't create a DIE if we have a single Range and the end label
551 return !getLabelAfterInsn(Ranges
.front().second
);
554 template <typename Func
> static void forBothCUs(DwarfCompileUnit
&CU
, Func F
) {
556 if (auto *SkelCU
= CU
.getSkeleton())
557 if (CU
.getCUNode()->getSplitDebugInlining())
561 bool DwarfDebug::shareAcrossDWOCUs() const {
562 return SplitDwarfCrossCuReferences
;
565 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit
&SrcCU
,
566 LexicalScope
*Scope
) {
567 assert(Scope
&& Scope
->getScopeNode());
568 assert(Scope
->isAbstractScope());
569 assert(!Scope
->getInlinedAt());
571 auto *SP
= cast
<DISubprogram
>(Scope
->getScopeNode());
573 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
574 // was inlined from another compile unit.
575 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP
->getUnit()->getSplitDebugInlining())
576 // Avoid building the original CU if it won't be used
577 SrcCU
.constructAbstractSubprogramScopeDIE(Scope
);
579 auto &CU
= getOrCreateDwarfCompileUnit(SP
->getUnit());
580 if (auto *SkelCU
= CU
.getSkeleton()) {
581 (shareAcrossDWOCUs() ? CU
: SrcCU
)
582 .constructAbstractSubprogramScopeDIE(Scope
);
583 if (CU
.getCUNode()->getSplitDebugInlining())
584 SkelCU
->constructAbstractSubprogramScopeDIE(Scope
);
586 CU
.constructAbstractSubprogramScopeDIE(Scope
);
590 /// Represents a parameter whose call site value can be described by applying a
591 /// debug expression to a register in the forwarded register worklist.
592 struct FwdRegParamInfo
{
593 /// The described parameter register.
596 /// Debug expression that has been built up when walking through the
597 /// instruction chain that produces the parameter's value.
598 const DIExpression
*Expr
;
601 /// Register worklist for finding call site values.
602 using FwdRegWorklist
= MapVector
<unsigned, SmallVector
<FwdRegParamInfo
, 2>>;
604 /// Append the expression \p Addition to \p Original and return the result.
605 static 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
;
616 /// Emit call site parameter entries that are described by the given value and
617 /// debug expression.
618 template <typename ValT
>
619 static void finishCallSiteParams(ValT Val
, const DIExpression
*Expr
,
620 ArrayRef
<FwdRegParamInfo
> DescribedParams
,
622 for (auto Param
: DescribedParams
) {
623 bool ShouldCombineExpressions
= Expr
&& Param
.Expr
->getNumElements() > 0;
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())
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
634 const DIExpression
*CombinedExpr
=
635 ShouldCombineExpressions
? combineDIExpressions(Expr
, Param
.Expr
)
637 assert((!CombinedExpr
|| CombinedExpr
->isValid()) &&
638 "Combined debug expression is invalid");
640 DbgValueLoc
DbgLocVal(CombinedExpr
, DbgValueLocEntry(Val
));
641 DbgCallSiteParam
CSParm(Param
.ParamReg
, DbgLocVal
);
642 Params
.push_back(CSParm
);
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.
650 static 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
;
660 "Same parameter described twice by forwarding reg");
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
666 const DIExpression
*CombinedExpr
= combineDIExpressions(Expr
, Param
.Expr
);
667 ParamsForFwdReg
.push_back({Param
.ParamReg
, CombinedExpr
});
671 /// Interpret values loaded into registers by \p CurMI.
672 static void interpretValues(const MachineInstr
*CurMI
,
673 FwdRegWorklist
&ForwardedRegWorklist
,
676 const MachineFunction
*MF
= CurMI
->getMF();
677 const DIExpression
*EmptyExpr
=
678 DIExpression::get(MF
->getFunction().getContext(), {});
679 const auto &TRI
= *MF
->getSubtarget().getRegisterInfo();
680 const auto &TII
= *MF
->getSubtarget().getInstrInfo();
681 const auto &TLI
= *MF
->getSubtarget().getTargetLowering();
683 // If an instruction defines more than one item in the worklist, we may run
684 // into situations where a worklist register's value is (potentially)
685 // described by the previous value of another register that is also defined
686 // by that instruction.
688 // This can for example occur in cases like this:
691 // $r0, $r1 = mvrr $r1, 456
692 // call @foo, $r0, $r1
694 // When describing $r1's value for the mvrr instruction, we need to make sure
695 // that we don't finalize an entry value for $r0, as that is dependent on the
696 // previous value of $r1 (123 rather than 456).
698 // In order to not have to distinguish between those cases when finalizing
699 // entry values, we simply postpone adding new parameter registers to the
700 // worklist, by first keeping them in this temporary container until the
701 // instruction has been handled.
702 FwdRegWorklist TmpWorklistItems
;
704 // If the MI is an instruction defining one or more parameters' forwarding
705 // registers, add those defines.
706 auto getForwardingRegsDefinedByMI
= [&](const MachineInstr
&MI
,
707 SmallSetVector
<unsigned, 4> &Defs
) {
708 if (MI
.isDebugInstr())
711 for (const MachineOperand
&MO
: MI
.operands()) {
712 if (MO
.isReg() && MO
.isDef() &&
713 Register::isPhysicalRegister(MO
.getReg())) {
714 for (auto &FwdReg
: ForwardedRegWorklist
)
715 if (TRI
.regsOverlap(FwdReg
.first
, MO
.getReg()))
716 Defs
.insert(FwdReg
.first
);
721 // Set of worklist registers that are defined by this instruction.
722 SmallSetVector
<unsigned, 4> FwdRegDefs
;
724 getForwardingRegsDefinedByMI(*CurMI
, FwdRegDefs
);
725 if (FwdRegDefs
.empty())
728 for (auto ParamFwdReg
: FwdRegDefs
) {
729 if (auto ParamValue
= TII
.describeLoadedValue(*CurMI
, ParamFwdReg
)) {
730 if (ParamValue
->first
.isImm()) {
731 int64_t Val
= ParamValue
->first
.getImm();
732 finishCallSiteParams(Val
, ParamValue
->second
,
733 ForwardedRegWorklist
[ParamFwdReg
], Params
);
734 } else if (ParamValue
->first
.isReg()) {
735 Register RegLoc
= ParamValue
->first
.getReg();
736 Register SP
= TLI
.getStackPointerRegisterToSaveRestore();
737 Register FP
= TRI
.getFrameRegister(*MF
);
738 bool IsSPorFP
= (RegLoc
== SP
) || (RegLoc
== FP
);
739 if (TRI
.isCalleeSavedPhysReg(RegLoc
, *MF
) || IsSPorFP
) {
740 MachineLocation
MLoc(RegLoc
, /*Indirect=*/IsSPorFP
);
741 finishCallSiteParams(MLoc
, ParamValue
->second
,
742 ForwardedRegWorklist
[ParamFwdReg
], Params
);
744 // ParamFwdReg was described by the non-callee saved register
745 // RegLoc. Mark that the call site values for the parameters are
746 // dependent on that register instead of ParamFwdReg. Since RegLoc
747 // may be a register that will be handled in this iteration, we
748 // postpone adding the items to the worklist, and instead keep them
749 // in a temporary container.
750 addToFwdRegWorklist(TmpWorklistItems
, RegLoc
, ParamValue
->second
,
751 ForwardedRegWorklist
[ParamFwdReg
]);
757 // Remove all registers that this instruction defines from the worklist.
758 for (auto ParamFwdReg
: FwdRegDefs
)
759 ForwardedRegWorklist
.erase(ParamFwdReg
);
761 // Now that we are done handling this instruction, add items from the
762 // temporary worklist to the real one.
763 for (auto &New
: TmpWorklistItems
)
764 addToFwdRegWorklist(ForwardedRegWorklist
, New
.first
, EmptyExpr
, New
.second
);
765 TmpWorklistItems
.clear();
768 static bool interpretNextInstr(const MachineInstr
*CurMI
,
769 FwdRegWorklist
&ForwardedRegWorklist
,
771 // Skip bundle headers.
772 if (CurMI
->isBundle())
775 // If the next instruction is a call we can not interpret parameter's
776 // forwarding registers or we finished the interpretation of all
781 if (ForwardedRegWorklist
.empty())
784 // Avoid NOP description.
785 if (CurMI
->getNumOperands() == 0)
788 interpretValues(CurMI
, ForwardedRegWorklist
, Params
);
793 /// Try to interpret values loaded into registers that forward parameters
794 /// for \p CallMI. Store parameters with interpreted value into \p Params.
795 static void collectCallSiteParameters(const MachineInstr
*CallMI
,
797 const MachineFunction
*MF
= CallMI
->getMF();
798 const auto &CalleesMap
= MF
->getCallSitesInfo();
799 auto CallFwdRegsInfo
= CalleesMap
.find(CallMI
);
801 // There is no information for the call instruction.
802 if (CallFwdRegsInfo
== CalleesMap
.end())
805 const MachineBasicBlock
*MBB
= CallMI
->getParent();
807 // Skip the call instruction.
808 auto I
= std::next(CallMI
->getReverseIterator());
810 FwdRegWorklist ForwardedRegWorklist
;
812 const DIExpression
*EmptyExpr
=
813 DIExpression::get(MF
->getFunction().getContext(), {});
815 // Add all the forwarding registers into the ForwardedRegWorklist.
816 for (const auto &ArgReg
: CallFwdRegsInfo
->second
) {
818 ForwardedRegWorklist
.insert({ArgReg
.Reg
, {{ArgReg
.Reg
, EmptyExpr
}}})
820 assert(InsertedReg
&& "Single register used to forward two arguments?");
824 // Do not emit CSInfo for undef forwarding registers.
825 for (auto &MO
: CallMI
->uses())
826 if (MO
.isReg() && MO
.isUndef())
827 ForwardedRegWorklist
.erase(MO
.getReg());
829 // We erase, from the ForwardedRegWorklist, those forwarding registers for
830 // which we successfully describe a loaded value (by using
831 // the describeLoadedValue()). For those remaining arguments in the working
832 // list, for which we do not describe a loaded value by
833 // the describeLoadedValue(), we try to generate an entry value expression
834 // for their call site value description, if the call is within the entry MBB.
835 // TODO: Handle situations when call site parameter value can be described
836 // as the entry value within basic blocks other than the first one.
837 bool ShouldTryEmitEntryVals
= MBB
->getIterator() == MF
->begin();
839 // Search for a loading value in forwarding registers inside call delay slot.
840 if (CallMI
->hasDelaySlot()) {
841 auto Suc
= std::next(CallMI
->getIterator());
842 // Only one-instruction delay slot is supported.
843 auto BundleEnd
= llvm::getBundleEnd(CallMI
->getIterator());
845 assert(std::next(Suc
) == BundleEnd
&&
846 "More than one instruction in call delay slot");
847 // Try to interpret value loaded by instruction.
848 if (!interpretNextInstr(&*Suc
, ForwardedRegWorklist
, Params
))
852 // Search for a loading value in forwarding registers.
853 for (; I
!= MBB
->rend(); ++I
) {
854 // Try to interpret values loaded by instruction.
855 if (!interpretNextInstr(&*I
, ForwardedRegWorklist
, Params
))
859 // Emit the call site parameter's value as an entry value.
860 if (ShouldTryEmitEntryVals
) {
861 // Create an expression where the register's entry value is used.
862 DIExpression
*EntryExpr
= DIExpression::get(
863 MF
->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value
, 1});
864 for (auto &RegEntry
: ForwardedRegWorklist
) {
865 MachineLocation
MLoc(RegEntry
.first
);
866 finishCallSiteParams(MLoc
, EntryExpr
, RegEntry
.second
, Params
);
871 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram
&SP
,
872 DwarfCompileUnit
&CU
, DIE
&ScopeDIE
,
873 const MachineFunction
&MF
) {
874 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
875 // the subprogram is required to have one.
876 if (!SP
.areAllCallsDescribed() || !SP
.isDefinition())
879 // Use DW_AT_call_all_calls to express that call site entries are present
880 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
881 // because one of its requirements is not met: call site entries for
882 // optimized-out calls are elided.
883 CU
.addFlag(ScopeDIE
, CU
.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls
));
885 const TargetInstrInfo
*TII
= MF
.getSubtarget().getInstrInfo();
886 assert(TII
&& "TargetInstrInfo not found: cannot label tail calls");
888 // Delay slot support check.
889 auto delaySlotSupported
= [&](const MachineInstr
&MI
) {
890 if (!MI
.isBundledWithSucc())
892 auto Suc
= std::next(MI
.getIterator());
893 auto CallInstrBundle
= getBundleStart(MI
.getIterator());
894 (void)CallInstrBundle
;
895 auto DelaySlotBundle
= getBundleStart(Suc
);
896 (void)DelaySlotBundle
;
897 // Ensure that label after call is following delay slot instruction.
898 // Ex. CALL_INSTRUCTION {
899 // DELAY_SLOT_INSTRUCTION }
901 assert(getLabelAfterInsn(&*CallInstrBundle
) ==
902 getLabelAfterInsn(&*DelaySlotBundle
) &&
903 "Call and its successor instruction don't have same label after.");
907 // Emit call site entries for each call or tail call in the function.
908 for (const MachineBasicBlock
&MBB
: MF
) {
909 for (const MachineInstr
&MI
: MBB
.instrs()) {
910 // Bundles with call in them will pass the isCall() test below but do not
911 // have callee operand information so skip them here. Iterator will
912 // eventually reach the call MI.
916 // Skip instructions which aren't calls. Both calls and tail-calling jump
917 // instructions (e.g TAILJMPd64) are classified correctly here.
918 if (!MI
.isCandidateForCallSiteEntry())
921 // Skip instructions marked as frame setup, as they are not interesting to
923 if (MI
.getFlag(MachineInstr::FrameSetup
))
926 // Check if delay slot support is enabled.
927 if (MI
.hasDelaySlot() && !delaySlotSupported(*&MI
))
930 // If this is a direct call, find the callee's subprogram.
931 // In the case of an indirect call find the register that holds
933 const MachineOperand
&CalleeOp
= TII
->getCalleeOperand(MI
);
934 if (!CalleeOp
.isGlobal() &&
935 (!CalleeOp
.isReg() ||
936 !Register::isPhysicalRegister(CalleeOp
.getReg())))
939 unsigned CallReg
= 0;
940 const DISubprogram
*CalleeSP
= nullptr;
941 const Function
*CalleeDecl
= nullptr;
942 if (CalleeOp
.isReg()) {
943 CallReg
= CalleeOp
.getReg();
947 CalleeDecl
= dyn_cast
<Function
>(CalleeOp
.getGlobal());
948 if (!CalleeDecl
|| !CalleeDecl
->getSubprogram())
950 CalleeSP
= CalleeDecl
->getSubprogram();
953 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
955 bool IsTail
= TII
->isTailCall(MI
);
957 // If MI is in a bundle, the label was created after the bundle since
958 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
959 // to search for that label below.
960 const MachineInstr
*TopLevelCallMI
=
961 MI
.isInsideBundle() ? &*getBundleStart(MI
.getIterator()) : &MI
;
963 // For non-tail calls, the return PC is needed to disambiguate paths in
964 // the call graph which could lead to some target function. For tail
965 // calls, no return PC information is needed, unless tuning for GDB in
966 // DWARF4 mode in which case we fake a return PC for compatibility.
967 const MCSymbol
*PCAddr
=
968 (!IsTail
|| CU
.useGNUAnalogForDwarf5Feature())
969 ? const_cast<MCSymbol
*>(getLabelAfterInsn(TopLevelCallMI
))
972 // For tail calls, it's necessary to record the address of the branch
973 // instruction so that the debugger can show where the tail call occurred.
974 const MCSymbol
*CallAddr
=
975 IsTail
? getLabelBeforeInsn(TopLevelCallMI
) : nullptr;
977 assert((IsTail
|| PCAddr
) && "Non-tail call without return PC");
979 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF
.getName() << " -> "
980 << (CalleeDecl
? CalleeDecl
->getName()
981 : StringRef(MF
.getSubtarget()
984 << (IsTail
? " [IsTail]" : "") << "\n");
986 DIE
&CallSiteDIE
= CU
.constructCallSiteEntryDIE(
987 ScopeDIE
, CalleeSP
, IsTail
, PCAddr
, CallAddr
, CallReg
);
989 // Optionally emit call-site-param debug info.
990 if (emitDebugEntryValues()) {
992 // Try to interpret values of call site parameters.
993 collectCallSiteParameters(&MI
, Params
);
994 CU
.constructCallSiteParmEntryDIEs(CallSiteDIE
, Params
);
1000 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit
&U
, DIE
&D
) const {
1001 if (!U
.hasDwarfPubSections())
1004 U
.addFlag(D
, dwarf::DW_AT_GNU_pubnames
);
1007 void DwarfDebug::finishUnitAttributes(const DICompileUnit
*DIUnit
,
1008 DwarfCompileUnit
&NewCU
) {
1009 DIE
&Die
= NewCU
.getUnitDie();
1010 StringRef FN
= DIUnit
->getFilename();
1012 StringRef Producer
= DIUnit
->getProducer();
1013 StringRef Flags
= DIUnit
->getFlags();
1014 if (!Flags
.empty() && !useAppleExtensionAttributes()) {
1015 std::string ProducerWithFlags
= Producer
.str() + " " + Flags
.str();
1016 NewCU
.addString(Die
, dwarf::DW_AT_producer
, ProducerWithFlags
);
1018 NewCU
.addString(Die
, dwarf::DW_AT_producer
, Producer
);
1020 NewCU
.addUInt(Die
, dwarf::DW_AT_language
, dwarf::DW_FORM_data2
,
1021 DIUnit
->getSourceLanguage());
1022 NewCU
.addString(Die
, dwarf::DW_AT_name
, FN
);
1023 StringRef SysRoot
= DIUnit
->getSysRoot();
1024 if (!SysRoot
.empty())
1025 NewCU
.addString(Die
, dwarf::DW_AT_LLVM_sysroot
, SysRoot
);
1026 StringRef SDK
= DIUnit
->getSDK();
1028 NewCU
.addString(Die
, dwarf::DW_AT_APPLE_sdk
, SDK
);
1030 // Add DW_str_offsets_base to the unit DIE, except for split units.
1031 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
1032 NewCU
.addStringOffsetsStart();
1034 if (!useSplitDwarf()) {
1035 NewCU
.initStmtList();
1037 // If we're using split dwarf the compilation dir is going to be in the
1038 // skeleton CU and so we don't need to duplicate it here.
1039 if (!CompilationDir
.empty())
1040 NewCU
.addString(Die
, dwarf::DW_AT_comp_dir
, CompilationDir
);
1041 addGnuPubAttributes(NewCU
, Die
);
1044 if (useAppleExtensionAttributes()) {
1045 if (DIUnit
->isOptimized())
1046 NewCU
.addFlag(Die
, dwarf::DW_AT_APPLE_optimized
);
1048 StringRef Flags
= DIUnit
->getFlags();
1050 NewCU
.addString(Die
, dwarf::DW_AT_APPLE_flags
, Flags
);
1052 if (unsigned RVer
= DIUnit
->getRuntimeVersion())
1053 NewCU
.addUInt(Die
, dwarf::DW_AT_APPLE_major_runtime_vers
,
1054 dwarf::DW_FORM_data1
, RVer
);
1057 if (DIUnit
->getDWOId()) {
1058 // This CU is either a clang module DWO or a skeleton CU.
1059 NewCU
.addUInt(Die
, dwarf::DW_AT_GNU_dwo_id
, dwarf::DW_FORM_data8
,
1060 DIUnit
->getDWOId());
1061 if (!DIUnit
->getSplitDebugFilename().empty()) {
1062 // This is a prefabricated skeleton CU.
1063 dwarf::Attribute attrDWOName
= getDwarfVersion() >= 5
1064 ? dwarf::DW_AT_dwo_name
1065 : dwarf::DW_AT_GNU_dwo_name
;
1066 NewCU
.addString(Die
, attrDWOName
, DIUnit
->getSplitDebugFilename());
1070 // Create new DwarfCompileUnit for the given metadata node with tag
1071 // DW_TAG_compile_unit.
1073 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit
*DIUnit
) {
1074 if (auto *CU
= CUMap
.lookup(DIUnit
))
1077 CompilationDir
= DIUnit
->getDirectory();
1079 auto OwnedUnit
= std::make_unique
<DwarfCompileUnit
>(
1080 InfoHolder
.getUnits().size(), DIUnit
, Asm
, this, &InfoHolder
);
1081 DwarfCompileUnit
&NewCU
= *OwnedUnit
;
1082 InfoHolder
.addUnit(std::move(OwnedUnit
));
1084 for (auto *IE
: DIUnit
->getImportedEntities())
1085 NewCU
.addImportedEntity(IE
);
1087 // LTO with assembly output shares a single line table amongst multiple CUs.
1088 // To avoid the compilation directory being ambiguous, let the line table
1089 // explicitly describe the directory of all files, never relying on the
1090 // compilation directory.
1091 if (!Asm
->OutStreamer
->hasRawTextSupport() || SingleCU
)
1092 Asm
->OutStreamer
->emitDwarfFile0Directive(
1093 CompilationDir
, DIUnit
->getFilename(), getMD5AsBytes(DIUnit
->getFile()),
1094 DIUnit
->getSource(), NewCU
.getUniqueID());
1096 if (useSplitDwarf()) {
1097 NewCU
.setSkeleton(constructSkeletonCU(NewCU
));
1098 NewCU
.setSection(Asm
->getObjFileLowering().getDwarfInfoDWOSection());
1100 finishUnitAttributes(DIUnit
, NewCU
);
1101 NewCU
.setSection(Asm
->getObjFileLowering().getDwarfInfoSection());
1104 CUMap
.insert({DIUnit
, &NewCU
});
1105 CUDieMap
.insert({&NewCU
.getUnitDie(), &NewCU
});
1109 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit
&TheCU
,
1110 const DIImportedEntity
*N
) {
1111 if (isa
<DILocalScope
>(N
->getScope()))
1113 if (DIE
*D
= TheCU
.getOrCreateContextDIE(N
->getScope()))
1114 D
->addChild(TheCU
.constructImportedEntityDIE(N
));
1117 /// Sort and unique GVEs by comparing their fragment offset.
1118 static SmallVectorImpl
<DwarfCompileUnit::GlobalExpr
> &
1119 sortGlobalExprs(SmallVectorImpl
<DwarfCompileUnit::GlobalExpr
> &GVEs
) {
1121 GVEs
, [](DwarfCompileUnit::GlobalExpr A
, DwarfCompileUnit::GlobalExpr B
) {
1122 // Sort order: first null exprs, then exprs without fragment
1123 // info, then sort by fragment offset in bits.
1124 // FIXME: Come up with a more comprehensive comparator so
1125 // the sorting isn't non-deterministic, and so the following
1126 // std::unique call works correctly.
1127 if (!A
.Expr
|| !B
.Expr
)
1129 auto FragmentA
= A
.Expr
->getFragmentInfo();
1130 auto FragmentB
= B
.Expr
->getFragmentInfo();
1131 if (!FragmentA
|| !FragmentB
)
1133 return FragmentA
->OffsetInBits
< FragmentB
->OffsetInBits
;
1135 GVEs
.erase(std::unique(GVEs
.begin(), GVEs
.end(),
1136 [](DwarfCompileUnit::GlobalExpr A
,
1137 DwarfCompileUnit::GlobalExpr B
) {
1138 return A
.Expr
== B
.Expr
;
1144 // Emit all Dwarf sections that should come prior to the content. Create
1145 // global DIEs and emit initial debug info sections. This is invoked by
1146 // the target AsmPrinter.
1147 void DwarfDebug::beginModule(Module
*M
) {
1148 DebugHandlerBase::beginModule(M
);
1150 if (!Asm
|| !MMI
->hasDebugInfo())
1153 unsigned NumDebugCUs
= std::distance(M
->debug_compile_units_begin(),
1154 M
->debug_compile_units_end());
1155 assert(NumDebugCUs
> 0 && "Asm unexpectedly initialized");
1156 assert(MMI
->hasDebugInfo() &&
1157 "DebugInfoAvailabilty unexpectedly not initialized");
1158 SingleCU
= NumDebugCUs
== 1;
1159 DenseMap
<DIGlobalVariable
*, SmallVector
<DwarfCompileUnit::GlobalExpr
, 1>>
1161 for (const GlobalVariable
&Global
: M
->globals()) {
1162 SmallVector
<DIGlobalVariableExpression
*, 1> GVs
;
1163 Global
.getDebugInfo(GVs
);
1164 for (auto *GVE
: GVs
)
1165 GVMap
[GVE
->getVariable()].push_back({&Global
, GVE
->getExpression()});
1168 // Create the symbol that designates the start of the unit's contribution
1169 // to the string offsets table. In a split DWARF scenario, only the skeleton
1170 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1171 if (useSegmentedStringOffsetsTable())
1172 (useSplitDwarf() ? SkeletonHolder
: InfoHolder
)
1173 .setStringOffsetsStartSym(Asm
->createTempSymbol("str_offsets_base"));
1176 // Create the symbols that designates the start of the DWARF v5 range list
1177 // and locations list tables. They are located past the table headers.
1178 if (getDwarfVersion() >= 5) {
1179 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
1180 Holder
.setRnglistsTableBaseSym(
1181 Asm
->createTempSymbol("rnglists_table_base"));
1183 if (useSplitDwarf())
1184 InfoHolder
.setRnglistsTableBaseSym(
1185 Asm
->createTempSymbol("rnglists_dwo_table_base"));
1188 // Create the symbol that points to the first entry following the debug
1189 // address table (.debug_addr) header.
1190 AddrPool
.setLabel(Asm
->createTempSymbol("addr_table_base"));
1191 DebugLocs
.setSym(Asm
->createTempSymbol("loclists_table_base"));
1193 for (DICompileUnit
*CUNode
: M
->debug_compile_units()) {
1194 // FIXME: Move local imported entities into a list attached to the
1195 // subprogram, then this search won't be needed and a
1196 // getImportedEntities().empty() test should go below with the rest.
1197 bool HasNonLocalImportedEntities
= llvm::any_of(
1198 CUNode
->getImportedEntities(), [](const DIImportedEntity
*IE
) {
1199 return !isa
<DILocalScope
>(IE
->getScope());
1202 if (!HasNonLocalImportedEntities
&& CUNode
->getEnumTypes().empty() &&
1203 CUNode
->getRetainedTypes().empty() &&
1204 CUNode
->getGlobalVariables().empty() && CUNode
->getMacros().empty())
1207 DwarfCompileUnit
&CU
= getOrCreateDwarfCompileUnit(CUNode
);
1209 // Global Variables.
1210 for (auto *GVE
: CUNode
->getGlobalVariables()) {
1211 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1212 // already know about the variable and it isn't adding a constant
1214 auto &GVMapEntry
= GVMap
[GVE
->getVariable()];
1215 auto *Expr
= GVE
->getExpression();
1216 if (!GVMapEntry
.size() || (Expr
&& Expr
->isConstant()))
1217 GVMapEntry
.push_back({nullptr, Expr
});
1220 DenseSet
<DIGlobalVariable
*> Processed
;
1221 for (auto *GVE
: CUNode
->getGlobalVariables()) {
1222 DIGlobalVariable
*GV
= GVE
->getVariable();
1223 if (Processed
.insert(GV
).second
)
1224 CU
.getOrCreateGlobalVariableDIE(GV
, sortGlobalExprs(GVMap
[GV
]));
1227 for (auto *Ty
: CUNode
->getEnumTypes())
1228 CU
.getOrCreateTypeDIE(cast
<DIType
>(Ty
));
1230 for (auto *Ty
: CUNode
->getRetainedTypes()) {
1231 // The retained types array by design contains pointers to
1232 // MDNodes rather than DIRefs. Unique them here.
1233 if (DIType
*RT
= dyn_cast
<DIType
>(Ty
))
1234 // There is no point in force-emitting a forward declaration.
1235 CU
.getOrCreateTypeDIE(RT
);
1237 // Emit imported_modules last so that the relevant context is already
1239 for (auto *IE
: CUNode
->getImportedEntities())
1240 constructAndAddImportedEntityDIE(CU
, IE
);
1244 void DwarfDebug::finishEntityDefinitions() {
1245 for (const auto &Entity
: ConcreteEntities
) {
1246 DIE
*Die
= Entity
->getDIE();
1248 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1249 // in the ConcreteEntities list, rather than looking it up again here.
1250 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1251 DwarfCompileUnit
*Unit
= CUDieMap
.lookup(Die
->getUnitDie());
1253 Unit
->finishEntityDefinition(Entity
.get());
1257 void DwarfDebug::finishSubprogramDefinitions() {
1258 for (const DISubprogram
*SP
: ProcessedSPNodes
) {
1259 assert(SP
->getUnit()->getEmissionKind() != DICompileUnit::NoDebug
);
1261 getOrCreateDwarfCompileUnit(SP
->getUnit()),
1262 [&](DwarfCompileUnit
&CU
) { CU
.finishSubprogramDefinition(SP
); });
1266 void DwarfDebug::finalizeModuleInfo() {
1267 const TargetLoweringObjectFile
&TLOF
= Asm
->getObjFileLowering();
1269 finishSubprogramDefinitions();
1271 finishEntityDefinitions();
1273 // Include the DWO file name in the hash if there's more than one CU.
1274 // This handles ThinLTO's situation where imported CUs may very easily be
1275 // duplicate with the same CU partially imported into another ThinLTO unit.
1277 if (CUMap
.size() > 1)
1278 DWOName
= Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
;
1280 // Handle anything that needs to be done on a per-unit basis after
1281 // all other generation.
1282 for (const auto &P
: CUMap
) {
1283 auto &TheCU
= *P
.second
;
1284 if (TheCU
.getCUNode()->isDebugDirectivesOnly())
1286 // Emit DW_AT_containing_type attribute to connect types with their
1287 // vtable holding type.
1288 TheCU
.constructContainingTypeDIEs();
1290 // Add CU specific attributes if we need to add any.
1291 // If we're splitting the dwarf out now that we've got the entire
1292 // CU then add the dwo id to it.
1293 auto *SkCU
= TheCU
.getSkeleton();
1295 bool HasSplitUnit
= SkCU
&& !TheCU
.getUnitDie().children().empty();
1298 dwarf::Attribute attrDWOName
= getDwarfVersion() >= 5
1299 ? dwarf::DW_AT_dwo_name
1300 : dwarf::DW_AT_GNU_dwo_name
;
1301 finishUnitAttributes(TheCU
.getCUNode(), TheCU
);
1302 TheCU
.addString(TheCU
.getUnitDie(), attrDWOName
,
1303 Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
);
1304 SkCU
->addString(SkCU
->getUnitDie(), attrDWOName
,
1305 Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
);
1306 // Emit a unique identifier for this CU.
1308 DIEHash(Asm
, &TheCU
).computeCUSignature(DWOName
, TheCU
.getUnitDie());
1309 if (getDwarfVersion() >= 5) {
1313 TheCU
.addUInt(TheCU
.getUnitDie(), dwarf::DW_AT_GNU_dwo_id
,
1314 dwarf::DW_FORM_data8
, ID
);
1315 SkCU
->addUInt(SkCU
->getUnitDie(), dwarf::DW_AT_GNU_dwo_id
,
1316 dwarf::DW_FORM_data8
, ID
);
1319 if (getDwarfVersion() < 5 && !SkeletonHolder
.getRangeLists().empty()) {
1320 const MCSymbol
*Sym
= TLOF
.getDwarfRangesSection()->getBeginSymbol();
1321 SkCU
->addSectionLabel(SkCU
->getUnitDie(), dwarf::DW_AT_GNU_ranges_base
,
1325 finishUnitAttributes(SkCU
->getCUNode(), *SkCU
);
1328 // If we have code split among multiple sections or non-contiguous
1329 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1330 // remain in the .o file, otherwise add a DW_AT_low_pc.
1331 // FIXME: We should use ranges allow reordering of code ala
1332 // .subsections_via_symbols in mach-o. This would mean turning on
1333 // ranges for all subprogram DIEs for mach-o.
1334 DwarfCompileUnit
&U
= SkCU
? *SkCU
: TheCU
;
1336 if (unsigned NumRanges
= TheCU
.getRanges().size()) {
1337 if (NumRanges
> 1 && useRangesSection())
1338 // A DW_AT_low_pc attribute may also be specified in combination with
1339 // DW_AT_ranges to specify the default base address for use in
1340 // location lists (see Section 2.6.2) and range lists (see Section
1342 U
.addUInt(U
.getUnitDie(), dwarf::DW_AT_low_pc
, dwarf::DW_FORM_addr
, 0);
1344 U
.setBaseAddress(TheCU
.getRanges().front().Begin
);
1345 U
.attachRangesOrLowHighPC(U
.getUnitDie(), TheCU
.takeRanges());
1348 // We don't keep track of which addresses are used in which CU so this
1349 // is a bit pessimistic under LTO.
1350 if ((HasSplitUnit
|| getDwarfVersion() >= 5) && !AddrPool
.isEmpty())
1351 U
.addAddrTableBase();
1353 if (getDwarfVersion() >= 5) {
1354 if (U
.hasRangeLists())
1355 U
.addRnglistsBase();
1357 if (!DebugLocs
.getLists().empty()) {
1358 if (!useSplitDwarf())
1359 U
.addSectionLabel(U
.getUnitDie(), dwarf::DW_AT_loclists_base
,
1361 TLOF
.getDwarfLoclistsSection()->getBeginSymbol());
1365 auto *CUNode
= cast
<DICompileUnit
>(P
.first
);
1366 // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1368 if (CUNode
->getMacros()) {
1369 if (UseDebugMacroSection
) {
1370 if (useSplitDwarf())
1371 TheCU
.addSectionDelta(
1372 TheCU
.getUnitDie(), dwarf::DW_AT_macros
, U
.getMacroLabelBegin(),
1373 TLOF
.getDwarfMacroDWOSection()->getBeginSymbol());
1375 dwarf::Attribute MacrosAttr
= getDwarfVersion() >= 5
1376 ? dwarf::DW_AT_macros
1377 : dwarf::DW_AT_GNU_macros
;
1378 U
.addSectionLabel(U
.getUnitDie(), MacrosAttr
, U
.getMacroLabelBegin(),
1379 TLOF
.getDwarfMacroSection()->getBeginSymbol());
1382 if (useSplitDwarf())
1383 TheCU
.addSectionDelta(
1384 TheCU
.getUnitDie(), dwarf::DW_AT_macro_info
,
1385 U
.getMacroLabelBegin(),
1386 TLOF
.getDwarfMacinfoDWOSection()->getBeginSymbol());
1388 U
.addSectionLabel(U
.getUnitDie(), dwarf::DW_AT_macro_info
,
1389 U
.getMacroLabelBegin(),
1390 TLOF
.getDwarfMacinfoSection()->getBeginSymbol());
1395 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1396 for (auto *CUNode
: MMI
->getModule()->debug_compile_units())
1397 if (CUNode
->getDWOId())
1398 getOrCreateDwarfCompileUnit(CUNode
);
1400 // Compute DIE offsets and sizes.
1401 InfoHolder
.computeSizeAndOffsets();
1402 if (useSplitDwarf())
1403 SkeletonHolder
.computeSizeAndOffsets();
1406 // Emit all Dwarf sections that should come after the content.
1407 void DwarfDebug::endModule() {
1408 // Terminate the pending line table.
1410 terminateLineTable(PrevCU
);
1412 assert(CurFn
== nullptr);
1413 assert(CurMI
== nullptr);
1415 for (const auto &P
: CUMap
) {
1416 auto &CU
= *P
.second
;
1417 CU
.createBaseTypeDIEs();
1420 // If we aren't actually generating debug info (check beginModule -
1421 // conditionalized on the presence of the llvm.dbg.cu metadata node)
1422 if (!Asm
|| !MMI
->hasDebugInfo())
1425 // Finalize the debug info for the module.
1426 finalizeModuleInfo();
1428 if (useSplitDwarf())
1429 // Emit debug_loc.dwo/debug_loclists.dwo section.
1432 // Emit debug_loc/debug_loclists section.
1435 // Corresponding abbreviations into a abbrev section.
1436 emitAbbreviations();
1438 // Emit all the DIEs into a debug info section.
1441 // Emit info into a debug aranges section.
1442 if (GenerateARangeSection
)
1445 // Emit info into a debug ranges section.
1448 if (useSplitDwarf())
1449 // Emit info into a debug macinfo.dwo section.
1450 emitDebugMacinfoDWO();
1452 // Emit info into a debug macinfo/macro section.
1457 if (useSplitDwarf()) {
1460 emitDebugAbbrevDWO();
1462 emitDebugRangesDWO();
1467 // Emit info into the dwarf accelerator table sections.
1468 switch (getAccelTableKind()) {
1469 case AccelTableKind::Apple
:
1472 emitAccelNamespaces();
1475 case AccelTableKind::Dwarf
:
1476 emitAccelDebugNames();
1478 case AccelTableKind::None
:
1480 case AccelTableKind::Default
:
1481 llvm_unreachable("Default should have already been resolved.");
1484 // Emit the pubnames and pubtypes sections if requested.
1485 emitDebugPubSections();
1488 // FIXME: AbstractVariables.clear();
1491 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit
&CU
,
1493 const MDNode
*ScopeNode
) {
1494 if (CU
.getExistingAbstractEntity(Node
))
1497 CU
.createAbstractEntity(Node
, LScopes
.getOrCreateAbstractScope(
1498 cast
<DILocalScope
>(ScopeNode
)));
1501 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit
&CU
,
1502 const DINode
*Node
, const MDNode
*ScopeNode
) {
1503 if (CU
.getExistingAbstractEntity(Node
))
1506 if (LexicalScope
*Scope
=
1507 LScopes
.findAbstractScope(cast_or_null
<DILocalScope
>(ScopeNode
)))
1508 CU
.createAbstractEntity(Node
, Scope
);
1511 // Collect variable information from side table maintained by MF.
1512 void DwarfDebug::collectVariableInfoFromMFTable(
1513 DwarfCompileUnit
&TheCU
, DenseSet
<InlinedEntity
> &Processed
) {
1514 SmallDenseMap
<InlinedEntity
, DbgVariable
*> MFVars
;
1515 LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1516 for (const auto &VI
: Asm
->MF
->getVariableDbgInfo()) {
1519 assert(VI
.Var
->isValidLocationForIntrinsic(VI
.Loc
) &&
1520 "Expected inlined-at fields to agree");
1522 InlinedEntity
Var(VI
.Var
, VI
.Loc
->getInlinedAt());
1523 Processed
.insert(Var
);
1524 LexicalScope
*Scope
= LScopes
.findLexicalScope(VI
.Loc
);
1526 // If variable scope is not found then skip this variable.
1528 LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI
.Var
->getName()
1529 << ", no variable scope found\n");
1533 ensureAbstractEntityIsCreatedIfScoped(TheCU
, Var
.first
, Scope
->getScopeNode());
1534 auto RegVar
= std::make_unique
<DbgVariable
>(
1535 cast
<DILocalVariable
>(Var
.first
), Var
.second
);
1536 RegVar
->initializeMMI(VI
.Expr
, VI
.Slot
);
1537 LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI
.Var
->getName()
1540 if (DbgVariable
*DbgVar
= MFVars
.lookup(Var
))
1541 DbgVar
->addMMIEntry(*RegVar
);
1542 else if (InfoHolder
.addScopeVariable(Scope
, RegVar
.get())) {
1543 MFVars
.insert({Var
, RegVar
.get()});
1544 ConcreteEntities
.push_back(std::move(RegVar
));
1549 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1550 /// enclosing lexical scope. The check ensures there are no other instructions
1551 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1552 /// either open or otherwise rolls off the end of the scope.
1553 static bool validThroughout(LexicalScopes
&LScopes
,
1554 const MachineInstr
*DbgValue
,
1555 const MachineInstr
*RangeEnd
,
1556 const InstructionOrdering
&Ordering
) {
1557 assert(DbgValue
->getDebugLoc() && "DBG_VALUE without a debug location");
1558 auto MBB
= DbgValue
->getParent();
1559 auto DL
= DbgValue
->getDebugLoc();
1560 auto *LScope
= LScopes
.findLexicalScope(DL
);
1561 // Scope doesn't exist; this is a dead DBG_VALUE.
1564 auto &LSRange
= LScope
->getRanges();
1565 if (LSRange
.size() == 0)
1568 const MachineInstr
*LScopeBegin
= LSRange
.front().first
;
1569 // If the scope starts before the DBG_VALUE then we may have a negative
1570 // result. Otherwise the location is live coming into the scope and we
1571 // can skip the following checks.
1572 if (!Ordering
.isBefore(DbgValue
, LScopeBegin
)) {
1573 // Exit if the lexical scope begins outside of the current block.
1574 if (LScopeBegin
->getParent() != MBB
)
1577 MachineBasicBlock::const_reverse_iterator
Pred(DbgValue
);
1578 for (++Pred
; Pred
!= MBB
->rend(); ++Pred
) {
1579 if (Pred
->getFlag(MachineInstr::FrameSetup
))
1581 auto PredDL
= Pred
->getDebugLoc();
1582 if (!PredDL
|| Pred
->isMetaInstruction())
1584 // Check whether the instruction preceding the DBG_VALUE is in the same
1585 // (sub)scope as the DBG_VALUE.
1586 if (DL
->getScope() == PredDL
->getScope())
1588 auto *PredScope
= LScopes
.findLexicalScope(PredDL
);
1589 if (!PredScope
|| LScope
->dominates(PredScope
))
1594 // If the range of the DBG_VALUE is open-ended, report success.
1598 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1599 // throughout the function. This is a hack, presumably for DWARF v2 and not
1600 // necessarily correct. It would be much better to use a dbg.declare instead
1601 // if we know the constant is live throughout the scope.
1602 if (MBB
->pred_empty() &&
1603 all_of(DbgValue
->debug_operands(),
1604 [](const MachineOperand
&Op
) { return Op
.isImm(); }))
1607 // Test if the location terminates before the end of the scope.
1608 const MachineInstr
*LScopeEnd
= LSRange
.back().second
;
1609 if (Ordering
.isBefore(RangeEnd
, LScopeEnd
))
1612 // There's a single location which starts at the scope start, and ends at or
1613 // after the scope end.
1617 /// Build the location list for all DBG_VALUEs in the function that
1618 /// describe the same variable. The resulting DebugLocEntries will have
1619 /// strict monotonically increasing begin addresses and will never
1620 /// overlap. If the resulting list has only one entry that is valid
1621 /// throughout variable's scope return true.
1623 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1624 // different kinds of history map entries. One thing to be aware of is that if
1625 // a debug value is ended by another entry (rather than being valid until the
1626 // end of the function), that entry's instruction may or may not be included in
1627 // the range, depending on if the entry is a clobbering entry (it has an
1628 // instruction that clobbers one or more preceding locations), or if it is an
1629 // (overlapping) debug value entry. This distinction can be seen in the example
1630 // below. The first debug value is ended by the clobbering entry 2, and the
1631 // second and third debug values are ended by the overlapping debug value entry
1636 // History map entries [type, end index, mi]
1638 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1639 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1640 // 2 | | [Clobber, $reg0 = [...], -, -]
1641 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1642 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1644 // Output [start, end) [Value...]:
1646 // [0-1) [(reg0, fragment 0, 32)]
1647 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1648 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1649 // [4-) [(@g, fragment 0, 96)]
1650 bool DwarfDebug::buildLocationList(SmallVectorImpl
<DebugLocEntry
> &DebugLoc
,
1651 const DbgValueHistoryMap::Entries
&Entries
) {
1653 std::pair
<DbgValueHistoryMap::EntryIndex
, DbgValueLoc
>;
1654 SmallVector
<OpenRange
, 4> OpenRanges
;
1655 bool isSafeForSingleLocation
= true;
1656 const MachineInstr
*StartDebugMI
= nullptr;
1657 const MachineInstr
*EndMI
= nullptr;
1659 for (auto EB
= Entries
.begin(), EI
= EB
, EE
= Entries
.end(); EI
!= EE
; ++EI
) {
1660 const MachineInstr
*Instr
= EI
->getInstr();
1662 // Remove all values that are no longer live.
1663 size_t Index
= std::distance(EB
, EI
);
1664 erase_if(OpenRanges
, [&](OpenRange
&R
) { return R
.first
<= Index
; });
1666 // If we are dealing with a clobbering entry, this iteration will result in
1667 // a location list entry starting after the clobbering instruction.
1668 const MCSymbol
*StartLabel
=
1669 EI
->isClobber() ? getLabelAfterInsn(Instr
) : getLabelBeforeInsn(Instr
);
1670 assert(StartLabel
&&
1671 "Forgot label before/after instruction starting a range!");
1673 const MCSymbol
*EndLabel
;
1674 if (std::next(EI
) == Entries
.end()) {
1675 const MachineBasicBlock
&EndMBB
= Asm
->MF
->back();
1676 EndLabel
= Asm
->MBBSectionRanges
[EndMBB
.getSectionIDNum()].EndLabel
;
1677 if (EI
->isClobber())
1678 EndMI
= EI
->getInstr();
1680 else if (std::next(EI
)->isClobber())
1681 EndLabel
= getLabelAfterInsn(std::next(EI
)->getInstr());
1683 EndLabel
= getLabelBeforeInsn(std::next(EI
)->getInstr());
1684 assert(EndLabel
&& "Forgot label after instruction ending a range!");
1686 if (EI
->isDbgValue())
1687 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr
<< "\n");
1689 // If this history map entry has a debug value, add that to the list of
1690 // open ranges and check if its location is valid for a single value
1692 if (EI
->isDbgValue()) {
1693 // Do not add undef debug values, as they are redundant information in
1694 // the location list entries. An undef debug results in an empty location
1695 // description. If there are any non-undef fragments then padding pieces
1696 // with empty location descriptions will automatically be inserted, and if
1697 // all fragments are undef then the whole location list entry is
1699 if (!Instr
->isUndefDebugValue()) {
1700 auto Value
= getDebugLocValue(Instr
);
1701 OpenRanges
.emplace_back(EI
->getEndIndex(), Value
);
1703 // TODO: Add support for single value fragment locations.
1704 if (Instr
->getDebugExpression()->isFragment())
1705 isSafeForSingleLocation
= false;
1708 StartDebugMI
= Instr
;
1710 isSafeForSingleLocation
= false;
1714 // Location list entries with empty location descriptions are redundant
1715 // information in DWARF, so do not emit those.
1716 if (OpenRanges
.empty())
1719 // Omit entries with empty ranges as they do not have any effect in DWARF.
1720 if (StartLabel
== EndLabel
) {
1721 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1725 SmallVector
<DbgValueLoc
, 4> Values
;
1726 for (auto &R
: OpenRanges
)
1727 Values
.push_back(R
.second
);
1729 // With Basic block sections, it is posssible that the StartLabel and the
1730 // Instr are not in the same section. This happens when the StartLabel is
1731 // the function begin label and the dbg value appears in a basic block
1732 // that is not the entry. In this case, the range needs to be split to
1733 // span each individual section in the range from StartLabel to EndLabel.
1734 if (Asm
->MF
->hasBBSections() && StartLabel
== Asm
->getFunctionBegin() &&
1735 !Instr
->getParent()->sameSection(&Asm
->MF
->front())) {
1736 const MCSymbol
*BeginSectionLabel
= StartLabel
;
1738 for (const MachineBasicBlock
&MBB
: *Asm
->MF
) {
1739 if (MBB
.isBeginSection() && &MBB
!= &Asm
->MF
->front())
1740 BeginSectionLabel
= MBB
.getSymbol();
1742 if (MBB
.sameSection(Instr
->getParent())) {
1743 DebugLoc
.emplace_back(BeginSectionLabel
, EndLabel
, Values
);
1746 if (MBB
.isEndSection())
1747 DebugLoc
.emplace_back(BeginSectionLabel
, MBB
.getEndSymbol(), Values
);
1750 DebugLoc
.emplace_back(StartLabel
, EndLabel
, Values
);
1753 // Attempt to coalesce the ranges of two otherwise identical
1755 auto CurEntry
= DebugLoc
.rbegin();
1757 dbgs() << CurEntry
->getValues().size() << " Values:\n";
1758 for (auto &Value
: CurEntry
->getValues())
1760 dbgs() << "-----\n";
1763 auto PrevEntry
= std::next(CurEntry
);
1764 if (PrevEntry
!= DebugLoc
.rend() && PrevEntry
->MergeRanges(*CurEntry
))
1765 DebugLoc
.pop_back();
1768 if (!isSafeForSingleLocation
||
1769 !validThroughout(LScopes
, StartDebugMI
, EndMI
, getInstOrdering()))
1772 if (DebugLoc
.size() == 1)
1775 if (!Asm
->MF
->hasBBSections())
1778 // Check here to see if loclist can be merged into a single range. If not,
1779 // we must keep the split loclists per section. This does exactly what
1780 // MergeRanges does without sections. We don't actually merge the ranges
1781 // as the split ranges must be kept intact if this cannot be collapsed
1782 // into a single range.
1783 const MachineBasicBlock
*RangeMBB
= nullptr;
1784 if (DebugLoc
[0].getBeginSym() == Asm
->getFunctionBegin())
1785 RangeMBB
= &Asm
->MF
->front();
1787 RangeMBB
= Entries
.begin()->getInstr()->getParent();
1788 auto *CurEntry
= DebugLoc
.begin();
1789 auto *NextEntry
= std::next(CurEntry
);
1790 while (NextEntry
!= DebugLoc
.end()) {
1791 // Get the last machine basic block of this section.
1792 while (!RangeMBB
->isEndSection())
1793 RangeMBB
= RangeMBB
->getNextNode();
1794 if (!RangeMBB
->getNextNode())
1796 // CurEntry should end the current section and NextEntry should start
1797 // the next section and the Values must match for these two ranges to be
1799 if (CurEntry
->getEndSym() != RangeMBB
->getEndSymbol() ||
1800 NextEntry
->getBeginSym() != RangeMBB
->getNextNode()->getSymbol() ||
1801 CurEntry
->getValues() != NextEntry
->getValues())
1803 RangeMBB
= RangeMBB
->getNextNode();
1804 CurEntry
= NextEntry
;
1805 NextEntry
= std::next(CurEntry
);
1810 DbgEntity
*DwarfDebug::createConcreteEntity(DwarfCompileUnit
&TheCU
,
1811 LexicalScope
&Scope
,
1813 const DILocation
*Location
,
1814 const MCSymbol
*Sym
) {
1815 ensureAbstractEntityIsCreatedIfScoped(TheCU
, Node
, Scope
.getScopeNode());
1816 if (isa
<const DILocalVariable
>(Node
)) {
1817 ConcreteEntities
.push_back(
1818 std::make_unique
<DbgVariable
>(cast
<const DILocalVariable
>(Node
),
1820 InfoHolder
.addScopeVariable(&Scope
,
1821 cast
<DbgVariable
>(ConcreteEntities
.back().get()));
1822 } else if (isa
<const DILabel
>(Node
)) {
1823 ConcreteEntities
.push_back(
1824 std::make_unique
<DbgLabel
>(cast
<const DILabel
>(Node
),
1826 InfoHolder
.addScopeLabel(&Scope
,
1827 cast
<DbgLabel
>(ConcreteEntities
.back().get()));
1829 return ConcreteEntities
.back().get();
1832 // Find variables for each lexical scope.
1833 void DwarfDebug::collectEntityInfo(DwarfCompileUnit
&TheCU
,
1834 const DISubprogram
*SP
,
1835 DenseSet
<InlinedEntity
> &Processed
) {
1836 // Grab the variable info that was squirreled away in the MMI side-table.
1837 collectVariableInfoFromMFTable(TheCU
, Processed
);
1839 for (const auto &I
: DbgValues
) {
1840 InlinedEntity IV
= I
.first
;
1841 if (Processed
.count(IV
))
1844 // Instruction ranges, specifying where IV is accessible.
1845 const auto &HistoryMapEntries
= I
.second
;
1847 // Try to find any non-empty variable location. Do not create a concrete
1848 // entity if there are no locations.
1849 if (!DbgValues
.hasNonEmptyLocation(HistoryMapEntries
))
1852 LexicalScope
*Scope
= nullptr;
1853 const DILocalVariable
*LocalVar
= cast
<DILocalVariable
>(IV
.first
);
1854 if (const DILocation
*IA
= IV
.second
)
1855 Scope
= LScopes
.findInlinedScope(LocalVar
->getScope(), IA
);
1857 Scope
= LScopes
.findLexicalScope(LocalVar
->getScope());
1858 // If variable scope is not found then skip this variable.
1862 Processed
.insert(IV
);
1863 DbgVariable
*RegVar
= cast
<DbgVariable
>(createConcreteEntity(TheCU
,
1864 *Scope
, LocalVar
, IV
.second
));
1866 const MachineInstr
*MInsn
= HistoryMapEntries
.front().getInstr();
1867 assert(MInsn
->isDebugValue() && "History must begin with debug value");
1869 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1870 // If the history map contains a single debug value, there may be an
1871 // additional entry which clobbers the debug value.
1872 size_t HistSize
= HistoryMapEntries
.size();
1873 bool SingleValueWithClobber
=
1874 HistSize
== 2 && HistoryMapEntries
[1].isClobber();
1875 if (HistSize
== 1 || SingleValueWithClobber
) {
1877 SingleValueWithClobber
? HistoryMapEntries
[1].getInstr() : nullptr;
1878 if (validThroughout(LScopes
, MInsn
, End
, getInstOrdering())) {
1879 RegVar
->initializeDbgValue(MInsn
);
1884 // Do not emit location lists if .debug_loc secton is disabled.
1885 if (!useLocSection())
1888 // Handle multiple DBG_VALUE instructions describing one variable.
1889 DebugLocStream::ListBuilder
List(DebugLocs
, TheCU
, *Asm
, *RegVar
, *MInsn
);
1891 // Build the location list for this variable.
1892 SmallVector
<DebugLocEntry
, 8> Entries
;
1893 bool isValidSingleLocation
= buildLocationList(Entries
, HistoryMapEntries
);
1895 // Check whether buildLocationList managed to merge all locations to one
1896 // that is valid throughout the variable's scope. If so, produce single
1898 if (isValidSingleLocation
) {
1899 RegVar
->initializeDbgValue(Entries
[0].getValues()[0]);
1903 // If the variable has a DIBasicType, extract it. Basic types cannot have
1904 // unique identifiers, so don't bother resolving the type with the
1906 const DIBasicType
*BT
= dyn_cast
<DIBasicType
>(
1907 static_cast<const Metadata
*>(LocalVar
->getType()));
1909 // Finalize the entry by lowering it into a DWARF bytestream.
1910 for (auto &Entry
: Entries
)
1911 Entry
.finalize(*Asm
, List
, BT
, TheCU
);
1914 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1915 // DWARF-related DbgLabel.
1916 for (const auto &I
: DbgLabels
) {
1917 InlinedEntity IL
= I
.first
;
1918 const MachineInstr
*MI
= I
.second
;
1922 LexicalScope
*Scope
= nullptr;
1923 const DILabel
*Label
= cast
<DILabel
>(IL
.first
);
1924 // The scope could have an extra lexical block file.
1925 const DILocalScope
*LocalScope
=
1926 Label
->getScope()->getNonLexicalBlockFileScope();
1927 // Get inlined DILocation if it is inlined label.
1928 if (const DILocation
*IA
= IL
.second
)
1929 Scope
= LScopes
.findInlinedScope(LocalScope
, IA
);
1931 Scope
= LScopes
.findLexicalScope(LocalScope
);
1932 // If label scope is not found then skip this label.
1936 Processed
.insert(IL
);
1937 /// At this point, the temporary label is created.
1938 /// Save the temporary label to DbgLabel entity to get the
1939 /// actually address when generating Dwarf DIE.
1940 MCSymbol
*Sym
= getLabelBeforeInsn(MI
);
1941 createConcreteEntity(TheCU
, *Scope
, Label
, IL
.second
, Sym
);
1944 // Collect info for variables/labels that were optimized out.
1945 for (const DINode
*DN
: SP
->getRetainedNodes()) {
1946 if (!Processed
.insert(InlinedEntity(DN
, nullptr)).second
)
1948 LexicalScope
*Scope
= nullptr;
1949 if (auto *DV
= dyn_cast
<DILocalVariable
>(DN
)) {
1950 Scope
= LScopes
.findLexicalScope(DV
->getScope());
1951 } else if (auto *DL
= dyn_cast
<DILabel
>(DN
)) {
1952 Scope
= LScopes
.findLexicalScope(DL
->getScope());
1956 createConcreteEntity(TheCU
, *Scope
, DN
, nullptr);
1960 // Process beginning of an instruction.
1961 void DwarfDebug::beginInstruction(const MachineInstr
*MI
) {
1962 const MachineFunction
&MF
= *MI
->getMF();
1963 const auto *SP
= MF
.getFunction().getSubprogram();
1965 !SP
|| SP
->getUnit()->getEmissionKind() == DICompileUnit::NoDebug
;
1967 // Delay slot support check.
1968 auto delaySlotSupported
= [](const MachineInstr
&MI
) {
1969 if (!MI
.isBundledWithSucc())
1971 auto Suc
= std::next(MI
.getIterator());
1973 // Ensure that delay slot instruction is successor of the call instruction.
1974 // Ex. CALL_INSTRUCTION {
1975 // DELAY_SLOT_INSTRUCTION }
1976 assert(Suc
->isBundledWithPred() &&
1977 "Call bundle instructions are out of order");
1981 // When describing calls, we need a label for the call instruction.
1982 if (!NoDebug
&& SP
->areAllCallsDescribed() &&
1983 MI
->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle
) &&
1984 (!MI
->hasDelaySlot() || delaySlotSupported(*MI
))) {
1985 const TargetInstrInfo
*TII
= MF
.getSubtarget().getInstrInfo();
1986 bool IsTail
= TII
->isTailCall(*MI
);
1987 // For tail calls, we need the address of the branch instruction for
1990 requestLabelBeforeInsn(MI
);
1991 // For non-tail calls, we need the return address for the call for
1992 // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
1993 // tail calls as well.
1994 requestLabelAfterInsn(MI
);
1997 DebugHandlerBase::beginInstruction(MI
);
2004 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2005 // If the instruction is part of the function frame setup code, do not emit
2006 // any line record, as there is no correspondence with any user code.
2007 if (MI
->isMetaInstruction() || MI
->getFlag(MachineInstr::FrameSetup
))
2009 const DebugLoc
&DL
= MI
->getDebugLoc();
2010 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2011 // the last line number actually emitted, to see if it was line 0.
2012 unsigned LastAsmLine
=
2013 Asm
->OutStreamer
->getContext().getCurrentDwarfLoc().getLine();
2015 if (DL
== PrevInstLoc
) {
2016 // If we have an ongoing unspecified location, nothing to do here.
2019 // We have an explicit location, same as the previous location.
2020 // But we might be coming back to it after a line 0 record.
2021 if (LastAsmLine
== 0 && DL
.getLine() != 0) {
2022 // Reinstate the source location but not marked as a statement.
2023 const MDNode
*Scope
= DL
.getScope();
2024 recordSourceLine(DL
.getLine(), DL
.getCol(), Scope
, /*Flags=*/0);
2030 // We have an unspecified location, which might want to be line 0.
2031 // If we have already emitted a line-0 record, don't repeat it.
2032 if (LastAsmLine
== 0)
2034 // If user said Don't Do That, don't do that.
2035 if (UnknownLocations
== Disable
)
2037 // See if we have a reason to emit a line-0 record now.
2038 // Reasons to emit a line-0 record include:
2039 // - User asked for it (UnknownLocations).
2040 // - Instruction has a label, so it's referenced from somewhere else,
2041 // possibly debug information; we want it to have a source location.
2042 // - Instruction is at the top of a block; we don't want to inherit the
2043 // location from the physically previous (maybe unrelated) block.
2044 if (UnknownLocations
== Enable
|| PrevLabel
||
2045 (PrevInstBB
&& PrevInstBB
!= MI
->getParent())) {
2046 // Preserve the file and column numbers, if we can, to save space in
2047 // the encoded line table.
2048 // Do not update PrevInstLoc, it remembers the last non-0 line.
2049 const MDNode
*Scope
= nullptr;
2050 unsigned Column
= 0;
2052 Scope
= PrevInstLoc
.getScope();
2053 Column
= PrevInstLoc
.getCol();
2055 recordSourceLine(/*Line=*/0, Column
, Scope
, /*Flags=*/0);
2060 // We have an explicit location, different from the previous location.
2061 // Don't repeat a line-0 record, but otherwise emit the new location.
2062 // (The new location might be an explicit line 0, which we do emit.)
2063 if (DL
.getLine() == 0 && LastAsmLine
== 0)
2066 if (DL
== PrologEndLoc
) {
2067 Flags
|= DWARF2_FLAG_PROLOGUE_END
| DWARF2_FLAG_IS_STMT
;
2068 PrologEndLoc
= DebugLoc();
2070 // If the line changed, we call that a new statement; unless we went to
2071 // line 0 and came back, in which case it is not a new statement.
2072 unsigned OldLine
= PrevInstLoc
? PrevInstLoc
.getLine() : LastAsmLine
;
2073 if (DL
.getLine() && DL
.getLine() != OldLine
)
2074 Flags
|= DWARF2_FLAG_IS_STMT
;
2076 const MDNode
*Scope
= DL
.getScope();
2077 recordSourceLine(DL
.getLine(), DL
.getCol(), Scope
, Flags
);
2079 // If we're not at line 0, remember this location.
2084 static DebugLoc
findPrologueEndLoc(const MachineFunction
*MF
) {
2085 // First known non-DBG_VALUE and non-frame setup location marks
2086 // the beginning of the function body.
2087 DebugLoc LineZeroLoc
;
2088 for (const auto &MBB
: *MF
) {
2089 for (const auto &MI
: MBB
) {
2090 if (!MI
.isMetaInstruction() && !MI
.getFlag(MachineInstr::FrameSetup
) &&
2092 // Scan forward to try to find a non-zero line number. The prologue_end
2093 // marks the first breakpoint in the function after the frame setup, and
2094 // a compiler-generated line 0 location is not a meaningful breakpoint.
2095 // If none is found, return the first location after the frame setup.
2096 if (MI
.getDebugLoc().getLine())
2097 return MI
.getDebugLoc();
2098 LineZeroLoc
= MI
.getDebugLoc();
2105 /// Register a source line with debug info. Returns the unique label that was
2106 /// emitted and which provides correspondence to the source line list.
2107 static void recordSourceLine(AsmPrinter
&Asm
, unsigned Line
, unsigned Col
,
2108 const MDNode
*S
, unsigned Flags
, unsigned CUID
,
2109 uint16_t DwarfVersion
,
2110 ArrayRef
<std::unique_ptr
<DwarfCompileUnit
>> DCUs
) {
2112 unsigned FileNo
= 1;
2113 unsigned Discriminator
= 0;
2114 if (auto *Scope
= cast_or_null
<DIScope
>(S
)) {
2115 Fn
= Scope
->getFilename();
2116 if (Line
!= 0 && DwarfVersion
>= 4)
2117 if (auto *LBF
= dyn_cast
<DILexicalBlockFile
>(Scope
))
2118 Discriminator
= LBF
->getDiscriminator();
2120 FileNo
= static_cast<DwarfCompileUnit
&>(*DCUs
[CUID
])
2121 .getOrCreateSourceID(Scope
->getFile());
2123 Asm
.OutStreamer
->emitDwarfLocDirective(FileNo
, Line
, Col
, Flags
, 0,
2127 DebugLoc
DwarfDebug::emitInitialLocDirective(const MachineFunction
&MF
,
2129 // Get beginning of function.
2130 if (DebugLoc PrologEndLoc
= findPrologueEndLoc(&MF
)) {
2131 // Ensure the compile unit is created if the function is called before
2133 (void)getOrCreateDwarfCompileUnit(
2134 MF
.getFunction().getSubprogram()->getUnit());
2135 // We'd like to list the prologue as "not statements" but GDB behaves
2136 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2137 const DISubprogram
*SP
= PrologEndLoc
->getInlinedAtScope()->getSubprogram();
2138 ::recordSourceLine(*Asm
, SP
->getScopeLine(), 0, SP
, DWARF2_FLAG_IS_STMT
,
2139 CUID
, getDwarfVersion(), getUnits());
2140 return PrologEndLoc
;
2145 // Gather pre-function debug information. Assumes being called immediately
2146 // after the function entry point has been emitted.
2147 void DwarfDebug::beginFunctionImpl(const MachineFunction
*MF
) {
2150 auto *SP
= MF
->getFunction().getSubprogram();
2151 assert(LScopes
.empty() || SP
== LScopes
.getCurrentFunctionScope()->getScopeNode());
2152 if (SP
->getUnit()->getEmissionKind() == DICompileUnit::NoDebug
)
2155 DwarfCompileUnit
&CU
= getOrCreateDwarfCompileUnit(SP
->getUnit());
2157 Asm
->OutStreamer
->getContext().setDwarfCompileUnitID(
2158 getDwarfCompileUnitIDForLineTable(CU
));
2160 // Record beginning of function.
2161 PrologEndLoc
= emitInitialLocDirective(
2162 *MF
, Asm
->OutStreamer
->getContext().getDwarfCompileUnitID());
2166 DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit
&CU
) {
2167 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2168 // belongs to so that we add to the correct per-cu line table in the
2170 if (Asm
->OutStreamer
->hasRawTextSupport())
2171 // Use a single line table if we are generating assembly.
2174 return CU
.getUniqueID();
2177 void DwarfDebug::terminateLineTable(const DwarfCompileUnit
*CU
) {
2178 const auto &CURanges
= CU
->getRanges();
2179 auto &LineTable
= Asm
->OutStreamer
->getContext().getMCDwarfLineTable(
2180 getDwarfCompileUnitIDForLineTable(*CU
));
2181 // Add the last range label for the given CU.
2182 LineTable
.getMCLineSections().addEndEntry(
2183 const_cast<MCSymbol
*>(CURanges
.back().End
));
2186 void DwarfDebug::skippedNonDebugFunction() {
2187 // If we don't have a subprogram for this function then there will be a hole
2188 // in the range information. Keep note of this by setting the previously used
2189 // section to nullptr.
2190 // Terminate the pending line table.
2192 terminateLineTable(PrevCU
);
2197 // Gather and emit post-function debug information.
2198 void DwarfDebug::endFunctionImpl(const MachineFunction
*MF
) {
2199 const DISubprogram
*SP
= MF
->getFunction().getSubprogram();
2201 assert(CurFn
== MF
&&
2202 "endFunction should be called with the same function as beginFunction");
2204 // Set DwarfDwarfCompileUnitID in MCContext to default value.
2205 Asm
->OutStreamer
->getContext().setDwarfCompileUnitID(0);
2207 LexicalScope
*FnScope
= LScopes
.getCurrentFunctionScope();
2208 assert(!FnScope
|| SP
== FnScope
->getScopeNode());
2209 DwarfCompileUnit
&TheCU
= *CUMap
.lookup(SP
->getUnit());
2210 if (TheCU
.getCUNode()->isDebugDirectivesOnly()) {
2211 PrevLabel
= nullptr;
2216 DenseSet
<InlinedEntity
> Processed
;
2217 collectEntityInfo(TheCU
, SP
, Processed
);
2219 // Add the range of this function to the list of ranges for the CU.
2220 // With basic block sections, add ranges for all basic block sections.
2221 for (const auto &R
: Asm
->MBBSectionRanges
)
2222 TheCU
.addRange({R
.second
.BeginLabel
, R
.second
.EndLabel
});
2224 // Under -gmlt, skip building the subprogram if there are no inlined
2225 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2226 // is still needed as we need its source location.
2227 if (!TheCU
.getCUNode()->getDebugInfoForProfiling() &&
2228 TheCU
.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly
&&
2229 LScopes
.getAbstractScopesList().empty() && !IsDarwin
) {
2230 assert(InfoHolder
.getScopeVariables().empty());
2231 PrevLabel
= nullptr;
2237 size_t NumAbstractScopes
= LScopes
.getAbstractScopesList().size();
2239 // Construct abstract scopes.
2240 for (LexicalScope
*AScope
: LScopes
.getAbstractScopesList()) {
2241 auto *SP
= cast
<DISubprogram
>(AScope
->getScopeNode());
2242 for (const DINode
*DN
: SP
->getRetainedNodes()) {
2243 if (!Processed
.insert(InlinedEntity(DN
, nullptr)).second
)
2246 const MDNode
*Scope
= nullptr;
2247 if (auto *DV
= dyn_cast
<DILocalVariable
>(DN
))
2248 Scope
= DV
->getScope();
2249 else if (auto *DL
= dyn_cast
<DILabel
>(DN
))
2250 Scope
= DL
->getScope();
2252 llvm_unreachable("Unexpected DI type!");
2254 // Collect info for variables/labels that were optimized out.
2255 ensureAbstractEntityIsCreated(TheCU
, DN
, Scope
);
2256 assert(LScopes
.getAbstractScopesList().size() == NumAbstractScopes
2257 && "ensureAbstractEntityIsCreated inserted abstract scopes");
2259 constructAbstractSubprogramScopeDIE(TheCU
, AScope
);
2262 ProcessedSPNodes
.insert(SP
);
2263 DIE
&ScopeDIE
= TheCU
.constructSubprogramScopeDIE(SP
, FnScope
);
2264 if (auto *SkelCU
= TheCU
.getSkeleton())
2265 if (!LScopes
.getAbstractScopesList().empty() &&
2266 TheCU
.getCUNode()->getSplitDebugInlining())
2267 SkelCU
->constructSubprogramScopeDIE(SP
, FnScope
);
2269 // Construct call site entries.
2270 constructCallSiteEntryDIEs(*SP
, TheCU
, ScopeDIE
, *MF
);
2273 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2274 // DbgVariables except those that are also in AbstractVariables (since they
2275 // can be used cross-function)
2276 InfoHolder
.getScopeVariables().clear();
2277 InfoHolder
.getScopeLabels().clear();
2278 PrevLabel
= nullptr;
2282 // Register a source line with debug info. Returns the unique label that was
2283 // emitted and which provides correspondence to the source line list.
2284 void DwarfDebug::recordSourceLine(unsigned Line
, unsigned Col
, const MDNode
*S
,
2286 ::recordSourceLine(*Asm
, Line
, Col
, S
, Flags
,
2287 Asm
->OutStreamer
->getContext().getDwarfCompileUnitID(),
2288 getDwarfVersion(), getUnits());
2291 //===----------------------------------------------------------------------===//
2293 //===----------------------------------------------------------------------===//
2295 // Emit the debug info section.
2296 void DwarfDebug::emitDebugInfo() {
2297 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
2298 Holder
.emitUnits(/* UseOffsets */ false);
2301 // Emit the abbreviation section.
2302 void DwarfDebug::emitAbbreviations() {
2303 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
2305 Holder
.emitAbbrevs(Asm
->getObjFileLowering().getDwarfAbbrevSection());
2308 void DwarfDebug::emitStringOffsetsTableHeader() {
2309 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
2310 Holder
.getStringPool().emitStringOffsetsTableHeader(
2311 *Asm
, Asm
->getObjFileLowering().getDwarfStrOffSection(),
2312 Holder
.getStringOffsetsStartSym());
2315 template <typename AccelTableT
>
2316 void DwarfDebug::emitAccel(AccelTableT
&Accel
, MCSection
*Section
,
2317 StringRef TableName
) {
2318 Asm
->OutStreamer
->SwitchSection(Section
);
2320 // Emit the full data.
2321 emitAppleAccelTable(Asm
, Accel
, TableName
, Section
->getBeginSymbol());
2324 void DwarfDebug::emitAccelDebugNames() {
2325 // Don't emit anything if we have no compilation units to index.
2326 if (getUnits().empty())
2329 emitDWARF5AccelTable(Asm
, AccelDebugNames
, *this, getUnits());
2332 // Emit visible names into a hashed accelerator table section.
2333 void DwarfDebug::emitAccelNames() {
2334 emitAccel(AccelNames
, Asm
->getObjFileLowering().getDwarfAccelNamesSection(),
2338 // Emit objective C classes and categories into a hashed accelerator table
2340 void DwarfDebug::emitAccelObjC() {
2341 emitAccel(AccelObjC
, Asm
->getObjFileLowering().getDwarfAccelObjCSection(),
2345 // Emit namespace dies into a hashed accelerator table.
2346 void DwarfDebug::emitAccelNamespaces() {
2347 emitAccel(AccelNamespace
,
2348 Asm
->getObjFileLowering().getDwarfAccelNamespaceSection(),
2352 // Emit type dies into a hashed accelerator table.
2353 void DwarfDebug::emitAccelTypes() {
2354 emitAccel(AccelTypes
, Asm
->getObjFileLowering().getDwarfAccelTypesSection(),
2358 // Public name handling.
2359 // The format for the various pubnames:
2361 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2362 // for the DIE that is named.
2364 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2365 // into the CU and the index value is computed according to the type of value
2366 // for the DIE that is named.
2368 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2369 // it's the offset within the debug_info/debug_types dwo section, however, the
2370 // reference in the pubname header doesn't change.
2372 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2373 static dwarf::PubIndexEntryDescriptor
computeIndexValue(DwarfUnit
*CU
,
2375 // Entities that ended up only in a Type Unit reference the CU instead (since
2376 // the pub entry has offsets within the CU there's no real offset that can be
2377 // provided anyway). As it happens all such entities (namespaces and types,
2378 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2379 // not to be true it would be necessary to persist this information from the
2380 // point at which the entry is added to the index data structure - since by
2381 // the time the index is built from that, the original type/namespace DIE in a
2382 // type unit has already been destroyed so it can't be queried for properties
2384 if (Die
->getTag() == dwarf::DW_TAG_compile_unit
)
2385 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE
,
2386 dwarf::GIEL_EXTERNAL
);
2387 dwarf::GDBIndexEntryLinkage Linkage
= dwarf::GIEL_STATIC
;
2389 // We could have a specification DIE that has our most of our knowledge,
2390 // look for that now.
2391 if (DIEValue SpecVal
= Die
->findAttribute(dwarf::DW_AT_specification
)) {
2392 DIE
&SpecDIE
= SpecVal
.getDIEEntry().getEntry();
2393 if (SpecDIE
.findAttribute(dwarf::DW_AT_external
))
2394 Linkage
= dwarf::GIEL_EXTERNAL
;
2395 } else if (Die
->findAttribute(dwarf::DW_AT_external
))
2396 Linkage
= dwarf::GIEL_EXTERNAL
;
2398 switch (Die
->getTag()) {
2399 case dwarf::DW_TAG_class_type
:
2400 case dwarf::DW_TAG_structure_type
:
2401 case dwarf::DW_TAG_union_type
:
2402 case dwarf::DW_TAG_enumeration_type
:
2403 return dwarf::PubIndexEntryDescriptor(
2405 dwarf::isCPlusPlus((dwarf::SourceLanguage
)CU
->getLanguage())
2406 ? dwarf::GIEL_EXTERNAL
2407 : dwarf::GIEL_STATIC
);
2408 case dwarf::DW_TAG_typedef
:
2409 case dwarf::DW_TAG_base_type
:
2410 case dwarf::DW_TAG_subrange_type
:
2411 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE
, dwarf::GIEL_STATIC
);
2412 case dwarf::DW_TAG_namespace
:
2413 return dwarf::GIEK_TYPE
;
2414 case dwarf::DW_TAG_subprogram
:
2415 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION
, Linkage
);
2416 case dwarf::DW_TAG_variable
:
2417 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE
, Linkage
);
2418 case dwarf::DW_TAG_enumerator
:
2419 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE
,
2420 dwarf::GIEL_STATIC
);
2422 return dwarf::GIEK_NONE
;
2426 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2427 /// pubtypes sections.
2428 void DwarfDebug::emitDebugPubSections() {
2429 for (const auto &NU
: CUMap
) {
2430 DwarfCompileUnit
*TheU
= NU
.second
;
2431 if (!TheU
->hasDwarfPubSections())
2434 bool GnuStyle
= TheU
->getCUNode()->getNameTableKind() ==
2435 DICompileUnit::DebugNameTableKind::GNU
;
2437 Asm
->OutStreamer
->SwitchSection(
2438 GnuStyle
? Asm
->getObjFileLowering().getDwarfGnuPubNamesSection()
2439 : Asm
->getObjFileLowering().getDwarfPubNamesSection());
2440 emitDebugPubSection(GnuStyle
, "Names", TheU
, TheU
->getGlobalNames());
2442 Asm
->OutStreamer
->SwitchSection(
2443 GnuStyle
? Asm
->getObjFileLowering().getDwarfGnuPubTypesSection()
2444 : Asm
->getObjFileLowering().getDwarfPubTypesSection());
2445 emitDebugPubSection(GnuStyle
, "Types", TheU
, TheU
->getGlobalTypes());
2449 void DwarfDebug::emitSectionReference(const DwarfCompileUnit
&CU
) {
2450 if (useSectionsAsReferences())
2451 Asm
->emitDwarfOffset(CU
.getSection()->getBeginSymbol(),
2452 CU
.getDebugSectionOffset());
2454 Asm
->emitDwarfSymbolReference(CU
.getLabelBegin());
2457 void DwarfDebug::emitDebugPubSection(bool GnuStyle
, StringRef Name
,
2458 DwarfCompileUnit
*TheU
,
2459 const StringMap
<const DIE
*> &Globals
) {
2460 if (auto *Skeleton
= TheU
->getSkeleton())
2464 MCSymbol
*EndLabel
= Asm
->emitDwarfUnitLength(
2465 "pub" + Name
, "Length of Public " + Name
+ " Info");
2467 Asm
->OutStreamer
->AddComment("DWARF Version");
2468 Asm
->emitInt16(dwarf::DW_PUBNAMES_VERSION
);
2470 Asm
->OutStreamer
->AddComment("Offset of Compilation Unit Info");
2471 emitSectionReference(*TheU
);
2473 Asm
->OutStreamer
->AddComment("Compilation Unit Length");
2474 Asm
->emitDwarfLengthOrOffset(TheU
->getLength());
2476 // Emit the pubnames for this compilation unit.
2477 for (const auto &GI
: Globals
) {
2478 const char *Name
= GI
.getKeyData();
2479 const DIE
*Entity
= GI
.second
;
2481 Asm
->OutStreamer
->AddComment("DIE offset");
2482 Asm
->emitDwarfLengthOrOffset(Entity
->getOffset());
2485 dwarf::PubIndexEntryDescriptor Desc
= computeIndexValue(TheU
, Entity
);
2486 Asm
->OutStreamer
->AddComment(
2487 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc
.Kind
) +
2488 ", " + dwarf::GDBIndexEntryLinkageString(Desc
.Linkage
));
2489 Asm
->emitInt8(Desc
.toBits());
2492 Asm
->OutStreamer
->AddComment("External Name");
2493 Asm
->OutStreamer
->emitBytes(StringRef(Name
, GI
.getKeyLength() + 1));
2496 Asm
->OutStreamer
->AddComment("End Mark");
2497 Asm
->emitDwarfLengthOrOffset(0);
2498 Asm
->OutStreamer
->emitLabel(EndLabel
);
2501 /// Emit null-terminated strings into a debug str section.
2502 void DwarfDebug::emitDebugStr() {
2503 MCSection
*StringOffsetsSection
= nullptr;
2504 if (useSegmentedStringOffsetsTable()) {
2505 emitStringOffsetsTableHeader();
2506 StringOffsetsSection
= Asm
->getObjFileLowering().getDwarfStrOffSection();
2508 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
2509 Holder
.emitStrings(Asm
->getObjFileLowering().getDwarfStrSection(),
2510 StringOffsetsSection
, /* UseRelativeOffsets = */ true);
2513 void DwarfDebug::emitDebugLocEntry(ByteStreamer
&Streamer
,
2514 const DebugLocStream::Entry
&Entry
,
2515 const DwarfCompileUnit
*CU
) {
2516 auto &&Comments
= DebugLocs
.getComments(Entry
);
2517 auto Comment
= Comments
.begin();
2518 auto End
= Comments
.end();
2520 // The expressions are inserted into a byte stream rather early (see
2521 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2522 // need to reference a base_type DIE the offset of that DIE is not yet known.
2523 // To deal with this we instead insert a placeholder early and then extract
2524 // it here and replace it with the real reference.
2525 unsigned PtrSize
= Asm
->MAI
->getCodePointerSize();
2526 DWARFDataExtractor
Data(StringRef(DebugLocs
.getBytes(Entry
).data(),
2527 DebugLocs
.getBytes(Entry
).size()),
2528 Asm
->getDataLayout().isLittleEndian(), PtrSize
);
2529 DWARFExpression
Expr(Data
, PtrSize
, Asm
->OutContext
.getDwarfFormat());
2531 using Encoding
= DWARFExpression::Operation::Encoding
;
2532 uint64_t Offset
= 0;
2533 for (auto &Op
: Expr
) {
2534 assert(Op
.getCode() != dwarf::DW_OP_const_type
&&
2535 "3 operand ops not yet supported");
2536 Streamer
.emitInt8(Op
.getCode(), Comment
!= End
? *(Comment
++) : "");
2538 for (unsigned I
= 0; I
< 2; ++I
) {
2539 if (Op
.getDescription().Op
[I
] == Encoding::SizeNA
)
2541 if (Op
.getDescription().Op
[I
] == Encoding::BaseTypeRef
) {
2543 Streamer
.emitDIERef(*CU
->ExprRefedBaseTypes
[Op
.getRawOperand(I
)].Die
);
2544 // Make sure comments stay aligned.
2545 for (unsigned J
= 0; J
< Length
; ++J
)
2549 for (uint64_t J
= Offset
; J
< Op
.getOperandEndOffset(I
); ++J
)
2550 Streamer
.emitInt8(Data
.getData()[J
], Comment
!= End
? *(Comment
++) : "");
2552 Offset
= Op
.getOperandEndOffset(I
);
2554 assert(Offset
== Op
.getEndOffset());
2558 void DwarfDebug::emitDebugLocValue(const AsmPrinter
&AP
, const DIBasicType
*BT
,
2559 const DbgValueLoc
&Value
,
2560 DwarfExpression
&DwarfExpr
) {
2561 auto *DIExpr
= Value
.getExpression();
2562 DIExpressionCursor
ExprCursor(DIExpr
);
2563 DwarfExpr
.addFragmentOffset(DIExpr
);
2565 // If the DIExpr is is an Entry Value, we want to follow the same code path
2566 // regardless of whether the DBG_VALUE is variadic or not.
2567 if (DIExpr
&& DIExpr
->isEntryValue()) {
2568 // Entry values can only be a single register with no additional DIExpr,
2569 // so just add it directly.
2570 assert(Value
.getLocEntries().size() == 1);
2571 assert(Value
.getLocEntries()[0].isLocation());
2572 MachineLocation Location
= Value
.getLocEntries()[0].getLoc();
2573 DwarfExpr
.setLocation(Location
, DIExpr
);
2575 DwarfExpr
.beginEntryValueExpression(ExprCursor
);
2577 const TargetRegisterInfo
&TRI
= *AP
.MF
->getSubtarget().getRegisterInfo();
2578 if (!DwarfExpr
.addMachineRegExpression(TRI
, ExprCursor
, Location
.getReg()))
2580 return DwarfExpr
.addExpression(std::move(ExprCursor
));
2584 auto EmitValueLocEntry
= [&DwarfExpr
, &BT
,
2585 &AP
](const DbgValueLocEntry
&Entry
,
2586 DIExpressionCursor
&Cursor
) -> bool {
2587 if (Entry
.isInt()) {
2588 if (BT
&& (BT
->getEncoding() == dwarf::DW_ATE_signed
||
2589 BT
->getEncoding() == dwarf::DW_ATE_signed_char
))
2590 DwarfExpr
.addSignedConstant(Entry
.getInt());
2592 DwarfExpr
.addUnsignedConstant(Entry
.getInt());
2593 } else if (Entry
.isLocation()) {
2594 MachineLocation Location
= Entry
.getLoc();
2595 if (Location
.isIndirect())
2596 DwarfExpr
.setMemoryLocationKind();
2598 const TargetRegisterInfo
&TRI
= *AP
.MF
->getSubtarget().getRegisterInfo();
2599 if (!DwarfExpr
.addMachineRegExpression(TRI
, Cursor
, Location
.getReg()))
2601 } else if (Entry
.isTargetIndexLocation()) {
2602 TargetIndexLocation Loc
= Entry
.getTargetIndexLocation();
2603 // TODO TargetIndexLocation is a target-independent. Currently only the
2604 // WebAssembly-specific encoding is supported.
2605 assert(AP
.TM
.getTargetTriple().isWasm());
2606 DwarfExpr
.addWasmLocation(Loc
.Index
, static_cast<uint64_t>(Loc
.Offset
));
2607 } else if (Entry
.isConstantFP()) {
2608 if (AP
.getDwarfVersion() >= 4 && !AP
.getDwarfDebug()->tuneForSCE() &&
2610 DwarfExpr
.addConstantFP(Entry
.getConstantFP()->getValueAPF(), AP
);
2611 } else if (Entry
.getConstantFP()
2614 .getBitWidth() <= 64 /*bits*/) {
2615 DwarfExpr
.addUnsignedConstant(
2616 Entry
.getConstantFP()->getValueAPF().bitcastToAPInt());
2619 dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
2620 << Entry
.getConstantFP()
2631 if (!Value
.isVariadic()) {
2632 if (!EmitValueLocEntry(Value
.getLocEntries()[0], ExprCursor
))
2634 DwarfExpr
.addExpression(std::move(ExprCursor
));
2638 // If any of the location entries are registers with the value 0, then the
2639 // location is undefined.
2640 if (any_of(Value
.getLocEntries(), [](const DbgValueLocEntry
&Entry
) {
2641 return Entry
.isLocation() && !Entry
.getLoc().getReg();
2645 DwarfExpr
.addExpression(
2646 std::move(ExprCursor
),
2647 [EmitValueLocEntry
, &Value
](unsigned Idx
,
2648 DIExpressionCursor
&Cursor
) -> bool {
2649 return EmitValueLocEntry(Value
.getLocEntries()[Idx
], Cursor
);
2653 void DebugLocEntry::finalize(const AsmPrinter
&AP
,
2654 DebugLocStream::ListBuilder
&List
,
2655 const DIBasicType
*BT
,
2656 DwarfCompileUnit
&TheCU
) {
2657 assert(!Values
.empty() &&
2658 "location list entries without values are redundant");
2659 assert(Begin
!= End
&& "unexpected location list entry with empty range");
2660 DebugLocStream::EntryBuilder
Entry(List
, Begin
, End
);
2661 BufferByteStreamer Streamer
= Entry
.getStreamer();
2662 DebugLocDwarfExpression
DwarfExpr(AP
.getDwarfVersion(), Streamer
, TheCU
);
2663 const DbgValueLoc
&Value
= Values
[0];
2664 if (Value
.isFragment()) {
2665 // Emit all fragments that belong to the same variable and range.
2666 assert(llvm::all_of(Values
, [](DbgValueLoc P
) {
2667 return P
.isFragment();
2668 }) && "all values are expected to be fragments");
2669 assert(llvm::is_sorted(Values
) && "fragments are expected to be sorted");
2671 for (const auto &Fragment
: Values
)
2672 DwarfDebug::emitDebugLocValue(AP
, BT
, Fragment
, DwarfExpr
);
2675 assert(Values
.size() == 1 && "only fragments may have >1 value");
2676 DwarfDebug::emitDebugLocValue(AP
, BT
, Value
, DwarfExpr
);
2678 DwarfExpr
.finalize();
2679 if (DwarfExpr
.TagOffset
)
2680 List
.setTagOffset(*DwarfExpr
.TagOffset
);
2683 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry
&Entry
,
2684 const DwarfCompileUnit
*CU
) {
2686 Asm
->OutStreamer
->AddComment("Loc expr size");
2687 if (getDwarfVersion() >= 5)
2688 Asm
->emitULEB128(DebugLocs
.getBytes(Entry
).size());
2689 else if (DebugLocs
.getBytes(Entry
).size() <= std::numeric_limits
<uint16_t>::max())
2690 Asm
->emitInt16(DebugLocs
.getBytes(Entry
).size());
2692 // The entry is too big to fit into 16 bit, drop it as there is nothing we
2698 APByteStreamer
Streamer(*Asm
);
2699 emitDebugLocEntry(Streamer
, Entry
, CU
);
2702 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2703 // that designates the end of the table for the caller to emit when the table is
2705 static MCSymbol
*emitRnglistsTableHeader(AsmPrinter
*Asm
,
2706 const DwarfFile
&Holder
) {
2707 MCSymbol
*TableEnd
= mcdwarf::emitListsTableHeaderStart(*Asm
->OutStreamer
);
2709 Asm
->OutStreamer
->AddComment("Offset entry count");
2710 Asm
->emitInt32(Holder
.getRangeLists().size());
2711 Asm
->OutStreamer
->emitLabel(Holder
.getRnglistsTableBaseSym());
2713 for (const RangeSpanList
&List
: Holder
.getRangeLists())
2714 Asm
->emitLabelDifference(List
.Label
, Holder
.getRnglistsTableBaseSym(),
2715 Asm
->getDwarfOffsetByteSize());
2720 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2721 // designates the end of the table for the caller to emit when the table is
2723 static MCSymbol
*emitLoclistsTableHeader(AsmPrinter
*Asm
,
2724 const DwarfDebug
&DD
) {
2725 MCSymbol
*TableEnd
= mcdwarf::emitListsTableHeaderStart(*Asm
->OutStreamer
);
2727 const auto &DebugLocs
= DD
.getDebugLocs();
2729 Asm
->OutStreamer
->AddComment("Offset entry count");
2730 Asm
->emitInt32(DebugLocs
.getLists().size());
2731 Asm
->OutStreamer
->emitLabel(DebugLocs
.getSym());
2733 for (const auto &List
: DebugLocs
.getLists())
2734 Asm
->emitLabelDifference(List
.Label
, DebugLocs
.getSym(),
2735 Asm
->getDwarfOffsetByteSize());
2740 template <typename Ranges
, typename PayloadEmitter
>
2741 static void emitRangeList(
2742 DwarfDebug
&DD
, AsmPrinter
*Asm
, MCSymbol
*Sym
, const Ranges
&R
,
2743 const DwarfCompileUnit
&CU
, unsigned BaseAddressx
, unsigned OffsetPair
,
2744 unsigned StartxLength
, unsigned EndOfList
,
2745 StringRef (*StringifyEnum
)(unsigned),
2746 bool ShouldUseBaseAddress
,
2747 PayloadEmitter EmitPayload
) {
2749 auto Size
= Asm
->MAI
->getCodePointerSize();
2750 bool UseDwarf5
= DD
.getDwarfVersion() >= 5;
2752 // Emit our symbol so we can find the beginning of the range.
2753 Asm
->OutStreamer
->emitLabel(Sym
);
2755 // Gather all the ranges that apply to the same section so they can share
2756 // a base address entry.
2757 MapVector
<const MCSection
*, std::vector
<decltype(&*R
.begin())>> SectionRanges
;
2759 for (const auto &Range
: R
)
2760 SectionRanges
[&Range
.Begin
->getSection()].push_back(&Range
);
2762 const MCSymbol
*CUBase
= CU
.getBaseAddress();
2763 bool BaseIsSet
= false;
2764 for (const auto &P
: SectionRanges
) {
2765 auto *Base
= CUBase
;
2766 if (!Base
&& ShouldUseBaseAddress
) {
2767 const MCSymbol
*Begin
= P
.second
.front()->Begin
;
2768 const MCSymbol
*NewBase
= DD
.getSectionLabel(&Begin
->getSection());
2772 Asm
->OutStreamer
->emitIntValue(-1, Size
);
2773 Asm
->OutStreamer
->AddComment(" base address");
2774 Asm
->OutStreamer
->emitSymbolValue(Base
, Size
);
2775 } else if (NewBase
!= Begin
|| P
.second
.size() > 1) {
2776 // Only use a base address if
2777 // * the existing pool address doesn't match (NewBase != Begin)
2778 // * or, there's more than one entry to share the base address
2781 Asm
->OutStreamer
->AddComment(StringifyEnum(BaseAddressx
));
2782 Asm
->emitInt8(BaseAddressx
);
2783 Asm
->OutStreamer
->AddComment(" base address index");
2784 Asm
->emitULEB128(DD
.getAddressPool().getIndex(Base
));
2786 } else if (BaseIsSet
&& !UseDwarf5
) {
2789 Asm
->OutStreamer
->emitIntValue(-1, Size
);
2790 Asm
->OutStreamer
->emitIntValue(0, Size
);
2793 for (const auto *RS
: P
.second
) {
2794 const MCSymbol
*Begin
= RS
->Begin
;
2795 const MCSymbol
*End
= RS
->End
;
2796 assert(Begin
&& "Range without a begin symbol?");
2797 assert(End
&& "Range without an end symbol?");
2800 // Emit offset_pair when we have a base.
2801 Asm
->OutStreamer
->AddComment(StringifyEnum(OffsetPair
));
2802 Asm
->emitInt8(OffsetPair
);
2803 Asm
->OutStreamer
->AddComment(" starting offset");
2804 Asm
->emitLabelDifferenceAsULEB128(Begin
, Base
);
2805 Asm
->OutStreamer
->AddComment(" ending offset");
2806 Asm
->emitLabelDifferenceAsULEB128(End
, Base
);
2808 Asm
->emitLabelDifference(Begin
, Base
, Size
);
2809 Asm
->emitLabelDifference(End
, Base
, Size
);
2811 } else if (UseDwarf5
) {
2812 Asm
->OutStreamer
->AddComment(StringifyEnum(StartxLength
));
2813 Asm
->emitInt8(StartxLength
);
2814 Asm
->OutStreamer
->AddComment(" start index");
2815 Asm
->emitULEB128(DD
.getAddressPool().getIndex(Begin
));
2816 Asm
->OutStreamer
->AddComment(" length");
2817 Asm
->emitLabelDifferenceAsULEB128(End
, Begin
);
2819 Asm
->OutStreamer
->emitSymbolValue(Begin
, Size
);
2820 Asm
->OutStreamer
->emitSymbolValue(End
, Size
);
2827 Asm
->OutStreamer
->AddComment(StringifyEnum(EndOfList
));
2828 Asm
->emitInt8(EndOfList
);
2830 // Terminate the list with two 0 values.
2831 Asm
->OutStreamer
->emitIntValue(0, Size
);
2832 Asm
->OutStreamer
->emitIntValue(0, Size
);
2836 // Handles emission of both debug_loclist / debug_loclist.dwo
2837 static void emitLocList(DwarfDebug
&DD
, AsmPrinter
*Asm
, const DebugLocStream::List
&List
) {
2838 emitRangeList(DD
, Asm
, List
.Label
, DD
.getDebugLocs().getEntries(List
),
2839 *List
.CU
, dwarf::DW_LLE_base_addressx
,
2840 dwarf::DW_LLE_offset_pair
, dwarf::DW_LLE_startx_length
,
2841 dwarf::DW_LLE_end_of_list
, llvm::dwarf::LocListEncodingString
,
2842 /* ShouldUseBaseAddress */ true,
2843 [&](const DebugLocStream::Entry
&E
) {
2844 DD
.emitDebugLocEntryLocation(E
, List
.CU
);
2848 void DwarfDebug::emitDebugLocImpl(MCSection
*Sec
) {
2849 if (DebugLocs
.getLists().empty())
2852 Asm
->OutStreamer
->SwitchSection(Sec
);
2854 MCSymbol
*TableEnd
= nullptr;
2855 if (getDwarfVersion() >= 5)
2856 TableEnd
= emitLoclistsTableHeader(Asm
, *this);
2858 for (const auto &List
: DebugLocs
.getLists())
2859 emitLocList(*this, Asm
, List
);
2862 Asm
->OutStreamer
->emitLabel(TableEnd
);
2865 // Emit locations into the .debug_loc/.debug_loclists section.
2866 void DwarfDebug::emitDebugLoc() {
2868 getDwarfVersion() >= 5
2869 ? Asm
->getObjFileLowering().getDwarfLoclistsSection()
2870 : Asm
->getObjFileLowering().getDwarfLocSection());
2873 // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2874 void DwarfDebug::emitDebugLocDWO() {
2875 if (getDwarfVersion() >= 5) {
2877 Asm
->getObjFileLowering().getDwarfLoclistsDWOSection());
2882 for (const auto &List
: DebugLocs
.getLists()) {
2883 Asm
->OutStreamer
->SwitchSection(
2884 Asm
->getObjFileLowering().getDwarfLocDWOSection());
2885 Asm
->OutStreamer
->emitLabel(List
.Label
);
2887 for (const auto &Entry
: DebugLocs
.getEntries(List
)) {
2888 // GDB only supports startx_length in pre-standard split-DWARF.
2889 // (in v5 standard loclists, it currently* /only/ supports base_address +
2890 // offset_pair, so the implementations can't really share much since they
2891 // need to use different representations)
2892 // * as of October 2018, at least
2894 // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2895 // addresses in the address pool to minimize object size/relocations.
2896 Asm
->emitInt8(dwarf::DW_LLE_startx_length
);
2897 unsigned idx
= AddrPool
.getIndex(Entry
.Begin
);
2898 Asm
->emitULEB128(idx
);
2899 // Also the pre-standard encoding is slightly different, emitting this as
2900 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2901 Asm
->emitLabelDifference(Entry
.End
, Entry
.Begin
, 4);
2902 emitDebugLocEntryLocation(Entry
, List
.CU
);
2904 Asm
->emitInt8(dwarf::DW_LLE_end_of_list
);
2909 const MCSymbol
*Start
, *End
;
2912 // Emit a debug aranges section, containing a CU lookup for any
2913 // address we can tie back to a CU.
2914 void DwarfDebug::emitDebugARanges() {
2915 // Provides a unique id per text section.
2916 MapVector
<MCSection
*, SmallVector
<SymbolCU
, 8>> SectionMap
;
2918 // Filter labels by section.
2919 for (const SymbolCU
&SCU
: ArangeLabels
) {
2920 if (SCU
.Sym
->isInSection()) {
2921 // Make a note of this symbol and it's section.
2922 MCSection
*Section
= &SCU
.Sym
->getSection();
2923 if (!Section
->getKind().isMetadata())
2924 SectionMap
[Section
].push_back(SCU
);
2926 // Some symbols (e.g. common/bss on mach-o) can have no section but still
2927 // appear in the output. This sucks as we rely on sections to build
2928 // arange spans. We can do it without, but it's icky.
2929 SectionMap
[nullptr].push_back(SCU
);
2933 DenseMap
<DwarfCompileUnit
*, std::vector
<ArangeSpan
>> Spans
;
2935 for (auto &I
: SectionMap
) {
2936 MCSection
*Section
= I
.first
;
2937 SmallVector
<SymbolCU
, 8> &List
= I
.second
;
2938 if (List
.size() < 1)
2941 // If we have no section (e.g. common), just write out
2942 // individual spans for each symbol.
2944 for (const SymbolCU
&Cur
: List
) {
2946 Span
.Start
= Cur
.Sym
;
2949 Spans
[Cur
.CU
].push_back(Span
);
2954 // Sort the symbols by offset within the section.
2955 llvm::stable_sort(List
, [&](const SymbolCU
&A
, const SymbolCU
&B
) {
2956 unsigned IA
= A
.Sym
? Asm
->OutStreamer
->GetSymbolOrder(A
.Sym
) : 0;
2957 unsigned IB
= B
.Sym
? Asm
->OutStreamer
->GetSymbolOrder(B
.Sym
) : 0;
2959 // Symbols with no order assigned should be placed at the end.
2960 // (e.g. section end labels)
2968 // Insert a final terminator.
2969 List
.push_back(SymbolCU(nullptr, Asm
->OutStreamer
->endSection(Section
)));
2971 // Build spans between each label.
2972 const MCSymbol
*StartSym
= List
[0].Sym
;
2973 for (size_t n
= 1, e
= List
.size(); n
< e
; n
++) {
2974 const SymbolCU
&Prev
= List
[n
- 1];
2975 const SymbolCU
&Cur
= List
[n
];
2977 // Try and build the longest span we can within the same CU.
2978 if (Cur
.CU
!= Prev
.CU
) {
2980 Span
.Start
= StartSym
;
2983 Spans
[Prev
.CU
].push_back(Span
);
2989 // Start the dwarf aranges section.
2990 Asm
->OutStreamer
->SwitchSection(
2991 Asm
->getObjFileLowering().getDwarfARangesSection());
2993 unsigned PtrSize
= Asm
->MAI
->getCodePointerSize();
2995 // Build a list of CUs used.
2996 std::vector
<DwarfCompileUnit
*> CUs
;
2997 for (const auto &it
: Spans
) {
2998 DwarfCompileUnit
*CU
= it
.first
;
3002 // Sort the CU list (again, to ensure consistent output order).
3003 llvm::sort(CUs
, [](const DwarfCompileUnit
*A
, const DwarfCompileUnit
*B
) {
3004 return A
->getUniqueID() < B
->getUniqueID();
3007 // Emit an arange table for each CU we used.
3008 for (DwarfCompileUnit
*CU
: CUs
) {
3009 std::vector
<ArangeSpan
> &List
= Spans
[CU
];
3011 // Describe the skeleton CU's offset and length, not the dwo file's.
3012 if (auto *Skel
= CU
->getSkeleton())
3015 // Emit size of content not including length itself.
3016 unsigned ContentSize
=
3017 sizeof(int16_t) + // DWARF ARange version number
3018 Asm
->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3020 sizeof(int8_t) + // Pointer Size (in bytes)
3021 sizeof(int8_t); // Segment Size (in bytes)
3023 unsigned TupleSize
= PtrSize
* 2;
3025 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3026 unsigned Padding
= offsetToAlignment(
3027 Asm
->getUnitLengthFieldByteSize() + ContentSize
, Align(TupleSize
));
3029 ContentSize
+= Padding
;
3030 ContentSize
+= (List
.size() + 1) * TupleSize
;
3032 // For each compile unit, write the list of spans it covers.
3033 Asm
->emitDwarfUnitLength(ContentSize
, "Length of ARange Set");
3034 Asm
->OutStreamer
->AddComment("DWARF Arange version number");
3035 Asm
->emitInt16(dwarf::DW_ARANGES_VERSION
);
3036 Asm
->OutStreamer
->AddComment("Offset Into Debug Info Section");
3037 emitSectionReference(*CU
);
3038 Asm
->OutStreamer
->AddComment("Address Size (in bytes)");
3039 Asm
->emitInt8(PtrSize
);
3040 Asm
->OutStreamer
->AddComment("Segment Size (in bytes)");
3043 Asm
->OutStreamer
->emitFill(Padding
, 0xff);
3045 for (const ArangeSpan
&Span
: List
) {
3046 Asm
->emitLabelReference(Span
.Start
, PtrSize
);
3048 // Calculate the size as being from the span start to it's end.
3050 Asm
->emitLabelDifference(Span
.End
, Span
.Start
, PtrSize
);
3052 // For symbols without an end marker (e.g. common), we
3053 // write a single arange entry containing just that one symbol.
3054 uint64_t Size
= SymSize
[Span
.Start
];
3058 Asm
->OutStreamer
->emitIntValue(Size
, PtrSize
);
3062 Asm
->OutStreamer
->AddComment("ARange terminator");
3063 Asm
->OutStreamer
->emitIntValue(0, PtrSize
);
3064 Asm
->OutStreamer
->emitIntValue(0, PtrSize
);
3068 /// Emit a single range list. We handle both DWARF v5 and earlier.
3069 static void emitRangeList(DwarfDebug
&DD
, AsmPrinter
*Asm
,
3070 const RangeSpanList
&List
) {
3071 emitRangeList(DD
, Asm
, List
.Label
, List
.Ranges
, *List
.CU
,
3072 dwarf::DW_RLE_base_addressx
, dwarf::DW_RLE_offset_pair
,
3073 dwarf::DW_RLE_startx_length
, dwarf::DW_RLE_end_of_list
,
3074 llvm::dwarf::RangeListEncodingString
,
3075 List
.CU
->getCUNode()->getRangesBaseAddress() ||
3076 DD
.getDwarfVersion() >= 5,
3080 void DwarfDebug::emitDebugRangesImpl(const DwarfFile
&Holder
, MCSection
*Section
) {
3081 if (Holder
.getRangeLists().empty())
3084 assert(useRangesSection());
3085 assert(!CUMap
.empty());
3086 assert(llvm::any_of(CUMap
, [](const decltype(CUMap
)::value_type
&Pair
) {
3087 return !Pair
.second
->getCUNode()->isDebugDirectivesOnly();
3090 Asm
->OutStreamer
->SwitchSection(Section
);
3092 MCSymbol
*TableEnd
= nullptr;
3093 if (getDwarfVersion() >= 5)
3094 TableEnd
= emitRnglistsTableHeader(Asm
, Holder
);
3096 for (const RangeSpanList
&List
: Holder
.getRangeLists())
3097 emitRangeList(*this, Asm
, List
);
3100 Asm
->OutStreamer
->emitLabel(TableEnd
);
3103 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
3104 /// .debug_rnglists section.
3105 void DwarfDebug::emitDebugRanges() {
3106 const auto &Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
3108 emitDebugRangesImpl(Holder
,
3109 getDwarfVersion() >= 5
3110 ? Asm
->getObjFileLowering().getDwarfRnglistsSection()
3111 : Asm
->getObjFileLowering().getDwarfRangesSection());
3114 void DwarfDebug::emitDebugRangesDWO() {
3115 emitDebugRangesImpl(InfoHolder
,
3116 Asm
->getObjFileLowering().getDwarfRnglistsDWOSection());
3119 /// Emit the header of a DWARF 5 macro section, or the GNU extension for
3121 static void emitMacroHeader(AsmPrinter
*Asm
, const DwarfDebug
&DD
,
3122 const DwarfCompileUnit
&CU
, uint16_t DwarfVersion
) {
3123 enum HeaderFlagMask
{
3124 #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3125 #include "llvm/BinaryFormat/Dwarf.def"
3127 Asm
->OutStreamer
->AddComment("Macro information version");
3128 Asm
->emitInt16(DwarfVersion
>= 5 ? DwarfVersion
: 4);
3129 // We emit the line offset flag unconditionally here, since line offset should
3130 // be mostly present.
3131 if (Asm
->isDwarf64()) {
3132 Asm
->OutStreamer
->AddComment("Flags: 64 bit, debug_line_offset present");
3133 Asm
->emitInt8(MACRO_FLAG_OFFSET_SIZE
| MACRO_FLAG_DEBUG_LINE_OFFSET
);
3135 Asm
->OutStreamer
->AddComment("Flags: 32 bit, debug_line_offset present");
3136 Asm
->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET
);
3138 Asm
->OutStreamer
->AddComment("debug_line_offset");
3139 if (DD
.useSplitDwarf())
3140 Asm
->emitDwarfLengthOrOffset(0);
3142 Asm
->emitDwarfSymbolReference(CU
.getLineTableStartSym());
3145 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes
, DwarfCompileUnit
&U
) {
3146 for (auto *MN
: Nodes
) {
3147 if (auto *M
= dyn_cast
<DIMacro
>(MN
))
3149 else if (auto *F
= dyn_cast
<DIMacroFile
>(MN
))
3150 emitMacroFile(*F
, U
);
3152 llvm_unreachable("Unexpected DI type!");
3156 void DwarfDebug::emitMacro(DIMacro
&M
) {
3157 StringRef Name
= M
.getName();
3158 StringRef Value
= M
.getValue();
3160 // There should be one space between the macro name and the macro value in
3161 // define entries. In undef entries, only the macro name is emitted.
3162 std::string Str
= Value
.empty() ? Name
.str() : (Name
+ " " + Value
).str();
3164 if (UseDebugMacroSection
) {
3165 if (getDwarfVersion() >= 5) {
3166 unsigned Type
= M
.getMacinfoType() == dwarf::DW_MACINFO_define
3167 ? dwarf::DW_MACRO_define_strx
3168 : dwarf::DW_MACRO_undef_strx
;
3169 Asm
->OutStreamer
->AddComment(dwarf::MacroString(Type
));
3170 Asm
->emitULEB128(Type
);
3171 Asm
->OutStreamer
->AddComment("Line Number");
3172 Asm
->emitULEB128(M
.getLine());
3173 Asm
->OutStreamer
->AddComment("Macro String");
3175 InfoHolder
.getStringPool().getIndexedEntry(*Asm
, Str
).getIndex());
3177 unsigned Type
= M
.getMacinfoType() == dwarf::DW_MACINFO_define
3178 ? dwarf::DW_MACRO_GNU_define_indirect
3179 : dwarf::DW_MACRO_GNU_undef_indirect
;
3180 Asm
->OutStreamer
->AddComment(dwarf::GnuMacroString(Type
));
3181 Asm
->emitULEB128(Type
);
3182 Asm
->OutStreamer
->AddComment("Line Number");
3183 Asm
->emitULEB128(M
.getLine());
3184 Asm
->OutStreamer
->AddComment("Macro String");
3185 Asm
->emitDwarfSymbolReference(
3186 InfoHolder
.getStringPool().getEntry(*Asm
, Str
).getSymbol());
3189 Asm
->OutStreamer
->AddComment(dwarf::MacinfoString(M
.getMacinfoType()));
3190 Asm
->emitULEB128(M
.getMacinfoType());
3191 Asm
->OutStreamer
->AddComment("Line Number");
3192 Asm
->emitULEB128(M
.getLine());
3193 Asm
->OutStreamer
->AddComment("Macro String");
3194 Asm
->OutStreamer
->emitBytes(Str
);
3195 Asm
->emitInt8('\0');
3199 void DwarfDebug::emitMacroFileImpl(
3200 DIMacroFile
&MF
, DwarfCompileUnit
&U
, unsigned StartFile
, unsigned EndFile
,
3201 StringRef (*MacroFormToString
)(unsigned Form
)) {
3203 Asm
->OutStreamer
->AddComment(MacroFormToString(StartFile
));
3204 Asm
->emitULEB128(StartFile
);
3205 Asm
->OutStreamer
->AddComment("Line Number");
3206 Asm
->emitULEB128(MF
.getLine());
3207 Asm
->OutStreamer
->AddComment("File Number");
3208 DIFile
&F
= *MF
.getFile();
3209 if (useSplitDwarf())
3210 Asm
->emitULEB128(getDwoLineTable(U
)->getFile(
3211 F
.getDirectory(), F
.getFilename(), getMD5AsBytes(&F
),
3212 Asm
->OutContext
.getDwarfVersion(), F
.getSource()));
3214 Asm
->emitULEB128(U
.getOrCreateSourceID(&F
));
3215 handleMacroNodes(MF
.getElements(), U
);
3216 Asm
->OutStreamer
->AddComment(MacroFormToString(EndFile
));
3217 Asm
->emitULEB128(EndFile
);
3220 void DwarfDebug::emitMacroFile(DIMacroFile
&F
, DwarfCompileUnit
&U
) {
3221 // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3222 // so for readibility/uniformity, We are explicitly emitting those.
3223 assert(F
.getMacinfoType() == dwarf::DW_MACINFO_start_file
);
3224 if (UseDebugMacroSection
)
3226 F
, U
, dwarf::DW_MACRO_start_file
, dwarf::DW_MACRO_end_file
,
3227 (getDwarfVersion() >= 5) ? dwarf::MacroString
: dwarf::GnuMacroString
);
3229 emitMacroFileImpl(F
, U
, dwarf::DW_MACINFO_start_file
,
3230 dwarf::DW_MACINFO_end_file
, dwarf::MacinfoString
);
3233 void DwarfDebug::emitDebugMacinfoImpl(MCSection
*Section
) {
3234 for (const auto &P
: CUMap
) {
3235 auto &TheCU
= *P
.second
;
3236 auto *SkCU
= TheCU
.getSkeleton();
3237 DwarfCompileUnit
&U
= SkCU
? *SkCU
: TheCU
;
3238 auto *CUNode
= cast
<DICompileUnit
>(P
.first
);
3239 DIMacroNodeArray Macros
= CUNode
->getMacros();
3242 Asm
->OutStreamer
->SwitchSection(Section
);
3243 Asm
->OutStreamer
->emitLabel(U
.getMacroLabelBegin());
3244 if (UseDebugMacroSection
)
3245 emitMacroHeader(Asm
, *this, U
, getDwarfVersion());
3246 handleMacroNodes(Macros
, U
);
3247 Asm
->OutStreamer
->AddComment("End Of Macro List Mark");
3252 /// Emit macros into a debug macinfo/macro section.
3253 void DwarfDebug::emitDebugMacinfo() {
3254 auto &ObjLower
= Asm
->getObjFileLowering();
3255 emitDebugMacinfoImpl(UseDebugMacroSection
3256 ? ObjLower
.getDwarfMacroSection()
3257 : ObjLower
.getDwarfMacinfoSection());
3260 void DwarfDebug::emitDebugMacinfoDWO() {
3261 auto &ObjLower
= Asm
->getObjFileLowering();
3262 emitDebugMacinfoImpl(UseDebugMacroSection
3263 ? ObjLower
.getDwarfMacroDWOSection()
3264 : ObjLower
.getDwarfMacinfoDWOSection());
3267 // DWARF5 Experimental Separate Dwarf emitters.
3269 void DwarfDebug::initSkeletonUnit(const DwarfUnit
&U
, DIE
&Die
,
3270 std::unique_ptr
<DwarfCompileUnit
> NewU
) {
3272 if (!CompilationDir
.empty())
3273 NewU
->addString(Die
, dwarf::DW_AT_comp_dir
, CompilationDir
);
3274 addGnuPubAttributes(*NewU
, Die
);
3276 SkeletonHolder
.addUnit(std::move(NewU
));
3279 DwarfCompileUnit
&DwarfDebug::constructSkeletonCU(const DwarfCompileUnit
&CU
) {
3281 auto OwnedUnit
= std::make_unique
<DwarfCompileUnit
>(
3282 CU
.getUniqueID(), CU
.getCUNode(), Asm
, this, &SkeletonHolder
,
3283 UnitKind::Skeleton
);
3284 DwarfCompileUnit
&NewCU
= *OwnedUnit
;
3285 NewCU
.setSection(Asm
->getObjFileLowering().getDwarfInfoSection());
3287 NewCU
.initStmtList();
3289 if (useSegmentedStringOffsetsTable())
3290 NewCU
.addStringOffsetsStart();
3292 initSkeletonUnit(CU
, NewCU
.getUnitDie(), std::move(OwnedUnit
));
3297 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3298 // compile units that would normally be in debug_info.
3299 void DwarfDebug::emitDebugInfoDWO() {
3300 assert(useSplitDwarf() && "No split dwarf debug info?");
3301 // Don't emit relocations into the dwo file.
3302 InfoHolder
.emitUnits(/* UseOffsets */ true);
3305 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3306 // abbreviations for the .debug_info.dwo section.
3307 void DwarfDebug::emitDebugAbbrevDWO() {
3308 assert(useSplitDwarf() && "No split dwarf?");
3309 InfoHolder
.emitAbbrevs(Asm
->getObjFileLowering().getDwarfAbbrevDWOSection());
3312 void DwarfDebug::emitDebugLineDWO() {
3313 assert(useSplitDwarf() && "No split dwarf?");
3314 SplitTypeUnitFileTable
.Emit(
3315 *Asm
->OutStreamer
, MCDwarfLineTableParams(),
3316 Asm
->getObjFileLowering().getDwarfLineDWOSection());
3319 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3320 assert(useSplitDwarf() && "No split dwarf?");
3321 InfoHolder
.getStringPool().emitStringOffsetsTableHeader(
3322 *Asm
, Asm
->getObjFileLowering().getDwarfStrOffDWOSection(),
3323 InfoHolder
.getStringOffsetsStartSym());
3326 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3327 // string section and is identical in format to traditional .debug_str
3329 void DwarfDebug::emitDebugStrDWO() {
3330 if (useSegmentedStringOffsetsTable())
3331 emitStringOffsetsTableHeaderDWO();
3332 assert(useSplitDwarf() && "No split dwarf?");
3333 MCSection
*OffSec
= Asm
->getObjFileLowering().getDwarfStrOffDWOSection();
3334 InfoHolder
.emitStrings(Asm
->getObjFileLowering().getDwarfStrDWOSection(),
3335 OffSec
, /* UseRelativeOffsets = */ false);
3338 // Emit address pool.
3339 void DwarfDebug::emitDebugAddr() {
3340 AddrPool
.emit(*Asm
, Asm
->getObjFileLowering().getDwarfAddrSection());
3343 MCDwarfDwoLineTable
*DwarfDebug::getDwoLineTable(const DwarfCompileUnit
&CU
) {
3344 if (!useSplitDwarf())
3346 const DICompileUnit
*DIUnit
= CU
.getCUNode();
3347 SplitTypeUnitFileTable
.maybeSetRootFile(
3348 DIUnit
->getDirectory(), DIUnit
->getFilename(),
3349 getMD5AsBytes(DIUnit
->getFile()), DIUnit
->getSource());
3350 return &SplitTypeUnitFileTable
;
3353 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier
) {
3355 Hash
.update(Identifier
);
3356 // ... take the least significant 8 bytes and return those. Our MD5
3357 // implementation always returns its results in little endian, so we actually
3358 // need the "high" word.
3359 MD5::MD5Result Result
;
3361 return Result
.high();
3364 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit
&CU
,
3365 StringRef Identifier
, DIE
&RefDie
,
3366 const DICompositeType
*CTy
) {
3367 // Fast path if we're building some type units and one has already used the
3368 // address pool we know we're going to throw away all this work anyway, so
3369 // don't bother building dependent types.
3370 if (!TypeUnitsUnderConstruction
.empty() && AddrPool
.hasBeenUsed())
3373 auto Ins
= TypeSignatures
.insert(std::make_pair(CTy
, 0));
3375 CU
.addDIETypeSignature(RefDie
, Ins
.first
->second
);
3379 bool TopLevelType
= TypeUnitsUnderConstruction
.empty();
3380 AddrPool
.resetUsedFlag();
3382 auto OwnedUnit
= std::make_unique
<DwarfTypeUnit
>(CU
, Asm
, this, &InfoHolder
,
3383 getDwoLineTable(CU
));
3384 DwarfTypeUnit
&NewTU
= *OwnedUnit
;
3385 DIE
&UnitDie
= NewTU
.getUnitDie();
3386 TypeUnitsUnderConstruction
.emplace_back(std::move(OwnedUnit
), CTy
);
3388 NewTU
.addUInt(UnitDie
, dwarf::DW_AT_language
, dwarf::DW_FORM_data2
,
3391 uint64_t Signature
= makeTypeSignature(Identifier
);
3392 NewTU
.setTypeSignature(Signature
);
3393 Ins
.first
->second
= Signature
;
3395 if (useSplitDwarf()) {
3396 MCSection
*Section
=
3397 getDwarfVersion() <= 4
3398 ? Asm
->getObjFileLowering().getDwarfTypesDWOSection()
3399 : Asm
->getObjFileLowering().getDwarfInfoDWOSection();
3400 NewTU
.setSection(Section
);
3402 MCSection
*Section
=
3403 getDwarfVersion() <= 4
3404 ? Asm
->getObjFileLowering().getDwarfTypesSection(Signature
)
3405 : Asm
->getObjFileLowering().getDwarfInfoSection(Signature
);
3406 NewTU
.setSection(Section
);
3407 // Non-split type units reuse the compile unit's line table.
3408 CU
.applyStmtList(UnitDie
);
3411 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3413 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3414 NewTU
.addStringOffsetsStart();
3416 NewTU
.setType(NewTU
.createTypeDIE(CTy
));
3419 auto TypeUnitsToAdd
= std::move(TypeUnitsUnderConstruction
);
3420 TypeUnitsUnderConstruction
.clear();
3422 // Types referencing entries in the address table cannot be placed in type
3424 if (AddrPool
.hasBeenUsed()) {
3426 // Remove all the types built while building this type.
3427 // This is pessimistic as some of these types might not be dependent on
3428 // the type that used an address.
3429 for (const auto &TU
: TypeUnitsToAdd
)
3430 TypeSignatures
.erase(TU
.second
);
3432 // Construct this type in the CU directly.
3433 // This is inefficient because all the dependent types will be rebuilt
3434 // from scratch, including building them in type units, discovering that
3435 // they depend on addresses, throwing them out and rebuilding them.
3436 CU
.constructTypeDIE(RefDie
, cast
<DICompositeType
>(CTy
));
3440 // If the type wasn't dependent on fission addresses, finish adding the type
3441 // and all its dependent types.
3442 for (auto &TU
: TypeUnitsToAdd
) {
3443 InfoHolder
.computeSizeAndOffsetsForUnit(TU
.first
.get());
3444 InfoHolder
.emitUnit(TU
.first
.get(), useSplitDwarf());
3447 CU
.addDIETypeSignature(RefDie
, Signature
);
3450 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug
*DD
)
3452 TypeUnitsUnderConstruction(std::move(DD
->TypeUnitsUnderConstruction
)), AddrPoolUsed(DD
->AddrPool
.hasBeenUsed()) {
3453 DD
->TypeUnitsUnderConstruction
.clear();
3454 DD
->AddrPool
.resetUsedFlag();
3457 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3458 DD
->TypeUnitsUnderConstruction
= std::move(TypeUnitsUnderConstruction
);
3459 DD
->AddrPool
.resetUsedFlag(AddrPoolUsed
);
3462 DwarfDebug::NonTypeUnitContext
DwarfDebug::enterNonTypeUnitContext() {
3463 return NonTypeUnitContext(this);
3466 // Add the Name along with its companion DIE to the appropriate accelerator
3467 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3468 // AccelTableKind::Apple, we use the table we got as an argument). If
3469 // accelerator tables are disabled, this function does nothing.
3470 template <typename DataT
>
3471 void DwarfDebug::addAccelNameImpl(const DICompileUnit
&CU
,
3472 AccelTable
<DataT
> &AppleAccel
, StringRef Name
,
3474 if (getAccelTableKind() == AccelTableKind::None
)
3477 if (getAccelTableKind() != AccelTableKind::Apple
&&
3478 CU
.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default
)
3481 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
3482 DwarfStringPoolEntryRef Ref
= Holder
.getStringPool().getEntry(*Asm
, Name
);
3484 switch (getAccelTableKind()) {
3485 case AccelTableKind::Apple
:
3486 AppleAccel
.addName(Ref
, Die
);
3488 case AccelTableKind::Dwarf
:
3489 AccelDebugNames
.addName(Ref
, Die
);
3491 case AccelTableKind::Default
:
3492 llvm_unreachable("Default should have already been resolved.");
3493 case AccelTableKind::None
:
3494 llvm_unreachable("None handled above");
3498 void DwarfDebug::addAccelName(const DICompileUnit
&CU
, StringRef Name
,
3500 addAccelNameImpl(CU
, AccelNames
, Name
, Die
);
3503 void DwarfDebug::addAccelObjC(const DICompileUnit
&CU
, StringRef Name
,
3505 // ObjC names go only into the Apple accelerator tables.
3506 if (getAccelTableKind() == AccelTableKind::Apple
)
3507 addAccelNameImpl(CU
, AccelObjC
, Name
, Die
);
3510 void DwarfDebug::addAccelNamespace(const DICompileUnit
&CU
, StringRef Name
,
3512 addAccelNameImpl(CU
, AccelNamespace
, Name
, Die
);
3515 void DwarfDebug::addAccelType(const DICompileUnit
&CU
, StringRef Name
,
3516 const DIE
&Die
, char Flags
) {
3517 addAccelNameImpl(CU
, AccelTypes
, Name
, Die
);
3520 uint16_t DwarfDebug::getDwarfVersion() const {
3521 return Asm
->OutStreamer
->getContext().getDwarfVersion();
3524 dwarf::Form
DwarfDebug::getDwarfSectionOffsetForm() const {
3525 if (Asm
->getDwarfVersion() >= 4)
3526 return dwarf::Form::DW_FORM_sec_offset
;
3527 assert((!Asm
->isDwarf64() || (Asm
->getDwarfVersion() == 3)) &&
3528 "DWARF64 is not defined prior DWARFv3");
3529 return Asm
->isDwarf64() ? dwarf::Form::DW_FORM_data8
3530 : dwarf::Form::DW_FORM_data4
;
3533 const MCSymbol
*DwarfDebug::getSectionLabel(const MCSection
*S
) {
3534 auto I
= SectionLabels
.find(S
);
3535 if (I
== SectionLabels
.end())
3539 void DwarfDebug::insertSectionLabel(const MCSymbol
*S
) {
3540 if (SectionLabels
.insert(std::make_pair(&S
->getSection(), S
)).second
)
3541 if (useSplitDwarf() || getDwarfVersion() >= 5)
3542 AddrPool
.getIndex(S
);
3545 Optional
<MD5::MD5Result
> DwarfDebug::getMD5AsBytes(const DIFile
*File
) const {
3547 if (getDwarfVersion() < 5)
3549 Optional
<DIFile::ChecksumInfo
<StringRef
>> Checksum
= File
->getChecksum();
3550 if (!Checksum
|| Checksum
->Kind
!= DIFile::CSK_MD5
)
3553 // Convert the string checksum to an MD5Result for the streamer.
3554 // The verifier validates the checksum so we assume it's okay.
3555 // An MD5 checksum is 16 bytes.
3556 std::string ChecksumString
= fromHex(Checksum
->Value
);
3557 MD5::MD5Result CKMem
;
3558 std::copy(ChecksumString
.begin(), ChecksumString
.end(), CKMem
.Bytes
.data());