1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfExpression.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/DIE.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
110 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
111 : dwarf::OperationEncodingString(Op));
114 void DebugLocDwarfExpression::EmitSigned(int Value) {
115 BS.EmitSLEB128(Value, Twine(Value));
118 void DebugLocDwarfExpression::EmitUnsigned(unsigned Value) {
119 BS.EmitULEB128(Value, Twine(Value));
122 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
123 // This information is not available while emitting .debug_loc entries.
127 //===----------------------------------------------------------------------===//
129 /// resolve - Look in the DwarfDebug map for the MDNode that
130 /// corresponds to the reference.
131 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
132 return DD->resolve(Ref);
135 bool DbgVariable::isBlockByrefVariable() const {
136 assert(Var.isVariable() && "Invalid complex DbgVariable!");
137 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
140 DIType DbgVariable::getType() const {
141 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
142 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
143 // addresses instead.
144 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
145 /* Byref variables, in Blocks, are declared by the programmer as
146 "SomeType VarName;", but the compiler creates a
147 __Block_byref_x_VarName struct, and gives the variable VarName
148 either the struct, or a pointer to the struct, as its type. This
149 is necessary for various behind-the-scenes things the compiler
150 needs to do with by-reference variables in blocks.
152 However, as far as the original *programmer* is concerned, the
153 variable should still have type 'SomeType', as originally declared.
155 The following function dives into the __Block_byref_x_VarName
156 struct to find the original type of the variable. This will be
157 passed back to the code generating the type for the Debug
158 Information Entry for the variable 'VarName'. 'VarName' will then
159 have the original type 'SomeType' in its debug information.
161 The original type 'SomeType' will be the type of the field named
162 'VarName' inside the __Block_byref_x_VarName struct.
164 NOTE: In order for this to not completely fail on the debugger
165 side, the Debug Information Entry for the variable VarName needs to
166 have a DW_AT_location that tells the debugger how to unwind through
167 the pointers and __Block_byref_x_VarName struct to find the actual
168 value of the variable. The function addBlockByrefType does this. */
170 uint16_t tag = Ty.getTag();
172 if (tag == dwarf::DW_TAG_pointer_type)
173 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
175 DIArray Elements = DICompositeType(subType).getElements();
176 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
177 DIDerivedType DT(Elements.getElement(i));
178 if (getName() == DT.getName())
179 return (resolve(DT.getTypeDerivedFrom()));
185 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
186 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
187 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
188 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
192 InfoHolder(A, "info_string", DIEValueAllocator),
193 UsedNonDefaultText(false),
194 SkeletonHolder(A, "skel_string", DIEValueAllocator),
195 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196 IsPS4(Triple(A->getTargetTriple()).isPS4()),
197 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
198 dwarf::DW_FORM_data4)),
199 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
200 dwarf::DW_FORM_data4)),
201 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
202 dwarf::DW_FORM_data4)),
203 AccelTypes(TypeAtoms) {
205 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
206 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
207 DwarfLineSectionSym = nullptr;
208 DwarfAddrSectionSym = nullptr;
209 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
210 FunctionBeginSym = FunctionEndSym = nullptr;
214 // Turn on accelerator tables for Darwin by default, pubnames by
215 // default for non-Darwin/PS4, and handle split dwarf.
216 if (DwarfAccelTables == Default)
217 HasDwarfAccelTables = IsDarwin;
219 HasDwarfAccelTables = DwarfAccelTables == Enable;
221 if (SplitDwarf == Default)
222 HasSplitDwarf = false;
224 HasSplitDwarf = SplitDwarf == Enable;
226 if (DwarfPubSections == Default)
227 HasDwarfPubSections = !IsDarwin && !IsPS4;
229 HasDwarfPubSections = DwarfPubSections == Enable;
231 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
232 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
233 : MMI->getModule()->getDwarfVersion();
235 // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
236 // Everybody else uses GNU's.
237 UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
239 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
242 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
247 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
248 DwarfDebug::~DwarfDebug() { }
250 // Switch to the specified MCSection and emit an assembler
251 // temporary label to it if SymbolStem is specified.
252 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
253 const char *SymbolStem = nullptr) {
254 Asm->OutStreamer.SwitchSection(Section);
258 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
259 Asm->OutStreamer.EmitLabel(TmpSym);
263 static bool isObjCClass(StringRef Name) {
264 return Name.startswith("+") || Name.startswith("-");
267 static bool hasObjCCategory(StringRef Name) {
268 if (!isObjCClass(Name))
271 return Name.find(") ") != StringRef::npos;
274 static void getObjCClassCategory(StringRef In, StringRef &Class,
275 StringRef &Category) {
276 if (!hasObjCCategory(In)) {
277 Class = In.slice(In.find('[') + 1, In.find(' '));
282 Class = In.slice(In.find('[') + 1, In.find('('));
283 Category = In.slice(In.find('[') + 1, In.find(' '));
287 static StringRef getObjCMethodName(StringRef In) {
288 return In.slice(In.find(' ') + 1, In.find(']'));
291 // Helper for sorting sections into a stable output order.
292 static bool SectionSort(const MCSection *A, const MCSection *B) {
293 std::string LA = (A ? A->getLabelBeginName() : "");
294 std::string LB = (B ? B->getLabelBeginName() : "");
298 // Add the various names to the Dwarf accelerator table names.
299 // TODO: Determine whether or not we should add names for programs
300 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
301 // is only slightly different than the lookup of non-standard ObjC names.
302 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
303 if (!SP.isDefinition())
305 addAccelName(SP.getName(), Die);
307 // If the linkage name is different than the name, go ahead and output
308 // that as well into the name table.
309 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
310 addAccelName(SP.getLinkageName(), Die);
312 // If this is an Objective-C selector name add it to the ObjC accelerator
314 if (isObjCClass(SP.getName())) {
315 StringRef Class, Category;
316 getObjCClassCategory(SP.getName(), Class, Category);
317 addAccelObjC(Class, Die);
319 addAccelObjC(Category, Die);
320 // Also add the base method name to the name table.
321 addAccelName(getObjCMethodName(SP.getName()), Die);
325 /// isSubprogramContext - Return true if Context is either a subprogram
326 /// or another context nested inside a subprogram.
327 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
330 DIDescriptor D(Context);
331 if (D.isSubprogram())
334 return isSubprogramContext(resolve(DIType(Context).getContext()));
338 /// Check whether we should create a DIE for the given Scope, return true
339 /// if we don't create a DIE (the corresponding DIE is null).
340 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
341 if (Scope->isAbstractScope())
344 // We don't create a DIE if there is no Range.
345 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
349 if (Ranges.size() > 1)
352 // We don't create a DIE if we have a single Range and the end label
354 return !getLabelAfterInsn(Ranges.front().second);
357 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
359 if (auto *SkelCU = CU.getSkeleton())
363 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
364 assert(Scope && Scope->getScopeNode());
365 assert(Scope->isAbstractScope());
366 assert(!Scope->getInlinedAt());
368 const MDNode *SP = Scope->getScopeNode();
370 ProcessedSPNodes.insert(SP);
372 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
373 // was inlined from another compile unit.
374 auto &CU = SPMap[SP];
375 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
376 CU.constructAbstractSubprogramScopeDIE(Scope);
380 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
381 if (!GenerateGnuPubSections)
384 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
387 // Create new DwarfCompileUnit for the given metadata node with tag
388 // DW_TAG_compile_unit.
389 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
390 StringRef FN = DIUnit.getFilename();
391 CompilationDir = DIUnit.getDirectory();
393 auto OwnedUnit = make_unique<DwarfCompileUnit>(
394 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
395 DwarfCompileUnit &NewCU = *OwnedUnit;
396 DIE &Die = NewCU.getUnitDie();
397 InfoHolder.addUnit(std::move(OwnedUnit));
399 NewCU.setSkeleton(constructSkeletonCU(NewCU));
401 // LTO with assembly output shares a single line table amongst multiple CUs.
402 // To avoid the compilation directory being ambiguous, let the line table
403 // explicitly describe the directory of all files, never relying on the
404 // compilation directory.
405 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
406 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
407 NewCU.getUniqueID(), CompilationDir);
409 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
410 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
411 DIUnit.getLanguage());
412 NewCU.addString(Die, dwarf::DW_AT_name, FN);
414 if (!useSplitDwarf()) {
415 NewCU.initStmtList(DwarfLineSectionSym);
417 // If we're using split dwarf the compilation dir is going to be in the
418 // skeleton CU and so we don't need to duplicate it here.
419 if (!CompilationDir.empty())
420 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
422 addGnuPubAttributes(NewCU, Die);
425 if (DIUnit.isOptimized())
426 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
428 StringRef Flags = DIUnit.getFlags();
430 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
432 if (unsigned RVer = DIUnit.getRunTimeVersion())
433 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
434 dwarf::DW_FORM_data1, RVer);
437 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
438 DwarfInfoDWOSectionSym);
440 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
441 DwarfInfoSectionSym);
443 CUMap.insert(std::make_pair(DIUnit, &NewCU));
444 CUDieMap.insert(std::make_pair(&Die, &NewCU));
448 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
450 DIImportedEntity Module(N);
451 assert(Module.Verify());
452 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
453 D->addChild(TheCU.constructImportedEntityDIE(Module));
456 // Emit all Dwarf sections that should come prior to the content. Create
457 // global DIEs and emit initial debug info sections. This is invoked by
458 // the target AsmPrinter.
459 void DwarfDebug::beginModule() {
460 if (DisableDebugInfoPrinting)
463 const Module *M = MMI->getModule();
465 FunctionDIs = makeSubprogramMap(*M);
467 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
470 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
472 // Emit initial sections so we can reference labels later.
475 SingleCU = CU_Nodes->getNumOperands() == 1;
477 for (MDNode *N : CU_Nodes->operands()) {
478 DICompileUnit CUNode(N);
479 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
480 DIArray ImportedEntities = CUNode.getImportedEntities();
481 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
482 ScopesWithImportedEntities.push_back(std::make_pair(
483 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
484 ImportedEntities.getElement(i)));
485 // Stable sort to preserve the order of appearance of imported entities.
486 // This is to avoid out-of-order processing of interdependent declarations
487 // within the same scope, e.g. { namespace A = base; namespace B = A; }
488 std::stable_sort(ScopesWithImportedEntities.begin(),
489 ScopesWithImportedEntities.end(), less_first());
490 DIArray GVs = CUNode.getGlobalVariables();
491 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
492 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
493 DIArray SPs = CUNode.getSubprograms();
494 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
495 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
496 DIArray EnumTypes = CUNode.getEnumTypes();
497 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
498 DIType Ty(EnumTypes.getElement(i));
499 // The enum types array by design contains pointers to
500 // MDNodes rather than DIRefs. Unique them here.
501 DIType UniqueTy(resolve(Ty.getRef()));
502 CU.getOrCreateTypeDIE(UniqueTy);
504 DIArray RetainedTypes = CUNode.getRetainedTypes();
505 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
506 DIType Ty(RetainedTypes.getElement(i));
507 // The retained types array by design contains pointers to
508 // MDNodes rather than DIRefs. Unique them here.
509 DIType UniqueTy(resolve(Ty.getRef()));
510 CU.getOrCreateTypeDIE(UniqueTy);
512 // Emit imported_modules last so that the relevant context is already
514 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
515 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
518 // Tell MMI that we have debug info.
519 MMI->setDebugInfoAvailability(true);
522 void DwarfDebug::finishVariableDefinitions() {
523 for (const auto &Var : ConcreteVariables) {
524 DIE *VariableDie = Var->getDIE();
526 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
527 // in the ConcreteVariables list, rather than looking it up again here.
528 // DIE::getUnit isn't simple - it walks parent pointers, etc.
529 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
531 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
532 if (AbsVar && AbsVar->getDIE()) {
533 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
536 Unit->applyVariableAttributes(*Var, *VariableDie);
540 void DwarfDebug::finishSubprogramDefinitions() {
541 for (const auto &P : SPMap)
542 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
543 CU.finishSubprogramDefinition(DISubprogram(P.first));
548 // Collect info for variables that were optimized out.
549 void DwarfDebug::collectDeadVariables() {
550 const Module *M = MMI->getModule();
552 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
553 for (MDNode *N : CU_Nodes->operands()) {
554 DICompileUnit TheCU(N);
555 // Construct subprogram DIE and add variables DIEs.
556 DwarfCompileUnit *SPCU =
557 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
558 assert(SPCU && "Unable to find Compile Unit!");
559 DIArray Subprograms = TheCU.getSubprograms();
560 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
561 DISubprogram SP(Subprograms.getElement(i));
562 if (ProcessedSPNodes.count(SP) != 0)
564 SPCU->collectDeadVariables(SP);
570 void DwarfDebug::finalizeModuleInfo() {
571 finishSubprogramDefinitions();
573 finishVariableDefinitions();
575 // Collect info for variables that were optimized out.
576 collectDeadVariables();
578 // Handle anything that needs to be done on a per-unit basis after
579 // all other generation.
580 for (const auto &P : CUMap) {
581 auto &TheCU = *P.second;
582 // Emit DW_AT_containing_type attribute to connect types with their
583 // vtable holding type.
584 TheCU.constructContainingTypeDIEs();
586 // Add CU specific attributes if we need to add any.
587 // If we're splitting the dwarf out now that we've got the entire
588 // CU then add the dwo id to it.
589 auto *SkCU = TheCU.getSkeleton();
590 if (useSplitDwarf()) {
591 // Emit a unique identifier for this CU.
592 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
593 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
594 dwarf::DW_FORM_data8, ID);
595 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
596 dwarf::DW_FORM_data8, ID);
598 // We don't keep track of which addresses are used in which CU so this
599 // is a bit pessimistic under LTO.
600 if (!AddrPool.isEmpty())
601 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
602 DwarfAddrSectionSym, DwarfAddrSectionSym);
603 if (!SkCU->getRangeLists().empty())
604 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
605 DwarfDebugRangeSectionSym,
606 DwarfDebugRangeSectionSym);
609 // If we have code split among multiple sections or non-contiguous
610 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
611 // remain in the .o file, otherwise add a DW_AT_low_pc.
612 // FIXME: We should use ranges allow reordering of code ala
613 // .subsections_via_symbols in mach-o. This would mean turning on
614 // ranges for all subprogram DIEs for mach-o.
615 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
616 if (unsigned NumRanges = TheCU.getRanges().size()) {
618 // A DW_AT_low_pc attribute may also be specified in combination with
619 // DW_AT_ranges to specify the default base address for use in
620 // location lists (see Section 2.6.2) and range lists (see Section
622 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
624 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
625 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
629 // Compute DIE offsets and sizes.
630 InfoHolder.computeSizeAndOffsets();
632 SkeletonHolder.computeSizeAndOffsets();
635 // Emit all Dwarf sections that should come after the content.
636 void DwarfDebug::endModule() {
637 assert(CurFn == nullptr);
638 assert(CurMI == nullptr);
640 // If we aren't actually generating debug info (check beginModule -
641 // conditionalized on !DisableDebugInfoPrinting and the presence of the
642 // llvm.dbg.cu metadata node)
643 if (!DwarfInfoSectionSym)
646 // Finalize the debug info for the module.
647 finalizeModuleInfo();
651 // Emit all the DIEs into a debug info section.
654 // Corresponding abbreviations into a abbrev section.
657 // Emit info into a debug aranges section.
658 if (GenerateARangeSection)
661 // Emit info into a debug ranges section.
664 if (useSplitDwarf()) {
667 emitDebugAbbrevDWO();
670 // Emit DWO addresses.
671 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
673 // Emit info into a debug loc section.
676 // Emit info into the dwarf accelerator table sections.
677 if (useDwarfAccelTables()) {
680 emitAccelNamespaces();
684 // Emit the pubnames and pubtypes sections if requested.
685 if (HasDwarfPubSections) {
686 emitDebugPubNames(GenerateGnuPubSections);
687 emitDebugPubTypes(GenerateGnuPubSections);
692 AbstractVariables.clear();
695 // Find abstract variable, if any, associated with Var.
696 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
697 DIVariable &Cleansed) {
698 LLVMContext &Ctx = DV->getContext();
699 // More then one inlined variable corresponds to one abstract variable.
700 // FIXME: This duplication of variables when inlining should probably be
701 // removed. It's done to allow each DIVariable to describe its location
702 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
703 // make it accurate then remove this duplication/cleansing stuff.
704 Cleansed = cleanseInlinedVariable(DV, Ctx);
705 auto I = AbstractVariables.find(Cleansed);
706 if (I != AbstractVariables.end())
707 return I->second.get();
711 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
713 return getExistingAbstractVariable(DV, Cleansed);
716 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
717 LexicalScope *Scope) {
718 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
719 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
720 AbstractVariables[Var] = std::move(AbsDbgVariable);
723 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
724 const MDNode *ScopeNode) {
725 DIVariable Cleansed = DV;
726 if (getExistingAbstractVariable(DV, Cleansed))
729 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
733 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
734 const MDNode *ScopeNode) {
735 DIVariable Cleansed = DV;
736 if (getExistingAbstractVariable(DV, Cleansed))
739 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
740 createAbstractVariable(Cleansed, Scope);
743 // Collect variable information from side table maintained by MMI.
744 void DwarfDebug::collectVariableInfoFromMMITable(
745 SmallPtrSetImpl<const MDNode *> &Processed) {
746 for (const auto &VI : MMI->getVariableDbgInfo()) {
749 Processed.insert(VI.Var);
750 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
752 // If variable scope is not found then skip this variable.
756 DIVariable DV(VI.Var);
757 DIExpression Expr(VI.Expr);
758 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
759 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
760 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
761 ConcreteVariables.push_back(std::move(RegVar));
765 // Get .debug_loc entry for the instruction range starting at MI.
766 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
767 const MDNode *Expr = MI->getDebugExpression();
768 const MDNode *Var = MI->getDebugVariable();
770 assert(MI->getNumOperands() == 4);
771 if (MI->getOperand(0).isReg()) {
772 MachineLocation MLoc;
773 // If the second operand is an immediate, this is a
774 // register-indirect address.
775 if (!MI->getOperand(1).isImm())
776 MLoc.set(MI->getOperand(0).getReg());
778 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
779 return DebugLocEntry::Value(Var, Expr, MLoc);
781 if (MI->getOperand(0).isImm())
782 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
783 if (MI->getOperand(0).isFPImm())
784 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
785 if (MI->getOperand(0).isCImm())
786 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
788 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
791 /// Determine whether two variable pieces overlap.
792 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
793 if (!P1.isBitPiece() || !P2.isBitPiece())
795 unsigned l1 = P1.getBitPieceOffset();
796 unsigned l2 = P2.getBitPieceOffset();
797 unsigned r1 = l1 + P1.getBitPieceSize();
798 unsigned r2 = l2 + P2.getBitPieceSize();
799 // True where [l1,r1[ and [r1,r2[ overlap.
800 return (l1 < r2) && (l2 < r1);
803 /// Build the location list for all DBG_VALUEs in the function that
804 /// describe the same variable. If the ranges of several independent
805 /// pieces of the same variable overlap partially, split them up and
806 /// combine the ranges. The resulting DebugLocEntries are will have
807 /// strict monotonically increasing begin addresses and will never
812 // Ranges History [var, loc, piece ofs size]
813 // 0 | [x, (reg0, piece 0, 32)]
814 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
816 // 3 | [clobber reg0]
817 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
822 // [0-1] [x, (reg0, piece 0, 32)]
823 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
824 // [3-4] [x, (reg1, piece 32, 32)]
825 // [4- ] [x, (mem, piece 0, 64)]
827 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
828 const DbgValueHistoryMap::InstrRanges &Ranges) {
829 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
831 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
832 const MachineInstr *Begin = I->first;
833 const MachineInstr *End = I->second;
834 assert(Begin->isDebugValue() && "Invalid History entry");
836 // Check if a variable is inaccessible in this range.
837 if (Begin->getNumOperands() > 1 &&
838 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
843 // If this piece overlaps with any open ranges, truncate them.
844 DIExpression DIExpr = Begin->getDebugExpression();
845 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
846 [&](DebugLocEntry::Value R) {
847 return piecesOverlap(DIExpr, R.getExpression());
849 OpenRanges.erase(Last, OpenRanges.end());
851 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
852 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
854 const MCSymbol *EndLabel;
856 EndLabel = getLabelAfterInsn(End);
857 else if (std::next(I) == Ranges.end())
858 EndLabel = FunctionEndSym;
860 EndLabel = getLabelBeforeInsn(std::next(I)->first);
861 assert(EndLabel && "Forgot label after instruction ending a range!");
863 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
865 auto Value = getDebugLocValue(Begin);
866 DebugLocEntry Loc(StartLabel, EndLabel, Value);
867 bool couldMerge = false;
869 // If this is a piece, it may belong to the current DebugLocEntry.
870 if (DIExpr.isBitPiece()) {
871 // Add this value to the list of open ranges.
872 OpenRanges.push_back(Value);
874 // Attempt to add the piece to the last entry.
875 if (!DebugLoc.empty())
876 if (DebugLoc.back().MergeValues(Loc))
881 // Need to add a new DebugLocEntry. Add all values from still
882 // valid non-overlapping pieces.
883 if (OpenRanges.size())
884 Loc.addValues(OpenRanges);
886 DebugLoc.push_back(std::move(Loc));
889 // Attempt to coalesce the ranges of two otherwise identical
891 auto CurEntry = DebugLoc.rbegin();
892 auto PrevEntry = std::next(CurEntry);
893 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
897 dbgs() << CurEntry->getValues().size() << " Values:\n";
898 for (auto Value : CurEntry->getValues()) {
899 Value.getVariable()->dump();
900 Value.getExpression()->dump();
908 // Find variables for each lexical scope.
910 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
911 SmallPtrSetImpl<const MDNode *> &Processed) {
912 // Grab the variable info that was squirreled away in the MMI side-table.
913 collectVariableInfoFromMMITable(Processed);
915 for (const auto &I : DbgValues) {
916 DIVariable DV(I.first);
917 if (Processed.count(DV))
920 // Instruction ranges, specifying where DV is accessible.
921 const auto &Ranges = I.second;
925 LexicalScope *Scope = nullptr;
926 if (MDNode *IA = DV.getInlinedAt())
927 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
929 Scope = LScopes.findLexicalScope(DV.getContext());
930 // If variable scope is not found then skip this variable.
934 Processed.insert(DV);
935 const MachineInstr *MInsn = Ranges.front().first;
936 assert(MInsn->isDebugValue() && "History must begin with debug value");
937 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
938 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
939 DbgVariable *RegVar = ConcreteVariables.back().get();
940 InfoHolder.addScopeVariable(Scope, RegVar);
942 // Check if the first DBG_VALUE is valid for the rest of the function.
943 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
946 // Handle multiple DBG_VALUE instructions describing one variable.
947 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
949 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
950 DebugLocList &LocList = DotDebugLocEntries.back();
953 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
955 // Build the location list for this variable.
956 buildLocationList(LocList.List, Ranges);
957 // Finalize the entry by lowering it into a DWARF bytestream.
958 for (auto &Entry : LocList.List)
959 Entry.finalize(*Asm, TypeIdentifierMap);
962 // Collect info for variables that were optimized out.
963 DIArray Variables = SP.getVariables();
964 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
965 DIVariable DV(Variables.getElement(i));
966 assert(DV.isVariable());
967 if (!Processed.insert(DV).second)
969 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
970 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
972 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
973 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
978 // Return Label preceding the instruction.
979 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
980 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
981 assert(Label && "Didn't insert label before instruction");
985 // Return Label immediately following the instruction.
986 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
987 return LabelsAfterInsn.lookup(MI);
990 // Process beginning of an instruction.
991 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
992 assert(CurMI == nullptr);
994 // Check if source location changes, but ignore DBG_VALUE locations.
995 if (!MI->isDebugValue()) {
996 DebugLoc DL = MI->getDebugLoc();
997 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1000 if (DL == PrologEndLoc) {
1001 Flags |= DWARF2_FLAG_PROLOGUE_END;
1002 PrologEndLoc = DebugLoc();
1003 Flags |= DWARF2_FLAG_IS_STMT;
1006 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
1007 Flags |= DWARF2_FLAG_IS_STMT;
1009 if (!DL.isUnknown()) {
1010 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1011 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1013 recordSourceLine(0, 0, nullptr, 0);
1017 // Insert labels where requested.
1018 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1019 LabelsBeforeInsn.find(MI);
1022 if (I == LabelsBeforeInsn.end())
1025 // Label already assigned.
1030 PrevLabel = MMI->getContext().CreateTempSymbol();
1031 Asm->OutStreamer.EmitLabel(PrevLabel);
1033 I->second = PrevLabel;
1036 // Process end of an instruction.
1037 void DwarfDebug::endInstruction() {
1038 assert(CurMI != nullptr);
1039 // Don't create a new label after DBG_VALUE instructions.
1040 // They don't generate code.
1041 if (!CurMI->isDebugValue())
1042 PrevLabel = nullptr;
1044 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1045 LabelsAfterInsn.find(CurMI);
1049 if (I == LabelsAfterInsn.end())
1052 // Label already assigned.
1056 // We need a label after this instruction.
1058 PrevLabel = MMI->getContext().CreateTempSymbol();
1059 Asm->OutStreamer.EmitLabel(PrevLabel);
1061 I->second = PrevLabel;
1064 // Each LexicalScope has first instruction and last instruction to mark
1065 // beginning and end of a scope respectively. Create an inverse map that list
1066 // scopes starts (and ends) with an instruction. One instruction may start (or
1067 // end) multiple scopes. Ignore scopes that are not reachable.
1068 void DwarfDebug::identifyScopeMarkers() {
1069 SmallVector<LexicalScope *, 4> WorkList;
1070 WorkList.push_back(LScopes.getCurrentFunctionScope());
1071 while (!WorkList.empty()) {
1072 LexicalScope *S = WorkList.pop_back_val();
1074 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1075 if (!Children.empty())
1076 WorkList.append(Children.begin(), Children.end());
1078 if (S->isAbstractScope())
1081 for (const InsnRange &R : S->getRanges()) {
1082 assert(R.first && "InsnRange does not have first instruction!");
1083 assert(R.second && "InsnRange does not have second instruction!");
1084 requestLabelBeforeInsn(R.first);
1085 requestLabelAfterInsn(R.second);
1090 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1091 // First known non-DBG_VALUE and non-frame setup location marks
1092 // the beginning of the function body.
1093 for (const auto &MBB : *MF)
1094 for (const auto &MI : MBB)
1095 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1096 !MI.getDebugLoc().isUnknown()) {
1097 // Did the target forget to set the FrameSetup flag for CFI insns?
1098 assert(!MI.isCFIInstruction() &&
1099 "First non-frame-setup instruction is a CFI instruction.");
1100 return MI.getDebugLoc();
1105 // Gather pre-function debug information. Assumes being called immediately
1106 // after the function entry point has been emitted.
1107 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1110 // If there's no debug info for the function we're not going to do anything.
1111 if (!MMI->hasDebugInfo())
1114 auto DI = FunctionDIs.find(MF->getFunction());
1115 if (DI == FunctionDIs.end())
1118 // Grab the lexical scopes for the function, if we don't have any of those
1119 // then we're not going to be able to do anything.
1120 LScopes.initialize(*MF);
1121 if (LScopes.empty())
1124 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1126 // Make sure that each lexical scope will have a begin/end label.
1127 identifyScopeMarkers();
1129 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1130 // belongs to so that we add to the correct per-cu line table in the
1132 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1133 // FnScope->getScopeNode() and DI->second should represent the same function,
1134 // though they may not be the same MDNode due to inline functions merged in
1135 // LTO where the debug info metadata still differs (either due to distinct
1136 // written differences - two versions of a linkonce_odr function
1137 // written/copied into two separate files, or some sub-optimal metadata that
1138 // isn't structurally identical (see: file path/name info from clang, which
1139 // includes the directory of the cpp file being built, even when the file name
1140 // is absolute (such as an <> lookup header)))
1141 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1142 assert(TheCU && "Unable to find compile unit!");
1143 if (Asm->OutStreamer.hasRawTextSupport())
1144 // Use a single line table if we are generating assembly.
1145 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1147 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1149 // Emit a label for the function so that we have a beginning address.
1150 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1151 // Assumes in correct section after the entry point.
1152 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1154 // Calculate history for local variables.
1155 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1158 // Request labels for the full history.
1159 for (const auto &I : DbgValues) {
1160 const auto &Ranges = I.second;
1164 // The first mention of a function argument gets the FunctionBeginSym
1165 // label, so arguments are visible when breaking at function entry.
1166 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1167 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1168 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1169 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1170 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1171 // Mark all non-overlapping initial pieces.
1172 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1173 DIExpression Piece = I->first->getDebugExpression();
1174 if (std::all_of(Ranges.begin(), I,
1175 [&](DbgValueHistoryMap::InstrRange Pred) {
1176 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1178 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1185 for (const auto &Range : Ranges) {
1186 requestLabelBeforeInsn(Range.first);
1188 requestLabelAfterInsn(Range.second);
1192 PrevInstLoc = DebugLoc();
1193 PrevLabel = FunctionBeginSym;
1195 // Record beginning of function.
1196 PrologEndLoc = findPrologueEndLoc(MF);
1197 if (!PrologEndLoc.isUnknown()) {
1198 DebugLoc FnStartDL =
1199 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1201 // We'd like to list the prologue as "not statements" but GDB behaves
1202 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1203 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1204 FnStartDL.getScope(MF->getFunction()->getContext()),
1205 DWARF2_FLAG_IS_STMT);
1209 // Gather and emit post-function debug information.
1210 void DwarfDebug::endFunction(const MachineFunction *MF) {
1211 assert(CurFn == MF &&
1212 "endFunction should be called with the same function as beginFunction");
1214 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1215 !FunctionDIs.count(MF->getFunction())) {
1216 // If we don't have a lexical scope for this function then there will
1217 // be a hole in the range information. Keep note of this by setting the
1218 // previously used section to nullptr.
1224 // Define end label for subprogram.
1225 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1226 // Assumes in correct section after the entry point.
1227 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1229 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1230 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1232 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1233 DISubprogram SP(FnScope->getScopeNode());
1234 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1236 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1237 collectVariableInfo(TheCU, SP, ProcessedVars);
1239 // Add the range of this function to the list of ranges for the CU.
1240 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1242 // Under -gmlt, skip building the subprogram if there are no inlined
1243 // subroutines inside it.
1244 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1245 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1246 assert(InfoHolder.getScopeVariables().empty());
1247 assert(DbgValues.empty());
1248 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1249 // by a -gmlt CU. Add a test and remove this assertion.
1250 assert(AbstractVariables.empty());
1251 LabelsBeforeInsn.clear();
1252 LabelsAfterInsn.clear();
1253 PrevLabel = nullptr;
1259 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1261 // Construct abstract scopes.
1262 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1263 DISubprogram SP(AScope->getScopeNode());
1264 assert(SP.isSubprogram());
1265 // Collect info for variables that were optimized out.
1266 DIArray Variables = SP.getVariables();
1267 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1268 DIVariable DV(Variables.getElement(i));
1269 assert(DV && DV.isVariable());
1270 if (!ProcessedVars.insert(DV).second)
1272 ensureAbstractVariableIsCreated(DV, DV.getContext());
1273 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1274 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1276 constructAbstractSubprogramScopeDIE(AScope);
1279 TheCU.constructSubprogramScopeDIE(FnScope);
1280 if (auto *SkelCU = TheCU.getSkeleton())
1281 if (!LScopes.getAbstractScopesList().empty())
1282 SkelCU->constructSubprogramScopeDIE(FnScope);
1285 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1286 // DbgVariables except those that are also in AbstractVariables (since they
1287 // can be used cross-function)
1288 InfoHolder.getScopeVariables().clear();
1290 LabelsBeforeInsn.clear();
1291 LabelsAfterInsn.clear();
1292 PrevLabel = nullptr;
1296 // Register a source line with debug info. Returns the unique label that was
1297 // emitted and which provides correspondence to the source line list.
1298 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1303 unsigned Discriminator = 0;
1304 if (DIScope Scope = DIScope(S)) {
1305 assert(Scope.isScope());
1306 Fn = Scope.getFilename();
1307 Dir = Scope.getDirectory();
1308 if (Scope.isLexicalBlockFile())
1309 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1311 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1312 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1313 .getOrCreateSourceID(Fn, Dir);
1315 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1319 //===----------------------------------------------------------------------===//
1321 //===----------------------------------------------------------------------===//
1323 // Emit initial Dwarf sections with a label at the start of each one.
1324 void DwarfDebug::emitSectionLabels() {
1325 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1327 // Dwarf sections base addresses.
1328 DwarfInfoSectionSym =
1329 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1330 if (useSplitDwarf()) {
1331 DwarfInfoDWOSectionSym =
1332 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1333 DwarfTypesDWOSectionSym = emitSectionSym(
1334 Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1336 DwarfAbbrevSectionSym =
1337 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1338 if (useSplitDwarf())
1339 DwarfAbbrevDWOSectionSym = emitSectionSym(
1340 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1341 if (GenerateARangeSection)
1342 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1344 DwarfLineSectionSym =
1345 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1346 if (GenerateGnuPubSections) {
1347 DwarfGnuPubNamesSectionSym =
1348 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1349 DwarfGnuPubTypesSectionSym =
1350 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1351 } else if (HasDwarfPubSections) {
1352 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1353 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1356 DwarfStrSectionSym =
1357 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1358 if (useSplitDwarf()) {
1359 DwarfStrDWOSectionSym =
1360 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1361 DwarfAddrSectionSym =
1362 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1363 DwarfDebugLocSectionSym =
1364 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1366 DwarfDebugLocSectionSym =
1367 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1368 DwarfDebugRangeSectionSym =
1369 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1372 // Emit the debug info section.
1373 void DwarfDebug::emitDebugInfo() {
1374 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1376 Holder.emitUnits(DwarfAbbrevSectionSym);
1379 // Emit the abbreviation section.
1380 void DwarfDebug::emitAbbreviations() {
1381 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1383 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1386 // Emit the last address of the section and the end of the line matrix.
1387 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1388 // Define last address of section.
1389 Asm->OutStreamer.AddComment("Extended Op");
1392 Asm->OutStreamer.AddComment("Op size");
1393 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1394 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1395 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1397 Asm->OutStreamer.AddComment("Section end label");
1399 Asm->OutStreamer.EmitSymbolValue(
1400 Asm->GetTempSymbol("section_end", SectionEnd),
1401 Asm->getDataLayout().getPointerSize());
1403 // Mark end of matrix.
1404 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1410 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1411 StringRef TableName, StringRef SymName) {
1412 Accel.FinalizeTable(Asm, TableName);
1413 Asm->OutStreamer.SwitchSection(Section);
1414 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1415 Asm->OutStreamer.EmitLabel(SectionBegin);
1417 // Emit the full data.
1418 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1421 // Emit visible names into a hashed accelerator table section.
1422 void DwarfDebug::emitAccelNames() {
1423 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1424 "Names", "names_begin");
1427 // Emit objective C classes and categories into a hashed accelerator table
1429 void DwarfDebug::emitAccelObjC() {
1430 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1431 "ObjC", "objc_begin");
1434 // Emit namespace dies into a hashed accelerator table.
1435 void DwarfDebug::emitAccelNamespaces() {
1436 emitAccel(AccelNamespace,
1437 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1438 "namespac", "namespac_begin");
1441 // Emit type dies into a hashed accelerator table.
1442 void DwarfDebug::emitAccelTypes() {
1443 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1444 "types", "types_begin");
1447 // Public name handling.
1448 // The format for the various pubnames:
1450 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1451 // for the DIE that is named.
1453 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1454 // into the CU and the index value is computed according to the type of value
1455 // for the DIE that is named.
1457 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1458 // it's the offset within the debug_info/debug_types dwo section, however, the
1459 // reference in the pubname header doesn't change.
1461 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1462 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1464 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1466 // We could have a specification DIE that has our most of our knowledge,
1467 // look for that now.
1468 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1470 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1471 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1472 Linkage = dwarf::GIEL_EXTERNAL;
1473 } else if (Die->findAttribute(dwarf::DW_AT_external))
1474 Linkage = dwarf::GIEL_EXTERNAL;
1476 switch (Die->getTag()) {
1477 case dwarf::DW_TAG_class_type:
1478 case dwarf::DW_TAG_structure_type:
1479 case dwarf::DW_TAG_union_type:
1480 case dwarf::DW_TAG_enumeration_type:
1481 return dwarf::PubIndexEntryDescriptor(
1482 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1483 ? dwarf::GIEL_STATIC
1484 : dwarf::GIEL_EXTERNAL);
1485 case dwarf::DW_TAG_typedef:
1486 case dwarf::DW_TAG_base_type:
1487 case dwarf::DW_TAG_subrange_type:
1488 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1489 case dwarf::DW_TAG_namespace:
1490 return dwarf::GIEK_TYPE;
1491 case dwarf::DW_TAG_subprogram:
1492 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1493 case dwarf::DW_TAG_variable:
1494 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1495 case dwarf::DW_TAG_enumerator:
1496 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1497 dwarf::GIEL_STATIC);
1499 return dwarf::GIEK_NONE;
1503 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1505 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1506 const MCSection *PSec =
1507 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1508 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1510 emitDebugPubSection(GnuStyle, PSec, "Names",
1511 &DwarfCompileUnit::getGlobalNames);
1514 void DwarfDebug::emitDebugPubSection(
1515 bool GnuStyle, const MCSection *PSec, StringRef Name,
1516 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1517 for (const auto &NU : CUMap) {
1518 DwarfCompileUnit *TheU = NU.second;
1520 const auto &Globals = (TheU->*Accessor)();
1522 if (Globals.empty())
1525 if (auto *Skeleton = TheU->getSkeleton())
1527 unsigned ID = TheU->getUniqueID();
1529 // Start the dwarf pubnames section.
1530 Asm->OutStreamer.SwitchSection(PSec);
1533 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1534 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1535 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1536 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1538 Asm->OutStreamer.EmitLabel(BeginLabel);
1540 Asm->OutStreamer.AddComment("DWARF Version");
1541 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1543 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1544 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1546 Asm->OutStreamer.AddComment("Compilation Unit Length");
1547 Asm->EmitInt32(TheU->getLength());
1549 // Emit the pubnames for this compilation unit.
1550 for (const auto &GI : Globals) {
1551 const char *Name = GI.getKeyData();
1552 const DIE *Entity = GI.second;
1554 Asm->OutStreamer.AddComment("DIE offset");
1555 Asm->EmitInt32(Entity->getOffset());
1558 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1559 Asm->OutStreamer.AddComment(
1560 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1561 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1562 Asm->EmitInt8(Desc.toBits());
1565 Asm->OutStreamer.AddComment("External Name");
1566 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1569 Asm->OutStreamer.AddComment("End Mark");
1571 Asm->OutStreamer.EmitLabel(EndLabel);
1575 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1576 const MCSection *PSec =
1577 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1578 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1580 emitDebugPubSection(GnuStyle, PSec, "Types",
1581 &DwarfCompileUnit::getGlobalTypes);
1584 // Emit visible names into a debug str section.
1585 void DwarfDebug::emitDebugStr() {
1586 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1587 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1591 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1592 const DebugLocEntry &Entry) {
1593 auto Comment = Entry.getComments().begin();
1594 auto End = Entry.getComments().end();
1595 for (uint8_t Byte : Entry.getDWARFBytes())
1596 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1599 static void emitDebugLocValue(const AsmPrinter &AP,
1600 const DITypeIdentifierMap &TypeIdentifierMap,
1601 ByteStreamer &Streamer,
1602 const DebugLocEntry::Value &Value,
1603 unsigned PieceOffsetInBits) {
1604 DIVariable DV = Value.getVariable();
1605 DebugLocDwarfExpression DwarfExpr(
1606 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1607 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1609 if (Value.isInt()) {
1610 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1611 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1612 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1613 DwarfExpr.AddSignedConstant(Value.getInt());
1615 DwarfExpr.AddUnsignedConstant(Value.getInt());
1616 } else if (Value.isLocation()) {
1617 MachineLocation Loc = Value.getLoc();
1618 DIExpression Expr = Value.getExpression();
1619 if (!Expr || (Expr.getNumElements() == 0))
1621 AP.EmitDwarfRegOp(Streamer, Loc);
1623 // Complex address entry.
1624 if (Loc.getOffset()) {
1625 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1626 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1628 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1632 // else ... ignore constant fp. There is not any good way to
1633 // to represent them here in dwarf.
1638 void DebugLocEntry::finalize(const AsmPrinter &AP,
1639 const DITypeIdentifierMap &TypeIdentifierMap) {
1640 BufferByteStreamer Streamer(DWARFBytes, Comments);
1641 const DebugLocEntry::Value Value = Values[0];
1642 if (Value.isBitPiece()) {
1643 // Emit all pieces that belong to the same variable and range.
1644 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1645 return P.isBitPiece();
1646 }) && "all values are expected to be pieces");
1647 assert(std::is_sorted(Values.begin(), Values.end()) &&
1648 "pieces are expected to be sorted");
1650 unsigned Offset = 0;
1651 for (auto Piece : Values) {
1652 DIExpression Expr = Piece.getExpression();
1653 unsigned PieceOffset = Expr.getBitPieceOffset();
1654 unsigned PieceSize = Expr.getBitPieceSize();
1655 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1656 if (Offset < PieceOffset) {
1657 // The DWARF spec seriously mandates pieces with no locations for gaps.
1658 DebugLocDwarfExpression Expr(
1659 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1660 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1661 Expr.AddOpPiece(PieceOffset-Offset, 0);
1662 Offset += PieceOffset-Offset;
1664 Offset += PieceSize;
1667 DIVariable Var = Piece.getVariable();
1668 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1669 assert(PieceSize+PieceOffset <= VarSize
1670 && "piece is larger than or outside of variable");
1671 assert(PieceSize != VarSize
1672 && "piece covers entire variable");
1674 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1677 assert(Values.size() == 1 && "only pieces may have >1 value");
1678 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1683 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1684 Asm->OutStreamer.AddComment("Loc expr size");
1685 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1686 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1687 Asm->EmitLabelDifference(end, begin, 2);
1688 Asm->OutStreamer.EmitLabel(begin);
1690 APByteStreamer Streamer(*Asm);
1691 emitDebugLocEntry(Streamer, Entry);
1693 Asm->OutStreamer.EmitLabel(end);
1696 // Emit locations into the debug loc section.
1697 void DwarfDebug::emitDebugLoc() {
1698 // Start the dwarf loc section.
1699 Asm->OutStreamer.SwitchSection(
1700 Asm->getObjFileLowering().getDwarfLocSection());
1701 unsigned char Size = Asm->getDataLayout().getPointerSize();
1702 for (const auto &DebugLoc : DotDebugLocEntries) {
1703 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1704 const DwarfCompileUnit *CU = DebugLoc.CU;
1705 for (const auto &Entry : DebugLoc.List) {
1706 // Set up the range. This range is relative to the entry point of the
1707 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1708 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1709 if (auto *Base = CU->getBaseAddress()) {
1710 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1711 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1713 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1714 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1717 emitDebugLocEntryLocation(Entry);
1719 Asm->OutStreamer.EmitIntValue(0, Size);
1720 Asm->OutStreamer.EmitIntValue(0, Size);
1724 void DwarfDebug::emitDebugLocDWO() {
1725 Asm->OutStreamer.SwitchSection(
1726 Asm->getObjFileLowering().getDwarfLocDWOSection());
1727 for (const auto &DebugLoc : DotDebugLocEntries) {
1728 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1729 for (const auto &Entry : DebugLoc.List) {
1730 // Just always use start_length for now - at least that's one address
1731 // rather than two. We could get fancier and try to, say, reuse an
1732 // address we know we've emitted elsewhere (the start of the function?
1733 // The start of the CU or CU subrange that encloses this range?)
1734 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1735 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1736 Asm->EmitULEB128(idx);
1737 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1739 emitDebugLocEntryLocation(Entry);
1741 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1746 const MCSymbol *Start, *End;
1749 // Emit a debug aranges section, containing a CU lookup for any
1750 // address we can tie back to a CU.
1751 void DwarfDebug::emitDebugARanges() {
1752 // Provides a unique id per text section.
1753 DenseMap<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1755 // Prime section data.
1756 SectionMap[Asm->getObjFileLowering().getTextSection()];
1758 // Filter labels by section.
1759 for (const SymbolCU &SCU : ArangeLabels) {
1760 if (SCU.Sym->isInSection()) {
1761 // Make a note of this symbol and it's section.
1762 const MCSection *Section = &SCU.Sym->getSection();
1763 if (!Section->getKind().isMetadata())
1764 SectionMap[Section].push_back(SCU);
1766 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1767 // appear in the output. This sucks as we rely on sections to build
1768 // arange spans. We can do it without, but it's icky.
1769 SectionMap[nullptr].push_back(SCU);
1773 // Build a list of sections used.
1774 std::vector<const MCSection *> Sections;
1775 for (const auto &it : SectionMap) {
1776 const MCSection *Section = it.first;
1777 Sections.push_back(Section);
1780 // Sort the sections into order.
1781 // This is only done to ensure consistent output order across different runs.
1782 std::sort(Sections.begin(), Sections.end(), SectionSort);
1784 // Add terminating symbols for each section.
1785 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1786 const MCSection *Section = Sections[ID];
1787 MCSymbol *Sym = nullptr;
1790 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1791 // if we know the section name up-front. For user-created sections, the
1792 // resulting label may not be valid to use as a label. (section names can
1793 // use a greater set of characters on some systems)
1794 Sym = Asm->GetTempSymbol("debug_end", ID);
1795 Asm->OutStreamer.SwitchSection(Section);
1796 Asm->OutStreamer.EmitLabel(Sym);
1799 // Insert a final terminator.
1800 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1803 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1805 for (const MCSection *Section : Sections) {
1806 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1807 if (List.size() < 2)
1810 // If we have no section (e.g. common), just write out
1811 // individual spans for each symbol.
1813 for (const SymbolCU &Cur : List) {
1815 Span.Start = Cur.Sym;
1818 Spans[Cur.CU].push_back(Span);
1823 // Sort the symbols by offset within the section.
1824 std::sort(List.begin(), List.end(),
1825 [&](const SymbolCU &A, const SymbolCU &B) {
1826 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1827 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1829 // Symbols with no order assigned should be placed at the end.
1830 // (e.g. section end labels)
1838 // Build spans between each label.
1839 const MCSymbol *StartSym = List[0].Sym;
1840 for (size_t n = 1, e = List.size(); n < e; n++) {
1841 const SymbolCU &Prev = List[n - 1];
1842 const SymbolCU &Cur = List[n];
1844 // Try and build the longest span we can within the same CU.
1845 if (Cur.CU != Prev.CU) {
1847 Span.Start = StartSym;
1849 Spans[Prev.CU].push_back(Span);
1855 // Start the dwarf aranges section.
1856 Asm->OutStreamer.SwitchSection(
1857 Asm->getObjFileLowering().getDwarfARangesSection());
1859 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1861 // Build a list of CUs used.
1862 std::vector<DwarfCompileUnit *> CUs;
1863 for (const auto &it : Spans) {
1864 DwarfCompileUnit *CU = it.first;
1868 // Sort the CU list (again, to ensure consistent output order).
1869 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1870 return A->getUniqueID() < B->getUniqueID();
1873 // Emit an arange table for each CU we used.
1874 for (DwarfCompileUnit *CU : CUs) {
1875 std::vector<ArangeSpan> &List = Spans[CU];
1877 // Describe the skeleton CU's offset and length, not the dwo file's.
1878 if (auto *Skel = CU->getSkeleton())
1881 // Emit size of content not including length itself.
1882 unsigned ContentSize =
1883 sizeof(int16_t) + // DWARF ARange version number
1884 sizeof(int32_t) + // Offset of CU in the .debug_info section
1885 sizeof(int8_t) + // Pointer Size (in bytes)
1886 sizeof(int8_t); // Segment Size (in bytes)
1888 unsigned TupleSize = PtrSize * 2;
1890 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1892 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1894 ContentSize += Padding;
1895 ContentSize += (List.size() + 1) * TupleSize;
1897 // For each compile unit, write the list of spans it covers.
1898 Asm->OutStreamer.AddComment("Length of ARange Set");
1899 Asm->EmitInt32(ContentSize);
1900 Asm->OutStreamer.AddComment("DWARF Arange version number");
1901 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1902 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1903 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1904 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1905 Asm->EmitInt8(PtrSize);
1906 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1909 Asm->OutStreamer.EmitFill(Padding, 0xff);
1911 for (const ArangeSpan &Span : List) {
1912 Asm->EmitLabelReference(Span.Start, PtrSize);
1914 // Calculate the size as being from the span start to it's end.
1916 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1918 // For symbols without an end marker (e.g. common), we
1919 // write a single arange entry containing just that one symbol.
1920 uint64_t Size = SymSize[Span.Start];
1924 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1928 Asm->OutStreamer.AddComment("ARange terminator");
1929 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1930 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1934 // Emit visible names into a debug ranges section.
1935 void DwarfDebug::emitDebugRanges() {
1936 // Start the dwarf ranges section.
1937 Asm->OutStreamer.SwitchSection(
1938 Asm->getObjFileLowering().getDwarfRangesSection());
1940 // Size for our labels.
1941 unsigned char Size = Asm->getDataLayout().getPointerSize();
1943 // Grab the specific ranges for the compile units in the module.
1944 for (const auto &I : CUMap) {
1945 DwarfCompileUnit *TheCU = I.second;
1947 if (auto *Skel = TheCU->getSkeleton())
1950 // Iterate over the misc ranges for the compile units in the module.
1951 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1952 // Emit our symbol so we can find the beginning of the range.
1953 Asm->OutStreamer.EmitLabel(List.getSym());
1955 for (const RangeSpan &Range : List.getRanges()) {
1956 const MCSymbol *Begin = Range.getStart();
1957 const MCSymbol *End = Range.getEnd();
1958 assert(Begin && "Range without a begin symbol?");
1959 assert(End && "Range without an end symbol?");
1960 if (auto *Base = TheCU->getBaseAddress()) {
1961 Asm->EmitLabelDifference(Begin, Base, Size);
1962 Asm->EmitLabelDifference(End, Base, Size);
1964 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1965 Asm->OutStreamer.EmitSymbolValue(End, Size);
1969 // And terminate the list with two 0 values.
1970 Asm->OutStreamer.EmitIntValue(0, Size);
1971 Asm->OutStreamer.EmitIntValue(0, Size);
1976 // DWARF5 Experimental Separate Dwarf emitters.
1978 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1979 std::unique_ptr<DwarfUnit> NewU) {
1980 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1981 U.getCUNode().getSplitDebugFilename());
1983 if (!CompilationDir.empty())
1984 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1986 addGnuPubAttributes(*NewU, Die);
1988 SkeletonHolder.addUnit(std::move(NewU));
1991 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1992 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1993 // DW_AT_addr_base, DW_AT_ranges_base.
1994 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1996 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1997 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1998 DwarfCompileUnit &NewCU = *OwnedUnit;
1999 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2000 DwarfInfoSectionSym);
2002 NewCU.initStmtList(DwarfLineSectionSym);
2004 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2009 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2010 // compile units that would normally be in debug_info.
2011 void DwarfDebug::emitDebugInfoDWO() {
2012 assert(useSplitDwarf() && "No split dwarf debug info?");
2013 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2014 // emit relocations into the dwo file.
2015 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2018 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2019 // abbreviations for the .debug_info.dwo section.
2020 void DwarfDebug::emitDebugAbbrevDWO() {
2021 assert(useSplitDwarf() && "No split dwarf?");
2022 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2025 void DwarfDebug::emitDebugLineDWO() {
2026 assert(useSplitDwarf() && "No split dwarf?");
2027 Asm->OutStreamer.SwitchSection(
2028 Asm->getObjFileLowering().getDwarfLineDWOSection());
2029 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2032 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2033 // string section and is identical in format to traditional .debug_str
2035 void DwarfDebug::emitDebugStrDWO() {
2036 assert(useSplitDwarf() && "No split dwarf?");
2037 const MCSection *OffSec =
2038 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2039 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2043 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2044 if (!useSplitDwarf())
2047 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2048 return &SplitTypeUnitFileTable;
2051 static uint64_t makeTypeSignature(StringRef Identifier) {
2053 Hash.update(Identifier);
2054 // ... take the least significant 8 bytes and return those. Our MD5
2055 // implementation always returns its results in little endian, swap bytes
2057 MD5::MD5Result Result;
2059 return support::endian::read64le(Result + 8);
2062 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2063 StringRef Identifier, DIE &RefDie,
2064 DICompositeType CTy) {
2065 // Fast path if we're building some type units and one has already used the
2066 // address pool we know we're going to throw away all this work anyway, so
2067 // don't bother building dependent types.
2068 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2071 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2073 CU.addDIETypeSignature(RefDie, *TU);
2077 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2078 AddrPool.resetUsedFlag();
2080 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2081 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2082 this, &InfoHolder, getDwoLineTable(CU));
2083 DwarfTypeUnit &NewTU = *OwnedUnit;
2084 DIE &UnitDie = NewTU.getUnitDie();
2086 TypeUnitsUnderConstruction.push_back(
2087 std::make_pair(std::move(OwnedUnit), CTy));
2089 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2092 uint64_t Signature = makeTypeSignature(Identifier);
2093 NewTU.setTypeSignature(Signature);
2095 if (useSplitDwarf())
2096 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2098 CU.applyStmtList(UnitDie);
2100 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2103 NewTU.setType(NewTU.createTypeDIE(CTy));
2106 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2107 TypeUnitsUnderConstruction.clear();
2109 // Types referencing entries in the address table cannot be placed in type
2111 if (AddrPool.hasBeenUsed()) {
2113 // Remove all the types built while building this type.
2114 // This is pessimistic as some of these types might not be dependent on
2115 // the type that used an address.
2116 for (const auto &TU : TypeUnitsToAdd)
2117 DwarfTypeUnits.erase(TU.second);
2119 // Construct this type in the CU directly.
2120 // This is inefficient because all the dependent types will be rebuilt
2121 // from scratch, including building them in type units, discovering that
2122 // they depend on addresses, throwing them out and rebuilding them.
2123 CU.constructTypeDIE(RefDie, CTy);
2127 // If the type wasn't dependent on fission addresses, finish adding the type
2128 // and all its dependent types.
2129 for (auto &TU : TypeUnitsToAdd)
2130 InfoHolder.addUnit(std::move(TU.first));
2132 CU.addDIETypeSignature(RefDie, NewTU);
2135 // Accelerator table mutators - add each name along with its companion
2136 // DIE to the proper table while ensuring that the name that we're going
2137 // to reference is in the string table. We do this since the names we
2138 // add may not only be identical to the names in the DIE.
2139 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2140 if (!useDwarfAccelTables())
2142 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2146 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2147 if (!useDwarfAccelTables())
2149 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2153 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2154 if (!useDwarfAccelTables())
2156 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2160 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2161 if (!useDwarfAccelTables())
2163 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),