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) {
173 getActiveStreamer().EmitInt8(
174 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
175 : dwarf::OperationEncodingString(Op));
178 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
179 getActiveStreamer().EmitSLEB128(Value, Twine(Value));
182 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
183 getActiveStreamer().EmitULEB128(Value, Twine(Value));
186 void DebugLocDwarfExpression::emitData1(uint8_t Value) {
187 getActiveStreamer().EmitInt8(Value, Twine(Value));
190 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
191 assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
192 getActiveStreamer().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 void DebugLocDwarfExpression::enableTemporaryBuffer() {
202 assert(!IsBuffering && "Already buffering?");
204 TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
208 void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
210 unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
211 return TmpBuf ? TmpBuf->Bytes.size() : 0;
214 void DebugLocDwarfExpression::commitTemporaryBuffer() {
217 for (auto Byte : enumerate(TmpBuf->Bytes)) {
218 const char *Comment = (Byte.index() < TmpBuf->Comments.size())
219 ? TmpBuf->Comments[Byte.index()].c_str()
221 OutBS.EmitInt8(Byte.value(), Comment);
223 TmpBuf->Bytes.clear();
224 TmpBuf->Comments.clear();
227 const DIType *DbgVariable::getType() const {
228 return getVariable()->getType();
231 /// Get .debug_loc entry for the instruction range starting at MI.
232 static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
233 const DIExpression *Expr = MI->getDebugExpression();
234 assert(MI->getNumOperands() == 4);
235 if (MI->getOperand(0).isReg()) {
236 auto RegOp = MI->getOperand(0);
237 auto Op1 = MI->getOperand(1);
238 // If the second operand is an immediate, this is a
239 // register-indirect address.
240 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
241 MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
242 return DbgValueLoc(Expr, MLoc);
244 if (MI->getOperand(0).isTargetIndex()) {
245 auto Op = MI->getOperand(0);
246 return DbgValueLoc(Expr,
247 TargetIndexLocation(Op.getIndex(), Op.getOffset()));
249 if (MI->getOperand(0).isImm())
250 return DbgValueLoc(Expr, MI->getOperand(0).getImm());
251 if (MI->getOperand(0).isFPImm())
252 return DbgValueLoc(Expr, MI->getOperand(0).getFPImm());
253 if (MI->getOperand(0).isCImm())
254 return DbgValueLoc(Expr, MI->getOperand(0).getCImm());
256 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
259 void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
260 assert(FrameIndexExprs.empty() && "Already initialized?");
261 assert(!ValueLoc.get() && "Already initialized?");
263 assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
264 assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
267 ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
268 if (auto *E = DbgValue->getDebugExpression())
269 if (E->getNumElements())
270 FrameIndexExprs.push_back({0, E});
273 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
274 if (FrameIndexExprs.size() == 1)
275 return FrameIndexExprs;
277 assert(llvm::all_of(FrameIndexExprs,
278 [](const FrameIndexExpr &A) {
279 return A.Expr->isFragment();
281 "multiple FI expressions without DW_OP_LLVM_fragment");
282 llvm::sort(FrameIndexExprs,
283 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
284 return A.Expr->getFragmentInfo()->OffsetInBits <
285 B.Expr->getFragmentInfo()->OffsetInBits;
288 return FrameIndexExprs;
291 void DbgVariable::addMMIEntry(const DbgVariable &V) {
292 assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
293 assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
294 assert(V.getVariable() == getVariable() && "conflicting variable");
295 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
297 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
298 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
300 // FIXME: This logic should not be necessary anymore, as we now have proper
301 // deduplication. However, without it, we currently run into the assertion
302 // below, which means that we are likely dealing with broken input, i.e. two
303 // non-fragment entries for the same variable at different frame indices.
304 if (FrameIndexExprs.size()) {
305 auto *Expr = FrameIndexExprs.back().Expr;
306 if (!Expr || !Expr->isFragment())
310 for (const auto &FIE : V.FrameIndexExprs)
311 // Ignore duplicate entries.
312 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
313 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
315 FrameIndexExprs.push_back(FIE);
317 assert((FrameIndexExprs.size() == 1 ||
318 llvm::all_of(FrameIndexExprs,
319 [](FrameIndexExpr &FIE) {
320 return FIE.Expr && FIE.Expr->isFragment();
322 "conflicting locations for variable");
325 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
326 bool GenerateTypeUnits,
329 // Honor an explicit request.
330 if (AccelTables != AccelTableKind::Default)
333 // Accelerator tables with type units are currently not supported.
334 if (GenerateTypeUnits)
335 return AccelTableKind::None;
337 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
338 // always implies debug_names. For lower standard versions we use apple
339 // accelerator tables on apple platforms and debug_names elsewhere.
340 if (DwarfVersion >= 5)
341 return AccelTableKind::Dwarf;
342 if (Tuning == DebuggerKind::LLDB)
343 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
344 : AccelTableKind::Dwarf;
345 return AccelTableKind::None;
348 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
349 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
350 InfoHolder(A, "info_string", DIEValueAllocator),
351 SkeletonHolder(A, "skel_string", DIEValueAllocator),
352 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
353 const Triple &TT = Asm->TM.getTargetTriple();
355 // Make sure we know our "debugger tuning". The target option takes
356 // precedence; fall back to triple-based defaults.
357 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
358 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
360 DebuggerTuning = DebuggerKind::LLDB;
361 else if (TT.isPS4CPU())
362 DebuggerTuning = DebuggerKind::SCE;
364 DebuggerTuning = DebuggerKind::GDB;
366 if (DwarfInlinedStrings == Default)
367 UseInlineStrings = TT.isNVPTX();
369 UseInlineStrings = DwarfInlinedStrings == Enable;
371 UseLocSection = !TT.isNVPTX();
373 HasAppleExtensionAttributes = tuneForLLDB();
375 // Handle split DWARF.
376 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
378 // SCE defaults to linkage names only for abstract subprograms.
379 if (DwarfLinkageNames == DefaultLinkageNames)
380 UseAllLinkageNames = !tuneForSCE();
382 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
384 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
385 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
386 : MMI->getModule()->getDwarfVersion();
387 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
389 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
391 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
393 // Use sections as references. Force for NVPTX.
394 if (DwarfSectionsAsReferences == Default)
395 UseSectionsAsReferences = TT.isNVPTX();
397 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
399 // Don't generate type units for unsupported object file formats.
401 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
403 TheAccelTableKind = computeAccelTableKind(
404 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
406 // Work around a GDB bug. GDB doesn't support the standard opcode;
407 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
408 // is defined as of DWARF 3.
409 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
410 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
411 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
413 // GDB does not fully support the DWARF 4 representation for bitfields.
414 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
416 // The DWARF v5 string offsets table has - possibly shared - contributions
417 // from each compile and type unit each preceded by a header. The string
418 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
419 // a monolithic string offsets table without any header.
420 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
422 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
425 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
426 DwarfDebug::~DwarfDebug() = default;
428 static bool isObjCClass(StringRef Name) {
429 return Name.startswith("+") || Name.startswith("-");
432 static bool hasObjCCategory(StringRef Name) {
433 if (!isObjCClass(Name))
436 return Name.find(") ") != StringRef::npos;
439 static void getObjCClassCategory(StringRef In, StringRef &Class,
440 StringRef &Category) {
441 if (!hasObjCCategory(In)) {
442 Class = In.slice(In.find('[') + 1, In.find(' '));
447 Class = In.slice(In.find('[') + 1, In.find('('));
448 Category = In.slice(In.find('[') + 1, In.find(' '));
451 static StringRef getObjCMethodName(StringRef In) {
452 return In.slice(In.find(' ') + 1, In.find(']'));
455 // Add the various names to the Dwarf accelerator table names.
456 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
457 const DISubprogram *SP, DIE &Die) {
458 if (getAccelTableKind() != AccelTableKind::Apple &&
459 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
462 if (!SP->isDefinition())
465 if (SP->getName() != "")
466 addAccelName(CU, SP->getName(), Die);
468 // If the linkage name is different than the name, go ahead and output that as
469 // well into the name table. Only do that if we are going to actually emit
471 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
472 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
473 addAccelName(CU, SP->getLinkageName(), Die);
475 // If this is an Objective-C selector name add it to the ObjC accelerator
477 if (isObjCClass(SP->getName())) {
478 StringRef Class, Category;
479 getObjCClassCategory(SP->getName(), Class, Category);
480 addAccelObjC(CU, Class, Die);
482 addAccelObjC(CU, Category, Die);
483 // Also add the base method name to the name table.
484 addAccelName(CU, getObjCMethodName(SP->getName()), Die);
488 /// Check whether we should create a DIE for the given Scope, return true
489 /// if we don't create a DIE (the corresponding DIE is null).
490 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
491 if (Scope->isAbstractScope())
494 // We don't create a DIE if there is no Range.
495 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
499 if (Ranges.size() > 1)
502 // We don't create a DIE if we have a single Range and the end label
504 return !getLabelAfterInsn(Ranges.front().second);
507 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
509 if (auto *SkelCU = CU.getSkeleton())
510 if (CU.getCUNode()->getSplitDebugInlining())
514 bool DwarfDebug::shareAcrossDWOCUs() const {
515 return SplitDwarfCrossCuReferences;
518 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
519 LexicalScope *Scope) {
520 assert(Scope && Scope->getScopeNode());
521 assert(Scope->isAbstractScope());
522 assert(!Scope->getInlinedAt());
524 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
526 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
527 // was inlined from another compile unit.
528 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
529 // Avoid building the original CU if it won't be used
530 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
532 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
533 if (auto *SkelCU = CU.getSkeleton()) {
534 (shareAcrossDWOCUs() ? CU : SrcCU)
535 .constructAbstractSubprogramScopeDIE(Scope);
536 if (CU.getCUNode()->getSplitDebugInlining())
537 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
539 CU.constructAbstractSubprogramScopeDIE(Scope);
543 /// Try to interpret values loaded into registers that forward parameters
544 /// for \p CallMI. Store parameters with interpreted value into \p Params.
545 static void collectCallSiteParameters(const MachineInstr *CallMI,
547 auto *MF = CallMI->getMF();
548 auto CalleesMap = MF->getCallSitesInfo();
549 auto CallFwdRegsInfo = CalleesMap.find(CallMI);
551 // There is no information for the call instruction.
552 if (CallFwdRegsInfo == CalleesMap.end())
555 auto *MBB = CallMI->getParent();
556 const auto &TRI = MF->getSubtarget().getRegisterInfo();
557 const auto &TII = MF->getSubtarget().getInstrInfo();
558 const auto &TLI = MF->getSubtarget().getTargetLowering();
560 // Skip the call instruction.
561 auto I = std::next(CallMI->getReverseIterator());
563 DenseSet<unsigned> ForwardedRegWorklist;
564 // Add all the forwarding registers into the ForwardedRegWorklist.
565 for (auto ArgReg : CallFwdRegsInfo->second) {
566 bool InsertedReg = ForwardedRegWorklist.insert(ArgReg.Reg).second;
567 assert(InsertedReg && "Single register used to forward two arguments?");
571 // We erase, from the ForwardedRegWorklist, those forwarding registers for
572 // which we successfully describe a loaded value (by using
573 // the describeLoadedValue()). For those remaining arguments in the working
574 // list, for which we do not describe a loaded value by
575 // the describeLoadedValue(), we try to generate an entry value expression
576 // for their call site value desctipion, if the call is within the entry MBB.
577 // The RegsForEntryValues maps a forwarding register into the register holding
579 // TODO: Handle situations when call site parameter value can be described
580 // as the entry value within basic blocks other then the first one.
581 bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
582 DenseMap<unsigned, unsigned> RegsForEntryValues;
584 // If the MI is an instruction defining one or more parameters' forwarding
585 // registers, add those defines. We can currently only describe forwarded
586 // registers that are explicitly defined, but keep track of implicit defines
587 // also to remove those registers from the work list.
588 auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
589 SmallVectorImpl<unsigned> &Explicit,
590 SmallVectorImpl<unsigned> &Implicit) {
591 if (MI.isDebugInstr())
594 for (const MachineOperand &MO : MI.operands()) {
595 if (MO.isReg() && MO.isDef() &&
596 Register::isPhysicalRegister(MO.getReg())) {
597 for (auto FwdReg : ForwardedRegWorklist) {
598 if (TRI->regsOverlap(FwdReg, MO.getReg())) {
600 Implicit.push_back(FwdReg);
602 Explicit.push_back(FwdReg);
609 auto finishCallSiteParam = [&](DbgValueLoc DbgLocVal, unsigned Reg) {
610 unsigned FwdReg = Reg;
611 if (ShouldTryEmitEntryVals) {
612 auto EntryValReg = RegsForEntryValues.find(Reg);
613 if (EntryValReg != RegsForEntryValues.end())
614 FwdReg = EntryValReg->second;
617 DbgCallSiteParam CSParm(FwdReg, DbgLocVal);
618 Params.push_back(CSParm);
622 // Search for a loading value in forwarding registers.
623 for (; I != MBB->rend(); ++I) {
624 // Skip bundle headers.
628 // If the next instruction is a call we can not interpret parameter's
629 // forwarding registers or we finished the interpretation of all parameters.
633 if (ForwardedRegWorklist.empty())
636 SmallVector<unsigned, 4> ExplicitFwdRegDefs;
637 SmallVector<unsigned, 4> ImplicitFwdRegDefs;
638 getForwardingRegsDefinedByMI(*I, ExplicitFwdRegDefs, ImplicitFwdRegDefs);
639 if (ExplicitFwdRegDefs.empty() && ImplicitFwdRegDefs.empty())
642 // If the MI clobbers more then one forwarding register we must remove
643 // all of them from the working list.
644 for (auto Reg : concat<unsigned>(ExplicitFwdRegDefs, ImplicitFwdRegDefs))
645 ForwardedRegWorklist.erase(Reg);
647 for (auto ParamFwdReg : ExplicitFwdRegDefs) {
648 if (auto ParamValue = TII->describeLoadedValue(*I, ParamFwdReg)) {
649 if (ParamValue->first.isImm()) {
650 int64_t Val = ParamValue->first.getImm();
651 DbgValueLoc DbgLocVal(ParamValue->second, Val);
652 finishCallSiteParam(DbgLocVal, ParamFwdReg);
653 } else if (ParamValue->first.isReg()) {
654 Register RegLoc = ParamValue->first.getReg();
655 // TODO: For now, there is no use of describing the value loaded into the
656 // register that is also the source registers (e.g. $r0 = add $r0, x).
657 if (ParamFwdReg == RegLoc)
660 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
661 Register FP = TRI->getFrameRegister(*MF);
662 bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
663 if (TRI->isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
664 DbgValueLoc DbgLocVal(ParamValue->second,
665 MachineLocation(RegLoc,
666 /*IsIndirect=*/IsSPorFP));
667 finishCallSiteParam(DbgLocVal, ParamFwdReg);
668 // TODO: Add support for entry value plus an expression.
669 } else if (ShouldTryEmitEntryVals &&
670 ParamValue->second->getNumElements() == 0) {
671 ForwardedRegWorklist.insert(RegLoc);
672 RegsForEntryValues[RegLoc] = ParamFwdReg;
679 // Emit the call site parameter's value as an entry value.
680 if (ShouldTryEmitEntryVals) {
681 // Create an expression where the register's entry value is used.
682 DIExpression *EntryExpr = DIExpression::get(
683 MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
684 for (auto RegEntry : ForwardedRegWorklist) {
685 unsigned FwdReg = RegEntry;
686 auto EntryValReg = RegsForEntryValues.find(RegEntry);
687 if (EntryValReg != RegsForEntryValues.end())
688 FwdReg = EntryValReg->second;
690 DbgValueLoc DbgLocVal(EntryExpr, MachineLocation(RegEntry));
691 DbgCallSiteParam CSParm(FwdReg, DbgLocVal);
692 Params.push_back(CSParm);
698 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
699 DwarfCompileUnit &CU, DIE &ScopeDIE,
700 const MachineFunction &MF) {
701 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
702 // the subprogram is required to have one.
703 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
706 // Use DW_AT_call_all_calls to express that call site entries are present
707 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
708 // because one of its requirements is not met: call site entries for
709 // optimized-out calls are elided.
710 CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
712 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
713 assert(TII && "TargetInstrInfo not found: cannot label tail calls");
714 bool ApplyGNUExtensions = getDwarfVersion() == 4 && tuneForGDB();
716 // Emit call site entries for each call or tail call in the function.
717 for (const MachineBasicBlock &MBB : MF) {
718 for (const MachineInstr &MI : MBB.instrs()) {
719 // Bundles with call in them will pass the isCall() test below but do not
720 // have callee operand information so skip them here. Iterator will
721 // eventually reach the call MI.
725 // Skip instructions which aren't calls. Both calls and tail-calling jump
726 // instructions (e.g TAILJMPd64) are classified correctly here.
730 // TODO: Add support for targets with delay slots (see: beginInstruction).
731 if (MI.hasDelaySlot())
734 // If this is a direct call, find the callee's subprogram.
735 // In the case of an indirect call find the register that holds
737 const MachineOperand &CalleeOp = MI.getOperand(0);
738 if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
741 unsigned CallReg = 0;
742 const DISubprogram *CalleeSP = nullptr;
743 const Function *CalleeDecl = nullptr;
744 if (CalleeOp.isReg()) {
745 CallReg = CalleeOp.getReg();
749 CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
750 if (!CalleeDecl || !CalleeDecl->getSubprogram())
752 CalleeSP = CalleeDecl->getSubprogram();
755 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
757 bool IsTail = TII->isTailCall(MI);
759 // If MI is in a bundle, the label was created after the bundle since
760 // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
761 // to search for that label below.
762 const MachineInstr *TopLevelCallMI =
763 MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
765 // For tail calls, for non-gdb tuning, no return PC information is needed.
766 // For regular calls (and tail calls in GDB tuning), the return PC
767 // is needed to disambiguate paths in the call graph which could lead to
768 // some target function.
769 const MCExpr *PCOffset =
770 (IsTail && !tuneForGDB())
772 : getFunctionLocalOffsetAfterInsn(TopLevelCallMI);
774 // Return address of a call-like instruction for a normal call or a
775 // jump-like instruction for a tail call. This is needed for
776 // GDB + DWARF 4 tuning.
777 const MCSymbol *PCAddr =
779 ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
782 assert((IsTail || PCOffset || PCAddr) &&
783 "Call without return PC information");
785 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
786 << (CalleeDecl ? CalleeDecl->getName()
787 : StringRef(MF.getSubtarget()
790 << (IsTail ? " [IsTail]" : "") << "\n");
793 CU.constructCallSiteEntryDIE(ScopeDIE, CalleeSP, IsTail, PCAddr,
796 // GDB and LLDB support call site parameter debug info.
797 if (Asm->TM.Options.EnableDebugEntryValues &&
798 (tuneForGDB() || tuneForLLDB())) {
800 // Try to interpret values of call site parameters.
801 collectCallSiteParameters(&MI, Params);
802 CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
808 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
809 if (!U.hasDwarfPubSections())
812 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
815 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
816 DwarfCompileUnit &NewCU) {
817 DIE &Die = NewCU.getUnitDie();
818 StringRef FN = DIUnit->getFilename();
820 StringRef Producer = DIUnit->getProducer();
821 StringRef Flags = DIUnit->getFlags();
822 if (!Flags.empty() && !useAppleExtensionAttributes()) {
823 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
824 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
826 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
828 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
829 DIUnit->getSourceLanguage());
830 NewCU.addString(Die, dwarf::DW_AT_name, FN);
832 // Add DW_str_offsets_base to the unit DIE, except for split units.
833 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
834 NewCU.addStringOffsetsStart();
836 if (!useSplitDwarf()) {
837 NewCU.initStmtList();
839 // If we're using split dwarf the compilation dir is going to be in the
840 // skeleton CU and so we don't need to duplicate it here.
841 if (!CompilationDir.empty())
842 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
844 addGnuPubAttributes(NewCU, Die);
847 if (useAppleExtensionAttributes()) {
848 if (DIUnit->isOptimized())
849 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
851 StringRef Flags = DIUnit->getFlags();
853 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
855 if (unsigned RVer = DIUnit->getRuntimeVersion())
856 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
857 dwarf::DW_FORM_data1, RVer);
860 if (DIUnit->getDWOId()) {
861 // This CU is either a clang module DWO or a skeleton CU.
862 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
864 if (!DIUnit->getSplitDebugFilename().empty()) {
865 // This is a prefabricated skeleton CU.
866 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
867 ? dwarf::DW_AT_dwo_name
868 : dwarf::DW_AT_GNU_dwo_name;
869 NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
873 // Create new DwarfCompileUnit for the given metadata node with tag
874 // DW_TAG_compile_unit.
876 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
877 if (auto *CU = CUMap.lookup(DIUnit))
880 CompilationDir = DIUnit->getDirectory();
882 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
883 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
884 DwarfCompileUnit &NewCU = *OwnedUnit;
885 InfoHolder.addUnit(std::move(OwnedUnit));
887 for (auto *IE : DIUnit->getImportedEntities())
888 NewCU.addImportedEntity(IE);
890 // LTO with assembly output shares a single line table amongst multiple CUs.
891 // To avoid the compilation directory being ambiguous, let the line table
892 // explicitly describe the directory of all files, never relying on the
893 // compilation directory.
894 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
895 Asm->OutStreamer->emitDwarfFile0Directive(
896 CompilationDir, DIUnit->getFilename(),
897 NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
898 NewCU.getUniqueID());
900 if (useSplitDwarf()) {
901 NewCU.setSkeleton(constructSkeletonCU(NewCU));
902 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
904 finishUnitAttributes(DIUnit, NewCU);
905 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
908 // Create DIEs for function declarations used for call site debug info.
909 for (auto Scope : DIUnit->getRetainedTypes())
910 if (auto *SP = dyn_cast_or_null<DISubprogram>(Scope))
911 NewCU.getOrCreateSubprogramDIE(SP);
913 CUMap.insert({DIUnit, &NewCU});
914 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
918 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
919 const DIImportedEntity *N) {
920 if (isa<DILocalScope>(N->getScope()))
922 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
923 D->addChild(TheCU.constructImportedEntityDIE(N));
926 /// Sort and unique GVEs by comparing their fragment offset.
927 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
928 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
930 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
931 // Sort order: first null exprs, then exprs without fragment
932 // info, then sort by fragment offset in bits.
933 // FIXME: Come up with a more comprehensive comparator so
934 // the sorting isn't non-deterministic, and so the following
935 // std::unique call works correctly.
936 if (!A.Expr || !B.Expr)
938 auto FragmentA = A.Expr->getFragmentInfo();
939 auto FragmentB = B.Expr->getFragmentInfo();
940 if (!FragmentA || !FragmentB)
942 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
944 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
945 [](DwarfCompileUnit::GlobalExpr A,
946 DwarfCompileUnit::GlobalExpr B) {
947 return A.Expr == B.Expr;
953 // Emit all Dwarf sections that should come prior to the content. Create
954 // global DIEs and emit initial debug info sections. This is invoked by
955 // the target AsmPrinter.
956 void DwarfDebug::beginModule() {
957 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
958 DWARFGroupDescription, TimePassesIsEnabled);
959 if (DisableDebugInfoPrinting) {
960 MMI->setDebugInfoAvailability(false);
964 const Module *M = MMI->getModule();
966 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
967 M->debug_compile_units_end());
968 // Tell MMI whether we have debug info.
969 assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
970 "DebugInfoAvailabilty initialized unexpectedly");
971 SingleCU = NumDebugCUs == 1;
972 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
974 for (const GlobalVariable &Global : M->globals()) {
975 SmallVector<DIGlobalVariableExpression *, 1> GVs;
976 Global.getDebugInfo(GVs);
977 for (auto *GVE : GVs)
978 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
981 // Create the symbol that designates the start of the unit's contribution
982 // to the string offsets table. In a split DWARF scenario, only the skeleton
983 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
984 if (useSegmentedStringOffsetsTable())
985 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
986 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
989 // Create the symbols that designates the start of the DWARF v5 range list
990 // and locations list tables. They are located past the table headers.
991 if (getDwarfVersion() >= 5) {
992 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
993 Holder.setRnglistsTableBaseSym(
994 Asm->createTempSymbol("rnglists_table_base"));
997 InfoHolder.setRnglistsTableBaseSym(
998 Asm->createTempSymbol("rnglists_dwo_table_base"));
1001 // Create the symbol that points to the first entry following the debug
1002 // address table (.debug_addr) header.
1003 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1004 DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1006 for (DICompileUnit *CUNode : M->debug_compile_units()) {
1007 // FIXME: Move local imported entities into a list attached to the
1008 // subprogram, then this search won't be needed and a
1009 // getImportedEntities().empty() test should go below with the rest.
1010 bool HasNonLocalImportedEntities = llvm::any_of(
1011 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1012 return !isa<DILocalScope>(IE->getScope());
1015 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1016 CUNode->getRetainedTypes().empty() &&
1017 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1020 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1022 // Global Variables.
1023 for (auto *GVE : CUNode->getGlobalVariables()) {
1024 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1025 // already know about the variable and it isn't adding a constant
1027 auto &GVMapEntry = GVMap[GVE->getVariable()];
1028 auto *Expr = GVE->getExpression();
1029 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1030 GVMapEntry.push_back({nullptr, Expr});
1032 DenseSet<DIGlobalVariable *> Processed;
1033 for (auto *GVE : CUNode->getGlobalVariables()) {
1034 DIGlobalVariable *GV = GVE->getVariable();
1035 if (Processed.insert(GV).second)
1036 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1039 for (auto *Ty : CUNode->getEnumTypes()) {
1040 // The enum types array by design contains pointers to
1041 // MDNodes rather than DIRefs. Unique them here.
1042 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1044 for (auto *Ty : CUNode->getRetainedTypes()) {
1045 // The retained types array by design contains pointers to
1046 // MDNodes rather than DIRefs. Unique them here.
1047 if (DIType *RT = dyn_cast<DIType>(Ty))
1048 // There is no point in force-emitting a forward declaration.
1049 CU.getOrCreateTypeDIE(RT);
1051 // Emit imported_modules last so that the relevant context is already
1053 for (auto *IE : CUNode->getImportedEntities())
1054 constructAndAddImportedEntityDIE(CU, IE);
1058 void DwarfDebug::finishEntityDefinitions() {
1059 for (const auto &Entity : ConcreteEntities) {
1060 DIE *Die = Entity->getDIE();
1062 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1063 // in the ConcreteEntities list, rather than looking it up again here.
1064 // DIE::getUnit isn't simple - it walks parent pointers, etc.
1065 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1067 Unit->finishEntityDefinition(Entity.get());
1071 void DwarfDebug::finishSubprogramDefinitions() {
1072 for (const DISubprogram *SP : ProcessedSPNodes) {
1073 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1075 getOrCreateDwarfCompileUnit(SP->getUnit()),
1076 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1080 void DwarfDebug::finalizeModuleInfo() {
1081 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1083 finishSubprogramDefinitions();
1085 finishEntityDefinitions();
1087 // Include the DWO file name in the hash if there's more than one CU.
1088 // This handles ThinLTO's situation where imported CUs may very easily be
1089 // duplicate with the same CU partially imported into another ThinLTO unit.
1091 if (CUMap.size() > 1)
1092 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1094 // Handle anything that needs to be done on a per-unit basis after
1095 // all other generation.
1096 for (const auto &P : CUMap) {
1097 auto &TheCU = *P.second;
1098 if (TheCU.getCUNode()->isDebugDirectivesOnly())
1100 // Emit DW_AT_containing_type attribute to connect types with their
1101 // vtable holding type.
1102 TheCU.constructContainingTypeDIEs();
1104 // Add CU specific attributes if we need to add any.
1105 // If we're splitting the dwarf out now that we've got the entire
1106 // CU then add the dwo id to it.
1107 auto *SkCU = TheCU.getSkeleton();
1109 bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1112 dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1113 ? dwarf::DW_AT_dwo_name
1114 : dwarf::DW_AT_GNU_dwo_name;
1115 finishUnitAttributes(TheCU.getCUNode(), TheCU);
1116 TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1117 Asm->TM.Options.MCOptions.SplitDwarfFile);
1118 SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1119 Asm->TM.Options.MCOptions.SplitDwarfFile);
1120 // Emit a unique identifier for this CU.
1122 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
1123 if (getDwarfVersion() >= 5) {
1127 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1128 dwarf::DW_FORM_data8, ID);
1129 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1130 dwarf::DW_FORM_data8, ID);
1133 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1134 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1135 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1139 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1142 // If we have code split among multiple sections or non-contiguous
1143 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1144 // remain in the .o file, otherwise add a DW_AT_low_pc.
1145 // FIXME: We should use ranges allow reordering of code ala
1146 // .subsections_via_symbols in mach-o. This would mean turning on
1147 // ranges for all subprogram DIEs for mach-o.
1148 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1150 if (unsigned NumRanges = TheCU.getRanges().size()) {
1151 if (NumRanges > 1 && useRangesSection())
1152 // A DW_AT_low_pc attribute may also be specified in combination with
1153 // DW_AT_ranges to specify the default base address for use in
1154 // location lists (see Section 2.6.2) and range lists (see Section
1156 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1158 U.setBaseAddress(TheCU.getRanges().front().Begin);
1159 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1162 // We don't keep track of which addresses are used in which CU so this
1163 // is a bit pessimistic under LTO.
1164 if ((!AddrPool.isEmpty() || TheCU.hasRangeLists()) &&
1165 (getDwarfVersion() >= 5 || HasSplitUnit))
1166 U.addAddrTableBase();
1168 if (getDwarfVersion() >= 5) {
1169 if (U.hasRangeLists())
1170 U.addRnglistsBase();
1172 if (!DebugLocs.getLists().empty()) {
1173 if (!useSplitDwarf())
1174 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1176 TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1180 auto *CUNode = cast<DICompileUnit>(P.first);
1181 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
1182 if (CUNode->getMacros()) {
1183 if (useSplitDwarf())
1184 TheCU.addSectionDelta(TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1185 U.getMacroLabelBegin(),
1186 TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1188 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1189 U.getMacroLabelBegin(),
1190 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1194 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1195 for (auto *CUNode : MMI->getModule()->debug_compile_units())
1196 if (CUNode->getDWOId())
1197 getOrCreateDwarfCompileUnit(CUNode);
1199 // Compute DIE offsets and sizes.
1200 InfoHolder.computeSizeAndOffsets();
1201 if (useSplitDwarf())
1202 SkeletonHolder.computeSizeAndOffsets();
1205 // Emit all Dwarf sections that should come after the content.
1206 void DwarfDebug::endModule() {
1207 assert(CurFn == nullptr);
1208 assert(CurMI == nullptr);
1210 for (const auto &P : CUMap) {
1211 auto &CU = *P.second;
1212 CU.createBaseTypeDIEs();
1215 // If we aren't actually generating debug info (check beginModule -
1216 // conditionalized on !DisableDebugInfoPrinting and the presence of the
1217 // llvm.dbg.cu metadata node)
1218 if (!MMI->hasDebugInfo())
1221 // Finalize the debug info for the module.
1222 finalizeModuleInfo();
1226 if (useSplitDwarf())
1227 // Emit debug_loc.dwo/debug_loclists.dwo section.
1230 // Emit debug_loc/debug_loclists section.
1233 // Corresponding abbreviations into a abbrev section.
1234 emitAbbreviations();
1236 // Emit all the DIEs into a debug info section.
1239 // Emit info into a debug aranges section.
1240 if (GenerateARangeSection)
1243 // Emit info into a debug ranges section.
1246 if (useSplitDwarf())
1247 // Emit info into a debug macinfo.dwo section.
1248 emitDebugMacinfoDWO();
1250 // Emit info into a debug macinfo section.
1253 if (useSplitDwarf()) {
1256 emitDebugAbbrevDWO();
1258 emitDebugRangesDWO();
1263 // Emit info into the dwarf accelerator table sections.
1264 switch (getAccelTableKind()) {
1265 case AccelTableKind::Apple:
1268 emitAccelNamespaces();
1271 case AccelTableKind::Dwarf:
1272 emitAccelDebugNames();
1274 case AccelTableKind::None:
1276 case AccelTableKind::Default:
1277 llvm_unreachable("Default should have already been resolved.");
1280 // Emit the pubnames and pubtypes sections if requested.
1281 emitDebugPubSections();
1284 // FIXME: AbstractVariables.clear();
1287 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1289 const MDNode *ScopeNode) {
1290 if (CU.getExistingAbstractEntity(Node))
1293 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1294 cast<DILocalScope>(ScopeNode)));
1297 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1298 const DINode *Node, const MDNode *ScopeNode) {
1299 if (CU.getExistingAbstractEntity(Node))
1302 if (LexicalScope *Scope =
1303 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1304 CU.createAbstractEntity(Node, Scope);
1307 // Collect variable information from side table maintained by MF.
1308 void DwarfDebug::collectVariableInfoFromMFTable(
1309 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1310 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1311 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1314 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1315 "Expected inlined-at fields to agree");
1317 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1318 Processed.insert(Var);
1319 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1321 // If variable scope is not found then skip this variable.
1325 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1326 auto RegVar = std::make_unique<DbgVariable>(
1327 cast<DILocalVariable>(Var.first), Var.second);
1328 RegVar->initializeMMI(VI.Expr, VI.Slot);
1329 if (DbgVariable *DbgVar = MFVars.lookup(Var))
1330 DbgVar->addMMIEntry(*RegVar);
1331 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1332 MFVars.insert({Var, RegVar.get()});
1333 ConcreteEntities.push_back(std::move(RegVar));
1338 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1339 /// enclosing lexical scope. The check ensures there are no other instructions
1340 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1341 /// either open or otherwise rolls off the end of the scope.
1342 static bool validThroughout(LexicalScopes &LScopes,
1343 const MachineInstr *DbgValue,
1344 const MachineInstr *RangeEnd) {
1345 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1346 auto MBB = DbgValue->getParent();
1347 auto DL = DbgValue->getDebugLoc();
1348 auto *LScope = LScopes.findLexicalScope(DL);
1349 // Scope doesn't exist; this is a dead DBG_VALUE.
1352 auto &LSRange = LScope->getRanges();
1353 if (LSRange.size() == 0)
1356 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1357 const MachineInstr *LScopeBegin = LSRange.front().first;
1358 // Early exit if the lexical scope begins outside of the current block.
1359 if (LScopeBegin->getParent() != MBB)
1361 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1362 for (++Pred; Pred != MBB->rend(); ++Pred) {
1363 if (Pred->getFlag(MachineInstr::FrameSetup))
1365 auto PredDL = Pred->getDebugLoc();
1366 if (!PredDL || Pred->isMetaInstruction())
1368 // Check whether the instruction preceding the DBG_VALUE is in the same
1369 // (sub)scope as the DBG_VALUE.
1370 if (DL->getScope() == PredDL->getScope())
1372 auto *PredScope = LScopes.findLexicalScope(PredDL);
1373 if (!PredScope || LScope->dominates(PredScope))
1377 // If the range of the DBG_VALUE is open-ended, report success.
1381 // Fail if there are instructions belonging to our scope in another block.
1382 const MachineInstr *LScopeEnd = LSRange.back().second;
1383 if (LScopeEnd->getParent() != MBB)
1386 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1387 // throughout the function. This is a hack, presumably for DWARF v2 and not
1388 // necessarily correct. It would be much better to use a dbg.declare instead
1389 // if we know the constant is live throughout the scope.
1390 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1396 /// Build the location list for all DBG_VALUEs in the function that
1397 /// describe the same variable. The resulting DebugLocEntries will have
1398 /// strict monotonically increasing begin addresses and will never
1399 /// overlap. If the resulting list has only one entry that is valid
1400 /// throughout variable's scope return true.
1402 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1403 // different kinds of history map entries. One thing to be aware of is that if
1404 // a debug value is ended by another entry (rather than being valid until the
1405 // end of the function), that entry's instruction may or may not be included in
1406 // the range, depending on if the entry is a clobbering entry (it has an
1407 // instruction that clobbers one or more preceding locations), or if it is an
1408 // (overlapping) debug value entry. This distinction can be seen in the example
1409 // below. The first debug value is ended by the clobbering entry 2, and the
1410 // second and third debug values are ended by the overlapping debug value entry
1415 // History map entries [type, end index, mi]
1417 // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1418 // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1419 // 2 | | [Clobber, $reg0 = [...], -, -]
1420 // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1421 // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1423 // Output [start, end) [Value...]:
1425 // [0-1) [(reg0, fragment 0, 32)]
1426 // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1427 // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1428 // [4-) [(@g, fragment 0, 96)]
1429 bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1430 const DbgValueHistoryMap::Entries &Entries) {
1432 std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1433 SmallVector<OpenRange, 4> OpenRanges;
1434 bool isSafeForSingleLocation = true;
1435 const MachineInstr *StartDebugMI = nullptr;
1436 const MachineInstr *EndMI = nullptr;
1438 for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1439 const MachineInstr *Instr = EI->getInstr();
1441 // Remove all values that are no longer live.
1442 size_t Index = std::distance(EB, EI);
1444 remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1445 OpenRanges.erase(Last, OpenRanges.end());
1447 // If we are dealing with a clobbering entry, this iteration will result in
1448 // a location list entry starting after the clobbering instruction.
1449 const MCSymbol *StartLabel =
1450 EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1451 assert(StartLabel &&
1452 "Forgot label before/after instruction starting a range!");
1454 const MCSymbol *EndLabel;
1455 if (std::next(EI) == Entries.end()) {
1456 EndLabel = Asm->getFunctionEnd();
1457 if (EI->isClobber())
1458 EndMI = EI->getInstr();
1460 else if (std::next(EI)->isClobber())
1461 EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1463 EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1464 assert(EndLabel && "Forgot label after instruction ending a range!");
1466 if (EI->isDbgValue())
1467 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1469 // If this history map entry has a debug value, add that to the list of
1470 // open ranges and check if its location is valid for a single value
1472 if (EI->isDbgValue()) {
1473 // Do not add undef debug values, as they are redundant information in
1474 // the location list entries. An undef debug results in an empty location
1475 // description. If there are any non-undef fragments then padding pieces
1476 // with empty location descriptions will automatically be inserted, and if
1477 // all fragments are undef then the whole location list entry is
1479 if (!Instr->isUndefDebugValue()) {
1480 auto Value = getDebugLocValue(Instr);
1481 OpenRanges.emplace_back(EI->getEndIndex(), Value);
1483 // TODO: Add support for single value fragment locations.
1484 if (Instr->getDebugExpression()->isFragment())
1485 isSafeForSingleLocation = false;
1488 StartDebugMI = Instr;
1490 isSafeForSingleLocation = false;
1494 // Location list entries with empty location descriptions are redundant
1495 // information in DWARF, so do not emit those.
1496 if (OpenRanges.empty())
1499 // Omit entries with empty ranges as they do not have any effect in DWARF.
1500 if (StartLabel == EndLabel) {
1501 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1505 SmallVector<DbgValueLoc, 4> Values;
1506 for (auto &R : OpenRanges)
1507 Values.push_back(R.second);
1508 DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1510 // Attempt to coalesce the ranges of two otherwise identical
1512 auto CurEntry = DebugLoc.rbegin();
1514 dbgs() << CurEntry->getValues().size() << " Values:\n";
1515 for (auto &Value : CurEntry->getValues())
1517 dbgs() << "-----\n";
1520 auto PrevEntry = std::next(CurEntry);
1521 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1522 DebugLoc.pop_back();
1525 return DebugLoc.size() == 1 && isSafeForSingleLocation &&
1526 validThroughout(LScopes, StartDebugMI, EndMI);
1529 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1530 LexicalScope &Scope,
1532 const DILocation *Location,
1533 const MCSymbol *Sym) {
1534 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1535 if (isa<const DILocalVariable>(Node)) {
1536 ConcreteEntities.push_back(
1537 std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1539 InfoHolder.addScopeVariable(&Scope,
1540 cast<DbgVariable>(ConcreteEntities.back().get()));
1541 } else if (isa<const DILabel>(Node)) {
1542 ConcreteEntities.push_back(
1543 std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1545 InfoHolder.addScopeLabel(&Scope,
1546 cast<DbgLabel>(ConcreteEntities.back().get()));
1548 return ConcreteEntities.back().get();
1551 // Find variables for each lexical scope.
1552 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1553 const DISubprogram *SP,
1554 DenseSet<InlinedEntity> &Processed) {
1555 // Grab the variable info that was squirreled away in the MMI side-table.
1556 collectVariableInfoFromMFTable(TheCU, Processed);
1558 for (const auto &I : DbgValues) {
1559 InlinedEntity IV = I.first;
1560 if (Processed.count(IV))
1563 // Instruction ranges, specifying where IV is accessible.
1564 const auto &HistoryMapEntries = I.second;
1565 if (HistoryMapEntries.empty())
1568 LexicalScope *Scope = nullptr;
1569 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1570 if (const DILocation *IA = IV.second)
1571 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1573 Scope = LScopes.findLexicalScope(LocalVar->getScope());
1574 // If variable scope is not found then skip this variable.
1578 Processed.insert(IV);
1579 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1580 *Scope, LocalVar, IV.second));
1582 const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1583 assert(MInsn->isDebugValue() && "History must begin with debug value");
1585 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1586 // If the history map contains a single debug value, there may be an
1587 // additional entry which clobbers the debug value.
1588 size_t HistSize = HistoryMapEntries.size();
1589 bool SingleValueWithClobber =
1590 HistSize == 2 && HistoryMapEntries[1].isClobber();
1591 if (HistSize == 1 || SingleValueWithClobber) {
1593 SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1594 if (validThroughout(LScopes, MInsn, End)) {
1595 RegVar->initializeDbgValue(MInsn);
1600 // Do not emit location lists if .debug_loc secton is disabled.
1601 if (!useLocSection())
1604 // Handle multiple DBG_VALUE instructions describing one variable.
1605 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1607 // Build the location list for this variable.
1608 SmallVector<DebugLocEntry, 8> Entries;
1609 bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1611 // Check whether buildLocationList managed to merge all locations to one
1612 // that is valid throughout the variable's scope. If so, produce single
1614 if (isValidSingleLocation) {
1615 RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1619 // If the variable has a DIBasicType, extract it. Basic types cannot have
1620 // unique identifiers, so don't bother resolving the type with the
1622 const DIBasicType *BT = dyn_cast<DIBasicType>(
1623 static_cast<const Metadata *>(LocalVar->getType()));
1625 // Finalize the entry by lowering it into a DWARF bytestream.
1626 for (auto &Entry : Entries)
1627 Entry.finalize(*Asm, List, BT, TheCU);
1630 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1631 // DWARF-related DbgLabel.
1632 for (const auto &I : DbgLabels) {
1633 InlinedEntity IL = I.first;
1634 const MachineInstr *MI = I.second;
1638 LexicalScope *Scope = nullptr;
1639 const DILabel *Label = cast<DILabel>(IL.first);
1640 // The scope could have an extra lexical block file.
1641 const DILocalScope *LocalScope =
1642 Label->getScope()->getNonLexicalBlockFileScope();
1643 // Get inlined DILocation if it is inlined label.
1644 if (const DILocation *IA = IL.second)
1645 Scope = LScopes.findInlinedScope(LocalScope, IA);
1647 Scope = LScopes.findLexicalScope(LocalScope);
1648 // If label scope is not found then skip this label.
1652 Processed.insert(IL);
1653 /// At this point, the temporary label is created.
1654 /// Save the temporary label to DbgLabel entity to get the
1655 /// actually address when generating Dwarf DIE.
1656 MCSymbol *Sym = getLabelBeforeInsn(MI);
1657 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1660 // Collect info for variables/labels that were optimized out.
1661 for (const DINode *DN : SP->getRetainedNodes()) {
1662 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1664 LexicalScope *Scope = nullptr;
1665 if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1666 Scope = LScopes.findLexicalScope(DV->getScope());
1667 } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1668 Scope = LScopes.findLexicalScope(DL->getScope());
1672 createConcreteEntity(TheCU, *Scope, DN, nullptr);
1676 // Process beginning of an instruction.
1677 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1678 DebugHandlerBase::beginInstruction(MI);
1681 const auto *SP = MI->getMF()->getFunction().getSubprogram();
1682 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1685 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1686 // If the instruction is part of the function frame setup code, do not emit
1687 // any line record, as there is no correspondence with any user code.
1688 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1690 const DebugLoc &DL = MI->getDebugLoc();
1691 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1692 // the last line number actually emitted, to see if it was line 0.
1693 unsigned LastAsmLine =
1694 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1696 // Request a label after the call in order to emit AT_return_pc information
1697 // in call site entries. TODO: Add support for targets with delay slots.
1698 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1699 requestLabelAfterInsn(MI);
1701 if (DL == PrevInstLoc) {
1702 // If we have an ongoing unspecified location, nothing to do here.
1705 // We have an explicit location, same as the previous location.
1706 // But we might be coming back to it after a line 0 record.
1707 if (LastAsmLine == 0 && DL.getLine() != 0) {
1708 // Reinstate the source location but not marked as a statement.
1709 const MDNode *Scope = DL.getScope();
1710 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1716 // We have an unspecified location, which might want to be line 0.
1717 // If we have already emitted a line-0 record, don't repeat it.
1718 if (LastAsmLine == 0)
1720 // If user said Don't Do That, don't do that.
1721 if (UnknownLocations == Disable)
1723 // See if we have a reason to emit a line-0 record now.
1724 // Reasons to emit a line-0 record include:
1725 // - User asked for it (UnknownLocations).
1726 // - Instruction has a label, so it's referenced from somewhere else,
1727 // possibly debug information; we want it to have a source location.
1728 // - Instruction is at the top of a block; we don't want to inherit the
1729 // location from the physically previous (maybe unrelated) block.
1730 if (UnknownLocations == Enable || PrevLabel ||
1731 (PrevInstBB && PrevInstBB != MI->getParent())) {
1732 // Preserve the file and column numbers, if we can, to save space in
1733 // the encoded line table.
1734 // Do not update PrevInstLoc, it remembers the last non-0 line.
1735 const MDNode *Scope = nullptr;
1736 unsigned Column = 0;
1738 Scope = PrevInstLoc.getScope();
1739 Column = PrevInstLoc.getCol();
1741 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1746 // We have an explicit location, different from the previous location.
1747 // Don't repeat a line-0 record, but otherwise emit the new location.
1748 // (The new location might be an explicit line 0, which we do emit.)
1749 if (DL.getLine() == 0 && LastAsmLine == 0)
1752 if (DL == PrologEndLoc) {
1753 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1754 PrologEndLoc = DebugLoc();
1756 // If the line changed, we call that a new statement; unless we went to
1757 // line 0 and came back, in which case it is not a new statement.
1758 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1759 if (DL.getLine() && DL.getLine() != OldLine)
1760 Flags |= DWARF2_FLAG_IS_STMT;
1762 const MDNode *Scope = DL.getScope();
1763 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1765 // If we're not at line 0, remember this location.
1770 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1771 // First known non-DBG_VALUE and non-frame setup location marks
1772 // the beginning of the function body.
1773 for (const auto &MBB : *MF)
1774 for (const auto &MI : MBB)
1775 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1777 return MI.getDebugLoc();
1781 /// Register a source line with debug info. Returns the unique label that was
1782 /// emitted and which provides correspondence to the source line list.
1783 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1784 const MDNode *S, unsigned Flags, unsigned CUID,
1785 uint16_t DwarfVersion,
1786 ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1788 unsigned FileNo = 1;
1789 unsigned Discriminator = 0;
1790 if (auto *Scope = cast_or_null<DIScope>(S)) {
1791 Fn = Scope->getFilename();
1792 if (Line != 0 && DwarfVersion >= 4)
1793 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1794 Discriminator = LBF->getDiscriminator();
1796 FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1797 .getOrCreateSourceID(Scope->getFile());
1799 Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1803 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
1805 // Get beginning of function.
1806 if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1807 // Ensure the compile unit is created if the function is called before
1809 (void)getOrCreateDwarfCompileUnit(
1810 MF.getFunction().getSubprogram()->getUnit());
1811 // We'd like to list the prologue as "not statements" but GDB behaves
1812 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1813 const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1814 ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1815 CUID, getDwarfVersion(), getUnits());
1816 return PrologEndLoc;
1821 // Gather pre-function debug information. Assumes being called immediately
1822 // after the function entry point has been emitted.
1823 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1826 auto *SP = MF->getFunction().getSubprogram();
1827 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1828 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1831 SectionLabels.insert(std::make_pair(&Asm->getFunctionBegin()->getSection(),
1832 Asm->getFunctionBegin()));
1834 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1836 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1837 // belongs to so that we add to the correct per-cu line table in the
1839 if (Asm->OutStreamer->hasRawTextSupport())
1840 // Use a single line table if we are generating assembly.
1841 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1843 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1845 // Record beginning of function.
1846 PrologEndLoc = emitInitialLocDirective(
1847 *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1850 void DwarfDebug::skippedNonDebugFunction() {
1851 // If we don't have a subprogram for this function then there will be a hole
1852 // in the range information. Keep note of this by setting the previously used
1853 // section to nullptr.
1858 // Gather and emit post-function debug information.
1859 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1860 const DISubprogram *SP = MF->getFunction().getSubprogram();
1862 assert(CurFn == MF &&
1863 "endFunction should be called with the same function as beginFunction");
1865 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1866 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1868 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1869 assert(!FnScope || SP == FnScope->getScopeNode());
1870 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1871 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1872 PrevLabel = nullptr;
1877 DenseSet<InlinedEntity> Processed;
1878 collectEntityInfo(TheCU, SP, Processed);
1880 // Add the range of this function to the list of ranges for the CU.
1881 TheCU.addRange({Asm->getFunctionBegin(), Asm->getFunctionEnd()});
1883 // Under -gmlt, skip building the subprogram if there are no inlined
1884 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1885 // is still needed as we need its source location.
1886 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1887 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1888 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1889 assert(InfoHolder.getScopeVariables().empty());
1890 PrevLabel = nullptr;
1896 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1898 // Construct abstract scopes.
1899 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1900 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1901 for (const DINode *DN : SP->getRetainedNodes()) {
1902 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1905 const MDNode *Scope = nullptr;
1906 if (auto *DV = dyn_cast<DILocalVariable>(DN))
1907 Scope = DV->getScope();
1908 else if (auto *DL = dyn_cast<DILabel>(DN))
1909 Scope = DL->getScope();
1911 llvm_unreachable("Unexpected DI type!");
1913 // Collect info for variables/labels that were optimized out.
1914 ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1915 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1916 && "ensureAbstractEntityIsCreated inserted abstract scopes");
1918 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1921 ProcessedSPNodes.insert(SP);
1922 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1923 if (auto *SkelCU = TheCU.getSkeleton())
1924 if (!LScopes.getAbstractScopesList().empty() &&
1925 TheCU.getCUNode()->getSplitDebugInlining())
1926 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1928 // Construct call site entries.
1929 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1932 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1933 // DbgVariables except those that are also in AbstractVariables (since they
1934 // can be used cross-function)
1935 InfoHolder.getScopeVariables().clear();
1936 InfoHolder.getScopeLabels().clear();
1937 PrevLabel = nullptr;
1941 // Register a source line with debug info. Returns the unique label that was
1942 // emitted and which provides correspondence to the source line list.
1943 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1945 ::recordSourceLine(*Asm, Line, Col, S, Flags,
1946 Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
1947 getDwarfVersion(), getUnits());
1950 //===----------------------------------------------------------------------===//
1952 //===----------------------------------------------------------------------===//
1954 // Emit the debug info section.
1955 void DwarfDebug::emitDebugInfo() {
1956 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1957 Holder.emitUnits(/* UseOffsets */ false);
1960 // Emit the abbreviation section.
1961 void DwarfDebug::emitAbbreviations() {
1962 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1964 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1967 void DwarfDebug::emitStringOffsetsTableHeader() {
1968 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1969 Holder.getStringPool().emitStringOffsetsTableHeader(
1970 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1971 Holder.getStringOffsetsStartSym());
1974 template <typename AccelTableT>
1975 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1976 StringRef TableName) {
1977 Asm->OutStreamer->SwitchSection(Section);
1979 // Emit the full data.
1980 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1983 void DwarfDebug::emitAccelDebugNames() {
1984 // Don't emit anything if we have no compilation units to index.
1985 if (getUnits().empty())
1988 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1991 // Emit visible names into a hashed accelerator table section.
1992 void DwarfDebug::emitAccelNames() {
1993 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1997 // Emit objective C classes and categories into a hashed accelerator table
1999 void DwarfDebug::emitAccelObjC() {
2000 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2004 // Emit namespace dies into a hashed accelerator table.
2005 void DwarfDebug::emitAccelNamespaces() {
2006 emitAccel(AccelNamespace,
2007 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2011 // Emit type dies into a hashed accelerator table.
2012 void DwarfDebug::emitAccelTypes() {
2013 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2017 // Public name handling.
2018 // The format for the various pubnames:
2020 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2021 // for the DIE that is named.
2023 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2024 // into the CU and the index value is computed according to the type of value
2025 // for the DIE that is named.
2027 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2028 // it's the offset within the debug_info/debug_types dwo section, however, the
2029 // reference in the pubname header doesn't change.
2031 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2032 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2034 // Entities that ended up only in a Type Unit reference the CU instead (since
2035 // the pub entry has offsets within the CU there's no real offset that can be
2036 // provided anyway). As it happens all such entities (namespaces and types,
2037 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2038 // not to be true it would be necessary to persist this information from the
2039 // point at which the entry is added to the index data structure - since by
2040 // the time the index is built from that, the original type/namespace DIE in a
2041 // type unit has already been destroyed so it can't be queried for properties
2043 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2044 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2045 dwarf::GIEL_EXTERNAL);
2046 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2048 // We could have a specification DIE that has our most of our knowledge,
2049 // look for that now.
2050 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2051 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2052 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2053 Linkage = dwarf::GIEL_EXTERNAL;
2054 } else if (Die->findAttribute(dwarf::DW_AT_external))
2055 Linkage = dwarf::GIEL_EXTERNAL;
2057 switch (Die->getTag()) {
2058 case dwarf::DW_TAG_class_type:
2059 case dwarf::DW_TAG_structure_type:
2060 case dwarf::DW_TAG_union_type:
2061 case dwarf::DW_TAG_enumeration_type:
2062 return dwarf::PubIndexEntryDescriptor(
2064 dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2065 ? dwarf::GIEL_EXTERNAL
2066 : dwarf::GIEL_STATIC);
2067 case dwarf::DW_TAG_typedef:
2068 case dwarf::DW_TAG_base_type:
2069 case dwarf::DW_TAG_subrange_type:
2070 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2071 case dwarf::DW_TAG_namespace:
2072 return dwarf::GIEK_TYPE;
2073 case dwarf::DW_TAG_subprogram:
2074 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2075 case dwarf::DW_TAG_variable:
2076 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2077 case dwarf::DW_TAG_enumerator:
2078 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2079 dwarf::GIEL_STATIC);
2081 return dwarf::GIEK_NONE;
2085 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2086 /// pubtypes sections.
2087 void DwarfDebug::emitDebugPubSections() {
2088 for (const auto &NU : CUMap) {
2089 DwarfCompileUnit *TheU = NU.second;
2090 if (!TheU->hasDwarfPubSections())
2093 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2094 DICompileUnit::DebugNameTableKind::GNU;
2096 Asm->OutStreamer->SwitchSection(
2097 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2098 : Asm->getObjFileLowering().getDwarfPubNamesSection());
2099 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2101 Asm->OutStreamer->SwitchSection(
2102 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2103 : Asm->getObjFileLowering().getDwarfPubTypesSection());
2104 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2108 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2109 if (useSectionsAsReferences())
2110 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
2111 CU.getDebugSectionOffset());
2113 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2116 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2117 DwarfCompileUnit *TheU,
2118 const StringMap<const DIE *> &Globals) {
2119 if (auto *Skeleton = TheU->getSkeleton())
2123 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
2124 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2125 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2126 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2128 Asm->OutStreamer->EmitLabel(BeginLabel);
2130 Asm->OutStreamer->AddComment("DWARF Version");
2131 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2133 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2134 emitSectionReference(*TheU);
2136 Asm->OutStreamer->AddComment("Compilation Unit Length");
2137 Asm->emitInt32(TheU->getLength());
2139 // Emit the pubnames for this compilation unit.
2140 for (const auto &GI : Globals) {
2141 const char *Name = GI.getKeyData();
2142 const DIE *Entity = GI.second;
2144 Asm->OutStreamer->AddComment("DIE offset");
2145 Asm->emitInt32(Entity->getOffset());
2148 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2149 Asm->OutStreamer->AddComment(
2150 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2151 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2152 Asm->emitInt8(Desc.toBits());
2155 Asm->OutStreamer->AddComment("External Name");
2156 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2159 Asm->OutStreamer->AddComment("End Mark");
2161 Asm->OutStreamer->EmitLabel(EndLabel);
2164 /// Emit null-terminated strings into a debug str section.
2165 void DwarfDebug::emitDebugStr() {
2166 MCSection *StringOffsetsSection = nullptr;
2167 if (useSegmentedStringOffsetsTable()) {
2168 emitStringOffsetsTableHeader();
2169 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2171 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2172 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2173 StringOffsetsSection, /* UseRelativeOffsets = */ true);
2176 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2177 const DebugLocStream::Entry &Entry,
2178 const DwarfCompileUnit *CU) {
2179 auto &&Comments = DebugLocs.getComments(Entry);
2180 auto Comment = Comments.begin();
2181 auto End = Comments.end();
2183 // The expressions are inserted into a byte stream rather early (see
2184 // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2185 // need to reference a base_type DIE the offset of that DIE is not yet known.
2186 // To deal with this we instead insert a placeholder early and then extract
2187 // it here and replace it with the real reference.
2188 unsigned PtrSize = Asm->MAI->getCodePointerSize();
2189 DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2190 DebugLocs.getBytes(Entry).size()),
2191 Asm->getDataLayout().isLittleEndian(), PtrSize);
2192 DWARFExpression Expr(Data, getDwarfVersion(), PtrSize);
2194 using Encoding = DWARFExpression::Operation::Encoding;
2195 uint64_t Offset = 0;
2196 for (auto &Op : Expr) {
2197 assert(Op.getCode() != dwarf::DW_OP_const_type &&
2198 "3 operand ops not yet supported");
2199 Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2201 for (unsigned I = 0; I < 2; ++I) {
2202 if (Op.getDescription().Op[I] == Encoding::SizeNA)
2204 if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2206 uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2207 assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
2208 Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize);
2210 // Emit a reference to the 'generic type'.
2211 Asm->EmitULEB128(0, nullptr, ULEB128PadSize);
2213 // Make sure comments stay aligned.
2214 for (unsigned J = 0; J < ULEB128PadSize; ++J)
2218 for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2219 Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2221 Offset = Op.getOperandEndOffset(I);
2223 assert(Offset == Op.getEndOffset());
2227 void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2228 const DbgValueLoc &Value,
2229 DwarfExpression &DwarfExpr) {
2230 auto *DIExpr = Value.getExpression();
2231 DIExpressionCursor ExprCursor(DIExpr);
2232 DwarfExpr.addFragmentOffset(DIExpr);
2234 if (Value.isInt()) {
2235 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2236 BT->getEncoding() == dwarf::DW_ATE_signed_char))
2237 DwarfExpr.addSignedConstant(Value.getInt());
2239 DwarfExpr.addUnsignedConstant(Value.getInt());
2240 } else if (Value.isLocation()) {
2241 MachineLocation Location = Value.getLoc();
2242 if (Location.isIndirect())
2243 DwarfExpr.setMemoryLocationKind();
2244 DIExpressionCursor Cursor(DIExpr);
2246 if (DIExpr->isEntryValue()) {
2247 DwarfExpr.setEntryValueFlag();
2248 DwarfExpr.beginEntryValueExpression(Cursor);
2251 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2252 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2254 return DwarfExpr.addExpression(std::move(Cursor));
2255 } else if (Value.isTargetIndexLocation()) {
2256 TargetIndexLocation Loc = Value.getTargetIndexLocation();
2257 // TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific
2258 // encoding is supported.
2259 DwarfExpr.addWasmLocation(Loc.Index, Loc.Offset);
2260 } else if (Value.isConstantFP()) {
2261 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2262 DwarfExpr.addUnsignedConstant(RawBytes);
2264 DwarfExpr.addExpression(std::move(ExprCursor));
2267 void DebugLocEntry::finalize(const AsmPrinter &AP,
2268 DebugLocStream::ListBuilder &List,
2269 const DIBasicType *BT,
2270 DwarfCompileUnit &TheCU) {
2271 assert(!Values.empty() &&
2272 "location list entries without values are redundant");
2273 assert(Begin != End && "unexpected location list entry with empty range");
2274 DebugLocStream::EntryBuilder Entry(List, Begin, End);
2275 BufferByteStreamer Streamer = Entry.getStreamer();
2276 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2277 const DbgValueLoc &Value = Values[0];
2278 if (Value.isFragment()) {
2279 // Emit all fragments that belong to the same variable and range.
2280 assert(llvm::all_of(Values, [](DbgValueLoc P) {
2281 return P.isFragment();
2282 }) && "all values are expected to be fragments");
2283 assert(std::is_sorted(Values.begin(), Values.end()) &&
2284 "fragments are expected to be sorted");
2286 for (auto Fragment : Values)
2287 DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2290 assert(Values.size() == 1 && "only fragments may have >1 value");
2291 DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2293 DwarfExpr.finalize();
2294 if (DwarfExpr.TagOffset)
2295 List.setTagOffset(*DwarfExpr.TagOffset);
2298 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2299 const DwarfCompileUnit *CU) {
2301 Asm->OutStreamer->AddComment("Loc expr size");
2302 if (getDwarfVersion() >= 5)
2303 Asm->EmitULEB128(DebugLocs.getBytes(Entry).size());
2304 else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2305 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2307 // The entry is too big to fit into 16 bit, drop it as there is nothing we
2313 APByteStreamer Streamer(*Asm);
2314 emitDebugLocEntry(Streamer, Entry, CU);
2317 // Emit the common part of the DWARF 5 range/locations list tables header.
2318 static void emitListsTableHeaderStart(AsmPrinter *Asm,
2319 MCSymbol *TableStart,
2320 MCSymbol *TableEnd) {
2321 // Build the table header, which starts with the length field.
2322 Asm->OutStreamer->AddComment("Length");
2323 Asm->EmitLabelDifference(TableEnd, TableStart, 4);
2324 Asm->OutStreamer->EmitLabel(TableStart);
2325 // Version number (DWARF v5 and later).
2326 Asm->OutStreamer->AddComment("Version");
2327 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
2329 Asm->OutStreamer->AddComment("Address size");
2330 Asm->emitInt8(Asm->MAI->getCodePointerSize());
2331 // Segment selector size.
2332 Asm->OutStreamer->AddComment("Segment selector size");
2336 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2337 // that designates the end of the table for the caller to emit when the table is
2339 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2340 const DwarfFile &Holder) {
2341 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2342 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2343 emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2345 Asm->OutStreamer->AddComment("Offset entry count");
2346 Asm->emitInt32(Holder.getRangeLists().size());
2347 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
2349 for (const RangeSpanList &List : Holder.getRangeLists())
2350 Asm->EmitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2356 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2357 // designates the end of the table for the caller to emit when the table is
2359 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2360 const DwarfDebug &DD) {
2361 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2362 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2363 emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2365 const auto &DebugLocs = DD.getDebugLocs();
2367 Asm->OutStreamer->AddComment("Offset entry count");
2368 Asm->emitInt32(DebugLocs.getLists().size());
2369 Asm->OutStreamer->EmitLabel(DebugLocs.getSym());
2371 for (const auto &List : DebugLocs.getLists())
2372 Asm->EmitLabelDifference(List.Label, DebugLocs.getSym(), 4);
2377 template <typename Ranges, typename PayloadEmitter>
2378 static void emitRangeList(
2379 DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2380 const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2381 unsigned StartxLength, unsigned EndOfList,
2382 StringRef (*StringifyEnum)(unsigned),
2383 bool ShouldUseBaseAddress,
2384 PayloadEmitter EmitPayload) {
2386 auto Size = Asm->MAI->getCodePointerSize();
2387 bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2389 // Emit our symbol so we can find the beginning of the range.
2390 Asm->OutStreamer->EmitLabel(Sym);
2392 // Gather all the ranges that apply to the same section so they can share
2393 // a base address entry.
2394 MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2396 for (const auto &Range : R)
2397 SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2399 const MCSymbol *CUBase = CU.getBaseAddress();
2400 bool BaseIsSet = false;
2401 for (const auto &P : SectionRanges) {
2402 auto *Base = CUBase;
2403 if (!Base && ShouldUseBaseAddress) {
2404 const MCSymbol *Begin = P.second.front()->Begin;
2405 const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2409 Asm->OutStreamer->EmitIntValue(-1, Size);
2410 Asm->OutStreamer->AddComment(" base address");
2411 Asm->OutStreamer->EmitSymbolValue(Base, Size);
2412 } else if (NewBase != Begin || P.second.size() > 1) {
2413 // Only use a base address if
2414 // * the existing pool address doesn't match (NewBase != Begin)
2415 // * or, there's more than one entry to share the base address
2418 Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2419 Asm->emitInt8(BaseAddressx);
2420 Asm->OutStreamer->AddComment(" base address index");
2421 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2423 } else if (BaseIsSet && !UseDwarf5) {
2426 Asm->OutStreamer->EmitIntValue(-1, Size);
2427 Asm->OutStreamer->EmitIntValue(0, Size);
2430 for (const auto *RS : P.second) {
2431 const MCSymbol *Begin = RS->Begin;
2432 const MCSymbol *End = RS->End;
2433 assert(Begin && "Range without a begin symbol?");
2434 assert(End && "Range without an end symbol?");
2437 // Emit offset_pair when we have a base.
2438 Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2439 Asm->emitInt8(OffsetPair);
2440 Asm->OutStreamer->AddComment(" starting offset");
2441 Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2442 Asm->OutStreamer->AddComment(" ending offset");
2443 Asm->EmitLabelDifferenceAsULEB128(End, Base);
2445 Asm->EmitLabelDifference(Begin, Base, Size);
2446 Asm->EmitLabelDifference(End, Base, Size);
2448 } else if (UseDwarf5) {
2449 Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2450 Asm->emitInt8(StartxLength);
2451 Asm->OutStreamer->AddComment(" start index");
2452 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2453 Asm->OutStreamer->AddComment(" length");
2454 Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2456 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2457 Asm->OutStreamer->EmitSymbolValue(End, Size);
2464 Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2465 Asm->emitInt8(EndOfList);
2467 // Terminate the list with two 0 values.
2468 Asm->OutStreamer->EmitIntValue(0, Size);
2469 Asm->OutStreamer->EmitIntValue(0, Size);
2473 // Handles emission of both debug_loclist / debug_loclist.dwo
2474 static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2475 emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2476 *List.CU, dwarf::DW_LLE_base_addressx,
2477 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2478 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2479 /* ShouldUseBaseAddress */ true,
2480 [&](const DebugLocStream::Entry &E) {
2481 DD.emitDebugLocEntryLocation(E, List.CU);
2485 void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2486 if (DebugLocs.getLists().empty())
2489 Asm->OutStreamer->SwitchSection(Sec);
2491 MCSymbol *TableEnd = nullptr;
2492 if (getDwarfVersion() >= 5)
2493 TableEnd = emitLoclistsTableHeader(Asm, *this);
2495 for (const auto &List : DebugLocs.getLists())
2496 emitLocList(*this, Asm, List);
2499 Asm->OutStreamer->EmitLabel(TableEnd);
2502 // Emit locations into the .debug_loc/.debug_loclists section.
2503 void DwarfDebug::emitDebugLoc() {
2505 getDwarfVersion() >= 5
2506 ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2507 : Asm->getObjFileLowering().getDwarfLocSection());
2510 // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2511 void DwarfDebug::emitDebugLocDWO() {
2512 if (getDwarfVersion() >= 5) {
2514 Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2519 for (const auto &List : DebugLocs.getLists()) {
2520 Asm->OutStreamer->SwitchSection(
2521 Asm->getObjFileLowering().getDwarfLocDWOSection());
2522 Asm->OutStreamer->EmitLabel(List.Label);
2524 for (const auto &Entry : DebugLocs.getEntries(List)) {
2525 // GDB only supports startx_length in pre-standard split-DWARF.
2526 // (in v5 standard loclists, it currently* /only/ supports base_address +
2527 // offset_pair, so the implementations can't really share much since they
2528 // need to use different representations)
2529 // * as of October 2018, at least
2530 // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2531 // in the address pool to minimize object size/relocations.
2532 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2533 unsigned idx = AddrPool.getIndex(Entry.Begin);
2534 Asm->EmitULEB128(idx);
2535 // Also the pre-standard encoding is slightly different, emitting this as
2536 // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2537 Asm->EmitLabelDifference(Entry.End, Entry.Begin, 4);
2538 emitDebugLocEntryLocation(Entry, List.CU);
2540 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2545 const MCSymbol *Start, *End;
2548 // Emit a debug aranges section, containing a CU lookup for any
2549 // address we can tie back to a CU.
2550 void DwarfDebug::emitDebugARanges() {
2551 // Provides a unique id per text section.
2552 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2554 // Filter labels by section.
2555 for (const SymbolCU &SCU : ArangeLabels) {
2556 if (SCU.Sym->isInSection()) {
2557 // Make a note of this symbol and it's section.
2558 MCSection *Section = &SCU.Sym->getSection();
2559 if (!Section->getKind().isMetadata())
2560 SectionMap[Section].push_back(SCU);
2562 // Some symbols (e.g. common/bss on mach-o) can have no section but still
2563 // appear in the output. This sucks as we rely on sections to build
2564 // arange spans. We can do it without, but it's icky.
2565 SectionMap[nullptr].push_back(SCU);
2569 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2571 for (auto &I : SectionMap) {
2572 MCSection *Section = I.first;
2573 SmallVector<SymbolCU, 8> &List = I.second;
2574 if (List.size() < 1)
2577 // If we have no section (e.g. common), just write out
2578 // individual spans for each symbol.
2580 for (const SymbolCU &Cur : List) {
2582 Span.Start = Cur.Sym;
2585 Spans[Cur.CU].push_back(Span);
2590 // Sort the symbols by offset within the section.
2591 llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2592 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2593 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2595 // Symbols with no order assigned should be placed at the end.
2596 // (e.g. section end labels)
2604 // Insert a final terminator.
2605 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2607 // Build spans between each label.
2608 const MCSymbol *StartSym = List[0].Sym;
2609 for (size_t n = 1, e = List.size(); n < e; n++) {
2610 const SymbolCU &Prev = List[n - 1];
2611 const SymbolCU &Cur = List[n];
2613 // Try and build the longest span we can within the same CU.
2614 if (Cur.CU != Prev.CU) {
2616 Span.Start = StartSym;
2619 Spans[Prev.CU].push_back(Span);
2625 // Start the dwarf aranges section.
2626 Asm->OutStreamer->SwitchSection(
2627 Asm->getObjFileLowering().getDwarfARangesSection());
2629 unsigned PtrSize = Asm->MAI->getCodePointerSize();
2631 // Build a list of CUs used.
2632 std::vector<DwarfCompileUnit *> CUs;
2633 for (const auto &it : Spans) {
2634 DwarfCompileUnit *CU = it.first;
2638 // Sort the CU list (again, to ensure consistent output order).
2639 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2640 return A->getUniqueID() < B->getUniqueID();
2643 // Emit an arange table for each CU we used.
2644 for (DwarfCompileUnit *CU : CUs) {
2645 std::vector<ArangeSpan> &List = Spans[CU];
2647 // Describe the skeleton CU's offset and length, not the dwo file's.
2648 if (auto *Skel = CU->getSkeleton())
2651 // Emit size of content not including length itself.
2652 unsigned ContentSize =
2653 sizeof(int16_t) + // DWARF ARange version number
2654 sizeof(int32_t) + // Offset of CU in the .debug_info section
2655 sizeof(int8_t) + // Pointer Size (in bytes)
2656 sizeof(int8_t); // Segment Size (in bytes)
2658 unsigned TupleSize = PtrSize * 2;
2660 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2662 offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
2664 ContentSize += Padding;
2665 ContentSize += (List.size() + 1) * TupleSize;
2667 // For each compile unit, write the list of spans it covers.
2668 Asm->OutStreamer->AddComment("Length of ARange Set");
2669 Asm->emitInt32(ContentSize);
2670 Asm->OutStreamer->AddComment("DWARF Arange version number");
2671 Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2672 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2673 emitSectionReference(*CU);
2674 Asm->OutStreamer->AddComment("Address Size (in bytes)");
2675 Asm->emitInt8(PtrSize);
2676 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2679 Asm->OutStreamer->emitFill(Padding, 0xff);
2681 for (const ArangeSpan &Span : List) {
2682 Asm->EmitLabelReference(Span.Start, PtrSize);
2684 // Calculate the size as being from the span start to it's end.
2686 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2688 // For symbols without an end marker (e.g. common), we
2689 // write a single arange entry containing just that one symbol.
2690 uint64_t Size = SymSize[Span.Start];
2694 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2698 Asm->OutStreamer->AddComment("ARange terminator");
2699 Asm->OutStreamer->EmitIntValue(0, PtrSize);
2700 Asm->OutStreamer->EmitIntValue(0, PtrSize);
2704 /// Emit a single range list. We handle both DWARF v5 and earlier.
2705 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2706 const RangeSpanList &List) {
2707 emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
2708 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
2709 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
2710 llvm::dwarf::RangeListEncodingString,
2711 List.CU->getCUNode()->getRangesBaseAddress() ||
2712 DD.getDwarfVersion() >= 5,
2716 void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2717 if (Holder.getRangeLists().empty())
2720 assert(useRangesSection());
2721 assert(!CUMap.empty());
2722 assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2723 return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2726 Asm->OutStreamer->SwitchSection(Section);
2728 MCSymbol *TableEnd = nullptr;
2729 if (getDwarfVersion() >= 5)
2730 TableEnd = emitRnglistsTableHeader(Asm, Holder);
2732 for (const RangeSpanList &List : Holder.getRangeLists())
2733 emitRangeList(*this, Asm, List);
2736 Asm->OutStreamer->EmitLabel(TableEnd);
2739 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2740 /// .debug_rnglists section.
2741 void DwarfDebug::emitDebugRanges() {
2742 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2744 emitDebugRangesImpl(Holder,
2745 getDwarfVersion() >= 5
2746 ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2747 : Asm->getObjFileLowering().getDwarfRangesSection());
2750 void DwarfDebug::emitDebugRangesDWO() {
2751 emitDebugRangesImpl(InfoHolder,
2752 Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2755 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2756 for (auto *MN : Nodes) {
2757 if (auto *M = dyn_cast<DIMacro>(MN))
2759 else if (auto *F = dyn_cast<DIMacroFile>(MN))
2760 emitMacroFile(*F, U);
2762 llvm_unreachable("Unexpected DI type!");
2766 void DwarfDebug::emitMacro(DIMacro &M) {
2767 Asm->EmitULEB128(M.getMacinfoType());
2768 Asm->EmitULEB128(M.getLine());
2769 StringRef Name = M.getName();
2770 StringRef Value = M.getValue();
2771 Asm->OutStreamer->EmitBytes(Name);
2772 if (!Value.empty()) {
2773 // There should be one space between macro name and macro value.
2775 Asm->OutStreamer->EmitBytes(Value);
2777 Asm->emitInt8('\0');
2780 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2781 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2782 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2783 Asm->EmitULEB128(F.getLine());
2784 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2785 handleMacroNodes(F.getElements(), U);
2786 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2789 void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
2790 for (const auto &P : CUMap) {
2791 auto &TheCU = *P.second;
2792 auto *SkCU = TheCU.getSkeleton();
2793 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2794 auto *CUNode = cast<DICompileUnit>(P.first);
2795 DIMacroNodeArray Macros = CUNode->getMacros();
2798 Asm->OutStreamer->SwitchSection(Section);
2799 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2800 handleMacroNodes(Macros, U);
2801 Asm->OutStreamer->AddComment("End Of Macro List Mark");
2806 /// Emit macros into a debug macinfo section.
2807 void DwarfDebug::emitDebugMacinfo() {
2808 emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoSection());
2811 void DwarfDebug::emitDebugMacinfoDWO() {
2812 emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoDWOSection());
2815 // DWARF5 Experimental Separate Dwarf emitters.
2817 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2818 std::unique_ptr<DwarfCompileUnit> NewU) {
2820 if (!CompilationDir.empty())
2821 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2823 addGnuPubAttributes(*NewU, Die);
2825 SkeletonHolder.addUnit(std::move(NewU));
2828 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2830 auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
2831 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
2832 UnitKind::Skeleton);
2833 DwarfCompileUnit &NewCU = *OwnedUnit;
2834 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2836 NewCU.initStmtList();
2838 if (useSegmentedStringOffsetsTable())
2839 NewCU.addStringOffsetsStart();
2841 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2846 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2847 // compile units that would normally be in debug_info.
2848 void DwarfDebug::emitDebugInfoDWO() {
2849 assert(useSplitDwarf() && "No split dwarf debug info?");
2850 // Don't emit relocations into the dwo file.
2851 InfoHolder.emitUnits(/* UseOffsets */ true);
2854 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2855 // abbreviations for the .debug_info.dwo section.
2856 void DwarfDebug::emitDebugAbbrevDWO() {
2857 assert(useSplitDwarf() && "No split dwarf?");
2858 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2861 void DwarfDebug::emitDebugLineDWO() {
2862 assert(useSplitDwarf() && "No split dwarf?");
2863 SplitTypeUnitFileTable.Emit(
2864 *Asm->OutStreamer, MCDwarfLineTableParams(),
2865 Asm->getObjFileLowering().getDwarfLineDWOSection());
2868 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2869 assert(useSplitDwarf() && "No split dwarf?");
2870 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2871 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2872 InfoHolder.getStringOffsetsStartSym());
2875 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2876 // string section and is identical in format to traditional .debug_str
2878 void DwarfDebug::emitDebugStrDWO() {
2879 if (useSegmentedStringOffsetsTable())
2880 emitStringOffsetsTableHeaderDWO();
2881 assert(useSplitDwarf() && "No split dwarf?");
2882 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2883 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2884 OffSec, /* UseRelativeOffsets = */ false);
2887 // Emit address pool.
2888 void DwarfDebug::emitDebugAddr() {
2889 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2892 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2893 if (!useSplitDwarf())
2895 const DICompileUnit *DIUnit = CU.getCUNode();
2896 SplitTypeUnitFileTable.maybeSetRootFile(
2897 DIUnit->getDirectory(), DIUnit->getFilename(),
2898 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2899 return &SplitTypeUnitFileTable;
2902 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2904 Hash.update(Identifier);
2905 // ... take the least significant 8 bytes and return those. Our MD5
2906 // implementation always returns its results in little endian, so we actually
2907 // need the "high" word.
2908 MD5::MD5Result Result;
2910 return Result.high();
2913 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2914 StringRef Identifier, DIE &RefDie,
2915 const DICompositeType *CTy) {
2916 // Fast path if we're building some type units and one has already used the
2917 // address pool we know we're going to throw away all this work anyway, so
2918 // don't bother building dependent types.
2919 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2922 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2924 CU.addDIETypeSignature(RefDie, Ins.first->second);
2928 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2929 AddrPool.resetUsedFlag();
2931 auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2932 getDwoLineTable(CU));
2933 DwarfTypeUnit &NewTU = *OwnedUnit;
2934 DIE &UnitDie = NewTU.getUnitDie();
2935 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2937 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2940 uint64_t Signature = makeTypeSignature(Identifier);
2941 NewTU.setTypeSignature(Signature);
2942 Ins.first->second = Signature;
2944 if (useSplitDwarf()) {
2945 MCSection *Section =
2946 getDwarfVersion() <= 4
2947 ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2948 : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2949 NewTU.setSection(Section);
2951 MCSection *Section =
2952 getDwarfVersion() <= 4
2953 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2954 : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2955 NewTU.setSection(Section);
2956 // Non-split type units reuse the compile unit's line table.
2957 CU.applyStmtList(UnitDie);
2960 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2962 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2963 NewTU.addStringOffsetsStart();
2965 NewTU.setType(NewTU.createTypeDIE(CTy));
2968 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2969 TypeUnitsUnderConstruction.clear();
2971 // Types referencing entries in the address table cannot be placed in type
2973 if (AddrPool.hasBeenUsed()) {
2975 // Remove all the types built while building this type.
2976 // This is pessimistic as some of these types might not be dependent on
2977 // the type that used an address.
2978 for (const auto &TU : TypeUnitsToAdd)
2979 TypeSignatures.erase(TU.second);
2981 // Construct this type in the CU directly.
2982 // This is inefficient because all the dependent types will be rebuilt
2983 // from scratch, including building them in type units, discovering that
2984 // they depend on addresses, throwing them out and rebuilding them.
2985 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2989 // If the type wasn't dependent on fission addresses, finish adding the type
2990 // and all its dependent types.
2991 for (auto &TU : TypeUnitsToAdd) {
2992 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2993 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2996 CU.addDIETypeSignature(RefDie, Signature);
2999 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
3001 TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
3002 DD->TypeUnitsUnderConstruction.clear();
3003 assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
3006 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3007 DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3008 DD->AddrPool.resetUsedFlag();
3011 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3012 return NonTypeUnitContext(this);
3015 // Add the Name along with its companion DIE to the appropriate accelerator
3016 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3017 // AccelTableKind::Apple, we use the table we got as an argument). If
3018 // accelerator tables are disabled, this function does nothing.
3019 template <typename DataT>
3020 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3021 AccelTable<DataT> &AppleAccel, StringRef Name,
3023 if (getAccelTableKind() == AccelTableKind::None)
3026 if (getAccelTableKind() != AccelTableKind::Apple &&
3027 CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3030 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3031 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3033 switch (getAccelTableKind()) {
3034 case AccelTableKind::Apple:
3035 AppleAccel.addName(Ref, Die);
3037 case AccelTableKind::Dwarf:
3038 AccelDebugNames.addName(Ref, Die);
3040 case AccelTableKind::Default:
3041 llvm_unreachable("Default should have already been resolved.");
3042 case AccelTableKind::None:
3043 llvm_unreachable("None handled above");
3047 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3049 addAccelNameImpl(CU, AccelNames, Name, Die);
3052 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3054 // ObjC names go only into the Apple accelerator tables.
3055 if (getAccelTableKind() == AccelTableKind::Apple)
3056 addAccelNameImpl(CU, AccelObjC, Name, Die);
3059 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3061 addAccelNameImpl(CU, AccelNamespace, Name, Die);
3064 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3065 const DIE &Die, char Flags) {
3066 addAccelNameImpl(CU, AccelTypes, Name, Die);
3069 uint16_t DwarfDebug::getDwarfVersion() const {
3070 return Asm->OutStreamer->getContext().getDwarfVersion();
3073 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3074 return SectionLabels.find(S)->second;