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 "DebugLocEntry.h"
17 #include "DebugLocStream.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.h"
20 #include "DwarfFile.h"
21 #include "DwarfUnit.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/CodeGen/AccelTable.h"
34 #include "llvm/CodeGen/AsmPrinter.h"
35 #include "llvm/CodeGen/DIE.h"
36 #include "llvm/CodeGen/LexicalScopes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
47 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GlobalVariable.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/MC/MCAsmInfo.h"
55 #include "llvm/MC/MCContext.h"
56 #include "llvm/MC/MCDwarf.h"
57 #include "llvm/MC/MCSection.h"
58 #include "llvm/MC/MCStreamer.h"
59 #include "llvm/MC/MCSymbol.h"
60 #include "llvm/MC/MCTargetOptions.h"
61 #include "llvm/MC/MachineLocation.h"
62 #include "llvm/MC/SectionKind.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/MD5.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/Timer.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetLoweringObjectFile.h"
73 #include "llvm/Target/TargetMachine.h"
74 #include "llvm/Target/TargetOptions.h"
86 #define DEBUG_TYPE "dwarfdebug"
88 STATISTIC(NumCSParams
, "Number of dbg call site params created");
91 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden
,
92 cl::desc("Disable debug info printing"));
94 static cl::opt
<bool> UseDwarfRangesBaseAddressSpecifier(
95 "use-dwarf-ranges-base-address-specifier", cl::Hidden
,
96 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
98 static cl::opt
<bool> GenerateARangeSection("generate-arange-section",
100 cl::desc("Generate dwarf aranges"),
104 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden
,
105 cl::desc("Generate DWARF4 type units."),
108 static cl::opt
<bool> SplitDwarfCrossCuReferences(
109 "split-dwarf-cross-cu-references", cl::Hidden
,
110 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
112 enum DefaultOnOff
{ Default
, Enable
, Disable
};
114 static cl::opt
<DefaultOnOff
> UnknownLocations(
115 "use-unknown-locations", cl::Hidden
,
116 cl::desc("Make an absence of debug location information explicit."),
117 cl::values(clEnumVal(Default
, "At top of block or after label"),
118 clEnumVal(Enable
, "In all cases"), clEnumVal(Disable
, "Never")),
121 static cl::opt
<AccelTableKind
> AccelTables(
122 "accel-tables", cl::Hidden
, cl::desc("Output dwarf accelerator tables."),
123 cl::values(clEnumValN(AccelTableKind::Default
, "Default",
124 "Default for platform"),
125 clEnumValN(AccelTableKind::None
, "Disable", "Disabled."),
126 clEnumValN(AccelTableKind::Apple
, "Apple", "Apple"),
127 clEnumValN(AccelTableKind::Dwarf
, "Dwarf", "DWARF")),
128 cl::init(AccelTableKind::Default
));
130 static cl::opt
<DefaultOnOff
>
131 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden
,
132 cl::desc("Use inlined strings rather than string section."),
133 cl::values(clEnumVal(Default
, "Default for platform"),
134 clEnumVal(Enable
, "Enabled"),
135 clEnumVal(Disable
, "Disabled")),
139 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden
,
140 cl::desc("Disable emission .debug_ranges section."),
143 static cl::opt
<DefaultOnOff
> DwarfSectionsAsReferences(
144 "dwarf-sections-as-references", cl::Hidden
,
145 cl::desc("Use sections+offset as references rather than labels."),
146 cl::values(clEnumVal(Default
, "Default for platform"),
147 clEnumVal(Enable
, "Enabled"), clEnumVal(Disable
, "Disabled")),
150 enum LinkageNameOption
{
156 static cl::opt
<LinkageNameOption
>
157 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden
,
158 cl::desc("Which DWARF linkage-name attributes to emit."),
159 cl::values(clEnumValN(DefaultLinkageNames
, "Default",
160 "Default for platform"),
161 clEnumValN(AllLinkageNames
, "All", "All"),
162 clEnumValN(AbstractLinkageNames
, "Abstract",
163 "Abstract subprograms")),
164 cl::init(DefaultLinkageNames
));
166 static const char *const DWARFGroupName
= "dwarf";
167 static const char *const DWARFGroupDescription
= "DWARF Emission";
168 static const char *const DbgTimerName
= "writer";
169 static const char *const DbgTimerDescription
= "DWARF Debug Writer";
170 static constexpr unsigned ULEB128PadSize
= 4;
172 void DebugLocDwarfExpression::emitOp(uint8_t Op
, const char *Comment
) {
174 Op
, Comment
? Twine(Comment
) + " " + dwarf::OperationEncodingString(Op
)
175 : dwarf::OperationEncodingString(Op
));
178 void DebugLocDwarfExpression::emitSigned(int64_t Value
) {
179 BS
.EmitSLEB128(Value
, Twine(Value
));
182 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value
) {
183 BS
.EmitULEB128(Value
, Twine(Value
));
186 void DebugLocDwarfExpression::emitData1(uint8_t Value
) {
187 BS
.EmitInt8(Value
, Twine(Value
));
190 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx
) {
191 assert(Idx
< (1ULL << (ULEB128PadSize
* 7)) && "Idx wont fit");
192 BS
.EmitULEB128(Idx
, Twine(Idx
), ULEB128PadSize
);
195 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo
&TRI
,
196 unsigned MachineReg
) {
197 // This information is not available while emitting .debug_loc entries.
201 bool DbgVariable::isBlockByrefVariable() const {
202 assert(getVariable() && "Invalid complex DbgVariable!");
203 return getVariable()->getType()->isBlockByrefStruct();
206 const DIType
*DbgVariable::getType() const {
207 DIType
*Ty
= getVariable()->getType();
208 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
209 // addresses instead.
210 if (Ty
->isBlockByrefStruct()) {
211 /* Byref variables, in Blocks, are declared by the programmer as
212 "SomeType VarName;", but the compiler creates a
213 __Block_byref_x_VarName struct, and gives the variable VarName
214 either the struct, or a pointer to the struct, as its type. This
215 is necessary for various behind-the-scenes things the compiler
216 needs to do with by-reference variables in blocks.
218 However, as far as the original *programmer* is concerned, the
219 variable should still have type 'SomeType', as originally declared.
221 The following function dives into the __Block_byref_x_VarName
222 struct to find the original type of the variable. This will be
223 passed back to the code generating the type for the Debug
224 Information Entry for the variable 'VarName'. 'VarName' will then
225 have the original type 'SomeType' in its debug information.
227 The original type 'SomeType' will be the type of the field named
228 'VarName' inside the __Block_byref_x_VarName struct.
230 NOTE: In order for this to not completely fail on the debugger
231 side, the Debug Information Entry for the variable VarName needs to
232 have a DW_AT_location that tells the debugger how to unwind through
233 the pointers and __Block_byref_x_VarName struct to find the actual
234 value of the variable. The function addBlockByrefType does this. */
235 DIType
*subType
= Ty
;
236 uint16_t tag
= Ty
->getTag();
238 if (tag
== dwarf::DW_TAG_pointer_type
)
239 subType
= cast
<DIDerivedType
>(Ty
)->getBaseType();
241 auto Elements
= cast
<DICompositeType
>(subType
)->getElements();
242 for (unsigned i
= 0, N
= Elements
.size(); i
< N
; ++i
) {
243 auto *DT
= cast
<DIDerivedType
>(Elements
[i
]);
244 if (getName() == DT
->getName())
245 return DT
->getBaseType();
251 /// Get .debug_loc entry for the instruction range starting at MI.
252 static DbgValueLoc
getDebugLocValue(const MachineInstr
*MI
) {
253 const DIExpression
*Expr
= MI
->getDebugExpression();
254 assert(MI
->getNumOperands() == 4);
255 if (MI
->getOperand(0).isReg()) {
256 auto RegOp
= MI
->getOperand(0);
257 auto Op1
= MI
->getOperand(1);
258 // If the second operand is an immediate, this is a
259 // register-indirect address.
260 assert((!Op1
.isImm() || (Op1
.getImm() == 0)) && "unexpected offset");
261 MachineLocation
MLoc(RegOp
.getReg(), Op1
.isImm());
262 return DbgValueLoc(Expr
, MLoc
);
264 if (MI
->getOperand(0).isImm())
265 return DbgValueLoc(Expr
, MI
->getOperand(0).getImm());
266 if (MI
->getOperand(0).isFPImm())
267 return DbgValueLoc(Expr
, MI
->getOperand(0).getFPImm());
268 if (MI
->getOperand(0).isCImm())
269 return DbgValueLoc(Expr
, MI
->getOperand(0).getCImm());
271 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
274 void DbgVariable::initializeDbgValue(const MachineInstr
*DbgValue
) {
275 assert(FrameIndexExprs
.empty() && "Already initialized?");
276 assert(!ValueLoc
.get() && "Already initialized?");
278 assert(getVariable() == DbgValue
->getDebugVariable() && "Wrong variable");
279 assert(getInlinedAt() == DbgValue
->getDebugLoc()->getInlinedAt() &&
282 ValueLoc
= std::make_unique
<DbgValueLoc
>(getDebugLocValue(DbgValue
));
283 if (auto *E
= DbgValue
->getDebugExpression())
284 if (E
->getNumElements())
285 FrameIndexExprs
.push_back({0, E
});
288 ArrayRef
<DbgVariable::FrameIndexExpr
> DbgVariable::getFrameIndexExprs() const {
289 if (FrameIndexExprs
.size() == 1)
290 return FrameIndexExprs
;
292 assert(llvm::all_of(FrameIndexExprs
,
293 [](const FrameIndexExpr
&A
) {
294 return A
.Expr
->isFragment();
296 "multiple FI expressions without DW_OP_LLVM_fragment");
297 llvm::sort(FrameIndexExprs
,
298 [](const FrameIndexExpr
&A
, const FrameIndexExpr
&B
) -> bool {
299 return A
.Expr
->getFragmentInfo()->OffsetInBits
<
300 B
.Expr
->getFragmentInfo()->OffsetInBits
;
303 return FrameIndexExprs
;
306 void DbgVariable::addMMIEntry(const DbgVariable
&V
) {
307 assert(DebugLocListIndex
== ~0U && !ValueLoc
.get() && "not an MMI entry");
308 assert(V
.DebugLocListIndex
== ~0U && !V
.ValueLoc
.get() && "not an MMI entry");
309 assert(V
.getVariable() == getVariable() && "conflicting variable");
310 assert(V
.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
312 assert(!FrameIndexExprs
.empty() && "Expected an MMI entry");
313 assert(!V
.FrameIndexExprs
.empty() && "Expected an MMI entry");
315 // FIXME: This logic should not be necessary anymore, as we now have proper
316 // deduplication. However, without it, we currently run into the assertion
317 // below, which means that we are likely dealing with broken input, i.e. two
318 // non-fragment entries for the same variable at different frame indices.
319 if (FrameIndexExprs
.size()) {
320 auto *Expr
= FrameIndexExprs
.back().Expr
;
321 if (!Expr
|| !Expr
->isFragment())
325 for (const auto &FIE
: V
.FrameIndexExprs
)
326 // Ignore duplicate entries.
327 if (llvm::none_of(FrameIndexExprs
, [&](const FrameIndexExpr
&Other
) {
328 return FIE
.FI
== Other
.FI
&& FIE
.Expr
== Other
.Expr
;
330 FrameIndexExprs
.push_back(FIE
);
332 assert((FrameIndexExprs
.size() == 1 ||
333 llvm::all_of(FrameIndexExprs
,
334 [](FrameIndexExpr
&FIE
) {
335 return FIE
.Expr
&& FIE
.Expr
->isFragment();
337 "conflicting locations for variable");
340 static AccelTableKind
computeAccelTableKind(unsigned DwarfVersion
,
341 bool GenerateTypeUnits
,
344 // Honor an explicit request.
345 if (AccelTables
!= AccelTableKind::Default
)
348 // Accelerator tables with type units are currently not supported.
349 if (GenerateTypeUnits
)
350 return AccelTableKind::None
;
352 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
353 // always implies debug_names. For lower standard versions we use apple
354 // accelerator tables on apple platforms and debug_names elsewhere.
355 if (DwarfVersion
>= 5)
356 return AccelTableKind::Dwarf
;
357 if (Tuning
== DebuggerKind::LLDB
)
358 return TT
.isOSBinFormatMachO() ? AccelTableKind::Apple
359 : AccelTableKind::Dwarf
;
360 return AccelTableKind::None
;
363 DwarfDebug::DwarfDebug(AsmPrinter
*A
, Module
*M
)
364 : DebugHandlerBase(A
), DebugLocs(A
->OutStreamer
->isVerboseAsm()),
365 InfoHolder(A
, "info_string", DIEValueAllocator
),
366 SkeletonHolder(A
, "skel_string", DIEValueAllocator
),
367 IsDarwin(A
->TM
.getTargetTriple().isOSDarwin()) {
368 const Triple
&TT
= Asm
->TM
.getTargetTriple();
370 // Make sure we know our "debugger tuning". The target option takes
371 // precedence; fall back to triple-based defaults.
372 if (Asm
->TM
.Options
.DebuggerTuning
!= DebuggerKind::Default
)
373 DebuggerTuning
= Asm
->TM
.Options
.DebuggerTuning
;
375 DebuggerTuning
= DebuggerKind::LLDB
;
376 else if (TT
.isPS4CPU())
377 DebuggerTuning
= DebuggerKind::SCE
;
379 DebuggerTuning
= DebuggerKind::GDB
;
381 if (DwarfInlinedStrings
== Default
)
382 UseInlineStrings
= TT
.isNVPTX();
384 UseInlineStrings
= DwarfInlinedStrings
== Enable
;
386 UseLocSection
= !TT
.isNVPTX();
388 HasAppleExtensionAttributes
= tuneForLLDB();
390 // Handle split DWARF.
391 HasSplitDwarf
= !Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
.empty();
393 // SCE defaults to linkage names only for abstract subprograms.
394 if (DwarfLinkageNames
== DefaultLinkageNames
)
395 UseAllLinkageNames
= !tuneForSCE();
397 UseAllLinkageNames
= DwarfLinkageNames
== AllLinkageNames
;
399 unsigned DwarfVersionNumber
= Asm
->TM
.Options
.MCOptions
.DwarfVersion
;
400 unsigned DwarfVersion
= DwarfVersionNumber
? DwarfVersionNumber
401 : MMI
->getModule()->getDwarfVersion();
402 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
404 TT
.isNVPTX() ? 2 : (DwarfVersion
? DwarfVersion
: dwarf::DWARF_VERSION
);
406 UseRangesSection
= !NoDwarfRangesSection
&& !TT
.isNVPTX();
408 // Use sections as references. Force for NVPTX.
409 if (DwarfSectionsAsReferences
== Default
)
410 UseSectionsAsReferences
= TT
.isNVPTX();
412 UseSectionsAsReferences
= DwarfSectionsAsReferences
== Enable
;
414 // Don't generate type units for unsupported object file formats.
416 A
->TM
.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits
;
418 TheAccelTableKind
= computeAccelTableKind(
419 DwarfVersion
, GenerateTypeUnits
, DebuggerTuning
, A
->TM
.getTargetTriple());
421 // Work around a GDB bug. GDB doesn't support the standard opcode;
422 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
423 // is defined as of DWARF 3.
424 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
425 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
426 UseGNUTLSOpcode
= tuneForGDB() || DwarfVersion
< 3;
428 // GDB does not fully support the DWARF 4 representation for bitfields.
429 UseDWARF2Bitfields
= (DwarfVersion
< 4) || tuneForGDB();
431 // The DWARF v5 string offsets table has - possibly shared - contributions
432 // from each compile and type unit each preceded by a header. The string
433 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
434 // a monolithic string offsets table without any header.
435 UseSegmentedStringOffsetsTable
= DwarfVersion
>= 5;
437 Asm
->OutStreamer
->getContext().setDwarfVersion(DwarfVersion
);
440 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
441 DwarfDebug::~DwarfDebug() = default;
443 static bool isObjCClass(StringRef Name
) {
444 return Name
.startswith("+") || Name
.startswith("-");
447 static bool hasObjCCategory(StringRef Name
) {
448 if (!isObjCClass(Name
))
451 return Name
.find(") ") != StringRef::npos
;
454 static void getObjCClassCategory(StringRef In
, StringRef
&Class
,
455 StringRef
&Category
) {
456 if (!hasObjCCategory(In
)) {
457 Class
= In
.slice(In
.find('[') + 1, In
.find(' '));
462 Class
= In
.slice(In
.find('[') + 1, In
.find('('));
463 Category
= In
.slice(In
.find('[') + 1, In
.find(' '));
466 static StringRef
getObjCMethodName(StringRef In
) {
467 return In
.slice(In
.find(' ') + 1, In
.find(']'));
470 // Add the various names to the Dwarf accelerator table names.
471 void DwarfDebug::addSubprogramNames(const DICompileUnit
&CU
,
472 const DISubprogram
*SP
, DIE
&Die
) {
473 if (getAccelTableKind() != AccelTableKind::Apple
&&
474 CU
.getNameTableKind() == DICompileUnit::DebugNameTableKind::None
)
477 if (!SP
->isDefinition())
480 if (SP
->getName() != "")
481 addAccelName(CU
, SP
->getName(), Die
);
483 // If the linkage name is different than the name, go ahead and output that as
484 // well into the name table. Only do that if we are going to actually emit
486 if (SP
->getLinkageName() != "" && SP
->getName() != SP
->getLinkageName() &&
487 (useAllLinkageNames() || InfoHolder
.getAbstractSPDies().lookup(SP
)))
488 addAccelName(CU
, SP
->getLinkageName(), Die
);
490 // If this is an Objective-C selector name add it to the ObjC accelerator
492 if (isObjCClass(SP
->getName())) {
493 StringRef Class
, Category
;
494 getObjCClassCategory(SP
->getName(), Class
, Category
);
495 addAccelObjC(CU
, Class
, Die
);
497 addAccelObjC(CU
, Category
, Die
);
498 // Also add the base method name to the name table.
499 addAccelName(CU
, getObjCMethodName(SP
->getName()), Die
);
503 /// Check whether we should create a DIE for the given Scope, return true
504 /// if we don't create a DIE (the corresponding DIE is null).
505 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope
*Scope
) {
506 if (Scope
->isAbstractScope())
509 // We don't create a DIE if there is no Range.
510 const SmallVectorImpl
<InsnRange
> &Ranges
= Scope
->getRanges();
514 if (Ranges
.size() > 1)
517 // We don't create a DIE if we have a single Range and the end label
519 return !getLabelAfterInsn(Ranges
.front().second
);
522 template <typename Func
> static void forBothCUs(DwarfCompileUnit
&CU
, Func F
) {
524 if (auto *SkelCU
= CU
.getSkeleton())
525 if (CU
.getCUNode()->getSplitDebugInlining())
529 bool DwarfDebug::shareAcrossDWOCUs() const {
530 return SplitDwarfCrossCuReferences
;
533 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit
&SrcCU
,
534 LexicalScope
*Scope
) {
535 assert(Scope
&& Scope
->getScopeNode());
536 assert(Scope
->isAbstractScope());
537 assert(!Scope
->getInlinedAt());
539 auto *SP
= cast
<DISubprogram
>(Scope
->getScopeNode());
541 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
542 // was inlined from another compile unit.
543 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP
->getUnit()->getSplitDebugInlining())
544 // Avoid building the original CU if it won't be used
545 SrcCU
.constructAbstractSubprogramScopeDIE(Scope
);
547 auto &CU
= getOrCreateDwarfCompileUnit(SP
->getUnit());
548 if (auto *SkelCU
= CU
.getSkeleton()) {
549 (shareAcrossDWOCUs() ? CU
: SrcCU
)
550 .constructAbstractSubprogramScopeDIE(Scope
);
551 if (CU
.getCUNode()->getSplitDebugInlining())
552 SkelCU
->constructAbstractSubprogramScopeDIE(Scope
);
554 CU
.constructAbstractSubprogramScopeDIE(Scope
);
558 /// Try to interpret values loaded into registers that forward parameters
559 /// for \p CallMI. Store parameters with interpreted value into \p Params.
560 static void collectCallSiteParameters(const MachineInstr
*CallMI
,
562 auto *MF
= CallMI
->getMF();
563 auto CalleesMap
= MF
->getCallSitesInfo();
564 auto CallFwdRegsInfo
= CalleesMap
.find(CallMI
);
566 // There is no information for the call instruction.
567 if (CallFwdRegsInfo
== CalleesMap
.end())
570 auto *MBB
= CallMI
->getParent();
571 const auto &TRI
= MF
->getSubtarget().getRegisterInfo();
572 const auto &TII
= MF
->getSubtarget().getInstrInfo();
573 const auto &TLI
= MF
->getSubtarget().getTargetLowering();
575 // Skip the call instruction.
576 auto I
= std::next(CallMI
->getReverseIterator());
578 DenseSet
<unsigned> ForwardedRegWorklist
;
579 // Add all the forwarding registers into the ForwardedRegWorklist.
580 for (auto ArgReg
: CallFwdRegsInfo
->second
) {
581 bool InsertedReg
= ForwardedRegWorklist
.insert(ArgReg
.Reg
).second
;
582 assert(InsertedReg
&& "Single register used to forward two arguments?");
586 // We erase, from the ForwardedRegWorklist, those forwarding registers for
587 // which we successfully describe a loaded value (by using
588 // the describeLoadedValue()). For those remaining arguments in the working
589 // list, for which we do not describe a loaded value by
590 // the describeLoadedValue(), we try to generate an entry value expression
591 // for their call site value desctipion, if the call is within the entry MBB.
592 // The RegsForEntryValues maps a forwarding register into the register holding
594 // TODO: Handle situations when call site parameter value can be described
595 // as the entry value within basic blocks other then the first one.
596 bool ShouldTryEmitEntryVals
= MBB
->getIterator() == MF
->begin();
597 DenseMap
<unsigned, unsigned> RegsForEntryValues
;
599 // If the MI is an instruction defining a parameter's forwarding register,
600 // add it into the Defs. If the MI clobbers more then one register, we use
601 // the Defs in order to remove all the registers from
602 // the ForwardedRegWorklist, since we do not support such situations now.
603 auto getForwardingRegsDefinedByMI
= [&](const MachineInstr
&MI
,
604 SmallVectorImpl
<unsigned> &Defs
) {
605 if (MI
.isDebugInstr())
608 for (const MachineOperand
&MO
: MI
.operands()) {
609 if (MO
.isReg() && MO
.isDef() &&
610 Register::isPhysicalRegister(MO
.getReg())) {
611 for (auto FwdReg
: ForwardedRegWorklist
) {
612 if (TRI
->regsOverlap(FwdReg
, MO
.getReg())) {
613 Defs
.push_back(FwdReg
);
621 auto finishCallSiteParam
= [&](DbgValueLoc DbgLocVal
, unsigned Reg
) {
622 unsigned FwdReg
= Reg
;
623 if (ShouldTryEmitEntryVals
) {
624 auto EntryValReg
= RegsForEntryValues
.find(Reg
);
625 if (EntryValReg
!= RegsForEntryValues
.end())
626 FwdReg
= EntryValReg
->second
;
629 DbgCallSiteParam
CSParm(FwdReg
, DbgLocVal
);
630 Params
.push_back(CSParm
);
634 // Search for a loading value in forwaring registers.
635 for (; I
!= MBB
->rend(); ++I
) {
636 // If the next instruction is a call we can not interpret parameter's
637 // forwarding registers or we finished the interpretation of all parameters.
641 if (ForwardedRegWorklist
.empty())
644 SmallVector
<unsigned, 4> Defs
;
645 getForwardingRegsDefinedByMI(*I
, Defs
);
649 // If the MI clobbers more then one forwarding register we must remove
650 // all of them from the working list.
651 for (auto Reg
: Defs
)
652 ForwardedRegWorklist
.erase(Reg
);
653 if (I
->getNumDefs() != 1)
655 unsigned Reg
= Defs
[0];
657 if (auto ParamValue
= TII
->describeLoadedValue(*I
)) {
658 if (ParamValue
->first
->isImm()) {
659 unsigned Val
= ParamValue
->first
->getImm();
660 DbgValueLoc
DbgLocVal(ParamValue
->second
, Val
);
661 finishCallSiteParam(DbgLocVal
, Reg
);
662 } else if (ParamValue
->first
->isReg()) {
663 Register RegLoc
= ParamValue
->first
->getReg();
664 unsigned SP
= TLI
->getStackPointerRegisterToSaveRestore();
665 Register FP
= TRI
->getFrameRegister(*MF
);
666 bool IsSPorFP
= (RegLoc
== SP
) || (RegLoc
== FP
);
667 if (TRI
->isCalleeSavedPhysReg(RegLoc
, *MF
) || IsSPorFP
) {
668 DbgValueLoc
DbgLocVal(ParamValue
->second
,
669 MachineLocation(RegLoc
,
670 /*IsIndirect=*/IsSPorFP
));
671 finishCallSiteParam(DbgLocVal
, Reg
);
672 } else if (ShouldTryEmitEntryVals
) {
673 ForwardedRegWorklist
.insert(RegLoc
);
674 RegsForEntryValues
[RegLoc
] = Reg
;
680 // Emit the call site parameter's value as an entry value.
681 if (ShouldTryEmitEntryVals
) {
682 // Create an entry value expression where the expression following
683 // the 'DW_OP_entry_value' will be the size of 1 (a register operation).
684 DIExpression
*EntryExpr
= DIExpression::get(MF
->getFunction().getContext(),
685 {dwarf::DW_OP_entry_value
, 1});
686 for (auto RegEntry
: ForwardedRegWorklist
) {
687 unsigned FwdReg
= RegEntry
;
688 auto EntryValReg
= RegsForEntryValues
.find(RegEntry
);
689 if (EntryValReg
!= RegsForEntryValues
.end())
690 FwdReg
= EntryValReg
->second
;
692 DbgValueLoc
DbgLocVal(EntryExpr
, MachineLocation(RegEntry
));
693 DbgCallSiteParam
CSParm(FwdReg
, DbgLocVal
);
694 Params
.push_back(CSParm
);
700 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram
&SP
,
701 DwarfCompileUnit
&CU
, DIE
&ScopeDIE
,
702 const MachineFunction
&MF
) {
703 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
704 // the subprogram is required to have one.
705 if (!SP
.areAllCallsDescribed() || !SP
.isDefinition())
708 // Use DW_AT_call_all_calls to express that call site entries are present
709 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
710 // because one of its requirements is not met: call site entries for
711 // optimized-out calls are elided.
712 CU
.addFlag(ScopeDIE
, CU
.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls
));
714 const TargetInstrInfo
*TII
= MF
.getSubtarget().getInstrInfo();
715 assert(TII
&& "TargetInstrInfo not found: cannot label tail calls");
716 bool ApplyGNUExtensions
= getDwarfVersion() == 4 && tuneForGDB();
718 // Emit call site entries for each call or tail call in the function.
719 for (const MachineBasicBlock
&MBB
: MF
) {
720 for (const MachineInstr
&MI
: MBB
.instrs()) {
721 // Skip instructions which aren't calls. Both calls and tail-calling jump
722 // instructions (e.g TAILJMPd64) are classified correctly here.
726 // TODO: Add support for targets with delay slots (see: beginInstruction).
727 if (MI
.hasDelaySlot())
730 // If this is a direct call, find the callee's subprogram.
731 // In the case of an indirect call find the register that holds
733 const MachineOperand
&CalleeOp
= MI
.getOperand(0);
734 if (!CalleeOp
.isGlobal() && !CalleeOp
.isReg())
737 unsigned CallReg
= 0;
738 const DISubprogram
*CalleeSP
= nullptr;
739 const Function
*CalleeDecl
= nullptr;
740 if (CalleeOp
.isReg()) {
741 CallReg
= CalleeOp
.getReg();
745 CalleeDecl
= dyn_cast
<Function
>(CalleeOp
.getGlobal());
746 if (!CalleeDecl
|| !CalleeDecl
->getSubprogram())
748 CalleeSP
= CalleeDecl
->getSubprogram();
751 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
753 bool IsTail
= TII
->isTailCall(MI
);
755 // For tail calls, for non-gdb tuning, no return PC information is needed.
756 // For regular calls (and tail calls in GDB tuning), the return PC
757 // is needed to disambiguate paths in the call graph which could lead to
758 // some target function.
759 const MCExpr
*PCOffset
=
760 (IsTail
&& !tuneForGDB()) ? nullptr
761 : getFunctionLocalOffsetAfterInsn(&MI
);
763 // Address of a call-like instruction for a normal call or a jump-like
764 // instruction for a tail call. This is needed for GDB + DWARF 4 tuning.
765 const MCSymbol
*PCAddr
=
766 ApplyGNUExtensions
? const_cast<MCSymbol
*>(getLabelAfterInsn(&MI
))
769 assert((IsTail
|| PCOffset
|| PCAddr
) &&
770 "Call without return PC information");
772 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF
.getName() << " -> "
773 << (CalleeDecl
? CalleeDecl
->getName()
774 : StringRef(MF
.getSubtarget()
777 << (IsTail
? " [IsTail]" : "") << "\n");
780 CU
.constructCallSiteEntryDIE(ScopeDIE
, CalleeSP
, IsTail
, PCAddr
,
783 // For now only GDB supports call site parameter debug info.
784 if (Asm
->TM
.Options
.EnableDebugEntryValues
&&
787 // Try to interpret values of call site parameters.
788 collectCallSiteParameters(&MI
, Params
);
789 CU
.constructCallSiteParmEntryDIEs(CallSiteDIE
, Params
);
795 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit
&U
, DIE
&D
) const {
796 if (!U
.hasDwarfPubSections())
799 U
.addFlag(D
, dwarf::DW_AT_GNU_pubnames
);
802 void DwarfDebug::finishUnitAttributes(const DICompileUnit
*DIUnit
,
803 DwarfCompileUnit
&NewCU
) {
804 DIE
&Die
= NewCU
.getUnitDie();
805 StringRef FN
= DIUnit
->getFilename();
807 StringRef Producer
= DIUnit
->getProducer();
808 StringRef Flags
= DIUnit
->getFlags();
809 if (!Flags
.empty() && !useAppleExtensionAttributes()) {
810 std::string ProducerWithFlags
= Producer
.str() + " " + Flags
.str();
811 NewCU
.addString(Die
, dwarf::DW_AT_producer
, ProducerWithFlags
);
813 NewCU
.addString(Die
, dwarf::DW_AT_producer
, Producer
);
815 NewCU
.addUInt(Die
, dwarf::DW_AT_language
, dwarf::DW_FORM_data2
,
816 DIUnit
->getSourceLanguage());
817 NewCU
.addString(Die
, dwarf::DW_AT_name
, FN
);
819 // Add DW_str_offsets_base to the unit DIE, except for split units.
820 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
821 NewCU
.addStringOffsetsStart();
823 if (!useSplitDwarf()) {
824 NewCU
.initStmtList();
826 // If we're using split dwarf the compilation dir is going to be in the
827 // skeleton CU and so we don't need to duplicate it here.
828 if (!CompilationDir
.empty())
829 NewCU
.addString(Die
, dwarf::DW_AT_comp_dir
, CompilationDir
);
831 addGnuPubAttributes(NewCU
, Die
);
834 if (useAppleExtensionAttributes()) {
835 if (DIUnit
->isOptimized())
836 NewCU
.addFlag(Die
, dwarf::DW_AT_APPLE_optimized
);
838 StringRef Flags
= DIUnit
->getFlags();
840 NewCU
.addString(Die
, dwarf::DW_AT_APPLE_flags
, Flags
);
842 if (unsigned RVer
= DIUnit
->getRuntimeVersion())
843 NewCU
.addUInt(Die
, dwarf::DW_AT_APPLE_major_runtime_vers
,
844 dwarf::DW_FORM_data1
, RVer
);
847 if (DIUnit
->getDWOId()) {
848 // This CU is either a clang module DWO or a skeleton CU.
849 NewCU
.addUInt(Die
, dwarf::DW_AT_GNU_dwo_id
, dwarf::DW_FORM_data8
,
851 if (!DIUnit
->getSplitDebugFilename().empty())
852 // This is a prefabricated skeleton CU.
853 NewCU
.addString(Die
, dwarf::DW_AT_GNU_dwo_name
,
854 DIUnit
->getSplitDebugFilename());
857 // Create new DwarfCompileUnit for the given metadata node with tag
858 // DW_TAG_compile_unit.
860 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit
*DIUnit
) {
861 if (auto *CU
= CUMap
.lookup(DIUnit
))
864 CompilationDir
= DIUnit
->getDirectory();
866 auto OwnedUnit
= std::make_unique
<DwarfCompileUnit
>(
867 InfoHolder
.getUnits().size(), DIUnit
, Asm
, this, &InfoHolder
);
868 DwarfCompileUnit
&NewCU
= *OwnedUnit
;
869 InfoHolder
.addUnit(std::move(OwnedUnit
));
871 for (auto *IE
: DIUnit
->getImportedEntities())
872 NewCU
.addImportedEntity(IE
);
874 // LTO with assembly output shares a single line table amongst multiple CUs.
875 // To avoid the compilation directory being ambiguous, let the line table
876 // explicitly describe the directory of all files, never relying on the
877 // compilation directory.
878 if (!Asm
->OutStreamer
->hasRawTextSupport() || SingleCU
)
879 Asm
->OutStreamer
->emitDwarfFile0Directive(
880 CompilationDir
, DIUnit
->getFilename(),
881 NewCU
.getMD5AsBytes(DIUnit
->getFile()), DIUnit
->getSource(),
882 NewCU
.getUniqueID());
884 if (useSplitDwarf()) {
885 NewCU
.setSkeleton(constructSkeletonCU(NewCU
));
886 NewCU
.setSection(Asm
->getObjFileLowering().getDwarfInfoDWOSection());
888 finishUnitAttributes(DIUnit
, NewCU
);
889 NewCU
.setSection(Asm
->getObjFileLowering().getDwarfInfoSection());
892 // Create DIEs for function declarations used for call site debug info.
893 for (auto Scope
: DIUnit
->getRetainedTypes())
894 if (auto *SP
= dyn_cast_or_null
<DISubprogram
>(Scope
))
895 NewCU
.getOrCreateSubprogramDIE(SP
);
897 CUMap
.insert({DIUnit
, &NewCU
});
898 CUDieMap
.insert({&NewCU
.getUnitDie(), &NewCU
});
902 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit
&TheCU
,
903 const DIImportedEntity
*N
) {
904 if (isa
<DILocalScope
>(N
->getScope()))
906 if (DIE
*D
= TheCU
.getOrCreateContextDIE(N
->getScope()))
907 D
->addChild(TheCU
.constructImportedEntityDIE(N
));
910 /// Sort and unique GVEs by comparing their fragment offset.
911 static SmallVectorImpl
<DwarfCompileUnit::GlobalExpr
> &
912 sortGlobalExprs(SmallVectorImpl
<DwarfCompileUnit::GlobalExpr
> &GVEs
) {
914 GVEs
, [](DwarfCompileUnit::GlobalExpr A
, DwarfCompileUnit::GlobalExpr B
) {
915 // Sort order: first null exprs, then exprs without fragment
916 // info, then sort by fragment offset in bits.
917 // FIXME: Come up with a more comprehensive comparator so
918 // the sorting isn't non-deterministic, and so the following
919 // std::unique call works correctly.
920 if (!A
.Expr
|| !B
.Expr
)
922 auto FragmentA
= A
.Expr
->getFragmentInfo();
923 auto FragmentB
= B
.Expr
->getFragmentInfo();
924 if (!FragmentA
|| !FragmentB
)
926 return FragmentA
->OffsetInBits
< FragmentB
->OffsetInBits
;
928 GVEs
.erase(std::unique(GVEs
.begin(), GVEs
.end(),
929 [](DwarfCompileUnit::GlobalExpr A
,
930 DwarfCompileUnit::GlobalExpr B
) {
931 return A
.Expr
== B
.Expr
;
937 // Emit all Dwarf sections that should come prior to the content. Create
938 // global DIEs and emit initial debug info sections. This is invoked by
939 // the target AsmPrinter.
940 void DwarfDebug::beginModule() {
941 NamedRegionTimer
T(DbgTimerName
, DbgTimerDescription
, DWARFGroupName
,
942 DWARFGroupDescription
, TimePassesIsEnabled
);
943 if (DisableDebugInfoPrinting
) {
944 MMI
->setDebugInfoAvailability(false);
948 const Module
*M
= MMI
->getModule();
950 unsigned NumDebugCUs
= std::distance(M
->debug_compile_units_begin(),
951 M
->debug_compile_units_end());
952 // Tell MMI whether we have debug info.
953 assert(MMI
->hasDebugInfo() == (NumDebugCUs
> 0) &&
954 "DebugInfoAvailabilty initialized unexpectedly");
955 SingleCU
= NumDebugCUs
== 1;
956 DenseMap
<DIGlobalVariable
*, SmallVector
<DwarfCompileUnit::GlobalExpr
, 1>>
958 for (const GlobalVariable
&Global
: M
->globals()) {
959 SmallVector
<DIGlobalVariableExpression
*, 1> GVs
;
960 Global
.getDebugInfo(GVs
);
961 for (auto *GVE
: GVs
)
962 GVMap
[GVE
->getVariable()].push_back({&Global
, GVE
->getExpression()});
965 // Create the symbol that designates the start of the unit's contribution
966 // to the string offsets table. In a split DWARF scenario, only the skeleton
967 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
968 if (useSegmentedStringOffsetsTable())
969 (useSplitDwarf() ? SkeletonHolder
: InfoHolder
)
970 .setStringOffsetsStartSym(Asm
->createTempSymbol("str_offsets_base"));
973 // Create the symbols that designates the start of the DWARF v5 range list
974 // and locations list tables. They are located past the table headers.
975 if (getDwarfVersion() >= 5) {
976 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
977 Holder
.setRnglistsTableBaseSym(
978 Asm
->createTempSymbol("rnglists_table_base"));
979 Holder
.setLoclistsTableBaseSym(
980 Asm
->createTempSymbol("loclists_table_base"));
983 InfoHolder
.setRnglistsTableBaseSym(
984 Asm
->createTempSymbol("rnglists_dwo_table_base"));
987 // Create the symbol that points to the first entry following the debug
988 // address table (.debug_addr) header.
989 AddrPool
.setLabel(Asm
->createTempSymbol("addr_table_base"));
991 for (DICompileUnit
*CUNode
: M
->debug_compile_units()) {
992 // FIXME: Move local imported entities into a list attached to the
993 // subprogram, then this search won't be needed and a
994 // getImportedEntities().empty() test should go below with the rest.
995 bool HasNonLocalImportedEntities
= llvm::any_of(
996 CUNode
->getImportedEntities(), [](const DIImportedEntity
*IE
) {
997 return !isa
<DILocalScope
>(IE
->getScope());
1000 if (!HasNonLocalImportedEntities
&& CUNode
->getEnumTypes().empty() &&
1001 CUNode
->getRetainedTypes().empty() &&
1002 CUNode
->getGlobalVariables().empty() && CUNode
->getMacros().empty())
1005 DwarfCompileUnit
&CU
= getOrCreateDwarfCompileUnit(CUNode
);
1007 // Global Variables.
1008 for (auto *GVE
: CUNode
->getGlobalVariables()) {
1009 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1010 // already know about the variable and it isn't adding a constant
1012 auto &GVMapEntry
= GVMap
[GVE
->getVariable()];
1013 auto *Expr
= GVE
->getExpression();
1014 if (!GVMapEntry
.size() || (Expr
&& Expr
->isConstant()))
1015 GVMapEntry
.push_back({nullptr, Expr
});
1017 DenseSet
<DIGlobalVariable
*> Processed
;
1018 for (auto *GVE
: CUNode
->getGlobalVariables()) {
1019 DIGlobalVariable
*GV
= GVE
->getVariable();
1020 if (Processed
.insert(GV
).second
)
1021 CU
.getOrCreateGlobalVariableDIE(GV
, sortGlobalExprs(GVMap
[GV
]));
1024 for (auto *Ty
: CUNode
->getEnumTypes()) {
1025 // The enum types array by design contains pointers to
1026 // MDNodes rather than DIRefs. Unique them here.
1027 CU
.getOrCreateTypeDIE(cast
<DIType
>(Ty
));
1029 for (auto *Ty
: CUNode
->getRetainedTypes()) {
1030 // The retained types array by design contains pointers to
1031 // MDNodes rather than DIRefs. Unique them here.
1032 if (DIType
*RT
= dyn_cast
<DIType
>(Ty
))
1033 // There is no point in force-emitting a forward declaration.
1034 CU
.getOrCreateTypeDIE(RT
);
1036 // Emit imported_modules last so that the relevant context is already
1038 for (auto *IE
: CUNode
->getImportedEntities())
1039 constructAndAddImportedEntityDIE(CU
, IE
);
1043 void DwarfDebug::finishEntityDefinitions() {
1044 for (const auto &Entity
: ConcreteEntities
) {
1045 DIE
*Die
= Entity
->getDIE();
1047 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1048 // in the ConcreteEntities list, rather than looking it up again here.
1049 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1050 DwarfCompileUnit
*Unit
= CUDieMap
.lookup(Die
->getUnitDie());
1052 Unit
->finishEntityDefinition(Entity
.get());
1056 void DwarfDebug::finishSubprogramDefinitions() {
1057 for (const DISubprogram
*SP
: ProcessedSPNodes
) {
1058 assert(SP
->getUnit()->getEmissionKind() != DICompileUnit::NoDebug
);
1060 getOrCreateDwarfCompileUnit(SP
->getUnit()),
1061 [&](DwarfCompileUnit
&CU
) { CU
.finishSubprogramDefinition(SP
); });
1065 void DwarfDebug::finalizeModuleInfo() {
1066 const TargetLoweringObjectFile
&TLOF
= Asm
->getObjFileLowering();
1068 finishSubprogramDefinitions();
1070 finishEntityDefinitions();
1072 // Include the DWO file name in the hash if there's more than one CU.
1073 // This handles ThinLTO's situation where imported CUs may very easily be
1074 // duplicate with the same CU partially imported into another ThinLTO unit.
1076 if (CUMap
.size() > 1)
1077 DWOName
= Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
;
1079 // Handle anything that needs to be done on a per-unit basis after
1080 // all other generation.
1081 for (const auto &P
: CUMap
) {
1082 auto &TheCU
= *P
.second
;
1083 if (TheCU
.getCUNode()->isDebugDirectivesOnly())
1085 // Emit DW_AT_containing_type attribute to connect types with their
1086 // vtable holding type.
1087 TheCU
.constructContainingTypeDIEs();
1089 // Add CU specific attributes if we need to add any.
1090 // If we're splitting the dwarf out now that we've got the entire
1091 // CU then add the dwo id to it.
1092 auto *SkCU
= TheCU
.getSkeleton();
1093 if (useSplitDwarf() && !empty(TheCU
.getUnitDie().children())) {
1094 finishUnitAttributes(TheCU
.getCUNode(), TheCU
);
1095 TheCU
.addString(TheCU
.getUnitDie(), dwarf::DW_AT_GNU_dwo_name
,
1096 Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
);
1097 SkCU
->addString(SkCU
->getUnitDie(), dwarf::DW_AT_GNU_dwo_name
,
1098 Asm
->TM
.Options
.MCOptions
.SplitDwarfFile
);
1099 // Emit a unique identifier for this CU.
1101 DIEHash(Asm
).computeCUSignature(DWOName
, TheCU
.getUnitDie());
1102 if (getDwarfVersion() >= 5) {
1106 TheCU
.addUInt(TheCU
.getUnitDie(), dwarf::DW_AT_GNU_dwo_id
,
1107 dwarf::DW_FORM_data8
, ID
);
1108 SkCU
->addUInt(SkCU
->getUnitDie(), dwarf::DW_AT_GNU_dwo_id
,
1109 dwarf::DW_FORM_data8
, ID
);
1112 if (getDwarfVersion() < 5 && !SkeletonHolder
.getRangeLists().empty()) {
1113 const MCSymbol
*Sym
= TLOF
.getDwarfRangesSection()->getBeginSymbol();
1114 SkCU
->addSectionLabel(SkCU
->getUnitDie(), dwarf::DW_AT_GNU_ranges_base
,
1118 finishUnitAttributes(SkCU
->getCUNode(), *SkCU
);
1121 // If we have code split among multiple sections or non-contiguous
1122 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1123 // remain in the .o file, otherwise add a DW_AT_low_pc.
1124 // FIXME: We should use ranges allow reordering of code ala
1125 // .subsections_via_symbols in mach-o. This would mean turning on
1126 // ranges for all subprogram DIEs for mach-o.
1127 DwarfCompileUnit
&U
= SkCU
? *SkCU
: TheCU
;
1129 if (unsigned NumRanges
= TheCU
.getRanges().size()) {
1130 if (NumRanges
> 1 && useRangesSection())
1131 // A DW_AT_low_pc attribute may also be specified in combination with
1132 // DW_AT_ranges to specify the default base address for use in
1133 // location lists (see Section 2.6.2) and range lists (see Section
1135 U
.addUInt(U
.getUnitDie(), dwarf::DW_AT_low_pc
, dwarf::DW_FORM_addr
, 0);
1137 U
.setBaseAddress(TheCU
.getRanges().front().getStart());
1138 U
.attachRangesOrLowHighPC(U
.getUnitDie(), TheCU
.takeRanges());
1141 // We don't keep track of which addresses are used in which CU so this
1142 // is a bit pessimistic under LTO.
1143 if (!AddrPool
.isEmpty() &&
1144 (getDwarfVersion() >= 5 ||
1145 (SkCU
&& !empty(TheCU
.getUnitDie().children()))))
1146 U
.addAddrTableBase();
1148 if (getDwarfVersion() >= 5) {
1149 if (U
.hasRangeLists())
1150 U
.addRnglistsBase();
1152 if (!DebugLocs
.getLists().empty() && !useSplitDwarf())
1153 U
.addLoclistsBase();
1156 auto *CUNode
= cast
<DICompileUnit
>(P
.first
);
1157 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
1158 if (CUNode
->getMacros())
1159 U
.addSectionLabel(U
.getUnitDie(), dwarf::DW_AT_macro_info
,
1160 U
.getMacroLabelBegin(),
1161 TLOF
.getDwarfMacinfoSection()->getBeginSymbol());
1164 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1165 for (auto *CUNode
: MMI
->getModule()->debug_compile_units())
1166 if (CUNode
->getDWOId())
1167 getOrCreateDwarfCompileUnit(CUNode
);
1169 // Compute DIE offsets and sizes.
1170 InfoHolder
.computeSizeAndOffsets();
1171 if (useSplitDwarf())
1172 SkeletonHolder
.computeSizeAndOffsets();
1175 // Emit all Dwarf sections that should come after the content.
1176 void DwarfDebug::endModule() {
1177 assert(CurFn
== nullptr);
1178 assert(CurMI
== nullptr);
1180 for (const auto &P
: CUMap
) {
1181 auto &CU
= *P
.second
;
1182 CU
.createBaseTypeDIEs();
1185 // If we aren't actually generating debug info (check beginModule -
1186 // conditionalized on !DisableDebugInfoPrinting and the presence of the
1187 // llvm.dbg.cu metadata node)
1188 if (!MMI
->hasDebugInfo())
1191 // Finalize the debug info for the module.
1192 finalizeModuleInfo();
1196 if (useSplitDwarf())
1199 // Emit info into a debug loc section.
1202 // Corresponding abbreviations into a abbrev section.
1203 emitAbbreviations();
1205 // Emit all the DIEs into a debug info section.
1208 // Emit info into a debug aranges section.
1209 if (GenerateARangeSection
)
1212 // Emit info into a debug ranges section.
1215 // Emit info into a debug macinfo section.
1218 if (useSplitDwarf()) {
1221 emitDebugAbbrevDWO();
1223 emitDebugRangesDWO();
1228 // Emit info into the dwarf accelerator table sections.
1229 switch (getAccelTableKind()) {
1230 case AccelTableKind::Apple
:
1233 emitAccelNamespaces();
1236 case AccelTableKind::Dwarf
:
1237 emitAccelDebugNames();
1239 case AccelTableKind::None
:
1241 case AccelTableKind::Default
:
1242 llvm_unreachable("Default should have already been resolved.");
1245 // Emit the pubnames and pubtypes sections if requested.
1246 emitDebugPubSections();
1249 // FIXME: AbstractVariables.clear();
1252 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit
&CU
,
1254 const MDNode
*ScopeNode
) {
1255 if (CU
.getExistingAbstractEntity(Node
))
1258 CU
.createAbstractEntity(Node
, LScopes
.getOrCreateAbstractScope(
1259 cast
<DILocalScope
>(ScopeNode
)));
1262 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit
&CU
,
1263 const DINode
*Node
, const MDNode
*ScopeNode
) {
1264 if (CU
.getExistingAbstractEntity(Node
))
1267 if (LexicalScope
*Scope
=
1268 LScopes
.findAbstractScope(cast_or_null
<DILocalScope
>(ScopeNode
)))
1269 CU
.createAbstractEntity(Node
, Scope
);
1272 // Collect variable information from side table maintained by MF.
1273 void DwarfDebug::collectVariableInfoFromMFTable(
1274 DwarfCompileUnit
&TheCU
, DenseSet
<InlinedEntity
> &Processed
) {
1275 SmallDenseMap
<InlinedEntity
, DbgVariable
*> MFVars
;
1276 for (const auto &VI
: Asm
->MF
->getVariableDbgInfo()) {
1279 assert(VI
.Var
->isValidLocationForIntrinsic(VI
.Loc
) &&
1280 "Expected inlined-at fields to agree");
1282 InlinedEntity
Var(VI
.Var
, VI
.Loc
->getInlinedAt());
1283 Processed
.insert(Var
);
1284 LexicalScope
*Scope
= LScopes
.findLexicalScope(VI
.Loc
);
1286 // If variable scope is not found then skip this variable.
1290 ensureAbstractEntityIsCreatedIfScoped(TheCU
, Var
.first
, Scope
->getScopeNode());
1291 auto RegVar
= std::make_unique
<DbgVariable
>(
1292 cast
<DILocalVariable
>(Var
.first
), Var
.second
);
1293 RegVar
->initializeMMI(VI
.Expr
, VI
.Slot
);
1294 if (DbgVariable
*DbgVar
= MFVars
.lookup(Var
))
1295 DbgVar
->addMMIEntry(*RegVar
);
1296 else if (InfoHolder
.addScopeVariable(Scope
, RegVar
.get())) {
1297 MFVars
.insert({Var
, RegVar
.get()});
1298 ConcreteEntities
.push_back(std::move(RegVar
));
1303 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1304 /// enclosing lexical scope. The check ensures there are no other instructions
1305 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1306 /// either open or otherwise rolls off the end of the scope.
1307 static bool validThroughout(LexicalScopes
&LScopes
,
1308 const MachineInstr
*DbgValue
,
1309 const MachineInstr
*RangeEnd
) {
1310 assert(DbgValue
->getDebugLoc() && "DBG_VALUE without a debug location");
1311 auto MBB
= DbgValue
->getParent();
1312 auto DL
= DbgValue
->getDebugLoc();
1313 auto *LScope
= LScopes
.findLexicalScope(DL
);
1314 // Scope doesn't exist; this is a dead DBG_VALUE.
1317 auto &LSRange
= LScope
->getRanges();
1318 if (LSRange
.size() == 0)
1321 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1322 const MachineInstr
*LScopeBegin
= LSRange
.front().first
;
1323 // Early exit if the lexical scope begins outside of the current block.
1324 if (LScopeBegin
->getParent() != MBB
)
1326 MachineBasicBlock::const_reverse_iterator
Pred(DbgValue
);
1327 for (++Pred
; Pred
!= MBB
->rend(); ++Pred
) {
1328 if (Pred
->getFlag(MachineInstr::FrameSetup
))
1330 auto PredDL
= Pred
->getDebugLoc();
1331 if (!PredDL
|| Pred
->isMetaInstruction())
1333 // Check whether the instruction preceding the DBG_VALUE is in the same
1334 // (sub)scope as the DBG_VALUE.
1335 if (DL
->getScope() == PredDL
->getScope())
1337 auto *PredScope
= LScopes
.findLexicalScope(PredDL
);
1338 if (!PredScope
|| LScope
->dominates(PredScope
))
1342 // If the range of the DBG_VALUE is open-ended, report success.
1346 // Fail if there are instructions belonging to our scope in another block.
1347 const MachineInstr
*LScopeEnd
= LSRange
.back().second
;
1348 if (LScopeEnd
->getParent() != MBB
)
1351 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1352 // throughout the function. This is a hack, presumably for DWARF v2 and not
1353 // necessarily correct. It would be much better to use a dbg.declare instead
1354 // if we know the constant is live throughout the scope.
1355 if (DbgValue
->getOperand(0).isImm() && MBB
->pred_empty())
1361 /// Build the location list for all DBG_VALUEs in the function that
1362 /// describe the same variable. The resulting DebugLocEntries will have
1363 /// strict monotonically increasing begin addresses and will never
1364 /// overlap. If the resulting list has only one entry that is valid
1365 /// throughout variable's scope return true.
1367 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1368 // different kinds of history map entries. One thing to be aware of is that if
1369 // a debug value is ended by another entry (rather than being valid until the
1370 // end of the function), that entry's instruction may or may not be included in
1371 // the range, depending on if the entry is a clobbering entry (it has an
1372 // instruction that clobbers one or more preceding locations), or if it is an
1373 // (overlapping) debug value entry. This distinction can be seen in the example
1374 // below. The first debug value is ended by the clobbering entry 2, and the
1375 // second and third debug values are ended by the overlapping debug value entry
1380 // History map entries [type, end index, mi]
1382 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1383 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1384 // 2 | | [Clobber, $reg0 = [...], -, -]
1385 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1386 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1388 // Output [start, end) [Value...]:
1390 // [0-1) [(reg0, fragment 0, 32)]
1391 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1392 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1393 // [4-) [(@g, fragment 0, 96)]
1394 bool DwarfDebug::buildLocationList(SmallVectorImpl
<DebugLocEntry
> &DebugLoc
,
1395 const DbgValueHistoryMap::Entries
&Entries
) {
1397 std::pair
<DbgValueHistoryMap::EntryIndex
, DbgValueLoc
>;
1398 SmallVector
<OpenRange
, 4> OpenRanges
;
1399 bool isSafeForSingleLocation
= true;
1400 const MachineInstr
*StartDebugMI
= nullptr;
1401 const MachineInstr
*EndMI
= nullptr;
1403 for (auto EB
= Entries
.begin(), EI
= EB
, EE
= Entries
.end(); EI
!= EE
; ++EI
) {
1404 const MachineInstr
*Instr
= EI
->getInstr();
1406 // Remove all values that are no longer live.
1407 size_t Index
= std::distance(EB
, EI
);
1409 remove_if(OpenRanges
, [&](OpenRange
&R
) { return R
.first
<= Index
; });
1410 OpenRanges
.erase(Last
, OpenRanges
.end());
1412 // If we are dealing with a clobbering entry, this iteration will result in
1413 // a location list entry starting after the clobbering instruction.
1414 const MCSymbol
*StartLabel
=
1415 EI
->isClobber() ? getLabelAfterInsn(Instr
) : getLabelBeforeInsn(Instr
);
1416 assert(StartLabel
&&
1417 "Forgot label before/after instruction starting a range!");
1419 const MCSymbol
*EndLabel
;
1420 if (std::next(EI
) == Entries
.end()) {
1421 EndLabel
= Asm
->getFunctionEnd();
1422 if (EI
->isClobber())
1423 EndMI
= EI
->getInstr();
1425 else if (std::next(EI
)->isClobber())
1426 EndLabel
= getLabelAfterInsn(std::next(EI
)->getInstr());
1428 EndLabel
= getLabelBeforeInsn(std::next(EI
)->getInstr());
1429 assert(EndLabel
&& "Forgot label after instruction ending a range!");
1431 if (EI
->isDbgValue())
1432 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr
<< "\n");
1434 // If this history map entry has a debug value, add that to the list of
1435 // open ranges and check if its location is valid for a single value
1437 if (EI
->isDbgValue()) {
1438 // Do not add undef debug values, as they are redundant information in
1439 // the location list entries. An undef debug results in an empty location
1440 // description. If there are any non-undef fragments then padding pieces
1441 // with empty location descriptions will automatically be inserted, and if
1442 // all fragments are undef then the whole location list entry is
1444 if (!Instr
->isUndefDebugValue()) {
1445 auto Value
= getDebugLocValue(Instr
);
1446 OpenRanges
.emplace_back(EI
->getEndIndex(), Value
);
1448 // TODO: Add support for single value fragment locations.
1449 if (Instr
->getDebugExpression()->isFragment())
1450 isSafeForSingleLocation
= false;
1453 StartDebugMI
= Instr
;
1455 isSafeForSingleLocation
= false;
1459 // Location list entries with empty location descriptions are redundant
1460 // information in DWARF, so do not emit those.
1461 if (OpenRanges
.empty())
1464 // Omit entries with empty ranges as they do not have any effect in DWARF.
1465 if (StartLabel
== EndLabel
) {
1466 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1470 SmallVector
<DbgValueLoc
, 4> Values
;
1471 for (auto &R
: OpenRanges
)
1472 Values
.push_back(R
.second
);
1473 DebugLoc
.emplace_back(StartLabel
, EndLabel
, Values
);
1475 // Attempt to coalesce the ranges of two otherwise identical
1477 auto CurEntry
= DebugLoc
.rbegin();
1479 dbgs() << CurEntry
->getValues().size() << " Values:\n";
1480 for (auto &Value
: CurEntry
->getValues())
1482 dbgs() << "-----\n";
1485 auto PrevEntry
= std::next(CurEntry
);
1486 if (PrevEntry
!= DebugLoc
.rend() && PrevEntry
->MergeRanges(*CurEntry
))
1487 DebugLoc
.pop_back();
1490 return DebugLoc
.size() == 1 && isSafeForSingleLocation
&&
1491 validThroughout(LScopes
, StartDebugMI
, EndMI
);
1494 DbgEntity
*DwarfDebug::createConcreteEntity(DwarfCompileUnit
&TheCU
,
1495 LexicalScope
&Scope
,
1497 const DILocation
*Location
,
1498 const MCSymbol
*Sym
) {
1499 ensureAbstractEntityIsCreatedIfScoped(TheCU
, Node
, Scope
.getScopeNode());
1500 if (isa
<const DILocalVariable
>(Node
)) {
1501 ConcreteEntities
.push_back(
1502 std::make_unique
<DbgVariable
>(cast
<const DILocalVariable
>(Node
),
1504 InfoHolder
.addScopeVariable(&Scope
,
1505 cast
<DbgVariable
>(ConcreteEntities
.back().get()));
1506 } else if (isa
<const DILabel
>(Node
)) {
1507 ConcreteEntities
.push_back(
1508 std::make_unique
<DbgLabel
>(cast
<const DILabel
>(Node
),
1510 InfoHolder
.addScopeLabel(&Scope
,
1511 cast
<DbgLabel
>(ConcreteEntities
.back().get()));
1513 return ConcreteEntities
.back().get();
1516 // Find variables for each lexical scope.
1517 void DwarfDebug::collectEntityInfo(DwarfCompileUnit
&TheCU
,
1518 const DISubprogram
*SP
,
1519 DenseSet
<InlinedEntity
> &Processed
) {
1520 // Grab the variable info that was squirreled away in the MMI side-table.
1521 collectVariableInfoFromMFTable(TheCU
, Processed
);
1523 for (const auto &I
: DbgValues
) {
1524 InlinedEntity IV
= I
.first
;
1525 if (Processed
.count(IV
))
1528 // Instruction ranges, specifying where IV is accessible.
1529 const auto &HistoryMapEntries
= I
.second
;
1530 if (HistoryMapEntries
.empty())
1533 LexicalScope
*Scope
= nullptr;
1534 const DILocalVariable
*LocalVar
= cast
<DILocalVariable
>(IV
.first
);
1535 if (const DILocation
*IA
= IV
.second
)
1536 Scope
= LScopes
.findInlinedScope(LocalVar
->getScope(), IA
);
1538 Scope
= LScopes
.findLexicalScope(LocalVar
->getScope());
1539 // If variable scope is not found then skip this variable.
1543 Processed
.insert(IV
);
1544 DbgVariable
*RegVar
= cast
<DbgVariable
>(createConcreteEntity(TheCU
,
1545 *Scope
, LocalVar
, IV
.second
));
1547 const MachineInstr
*MInsn
= HistoryMapEntries
.front().getInstr();
1548 assert(MInsn
->isDebugValue() && "History must begin with debug value");
1550 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1551 // If the history map contains a single debug value, there may be an
1552 // additional entry which clobbers the debug value.
1553 size_t HistSize
= HistoryMapEntries
.size();
1554 bool SingleValueWithClobber
=
1555 HistSize
== 2 && HistoryMapEntries
[1].isClobber();
1556 if (HistSize
== 1 || SingleValueWithClobber
) {
1558 SingleValueWithClobber
? HistoryMapEntries
[1].getInstr() : nullptr;
1559 if (validThroughout(LScopes
, MInsn
, End
)) {
1560 RegVar
->initializeDbgValue(MInsn
);
1565 // Do not emit location lists if .debug_loc secton is disabled.
1566 if (!useLocSection())
1569 // Handle multiple DBG_VALUE instructions describing one variable.
1570 DebugLocStream::ListBuilder
List(DebugLocs
, TheCU
, *Asm
, *RegVar
, *MInsn
);
1572 // Build the location list for this variable.
1573 SmallVector
<DebugLocEntry
, 8> Entries
;
1574 bool isValidSingleLocation
= buildLocationList(Entries
, HistoryMapEntries
);
1576 // Check whether buildLocationList managed to merge all locations to one
1577 // that is valid throughout the variable's scope. If so, produce single
1579 if (isValidSingleLocation
) {
1580 RegVar
->initializeDbgValue(Entries
[0].getValues()[0]);
1584 // If the variable has a DIBasicType, extract it. Basic types cannot have
1585 // unique identifiers, so don't bother resolving the type with the
1587 const DIBasicType
*BT
= dyn_cast
<DIBasicType
>(
1588 static_cast<const Metadata
*>(LocalVar
->getType()));
1590 // Finalize the entry by lowering it into a DWARF bytestream.
1591 for (auto &Entry
: Entries
)
1592 Entry
.finalize(*Asm
, List
, BT
, TheCU
);
1595 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1596 // DWARF-related DbgLabel.
1597 for (const auto &I
: DbgLabels
) {
1598 InlinedEntity IL
= I
.first
;
1599 const MachineInstr
*MI
= I
.second
;
1603 LexicalScope
*Scope
= nullptr;
1604 const DILabel
*Label
= cast
<DILabel
>(IL
.first
);
1605 // The scope could have an extra lexical block file.
1606 const DILocalScope
*LocalScope
=
1607 Label
->getScope()->getNonLexicalBlockFileScope();
1608 // Get inlined DILocation if it is inlined label.
1609 if (const DILocation
*IA
= IL
.second
)
1610 Scope
= LScopes
.findInlinedScope(LocalScope
, IA
);
1612 Scope
= LScopes
.findLexicalScope(LocalScope
);
1613 // If label scope is not found then skip this label.
1617 Processed
.insert(IL
);
1618 /// At this point, the temporary label is created.
1619 /// Save the temporary label to DbgLabel entity to get the
1620 /// actually address when generating Dwarf DIE.
1621 MCSymbol
*Sym
= getLabelBeforeInsn(MI
);
1622 createConcreteEntity(TheCU
, *Scope
, Label
, IL
.second
, Sym
);
1625 // Collect info for variables/labels that were optimized out.
1626 for (const DINode
*DN
: SP
->getRetainedNodes()) {
1627 if (!Processed
.insert(InlinedEntity(DN
, nullptr)).second
)
1629 LexicalScope
*Scope
= nullptr;
1630 if (auto *DV
= dyn_cast
<DILocalVariable
>(DN
)) {
1631 Scope
= LScopes
.findLexicalScope(DV
->getScope());
1632 } else if (auto *DL
= dyn_cast
<DILabel
>(DN
)) {
1633 Scope
= LScopes
.findLexicalScope(DL
->getScope());
1637 createConcreteEntity(TheCU
, *Scope
, DN
, nullptr);
1641 // Process beginning of an instruction.
1642 void DwarfDebug::beginInstruction(const MachineInstr
*MI
) {
1643 DebugHandlerBase::beginInstruction(MI
);
1646 const auto *SP
= MI
->getMF()->getFunction().getSubprogram();
1647 if (!SP
|| SP
->getUnit()->getEmissionKind() == DICompileUnit::NoDebug
)
1650 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1651 // If the instruction is part of the function frame setup code, do not emit
1652 // any line record, as there is no correspondence with any user code.
1653 if (MI
->isMetaInstruction() || MI
->getFlag(MachineInstr::FrameSetup
))
1655 const DebugLoc
&DL
= MI
->getDebugLoc();
1656 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1657 // the last line number actually emitted, to see if it was line 0.
1658 unsigned LastAsmLine
=
1659 Asm
->OutStreamer
->getContext().getCurrentDwarfLoc().getLine();
1661 // Request a label after the call in order to emit AT_return_pc information
1662 // in call site entries. TODO: Add support for targets with delay slots.
1663 if (SP
->areAllCallsDescribed() && MI
->isCall() && !MI
->hasDelaySlot())
1664 requestLabelAfterInsn(MI
);
1666 if (DL
== PrevInstLoc
) {
1667 // If we have an ongoing unspecified location, nothing to do here.
1670 // We have an explicit location, same as the previous location.
1671 // But we might be coming back to it after a line 0 record.
1672 if (LastAsmLine
== 0 && DL
.getLine() != 0) {
1673 // Reinstate the source location but not marked as a statement.
1674 const MDNode
*Scope
= DL
.getScope();
1675 recordSourceLine(DL
.getLine(), DL
.getCol(), Scope
, /*Flags=*/0);
1681 // We have an unspecified location, which might want to be line 0.
1682 // If we have already emitted a line-0 record, don't repeat it.
1683 if (LastAsmLine
== 0)
1685 // If user said Don't Do That, don't do that.
1686 if (UnknownLocations
== Disable
)
1688 // See if we have a reason to emit a line-0 record now.
1689 // Reasons to emit a line-0 record include:
1690 // - User asked for it (UnknownLocations).
1691 // - Instruction has a label, so it's referenced from somewhere else,
1692 // possibly debug information; we want it to have a source location.
1693 // - Instruction is at the top of a block; we don't want to inherit the
1694 // location from the physically previous (maybe unrelated) block.
1695 if (UnknownLocations
== Enable
|| PrevLabel
||
1696 (PrevInstBB
&& PrevInstBB
!= MI
->getParent())) {
1697 // Preserve the file and column numbers, if we can, to save space in
1698 // the encoded line table.
1699 // Do not update PrevInstLoc, it remembers the last non-0 line.
1700 const MDNode
*Scope
= nullptr;
1701 unsigned Column
= 0;
1703 Scope
= PrevInstLoc
.getScope();
1704 Column
= PrevInstLoc
.getCol();
1706 recordSourceLine(/*Line=*/0, Column
, Scope
, /*Flags=*/0);
1711 // We have an explicit location, different from the previous location.
1712 // Don't repeat a line-0 record, but otherwise emit the new location.
1713 // (The new location might be an explicit line 0, which we do emit.)
1714 if (DL
.getLine() == 0 && LastAsmLine
== 0)
1717 if (DL
== PrologEndLoc
) {
1718 Flags
|= DWARF2_FLAG_PROLOGUE_END
| DWARF2_FLAG_IS_STMT
;
1719 PrologEndLoc
= DebugLoc();
1721 // If the line changed, we call that a new statement; unless we went to
1722 // line 0 and came back, in which case it is not a new statement.
1723 unsigned OldLine
= PrevInstLoc
? PrevInstLoc
.getLine() : LastAsmLine
;
1724 if (DL
.getLine() && DL
.getLine() != OldLine
)
1725 Flags
|= DWARF2_FLAG_IS_STMT
;
1727 const MDNode
*Scope
= DL
.getScope();
1728 recordSourceLine(DL
.getLine(), DL
.getCol(), Scope
, Flags
);
1730 // If we're not at line 0, remember this location.
1735 static DebugLoc
findPrologueEndLoc(const MachineFunction
*MF
) {
1736 // First known non-DBG_VALUE and non-frame setup location marks
1737 // the beginning of the function body.
1738 for (const auto &MBB
: *MF
)
1739 for (const auto &MI
: MBB
)
1740 if (!MI
.isMetaInstruction() && !MI
.getFlag(MachineInstr::FrameSetup
) &&
1742 return MI
.getDebugLoc();
1746 /// Register a source line with debug info. Returns the unique label that was
1747 /// emitted and which provides correspondence to the source line list.
1748 static void recordSourceLine(AsmPrinter
&Asm
, unsigned Line
, unsigned Col
,
1749 const MDNode
*S
, unsigned Flags
, unsigned CUID
,
1750 uint16_t DwarfVersion
,
1751 ArrayRef
<std::unique_ptr
<DwarfCompileUnit
>> DCUs
) {
1753 unsigned FileNo
= 1;
1754 unsigned Discriminator
= 0;
1755 if (auto *Scope
= cast_or_null
<DIScope
>(S
)) {
1756 Fn
= Scope
->getFilename();
1757 if (Line
!= 0 && DwarfVersion
>= 4)
1758 if (auto *LBF
= dyn_cast
<DILexicalBlockFile
>(Scope
))
1759 Discriminator
= LBF
->getDiscriminator();
1761 FileNo
= static_cast<DwarfCompileUnit
&>(*DCUs
[CUID
])
1762 .getOrCreateSourceID(Scope
->getFile());
1764 Asm
.OutStreamer
->EmitDwarfLocDirective(FileNo
, Line
, Col
, Flags
, 0,
1768 DebugLoc
DwarfDebug::emitInitialLocDirective(const MachineFunction
&MF
,
1770 // Get beginning of function.
1771 if (DebugLoc PrologEndLoc
= findPrologueEndLoc(&MF
)) {
1772 // Ensure the compile unit is created if the function is called before
1774 (void)getOrCreateDwarfCompileUnit(
1775 MF
.getFunction().getSubprogram()->getUnit());
1776 // We'd like to list the prologue as "not statements" but GDB behaves
1777 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1778 const DISubprogram
*SP
= PrologEndLoc
->getInlinedAtScope()->getSubprogram();
1779 ::recordSourceLine(*Asm
, SP
->getScopeLine(), 0, SP
, DWARF2_FLAG_IS_STMT
,
1780 CUID
, getDwarfVersion(), getUnits());
1781 return PrologEndLoc
;
1786 // Gather pre-function debug information. Assumes being called immediately
1787 // after the function entry point has been emitted.
1788 void DwarfDebug::beginFunctionImpl(const MachineFunction
*MF
) {
1791 auto *SP
= MF
->getFunction().getSubprogram();
1792 assert(LScopes
.empty() || SP
== LScopes
.getCurrentFunctionScope()->getScopeNode());
1793 if (SP
->getUnit()->getEmissionKind() == DICompileUnit::NoDebug
)
1796 DwarfCompileUnit
&CU
= getOrCreateDwarfCompileUnit(SP
->getUnit());
1798 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1799 // belongs to so that we add to the correct per-cu line table in the
1801 if (Asm
->OutStreamer
->hasRawTextSupport())
1802 // Use a single line table if we are generating assembly.
1803 Asm
->OutStreamer
->getContext().setDwarfCompileUnitID(0);
1805 Asm
->OutStreamer
->getContext().setDwarfCompileUnitID(CU
.getUniqueID());
1807 // Record beginning of function.
1808 PrologEndLoc
= emitInitialLocDirective(
1809 *MF
, Asm
->OutStreamer
->getContext().getDwarfCompileUnitID());
1812 void DwarfDebug::skippedNonDebugFunction() {
1813 // If we don't have a subprogram for this function then there will be a hole
1814 // in the range information. Keep note of this by setting the previously used
1815 // section to nullptr.
1820 // Gather and emit post-function debug information.
1821 void DwarfDebug::endFunctionImpl(const MachineFunction
*MF
) {
1822 const DISubprogram
*SP
= MF
->getFunction().getSubprogram();
1824 assert(CurFn
== MF
&&
1825 "endFunction should be called with the same function as beginFunction");
1827 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1828 Asm
->OutStreamer
->getContext().setDwarfCompileUnitID(0);
1830 LexicalScope
*FnScope
= LScopes
.getCurrentFunctionScope();
1831 assert(!FnScope
|| SP
== FnScope
->getScopeNode());
1832 DwarfCompileUnit
&TheCU
= *CUMap
.lookup(SP
->getUnit());
1833 if (TheCU
.getCUNode()->isDebugDirectivesOnly()) {
1834 PrevLabel
= nullptr;
1839 DenseSet
<InlinedEntity
> Processed
;
1840 collectEntityInfo(TheCU
, SP
, Processed
);
1842 // Add the range of this function to the list of ranges for the CU.
1843 TheCU
.addRange(RangeSpan(Asm
->getFunctionBegin(), Asm
->getFunctionEnd()));
1845 // Under -gmlt, skip building the subprogram if there are no inlined
1846 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1847 // is still needed as we need its source location.
1848 if (!TheCU
.getCUNode()->getDebugInfoForProfiling() &&
1849 TheCU
.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly
&&
1850 LScopes
.getAbstractScopesList().empty() && !IsDarwin
) {
1851 assert(InfoHolder
.getScopeVariables().empty());
1852 PrevLabel
= nullptr;
1858 size_t NumAbstractScopes
= LScopes
.getAbstractScopesList().size();
1860 // Construct abstract scopes.
1861 for (LexicalScope
*AScope
: LScopes
.getAbstractScopesList()) {
1862 auto *SP
= cast
<DISubprogram
>(AScope
->getScopeNode());
1863 for (const DINode
*DN
: SP
->getRetainedNodes()) {
1864 if (!Processed
.insert(InlinedEntity(DN
, nullptr)).second
)
1867 const MDNode
*Scope
= nullptr;
1868 if (auto *DV
= dyn_cast
<DILocalVariable
>(DN
))
1869 Scope
= DV
->getScope();
1870 else if (auto *DL
= dyn_cast
<DILabel
>(DN
))
1871 Scope
= DL
->getScope();
1873 llvm_unreachable("Unexpected DI type!");
1875 // Collect info for variables/labels that were optimized out.
1876 ensureAbstractEntityIsCreated(TheCU
, DN
, Scope
);
1877 assert(LScopes
.getAbstractScopesList().size() == NumAbstractScopes
1878 && "ensureAbstractEntityIsCreated inserted abstract scopes");
1880 constructAbstractSubprogramScopeDIE(TheCU
, AScope
);
1883 ProcessedSPNodes
.insert(SP
);
1884 DIE
&ScopeDIE
= TheCU
.constructSubprogramScopeDIE(SP
, FnScope
);
1885 if (auto *SkelCU
= TheCU
.getSkeleton())
1886 if (!LScopes
.getAbstractScopesList().empty() &&
1887 TheCU
.getCUNode()->getSplitDebugInlining())
1888 SkelCU
->constructSubprogramScopeDIE(SP
, FnScope
);
1890 // Construct call site entries.
1891 constructCallSiteEntryDIEs(*SP
, TheCU
, ScopeDIE
, *MF
);
1894 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1895 // DbgVariables except those that are also in AbstractVariables (since they
1896 // can be used cross-function)
1897 InfoHolder
.getScopeVariables().clear();
1898 InfoHolder
.getScopeLabels().clear();
1899 PrevLabel
= nullptr;
1903 // Register a source line with debug info. Returns the unique label that was
1904 // emitted and which provides correspondence to the source line list.
1905 void DwarfDebug::recordSourceLine(unsigned Line
, unsigned Col
, const MDNode
*S
,
1907 ::recordSourceLine(*Asm
, Line
, Col
, S
, Flags
,
1908 Asm
->OutStreamer
->getContext().getDwarfCompileUnitID(),
1909 getDwarfVersion(), getUnits());
1912 //===----------------------------------------------------------------------===//
1914 //===----------------------------------------------------------------------===//
1916 // Emit the debug info section.
1917 void DwarfDebug::emitDebugInfo() {
1918 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
1919 Holder
.emitUnits(/* UseOffsets */ false);
1922 // Emit the abbreviation section.
1923 void DwarfDebug::emitAbbreviations() {
1924 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
1926 Holder
.emitAbbrevs(Asm
->getObjFileLowering().getDwarfAbbrevSection());
1929 void DwarfDebug::emitStringOffsetsTableHeader() {
1930 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
1931 Holder
.getStringPool().emitStringOffsetsTableHeader(
1932 *Asm
, Asm
->getObjFileLowering().getDwarfStrOffSection(),
1933 Holder
.getStringOffsetsStartSym());
1936 template <typename AccelTableT
>
1937 void DwarfDebug::emitAccel(AccelTableT
&Accel
, MCSection
*Section
,
1938 StringRef TableName
) {
1939 Asm
->OutStreamer
->SwitchSection(Section
);
1941 // Emit the full data.
1942 emitAppleAccelTable(Asm
, Accel
, TableName
, Section
->getBeginSymbol());
1945 void DwarfDebug::emitAccelDebugNames() {
1946 // Don't emit anything if we have no compilation units to index.
1947 if (getUnits().empty())
1950 emitDWARF5AccelTable(Asm
, AccelDebugNames
, *this, getUnits());
1953 // Emit visible names into a hashed accelerator table section.
1954 void DwarfDebug::emitAccelNames() {
1955 emitAccel(AccelNames
, Asm
->getObjFileLowering().getDwarfAccelNamesSection(),
1959 // Emit objective C classes and categories into a hashed accelerator table
1961 void DwarfDebug::emitAccelObjC() {
1962 emitAccel(AccelObjC
, Asm
->getObjFileLowering().getDwarfAccelObjCSection(),
1966 // Emit namespace dies into a hashed accelerator table.
1967 void DwarfDebug::emitAccelNamespaces() {
1968 emitAccel(AccelNamespace
,
1969 Asm
->getObjFileLowering().getDwarfAccelNamespaceSection(),
1973 // Emit type dies into a hashed accelerator table.
1974 void DwarfDebug::emitAccelTypes() {
1975 emitAccel(AccelTypes
, Asm
->getObjFileLowering().getDwarfAccelTypesSection(),
1979 // Public name handling.
1980 // The format for the various pubnames:
1982 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1983 // for the DIE that is named.
1985 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1986 // into the CU and the index value is computed according to the type of value
1987 // for the DIE that is named.
1989 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1990 // it's the offset within the debug_info/debug_types dwo section, however, the
1991 // reference in the pubname header doesn't change.
1993 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1994 static dwarf::PubIndexEntryDescriptor
computeIndexValue(DwarfUnit
*CU
,
1996 // Entities that ended up only in a Type Unit reference the CU instead (since
1997 // the pub entry has offsets within the CU there's no real offset that can be
1998 // provided anyway). As it happens all such entities (namespaces and types,
1999 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2000 // not to be true it would be necessary to persist this information from the
2001 // point at which the entry is added to the index data structure - since by
2002 // the time the index is built from that, the original type/namespace DIE in a
2003 // type unit has already been destroyed so it can't be queried for properties
2005 if (Die
->getTag() == dwarf::DW_TAG_compile_unit
)
2006 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE
,
2007 dwarf::GIEL_EXTERNAL
);
2008 dwarf::GDBIndexEntryLinkage Linkage
= dwarf::GIEL_STATIC
;
2010 // We could have a specification DIE that has our most of our knowledge,
2011 // look for that now.
2012 if (DIEValue SpecVal
= Die
->findAttribute(dwarf::DW_AT_specification
)) {
2013 DIE
&SpecDIE
= SpecVal
.getDIEEntry().getEntry();
2014 if (SpecDIE
.findAttribute(dwarf::DW_AT_external
))
2015 Linkage
= dwarf::GIEL_EXTERNAL
;
2016 } else if (Die
->findAttribute(dwarf::DW_AT_external
))
2017 Linkage
= dwarf::GIEL_EXTERNAL
;
2019 switch (Die
->getTag()) {
2020 case dwarf::DW_TAG_class_type
:
2021 case dwarf::DW_TAG_structure_type
:
2022 case dwarf::DW_TAG_union_type
:
2023 case dwarf::DW_TAG_enumeration_type
:
2024 return dwarf::PubIndexEntryDescriptor(
2025 dwarf::GIEK_TYPE
, CU
->getLanguage() != dwarf::DW_LANG_C_plus_plus
2026 ? dwarf::GIEL_STATIC
2027 : dwarf::GIEL_EXTERNAL
);
2028 case dwarf::DW_TAG_typedef
:
2029 case dwarf::DW_TAG_base_type
:
2030 case dwarf::DW_TAG_subrange_type
:
2031 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE
, dwarf::GIEL_STATIC
);
2032 case dwarf::DW_TAG_namespace
:
2033 return dwarf::GIEK_TYPE
;
2034 case dwarf::DW_TAG_subprogram
:
2035 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION
, Linkage
);
2036 case dwarf::DW_TAG_variable
:
2037 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE
, Linkage
);
2038 case dwarf::DW_TAG_enumerator
:
2039 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE
,
2040 dwarf::GIEL_STATIC
);
2042 return dwarf::GIEK_NONE
;
2046 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2047 /// pubtypes sections.
2048 void DwarfDebug::emitDebugPubSections() {
2049 for (const auto &NU
: CUMap
) {
2050 DwarfCompileUnit
*TheU
= NU
.second
;
2051 if (!TheU
->hasDwarfPubSections())
2054 bool GnuStyle
= TheU
->getCUNode()->getNameTableKind() ==
2055 DICompileUnit::DebugNameTableKind::GNU
;
2057 Asm
->OutStreamer
->SwitchSection(
2058 GnuStyle
? Asm
->getObjFileLowering().getDwarfGnuPubNamesSection()
2059 : Asm
->getObjFileLowering().getDwarfPubNamesSection());
2060 emitDebugPubSection(GnuStyle
, "Names", TheU
, TheU
->getGlobalNames());
2062 Asm
->OutStreamer
->SwitchSection(
2063 GnuStyle
? Asm
->getObjFileLowering().getDwarfGnuPubTypesSection()
2064 : Asm
->getObjFileLowering().getDwarfPubTypesSection());
2065 emitDebugPubSection(GnuStyle
, "Types", TheU
, TheU
->getGlobalTypes());
2069 void DwarfDebug::emitSectionReference(const DwarfCompileUnit
&CU
) {
2070 if (useSectionsAsReferences())
2071 Asm
->EmitDwarfOffset(CU
.getSection()->getBeginSymbol(),
2072 CU
.getDebugSectionOffset());
2074 Asm
->emitDwarfSymbolReference(CU
.getLabelBegin());
2077 void DwarfDebug::emitDebugPubSection(bool GnuStyle
, StringRef Name
,
2078 DwarfCompileUnit
*TheU
,
2079 const StringMap
<const DIE
*> &Globals
) {
2080 if (auto *Skeleton
= TheU
->getSkeleton())
2084 Asm
->OutStreamer
->AddComment("Length of Public " + Name
+ " Info");
2085 MCSymbol
*BeginLabel
= Asm
->createTempSymbol("pub" + Name
+ "_begin");
2086 MCSymbol
*EndLabel
= Asm
->createTempSymbol("pub" + Name
+ "_end");
2087 Asm
->EmitLabelDifference(EndLabel
, BeginLabel
, 4);
2089 Asm
->OutStreamer
->EmitLabel(BeginLabel
);
2091 Asm
->OutStreamer
->AddComment("DWARF Version");
2092 Asm
->emitInt16(dwarf::DW_PUBNAMES_VERSION
);
2094 Asm
->OutStreamer
->AddComment("Offset of Compilation Unit Info");
2095 emitSectionReference(*TheU
);
2097 Asm
->OutStreamer
->AddComment("Compilation Unit Length");
2098 Asm
->emitInt32(TheU
->getLength());
2100 // Emit the pubnames for this compilation unit.
2101 for (const auto &GI
: Globals
) {
2102 const char *Name
= GI
.getKeyData();
2103 const DIE
*Entity
= GI
.second
;
2105 Asm
->OutStreamer
->AddComment("DIE offset");
2106 Asm
->emitInt32(Entity
->getOffset());
2109 dwarf::PubIndexEntryDescriptor Desc
= computeIndexValue(TheU
, Entity
);
2110 Asm
->OutStreamer
->AddComment(
2111 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc
.Kind
) +
2112 ", " + dwarf::GDBIndexEntryLinkageString(Desc
.Linkage
));
2113 Asm
->emitInt8(Desc
.toBits());
2116 Asm
->OutStreamer
->AddComment("External Name");
2117 Asm
->OutStreamer
->EmitBytes(StringRef(Name
, GI
.getKeyLength() + 1));
2120 Asm
->OutStreamer
->AddComment("End Mark");
2122 Asm
->OutStreamer
->EmitLabel(EndLabel
);
2125 /// Emit null-terminated strings into a debug str section.
2126 void DwarfDebug::emitDebugStr() {
2127 MCSection
*StringOffsetsSection
= nullptr;
2128 if (useSegmentedStringOffsetsTable()) {
2129 emitStringOffsetsTableHeader();
2130 StringOffsetsSection
= Asm
->getObjFileLowering().getDwarfStrOffSection();
2132 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
2133 Holder
.emitStrings(Asm
->getObjFileLowering().getDwarfStrSection(),
2134 StringOffsetsSection
, /* UseRelativeOffsets = */ true);
2137 void DwarfDebug::emitDebugLocEntry(ByteStreamer
&Streamer
,
2138 const DebugLocStream::Entry
&Entry
,
2139 const DwarfCompileUnit
*CU
) {
2140 auto &&Comments
= DebugLocs
.getComments(Entry
);
2141 auto Comment
= Comments
.begin();
2142 auto End
= Comments
.end();
2144 // The expressions are inserted into a byte stream rather early (see
2145 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2146 // need to reference a base_type DIE the offset of that DIE is not yet known.
2147 // To deal with this we instead insert a placeholder early and then extract
2148 // it here and replace it with the real reference.
2149 unsigned PtrSize
= Asm
->MAI
->getCodePointerSize();
2150 DWARFDataExtractor
Data(StringRef(DebugLocs
.getBytes(Entry
).data(),
2151 DebugLocs
.getBytes(Entry
).size()),
2152 Asm
->getDataLayout().isLittleEndian(), PtrSize
);
2153 DWARFExpression
Expr(Data
, getDwarfVersion(), PtrSize
);
2155 using Encoding
= DWARFExpression::Operation::Encoding
;
2156 uint64_t Offset
= 0;
2157 for (auto &Op
: Expr
) {
2158 assert(Op
.getCode() != dwarf::DW_OP_const_type
&&
2159 "3 operand ops not yet supported");
2160 Streamer
.EmitInt8(Op
.getCode(), Comment
!= End
? *(Comment
++) : "");
2162 for (unsigned I
= 0; I
< 2; ++I
) {
2163 if (Op
.getDescription().Op
[I
] == Encoding::SizeNA
)
2165 if (Op
.getDescription().Op
[I
] == Encoding::BaseTypeRef
) {
2167 uint64_t Offset
= CU
->ExprRefedBaseTypes
[Op
.getRawOperand(I
)].Die
->getOffset();
2168 assert(Offset
< (1ULL << (ULEB128PadSize
* 7)) && "Offset wont fit");
2169 Asm
->EmitULEB128(Offset
, nullptr, ULEB128PadSize
);
2171 // Emit a reference to the 'generic type'.
2172 Asm
->EmitULEB128(0, nullptr, ULEB128PadSize
);
2174 // Make sure comments stay aligned.
2175 for (unsigned J
= 0; J
< ULEB128PadSize
; ++J
)
2179 for (uint64_t J
= Offset
; J
< Op
.getOperandEndOffset(I
); ++J
)
2180 Streamer
.EmitInt8(Data
.getData()[J
], Comment
!= End
? *(Comment
++) : "");
2182 Offset
= Op
.getOperandEndOffset(I
);
2184 assert(Offset
== Op
.getEndOffset());
2188 void DwarfDebug::emitDebugLocValue(const AsmPrinter
&AP
, const DIBasicType
*BT
,
2189 const DbgValueLoc
&Value
,
2190 DwarfExpression
&DwarfExpr
) {
2191 auto *DIExpr
= Value
.getExpression();
2192 DIExpressionCursor
ExprCursor(DIExpr
);
2193 DwarfExpr
.addFragmentOffset(DIExpr
);
2195 if (Value
.isInt()) {
2196 if (BT
&& (BT
->getEncoding() == dwarf::DW_ATE_signed
||
2197 BT
->getEncoding() == dwarf::DW_ATE_signed_char
))
2198 DwarfExpr
.addSignedConstant(Value
.getInt());
2200 DwarfExpr
.addUnsignedConstant(Value
.getInt());
2201 } else if (Value
.isLocation()) {
2202 MachineLocation Location
= Value
.getLoc();
2203 if (Location
.isIndirect())
2204 DwarfExpr
.setMemoryLocationKind();
2205 DIExpressionCursor
Cursor(DIExpr
);
2207 if (DIExpr
->isEntryValue()) {
2208 DwarfExpr
.setEntryValueFlag();
2209 DwarfExpr
.addEntryValueExpression(Cursor
);
2212 const TargetRegisterInfo
&TRI
= *AP
.MF
->getSubtarget().getRegisterInfo();
2213 if (!DwarfExpr
.addMachineRegExpression(TRI
, Cursor
, Location
.getReg()))
2215 return DwarfExpr
.addExpression(std::move(Cursor
));
2216 } else if (Value
.isConstantFP()) {
2217 APInt RawBytes
= Value
.getConstantFP()->getValueAPF().bitcastToAPInt();
2218 DwarfExpr
.addUnsignedConstant(RawBytes
);
2220 DwarfExpr
.addExpression(std::move(ExprCursor
));
2223 void DebugLocEntry::finalize(const AsmPrinter
&AP
,
2224 DebugLocStream::ListBuilder
&List
,
2225 const DIBasicType
*BT
,
2226 DwarfCompileUnit
&TheCU
) {
2227 assert(!Values
.empty() &&
2228 "location list entries without values are redundant");
2229 assert(Begin
!= End
&& "unexpected location list entry with empty range");
2230 DebugLocStream::EntryBuilder
Entry(List
, Begin
, End
);
2231 BufferByteStreamer Streamer
= Entry
.getStreamer();
2232 DebugLocDwarfExpression
DwarfExpr(AP
.getDwarfVersion(), Streamer
, TheCU
);
2233 const DbgValueLoc
&Value
= Values
[0];
2234 if (Value
.isFragment()) {
2235 // Emit all fragments that belong to the same variable and range.
2236 assert(llvm::all_of(Values
, [](DbgValueLoc P
) {
2237 return P
.isFragment();
2238 }) && "all values are expected to be fragments");
2239 assert(std::is_sorted(Values
.begin(), Values
.end()) &&
2240 "fragments are expected to be sorted");
2242 for (auto Fragment
: Values
)
2243 DwarfDebug::emitDebugLocValue(AP
, BT
, Fragment
, DwarfExpr
);
2246 assert(Values
.size() == 1 && "only fragments may have >1 value");
2247 DwarfDebug::emitDebugLocValue(AP
, BT
, Value
, DwarfExpr
);
2249 DwarfExpr
.finalize();
2252 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry
&Entry
,
2253 const DwarfCompileUnit
*CU
) {
2255 Asm
->OutStreamer
->AddComment("Loc expr size");
2256 if (getDwarfVersion() >= 5)
2257 Asm
->EmitULEB128(DebugLocs
.getBytes(Entry
).size());
2258 else if (DebugLocs
.getBytes(Entry
).size() <= std::numeric_limits
<uint16_t>::max())
2259 Asm
->emitInt16(DebugLocs
.getBytes(Entry
).size());
2261 // The entry is too big to fit into 16 bit, drop it as there is nothing we
2267 APByteStreamer
Streamer(*Asm
);
2268 emitDebugLocEntry(Streamer
, Entry
, CU
);
2271 // Emit the common part of the DWARF 5 range/locations list tables header.
2272 static void emitListsTableHeaderStart(AsmPrinter
*Asm
, const DwarfFile
&Holder
,
2273 MCSymbol
*TableStart
,
2274 MCSymbol
*TableEnd
) {
2275 // Build the table header, which starts with the length field.
2276 Asm
->OutStreamer
->AddComment("Length");
2277 Asm
->EmitLabelDifference(TableEnd
, TableStart
, 4);
2278 Asm
->OutStreamer
->EmitLabel(TableStart
);
2279 // Version number (DWARF v5 and later).
2280 Asm
->OutStreamer
->AddComment("Version");
2281 Asm
->emitInt16(Asm
->OutStreamer
->getContext().getDwarfVersion());
2283 Asm
->OutStreamer
->AddComment("Address size");
2284 Asm
->emitInt8(Asm
->MAI
->getCodePointerSize());
2285 // Segment selector size.
2286 Asm
->OutStreamer
->AddComment("Segment selector size");
2290 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2291 // that designates the end of the table for the caller to emit when the table is
2293 static MCSymbol
*emitRnglistsTableHeader(AsmPrinter
*Asm
,
2294 const DwarfFile
&Holder
) {
2295 MCSymbol
*TableStart
= Asm
->createTempSymbol("debug_rnglist_table_start");
2296 MCSymbol
*TableEnd
= Asm
->createTempSymbol("debug_rnglist_table_end");
2297 emitListsTableHeaderStart(Asm
, Holder
, TableStart
, TableEnd
);
2299 Asm
->OutStreamer
->AddComment("Offset entry count");
2300 Asm
->emitInt32(Holder
.getRangeLists().size());
2301 Asm
->OutStreamer
->EmitLabel(Holder
.getRnglistsTableBaseSym());
2303 for (const RangeSpanList
&List
: Holder
.getRangeLists())
2304 Asm
->EmitLabelDifference(List
.getSym(), Holder
.getRnglistsTableBaseSym(),
2310 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2311 // designates the end of the table for the caller to emit when the table is
2313 static MCSymbol
*emitLoclistsTableHeader(AsmPrinter
*Asm
,
2314 const DwarfFile
&Holder
) {
2315 MCSymbol
*TableStart
= Asm
->createTempSymbol("debug_loclist_table_start");
2316 MCSymbol
*TableEnd
= Asm
->createTempSymbol("debug_loclist_table_end");
2317 emitListsTableHeaderStart(Asm
, Holder
, TableStart
, TableEnd
);
2319 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the
2320 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0.
2321 Asm
->OutStreamer
->AddComment("Offset entry count");
2323 Asm
->OutStreamer
->EmitLabel(Holder
.getLoclistsTableBaseSym());
2328 // Emit locations into the .debug_loc/.debug_rnglists section.
2329 void DwarfDebug::emitDebugLoc() {
2330 if (DebugLocs
.getLists().empty())
2333 bool IsLocLists
= getDwarfVersion() >= 5;
2334 MCSymbol
*TableEnd
= nullptr;
2336 Asm
->OutStreamer
->SwitchSection(
2337 Asm
->getObjFileLowering().getDwarfLoclistsSection());
2338 TableEnd
= emitLoclistsTableHeader(Asm
, useSplitDwarf() ? SkeletonHolder
2341 Asm
->OutStreamer
->SwitchSection(
2342 Asm
->getObjFileLowering().getDwarfLocSection());
2345 unsigned char Size
= Asm
->MAI
->getCodePointerSize();
2346 for (const auto &List
: DebugLocs
.getLists()) {
2347 Asm
->OutStreamer
->EmitLabel(List
.Label
);
2349 const DwarfCompileUnit
*CU
= List
.CU
;
2350 const MCSymbol
*Base
= CU
->getBaseAddress();
2351 for (const auto &Entry
: DebugLocs
.getEntries(List
)) {
2353 // Set up the range. This range is relative to the entry point of the
2354 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2355 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2357 Asm
->OutStreamer
->AddComment("DW_LLE_offset_pair");
2358 Asm
->OutStreamer
->EmitIntValue(dwarf::DW_LLE_offset_pair
, 1);
2359 Asm
->OutStreamer
->AddComment(" starting offset");
2360 Asm
->EmitLabelDifferenceAsULEB128(Entry
.BeginSym
, Base
);
2361 Asm
->OutStreamer
->AddComment(" ending offset");
2362 Asm
->EmitLabelDifferenceAsULEB128(Entry
.EndSym
, Base
);
2364 Asm
->EmitLabelDifference(Entry
.BeginSym
, Base
, Size
);
2365 Asm
->EmitLabelDifference(Entry
.EndSym
, Base
, Size
);
2368 emitDebugLocEntryLocation(Entry
, CU
);
2372 // We have no base address.
2374 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or
2375 // DW_LLE_startx_length in case if there is only a single range.
2376 // That should reduce the size of the debug data emited.
2377 // For now just use the DW_LLE_startx_length for all cases.
2378 Asm
->OutStreamer
->AddComment("DW_LLE_startx_length");
2379 Asm
->emitInt8(dwarf::DW_LLE_startx_length
);
2380 Asm
->OutStreamer
->AddComment(" start idx");
2381 Asm
->EmitULEB128(AddrPool
.getIndex(Entry
.BeginSym
));
2382 Asm
->OutStreamer
->AddComment(" length");
2383 Asm
->EmitLabelDifferenceAsULEB128(Entry
.EndSym
, Entry
.BeginSym
);
2385 Asm
->OutStreamer
->EmitSymbolValue(Entry
.BeginSym
, Size
);
2386 Asm
->OutStreamer
->EmitSymbolValue(Entry
.EndSym
, Size
);
2389 emitDebugLocEntryLocation(Entry
, CU
);
2393 // .debug_loclists section ends with DW_LLE_end_of_list.
2394 Asm
->OutStreamer
->AddComment("DW_LLE_end_of_list");
2395 Asm
->OutStreamer
->EmitIntValue(dwarf::DW_LLE_end_of_list
, 1);
2397 // Terminate the .debug_loc list with two 0 values.
2398 Asm
->OutStreamer
->EmitIntValue(0, Size
);
2399 Asm
->OutStreamer
->EmitIntValue(0, Size
);
2404 Asm
->OutStreamer
->EmitLabel(TableEnd
);
2407 void DwarfDebug::emitDebugLocDWO() {
2408 for (const auto &List
: DebugLocs
.getLists()) {
2409 Asm
->OutStreamer
->SwitchSection(
2410 Asm
->getObjFileLowering().getDwarfLocDWOSection());
2411 Asm
->OutStreamer
->EmitLabel(List
.Label
);
2412 for (const auto &Entry
: DebugLocs
.getEntries(List
)) {
2413 // GDB only supports startx_length in pre-standard split-DWARF.
2414 // (in v5 standard loclists, it currently* /only/ supports base_address +
2415 // offset_pair, so the implementations can't really share much since they
2416 // need to use different representations)
2417 // * as of October 2018, at least
2418 // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2419 // in the address pool to minimize object size/relocations.
2420 Asm
->emitInt8(dwarf::DW_LLE_startx_length
);
2421 unsigned idx
= AddrPool
.getIndex(Entry
.BeginSym
);
2422 Asm
->EmitULEB128(idx
);
2423 Asm
->EmitLabelDifference(Entry
.EndSym
, Entry
.BeginSym
, 4);
2425 emitDebugLocEntryLocation(Entry
, List
.CU
);
2427 Asm
->emitInt8(dwarf::DW_LLE_end_of_list
);
2432 const MCSymbol
*Start
, *End
;
2435 // Emit a debug aranges section, containing a CU lookup for any
2436 // address we can tie back to a CU.
2437 void DwarfDebug::emitDebugARanges() {
2438 // Provides a unique id per text section.
2439 MapVector
<MCSection
*, SmallVector
<SymbolCU
, 8>> SectionMap
;
2441 // Filter labels by section.
2442 for (const SymbolCU
&SCU
: ArangeLabels
) {
2443 if (SCU
.Sym
->isInSection()) {
2444 // Make a note of this symbol and it's section.
2445 MCSection
*Section
= &SCU
.Sym
->getSection();
2446 if (!Section
->getKind().isMetadata())
2447 SectionMap
[Section
].push_back(SCU
);
2449 // Some symbols (e.g. common/bss on mach-o) can have no section but still
2450 // appear in the output. This sucks as we rely on sections to build
2451 // arange spans. We can do it without, but it's icky.
2452 SectionMap
[nullptr].push_back(SCU
);
2456 DenseMap
<DwarfCompileUnit
*, std::vector
<ArangeSpan
>> Spans
;
2458 for (auto &I
: SectionMap
) {
2459 MCSection
*Section
= I
.first
;
2460 SmallVector
<SymbolCU
, 8> &List
= I
.second
;
2461 if (List
.size() < 1)
2464 // If we have no section (e.g. common), just write out
2465 // individual spans for each symbol.
2467 for (const SymbolCU
&Cur
: List
) {
2469 Span
.Start
= Cur
.Sym
;
2472 Spans
[Cur
.CU
].push_back(Span
);
2477 // Sort the symbols by offset within the section.
2478 llvm::stable_sort(List
, [&](const SymbolCU
&A
, const SymbolCU
&B
) {
2479 unsigned IA
= A
.Sym
? Asm
->OutStreamer
->GetSymbolOrder(A
.Sym
) : 0;
2480 unsigned IB
= B
.Sym
? Asm
->OutStreamer
->GetSymbolOrder(B
.Sym
) : 0;
2482 // Symbols with no order assigned should be placed at the end.
2483 // (e.g. section end labels)
2491 // Insert a final terminator.
2492 List
.push_back(SymbolCU(nullptr, Asm
->OutStreamer
->endSection(Section
)));
2494 // Build spans between each label.
2495 const MCSymbol
*StartSym
= List
[0].Sym
;
2496 for (size_t n
= 1, e
= List
.size(); n
< e
; n
++) {
2497 const SymbolCU
&Prev
= List
[n
- 1];
2498 const SymbolCU
&Cur
= List
[n
];
2500 // Try and build the longest span we can within the same CU.
2501 if (Cur
.CU
!= Prev
.CU
) {
2503 Span
.Start
= StartSym
;
2506 Spans
[Prev
.CU
].push_back(Span
);
2512 // Start the dwarf aranges section.
2513 Asm
->OutStreamer
->SwitchSection(
2514 Asm
->getObjFileLowering().getDwarfARangesSection());
2516 unsigned PtrSize
= Asm
->MAI
->getCodePointerSize();
2518 // Build a list of CUs used.
2519 std::vector
<DwarfCompileUnit
*> CUs
;
2520 for (const auto &it
: Spans
) {
2521 DwarfCompileUnit
*CU
= it
.first
;
2525 // Sort the CU list (again, to ensure consistent output order).
2526 llvm::sort(CUs
, [](const DwarfCompileUnit
*A
, const DwarfCompileUnit
*B
) {
2527 return A
->getUniqueID() < B
->getUniqueID();
2530 // Emit an arange table for each CU we used.
2531 for (DwarfCompileUnit
*CU
: CUs
) {
2532 std::vector
<ArangeSpan
> &List
= Spans
[CU
];
2534 // Describe the skeleton CU's offset and length, not the dwo file's.
2535 if (auto *Skel
= CU
->getSkeleton())
2538 // Emit size of content not including length itself.
2539 unsigned ContentSize
=
2540 sizeof(int16_t) + // DWARF ARange version number
2541 sizeof(int32_t) + // Offset of CU in the .debug_info section
2542 sizeof(int8_t) + // Pointer Size (in bytes)
2543 sizeof(int8_t); // Segment Size (in bytes)
2545 unsigned TupleSize
= PtrSize
* 2;
2547 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2549 OffsetToAlignment(sizeof(int32_t) + ContentSize
, TupleSize
);
2551 ContentSize
+= Padding
;
2552 ContentSize
+= (List
.size() + 1) * TupleSize
;
2554 // For each compile unit, write the list of spans it covers.
2555 Asm
->OutStreamer
->AddComment("Length of ARange Set");
2556 Asm
->emitInt32(ContentSize
);
2557 Asm
->OutStreamer
->AddComment("DWARF Arange version number");
2558 Asm
->emitInt16(dwarf::DW_ARANGES_VERSION
);
2559 Asm
->OutStreamer
->AddComment("Offset Into Debug Info Section");
2560 emitSectionReference(*CU
);
2561 Asm
->OutStreamer
->AddComment("Address Size (in bytes)");
2562 Asm
->emitInt8(PtrSize
);
2563 Asm
->OutStreamer
->AddComment("Segment Size (in bytes)");
2566 Asm
->OutStreamer
->emitFill(Padding
, 0xff);
2568 for (const ArangeSpan
&Span
: List
) {
2569 Asm
->EmitLabelReference(Span
.Start
, PtrSize
);
2571 // Calculate the size as being from the span start to it's end.
2573 Asm
->EmitLabelDifference(Span
.End
, Span
.Start
, PtrSize
);
2575 // For symbols without an end marker (e.g. common), we
2576 // write a single arange entry containing just that one symbol.
2577 uint64_t Size
= SymSize
[Span
.Start
];
2581 Asm
->OutStreamer
->EmitIntValue(Size
, PtrSize
);
2585 Asm
->OutStreamer
->AddComment("ARange terminator");
2586 Asm
->OutStreamer
->EmitIntValue(0, PtrSize
);
2587 Asm
->OutStreamer
->EmitIntValue(0, PtrSize
);
2591 /// Emit a single range list. We handle both DWARF v5 and earlier.
2592 static void emitRangeList(DwarfDebug
&DD
, AsmPrinter
*Asm
,
2593 const RangeSpanList
&List
) {
2595 auto DwarfVersion
= DD
.getDwarfVersion();
2596 // Emit our symbol so we can find the beginning of the range.
2597 Asm
->OutStreamer
->EmitLabel(List
.getSym());
2598 // Gather all the ranges that apply to the same section so they can share
2599 // a base address entry.
2600 MapVector
<const MCSection
*, std::vector
<const RangeSpan
*>> SectionRanges
;
2601 // Size for our labels.
2602 auto Size
= Asm
->MAI
->getCodePointerSize();
2604 for (const RangeSpan
&Range
: List
.getRanges())
2605 SectionRanges
[&Range
.getStart()->getSection()].push_back(&Range
);
2607 const DwarfCompileUnit
&CU
= List
.getCU();
2608 const MCSymbol
*CUBase
= CU
.getBaseAddress();
2609 bool BaseIsSet
= false;
2610 for (const auto &P
: SectionRanges
) {
2611 // Don't bother with a base address entry if there's only one range in
2612 // this section in this range list - for example ranges for a CU will
2613 // usually consist of single regions from each of many sections
2614 // (-ffunction-sections, or just C++ inline functions) except under LTO
2615 // or optnone where there may be holes in a single CU's section
2617 auto *Base
= CUBase
;
2618 if (!Base
&& (P
.second
.size() > 1 || DwarfVersion
< 5) &&
2619 (CU
.getCUNode()->getRangesBaseAddress() || DwarfVersion
>= 5)) {
2621 // FIXME/use care: This may not be a useful base address if it's not
2622 // the lowest address/range in this object.
2623 Base
= P
.second
.front()->getStart();
2624 if (DwarfVersion
>= 5) {
2625 Base
= DD
.getSectionLabel(&Base
->getSection());
2626 Asm
->OutStreamer
->AddComment("DW_RLE_base_addressx");
2627 Asm
->OutStreamer
->EmitIntValue(dwarf::DW_RLE_base_addressx
, 1);
2628 Asm
->OutStreamer
->AddComment(" base address index");
2629 Asm
->EmitULEB128(DD
.getAddressPool().getIndex(Base
));
2631 Asm
->OutStreamer
->EmitIntValue(-1, Size
);
2632 Asm
->OutStreamer
->AddComment(" base address");
2633 Asm
->OutStreamer
->EmitSymbolValue(Base
, Size
);
2635 } else if (BaseIsSet
&& DwarfVersion
< 5) {
2638 Asm
->OutStreamer
->EmitIntValue(-1, Size
);
2639 Asm
->OutStreamer
->EmitIntValue(0, Size
);
2642 for (const auto *RS
: P
.second
) {
2643 const MCSymbol
*Begin
= RS
->getStart();
2644 const MCSymbol
*End
= RS
->getEnd();
2645 assert(Begin
&& "Range without a begin symbol?");
2646 assert(End
&& "Range without an end symbol?");
2648 if (DwarfVersion
>= 5) {
2649 // Emit DW_RLE_offset_pair when we have a base.
2650 Asm
->OutStreamer
->AddComment("DW_RLE_offset_pair");
2651 Asm
->OutStreamer
->EmitIntValue(dwarf::DW_RLE_offset_pair
, 1);
2652 Asm
->OutStreamer
->AddComment(" starting offset");
2653 Asm
->EmitLabelDifferenceAsULEB128(Begin
, Base
);
2654 Asm
->OutStreamer
->AddComment(" ending offset");
2655 Asm
->EmitLabelDifferenceAsULEB128(End
, Base
);
2657 Asm
->EmitLabelDifference(Begin
, Base
, Size
);
2658 Asm
->EmitLabelDifference(End
, Base
, Size
);
2660 } else if (DwarfVersion
>= 5) {
2661 Asm
->OutStreamer
->AddComment("DW_RLE_startx_length");
2662 Asm
->OutStreamer
->EmitIntValue(dwarf::DW_RLE_startx_length
, 1);
2663 Asm
->OutStreamer
->AddComment(" start index");
2664 Asm
->EmitULEB128(DD
.getAddressPool().getIndex(Begin
));
2665 Asm
->OutStreamer
->AddComment(" length");
2666 Asm
->EmitLabelDifferenceAsULEB128(End
, Begin
);
2668 Asm
->OutStreamer
->EmitSymbolValue(Begin
, Size
);
2669 Asm
->OutStreamer
->EmitSymbolValue(End
, Size
);
2673 if (DwarfVersion
>= 5) {
2674 Asm
->OutStreamer
->AddComment("DW_RLE_end_of_list");
2675 Asm
->OutStreamer
->EmitIntValue(dwarf::DW_RLE_end_of_list
, 1);
2677 // Terminate the list with two 0 values.
2678 Asm
->OutStreamer
->EmitIntValue(0, Size
);
2679 Asm
->OutStreamer
->EmitIntValue(0, Size
);
2683 static void emitDebugRangesImpl(DwarfDebug
&DD
, AsmPrinter
*Asm
,
2684 const DwarfFile
&Holder
, MCSymbol
*TableEnd
) {
2685 for (const RangeSpanList
&List
: Holder
.getRangeLists())
2686 emitRangeList(DD
, Asm
, List
);
2689 Asm
->OutStreamer
->EmitLabel(TableEnd
);
2692 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2693 /// .debug_rnglists section.
2694 void DwarfDebug::emitDebugRanges() {
2698 const auto &Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
2700 if (Holder
.getRangeLists().empty())
2703 assert(useRangesSection());
2704 assert(llvm::none_of(CUMap
, [](const decltype(CUMap
)::value_type
&Pair
) {
2705 return Pair
.second
->getCUNode()->isDebugDirectivesOnly();
2708 // Start the dwarf ranges section.
2709 MCSymbol
*TableEnd
= nullptr;
2710 if (getDwarfVersion() >= 5) {
2711 Asm
->OutStreamer
->SwitchSection(
2712 Asm
->getObjFileLowering().getDwarfRnglistsSection());
2713 TableEnd
= emitRnglistsTableHeader(Asm
, Holder
);
2715 Asm
->OutStreamer
->SwitchSection(
2716 Asm
->getObjFileLowering().getDwarfRangesSection());
2718 emitDebugRangesImpl(*this, Asm
, Holder
, TableEnd
);
2721 void DwarfDebug::emitDebugRangesDWO() {
2722 assert(useSplitDwarf());
2727 const auto &Holder
= InfoHolder
;
2729 if (Holder
.getRangeLists().empty())
2732 assert(getDwarfVersion() >= 5);
2733 assert(useRangesSection());
2734 assert(llvm::none_of(CUMap
, [](const decltype(CUMap
)::value_type
&Pair
) {
2735 return Pair
.second
->getCUNode()->isDebugDirectivesOnly();
2738 // Start the dwarf ranges section.
2739 Asm
->OutStreamer
->SwitchSection(
2740 Asm
->getObjFileLowering().getDwarfRnglistsDWOSection());
2741 MCSymbol
*TableEnd
= emitRnglistsTableHeader(Asm
, Holder
);
2743 emitDebugRangesImpl(*this, Asm
, Holder
, TableEnd
);
2746 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes
, DwarfCompileUnit
&U
) {
2747 for (auto *MN
: Nodes
) {
2748 if (auto *M
= dyn_cast
<DIMacro
>(MN
))
2750 else if (auto *F
= dyn_cast
<DIMacroFile
>(MN
))
2751 emitMacroFile(*F
, U
);
2753 llvm_unreachable("Unexpected DI type!");
2757 void DwarfDebug::emitMacro(DIMacro
&M
) {
2758 Asm
->EmitULEB128(M
.getMacinfoType());
2759 Asm
->EmitULEB128(M
.getLine());
2760 StringRef Name
= M
.getName();
2761 StringRef Value
= M
.getValue();
2762 Asm
->OutStreamer
->EmitBytes(Name
);
2763 if (!Value
.empty()) {
2764 // There should be one space between macro name and macro value.
2766 Asm
->OutStreamer
->EmitBytes(Value
);
2768 Asm
->emitInt8('\0');
2771 void DwarfDebug::emitMacroFile(DIMacroFile
&F
, DwarfCompileUnit
&U
) {
2772 assert(F
.getMacinfoType() == dwarf::DW_MACINFO_start_file
);
2773 Asm
->EmitULEB128(dwarf::DW_MACINFO_start_file
);
2774 Asm
->EmitULEB128(F
.getLine());
2775 Asm
->EmitULEB128(U
.getOrCreateSourceID(F
.getFile()));
2776 handleMacroNodes(F
.getElements(), U
);
2777 Asm
->EmitULEB128(dwarf::DW_MACINFO_end_file
);
2780 /// Emit macros into a debug macinfo section.
2781 void DwarfDebug::emitDebugMacinfo() {
2785 if (llvm::all_of(CUMap
, [](const decltype(CUMap
)::value_type
&Pair
) {
2786 return Pair
.second
->getCUNode()->isDebugDirectivesOnly();
2790 // Start the dwarf macinfo section.
2791 Asm
->OutStreamer
->SwitchSection(
2792 Asm
->getObjFileLowering().getDwarfMacinfoSection());
2794 for (const auto &P
: CUMap
) {
2795 auto &TheCU
= *P
.second
;
2796 if (TheCU
.getCUNode()->isDebugDirectivesOnly())
2798 auto *SkCU
= TheCU
.getSkeleton();
2799 DwarfCompileUnit
&U
= SkCU
? *SkCU
: TheCU
;
2800 auto *CUNode
= cast
<DICompileUnit
>(P
.first
);
2801 DIMacroNodeArray Macros
= CUNode
->getMacros();
2802 if (!Macros
.empty()) {
2803 Asm
->OutStreamer
->EmitLabel(U
.getMacroLabelBegin());
2804 handleMacroNodes(Macros
, U
);
2807 Asm
->OutStreamer
->AddComment("End Of Macro List Mark");
2811 // DWARF5 Experimental Separate Dwarf emitters.
2813 void DwarfDebug::initSkeletonUnit(const DwarfUnit
&U
, DIE
&Die
,
2814 std::unique_ptr
<DwarfCompileUnit
> NewU
) {
2816 if (!CompilationDir
.empty())
2817 NewU
->addString(Die
, dwarf::DW_AT_comp_dir
, CompilationDir
);
2819 addGnuPubAttributes(*NewU
, Die
);
2821 SkeletonHolder
.addUnit(std::move(NewU
));
2824 DwarfCompileUnit
&DwarfDebug::constructSkeletonCU(const DwarfCompileUnit
&CU
) {
2826 auto OwnedUnit
= std::make_unique
<DwarfCompileUnit
>(
2827 CU
.getUniqueID(), CU
.getCUNode(), Asm
, this, &SkeletonHolder
);
2828 DwarfCompileUnit
&NewCU
= *OwnedUnit
;
2829 NewCU
.setSection(Asm
->getObjFileLowering().getDwarfInfoSection());
2831 NewCU
.initStmtList();
2833 if (useSegmentedStringOffsetsTable())
2834 NewCU
.addStringOffsetsStart();
2836 initSkeletonUnit(CU
, NewCU
.getUnitDie(), std::move(OwnedUnit
));
2841 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2842 // compile units that would normally be in debug_info.
2843 void DwarfDebug::emitDebugInfoDWO() {
2844 assert(useSplitDwarf() && "No split dwarf debug info?");
2845 // Don't emit relocations into the dwo file.
2846 InfoHolder
.emitUnits(/* UseOffsets */ true);
2849 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2850 // abbreviations for the .debug_info.dwo section.
2851 void DwarfDebug::emitDebugAbbrevDWO() {
2852 assert(useSplitDwarf() && "No split dwarf?");
2853 InfoHolder
.emitAbbrevs(Asm
->getObjFileLowering().getDwarfAbbrevDWOSection());
2856 void DwarfDebug::emitDebugLineDWO() {
2857 assert(useSplitDwarf() && "No split dwarf?");
2858 SplitTypeUnitFileTable
.Emit(
2859 *Asm
->OutStreamer
, MCDwarfLineTableParams(),
2860 Asm
->getObjFileLowering().getDwarfLineDWOSection());
2863 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2864 assert(useSplitDwarf() && "No split dwarf?");
2865 InfoHolder
.getStringPool().emitStringOffsetsTableHeader(
2866 *Asm
, Asm
->getObjFileLowering().getDwarfStrOffDWOSection(),
2867 InfoHolder
.getStringOffsetsStartSym());
2870 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2871 // string section and is identical in format to traditional .debug_str
2873 void DwarfDebug::emitDebugStrDWO() {
2874 if (useSegmentedStringOffsetsTable())
2875 emitStringOffsetsTableHeaderDWO();
2876 assert(useSplitDwarf() && "No split dwarf?");
2877 MCSection
*OffSec
= Asm
->getObjFileLowering().getDwarfStrOffDWOSection();
2878 InfoHolder
.emitStrings(Asm
->getObjFileLowering().getDwarfStrDWOSection(),
2879 OffSec
, /* UseRelativeOffsets = */ false);
2882 // Emit address pool.
2883 void DwarfDebug::emitDebugAddr() {
2884 AddrPool
.emit(*Asm
, Asm
->getObjFileLowering().getDwarfAddrSection());
2887 MCDwarfDwoLineTable
*DwarfDebug::getDwoLineTable(const DwarfCompileUnit
&CU
) {
2888 if (!useSplitDwarf())
2890 const DICompileUnit
*DIUnit
= CU
.getCUNode();
2891 SplitTypeUnitFileTable
.maybeSetRootFile(
2892 DIUnit
->getDirectory(), DIUnit
->getFilename(),
2893 CU
.getMD5AsBytes(DIUnit
->getFile()), DIUnit
->getSource());
2894 return &SplitTypeUnitFileTable
;
2897 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier
) {
2899 Hash
.update(Identifier
);
2900 // ... take the least significant 8 bytes and return those. Our MD5
2901 // implementation always returns its results in little endian, so we actually
2902 // need the "high" word.
2903 MD5::MD5Result Result
;
2905 return Result
.high();
2908 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit
&CU
,
2909 StringRef Identifier
, DIE
&RefDie
,
2910 const DICompositeType
*CTy
) {
2911 // Fast path if we're building some type units and one has already used the
2912 // address pool we know we're going to throw away all this work anyway, so
2913 // don't bother building dependent types.
2914 if (!TypeUnitsUnderConstruction
.empty() && AddrPool
.hasBeenUsed())
2917 auto Ins
= TypeSignatures
.insert(std::make_pair(CTy
, 0));
2919 CU
.addDIETypeSignature(RefDie
, Ins
.first
->second
);
2923 bool TopLevelType
= TypeUnitsUnderConstruction
.empty();
2924 AddrPool
.resetUsedFlag();
2926 auto OwnedUnit
= std::make_unique
<DwarfTypeUnit
>(CU
, Asm
, this, &InfoHolder
,
2927 getDwoLineTable(CU
));
2928 DwarfTypeUnit
&NewTU
= *OwnedUnit
;
2929 DIE
&UnitDie
= NewTU
.getUnitDie();
2930 TypeUnitsUnderConstruction
.emplace_back(std::move(OwnedUnit
), CTy
);
2932 NewTU
.addUInt(UnitDie
, dwarf::DW_AT_language
, dwarf::DW_FORM_data2
,
2935 uint64_t Signature
= makeTypeSignature(Identifier
);
2936 NewTU
.setTypeSignature(Signature
);
2937 Ins
.first
->second
= Signature
;
2939 if (useSplitDwarf()) {
2940 MCSection
*Section
=
2941 getDwarfVersion() <= 4
2942 ? Asm
->getObjFileLowering().getDwarfTypesDWOSection()
2943 : Asm
->getObjFileLowering().getDwarfInfoDWOSection();
2944 NewTU
.setSection(Section
);
2946 MCSection
*Section
=
2947 getDwarfVersion() <= 4
2948 ? Asm
->getObjFileLowering().getDwarfTypesSection(Signature
)
2949 : Asm
->getObjFileLowering().getDwarfInfoSection(Signature
);
2950 NewTU
.setSection(Section
);
2951 // Non-split type units reuse the compile unit's line table.
2952 CU
.applyStmtList(UnitDie
);
2955 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2957 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2958 NewTU
.addStringOffsetsStart();
2960 NewTU
.setType(NewTU
.createTypeDIE(CTy
));
2963 auto TypeUnitsToAdd
= std::move(TypeUnitsUnderConstruction
);
2964 TypeUnitsUnderConstruction
.clear();
2966 // Types referencing entries in the address table cannot be placed in type
2968 if (AddrPool
.hasBeenUsed()) {
2970 // Remove all the types built while building this type.
2971 // This is pessimistic as some of these types might not be dependent on
2972 // the type that used an address.
2973 for (const auto &TU
: TypeUnitsToAdd
)
2974 TypeSignatures
.erase(TU
.second
);
2976 // Construct this type in the CU directly.
2977 // This is inefficient because all the dependent types will be rebuilt
2978 // from scratch, including building them in type units, discovering that
2979 // they depend on addresses, throwing them out and rebuilding them.
2980 CU
.constructTypeDIE(RefDie
, cast
<DICompositeType
>(CTy
));
2984 // If the type wasn't dependent on fission addresses, finish adding the type
2985 // and all its dependent types.
2986 for (auto &TU
: TypeUnitsToAdd
) {
2987 InfoHolder
.computeSizeAndOffsetsForUnit(TU
.first
.get());
2988 InfoHolder
.emitUnit(TU
.first
.get(), useSplitDwarf());
2991 CU
.addDIETypeSignature(RefDie
, Signature
);
2994 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug
*DD
)
2996 TypeUnitsUnderConstruction(std::move(DD
->TypeUnitsUnderConstruction
)) {
2997 DD
->TypeUnitsUnderConstruction
.clear();
2998 assert(TypeUnitsUnderConstruction
.empty() || !DD
->AddrPool
.hasBeenUsed());
3001 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3002 DD
->TypeUnitsUnderConstruction
= std::move(TypeUnitsUnderConstruction
);
3003 DD
->AddrPool
.resetUsedFlag();
3006 DwarfDebug::NonTypeUnitContext
DwarfDebug::enterNonTypeUnitContext() {
3007 return NonTypeUnitContext(this);
3010 // Add the Name along with its companion DIE to the appropriate accelerator
3011 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3012 // AccelTableKind::Apple, we use the table we got as an argument). If
3013 // accelerator tables are disabled, this function does nothing.
3014 template <typename DataT
>
3015 void DwarfDebug::addAccelNameImpl(const DICompileUnit
&CU
,
3016 AccelTable
<DataT
> &AppleAccel
, StringRef Name
,
3018 if (getAccelTableKind() == AccelTableKind::None
)
3021 if (getAccelTableKind() != AccelTableKind::Apple
&&
3022 CU
.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default
)
3025 DwarfFile
&Holder
= useSplitDwarf() ? SkeletonHolder
: InfoHolder
;
3026 DwarfStringPoolEntryRef Ref
= Holder
.getStringPool().getEntry(*Asm
, Name
);
3028 switch (getAccelTableKind()) {
3029 case AccelTableKind::Apple
:
3030 AppleAccel
.addName(Ref
, Die
);
3032 case AccelTableKind::Dwarf
:
3033 AccelDebugNames
.addName(Ref
, Die
);
3035 case AccelTableKind::Default
:
3036 llvm_unreachable("Default should have already been resolved.");
3037 case AccelTableKind::None
:
3038 llvm_unreachable("None handled above");
3042 void DwarfDebug::addAccelName(const DICompileUnit
&CU
, StringRef Name
,
3044 addAccelNameImpl(CU
, AccelNames
, Name
, Die
);
3047 void DwarfDebug::addAccelObjC(const DICompileUnit
&CU
, StringRef Name
,
3049 // ObjC names go only into the Apple accelerator tables.
3050 if (getAccelTableKind() == AccelTableKind::Apple
)
3051 addAccelNameImpl(CU
, AccelObjC
, Name
, Die
);
3054 void DwarfDebug::addAccelNamespace(const DICompileUnit
&CU
, StringRef Name
,
3056 addAccelNameImpl(CU
, AccelNamespace
, Name
, Die
);
3059 void DwarfDebug::addAccelType(const DICompileUnit
&CU
, StringRef Name
,
3060 const DIE
&Die
, char Flags
) {
3061 addAccelNameImpl(CU
, AccelTypes
, Name
, Die
);
3064 uint16_t DwarfDebug::getDwarfVersion() const {
3065 return Asm
->OutStreamer
->getContext().getDwarfVersion();
3068 void DwarfDebug::addSectionLabel(const MCSymbol
*Sym
) {
3069 SectionLabels
.insert(std::make_pair(&Sym
->getSection(), Sym
));
3072 const MCSymbol
*DwarfDebug::getSectionLabel(const MCSection
*S
) {
3073 return SectionLabels
.find(S
)->second
;