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, *this, "info_string", DIEValueAllocator),
193 UsedNonDefaultText(false),
194 SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
195 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
197 dwarf::DW_FORM_data4)),
198 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
199 dwarf::DW_FORM_data4)),
200 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
201 dwarf::DW_FORM_data4)),
202 AccelTypes(TypeAtoms) {
204 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
205 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
206 DwarfLineSectionSym = nullptr;
207 DwarfAddrSectionSym = nullptr;
208 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
209 FunctionBeginSym = FunctionEndSym = nullptr;
213 // Turn on accelerator tables for Darwin by default, pubnames by
214 // default for non-Darwin, and handle split dwarf.
215 if (DwarfAccelTables == Default)
216 HasDwarfAccelTables = IsDarwin;
218 HasDwarfAccelTables = DwarfAccelTables == Enable;
220 if (SplitDwarf == Default)
221 HasSplitDwarf = false;
223 HasSplitDwarf = SplitDwarf == Enable;
225 if (DwarfPubSections == Default)
226 HasDwarfPubSections = !IsDarwin;
228 HasDwarfPubSections = DwarfPubSections == Enable;
230 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
231 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
232 : MMI->getModule()->getDwarfVersion();
234 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
237 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
242 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
243 DwarfDebug::~DwarfDebug() { }
245 // Switch to the specified MCSection and emit an assembler
246 // temporary label to it if SymbolStem is specified.
247 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
248 const char *SymbolStem = nullptr) {
249 Asm->OutStreamer.SwitchSection(Section);
253 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
254 Asm->OutStreamer.EmitLabel(TmpSym);
258 static bool isObjCClass(StringRef Name) {
259 return Name.startswith("+") || Name.startswith("-");
262 static bool hasObjCCategory(StringRef Name) {
263 if (!isObjCClass(Name))
266 return Name.find(") ") != StringRef::npos;
269 static void getObjCClassCategory(StringRef In, StringRef &Class,
270 StringRef &Category) {
271 if (!hasObjCCategory(In)) {
272 Class = In.slice(In.find('[') + 1, In.find(' '));
277 Class = In.slice(In.find('[') + 1, In.find('('));
278 Category = In.slice(In.find('[') + 1, In.find(' '));
282 static StringRef getObjCMethodName(StringRef In) {
283 return In.slice(In.find(' ') + 1, In.find(']'));
286 // Helper for sorting sections into a stable output order.
287 static bool SectionSort(const MCSection *A, const MCSection *B) {
288 std::string LA = (A ? A->getLabelBeginName() : "");
289 std::string LB = (B ? B->getLabelBeginName() : "");
293 // Add the various names to the Dwarf accelerator table names.
294 // TODO: Determine whether or not we should add names for programs
295 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
296 // is only slightly different than the lookup of non-standard ObjC names.
297 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
298 if (!SP.isDefinition())
300 addAccelName(SP.getName(), Die);
302 // If the linkage name is different than the name, go ahead and output
303 // that as well into the name table.
304 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
305 addAccelName(SP.getLinkageName(), Die);
307 // If this is an Objective-C selector name add it to the ObjC accelerator
309 if (isObjCClass(SP.getName())) {
310 StringRef Class, Category;
311 getObjCClassCategory(SP.getName(), Class, Category);
312 addAccelObjC(Class, Die);
314 addAccelObjC(Category, Die);
315 // Also add the base method name to the name table.
316 addAccelName(getObjCMethodName(SP.getName()), Die);
320 /// isSubprogramContext - Return true if Context is either a subprogram
321 /// or another context nested inside a subprogram.
322 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
325 DIDescriptor D(Context);
326 if (D.isSubprogram())
329 return isSubprogramContext(resolve(DIType(Context).getContext()));
333 /// Check whether we should create a DIE for the given Scope, return true
334 /// if we don't create a DIE (the corresponding DIE is null).
335 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
336 if (Scope->isAbstractScope())
339 // We don't create a DIE if there is no Range.
340 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
344 if (Ranges.size() > 1)
347 // We don't create a DIE if we have a single Range and the end label
349 return !getLabelAfterInsn(Ranges.front().second);
352 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
354 if (auto *SkelCU = CU.getSkeleton())
358 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
359 assert(Scope && Scope->getScopeNode());
360 assert(Scope->isAbstractScope());
361 assert(!Scope->getInlinedAt());
363 const MDNode *SP = Scope->getScopeNode();
365 ProcessedSPNodes.insert(SP);
367 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
368 // was inlined from another compile unit.
369 auto &CU = SPMap[SP];
370 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
371 CU.constructAbstractSubprogramScopeDIE(Scope);
375 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
376 if (!GenerateGnuPubSections)
379 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
382 // Create new DwarfCompileUnit for the given metadata node with tag
383 // DW_TAG_compile_unit.
384 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
385 StringRef FN = DIUnit.getFilename();
386 CompilationDir = DIUnit.getDirectory();
388 auto OwnedUnit = make_unique<DwarfCompileUnit>(
389 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
390 DwarfCompileUnit &NewCU = *OwnedUnit;
391 DIE &Die = NewCU.getUnitDie();
392 InfoHolder.addUnit(std::move(OwnedUnit));
394 NewCU.setSkeleton(constructSkeletonCU(NewCU));
396 // LTO with assembly output shares a single line table amongst multiple CUs.
397 // To avoid the compilation directory being ambiguous, let the line table
398 // explicitly describe the directory of all files, never relying on the
399 // compilation directory.
400 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
401 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
402 NewCU.getUniqueID(), CompilationDir);
404 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
405 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
406 DIUnit.getLanguage());
407 NewCU.addString(Die, dwarf::DW_AT_name, FN);
409 if (!useSplitDwarf()) {
410 NewCU.initStmtList(DwarfLineSectionSym);
412 // If we're using split dwarf the compilation dir is going to be in the
413 // skeleton CU and so we don't need to duplicate it here.
414 if (!CompilationDir.empty())
415 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
417 addGnuPubAttributes(NewCU, Die);
420 if (DIUnit.isOptimized())
421 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
423 StringRef Flags = DIUnit.getFlags();
425 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
427 if (unsigned RVer = DIUnit.getRunTimeVersion())
428 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
429 dwarf::DW_FORM_data1, RVer);
432 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
433 DwarfInfoDWOSectionSym);
435 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
436 DwarfInfoSectionSym);
438 CUMap.insert(std::make_pair(DIUnit, &NewCU));
439 CUDieMap.insert(std::make_pair(&Die, &NewCU));
443 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
445 DIImportedEntity Module(N);
446 assert(Module.Verify());
447 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
448 D->addChild(TheCU.constructImportedEntityDIE(Module));
451 // Emit all Dwarf sections that should come prior to the content. Create
452 // global DIEs and emit initial debug info sections. This is invoked by
453 // the target AsmPrinter.
454 void DwarfDebug::beginModule() {
455 if (DisableDebugInfoPrinting)
458 const Module *M = MMI->getModule();
460 FunctionDIs = makeSubprogramMap(*M);
462 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
465 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
467 // Emit initial sections so we can reference labels later.
470 SingleCU = CU_Nodes->getNumOperands() == 1;
472 for (MDNode *N : CU_Nodes->operands()) {
473 DICompileUnit CUNode(N);
474 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
475 DIArray ImportedEntities = CUNode.getImportedEntities();
476 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
477 ScopesWithImportedEntities.push_back(std::make_pair(
478 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
479 ImportedEntities.getElement(i)));
480 std::sort(ScopesWithImportedEntities.begin(),
481 ScopesWithImportedEntities.end(), less_first());
482 DIArray GVs = CUNode.getGlobalVariables();
483 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
484 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
485 DIArray SPs = CUNode.getSubprograms();
486 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
487 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
488 DIArray EnumTypes = CUNode.getEnumTypes();
489 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
490 DIType Ty(EnumTypes.getElement(i));
491 // The enum types array by design contains pointers to
492 // MDNodes rather than DIRefs. Unique them here.
493 DIType UniqueTy(resolve(Ty.getRef()));
494 CU.getOrCreateTypeDIE(UniqueTy);
496 DIArray RetainedTypes = CUNode.getRetainedTypes();
497 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
498 DIType Ty(RetainedTypes.getElement(i));
499 // The retained 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 // Emit imported_modules last so that the relevant context is already
506 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
507 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
510 // Tell MMI that we have debug info.
511 MMI->setDebugInfoAvailability(true);
514 void DwarfDebug::finishVariableDefinitions() {
515 for (const auto &Var : ConcreteVariables) {
516 DIE *VariableDie = Var->getDIE();
518 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
519 // in the ConcreteVariables list, rather than looking it up again here.
520 // DIE::getUnit isn't simple - it walks parent pointers, etc.
521 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
523 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
524 if (AbsVar && AbsVar->getDIE()) {
525 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
528 Unit->applyVariableAttributes(*Var, *VariableDie);
532 void DwarfDebug::finishSubprogramDefinitions() {
533 for (const auto &P : SPMap)
534 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
535 CU.finishSubprogramDefinition(DISubprogram(P.first));
540 // Collect info for variables that were optimized out.
541 void DwarfDebug::collectDeadVariables() {
542 const Module *M = MMI->getModule();
544 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
545 for (MDNode *N : CU_Nodes->operands()) {
546 DICompileUnit TheCU(N);
547 // Construct subprogram DIE and add variables DIEs.
548 DwarfCompileUnit *SPCU =
549 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
550 assert(SPCU && "Unable to find Compile Unit!");
551 DIArray Subprograms = TheCU.getSubprograms();
552 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
553 DISubprogram SP(Subprograms.getElement(i));
554 if (ProcessedSPNodes.count(SP) != 0)
556 SPCU->collectDeadVariables(SP);
562 void DwarfDebug::finalizeModuleInfo() {
563 finishSubprogramDefinitions();
565 finishVariableDefinitions();
567 // Collect info for variables that were optimized out.
568 collectDeadVariables();
570 // Handle anything that needs to be done on a per-unit basis after
571 // all other generation.
572 for (const auto &P : CUMap) {
573 auto &TheCU = *P.second;
574 // Emit DW_AT_containing_type attribute to connect types with their
575 // vtable holding type.
576 TheCU.constructContainingTypeDIEs();
578 // Add CU specific attributes if we need to add any.
579 // If we're splitting the dwarf out now that we've got the entire
580 // CU then add the dwo id to it.
581 auto *SkCU = TheCU.getSkeleton();
582 if (useSplitDwarf()) {
583 // Emit a unique identifier for this CU.
584 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
585 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
586 dwarf::DW_FORM_data8, ID);
587 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
588 dwarf::DW_FORM_data8, ID);
590 // We don't keep track of which addresses are used in which CU so this
591 // is a bit pessimistic under LTO.
592 if (!AddrPool.isEmpty())
593 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
594 DwarfAddrSectionSym, DwarfAddrSectionSym);
595 if (!SkCU->getRangeLists().empty())
596 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
597 DwarfDebugRangeSectionSym,
598 DwarfDebugRangeSectionSym);
601 // If we have code split among multiple sections or non-contiguous
602 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
603 // remain in the .o file, otherwise add a DW_AT_low_pc.
604 // FIXME: We should use ranges allow reordering of code ala
605 // .subsections_via_symbols in mach-o. This would mean turning on
606 // ranges for all subprogram DIEs for mach-o.
607 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
608 if (unsigned NumRanges = TheCU.getRanges().size()) {
610 // A DW_AT_low_pc attribute may also be specified in combination with
611 // DW_AT_ranges to specify the default base address for use in
612 // location lists (see Section 2.6.2) and range lists (see Section
614 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
616 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
617 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
621 // Compute DIE offsets and sizes.
622 InfoHolder.computeSizeAndOffsets();
624 SkeletonHolder.computeSizeAndOffsets();
627 // Emit all Dwarf sections that should come after the content.
628 void DwarfDebug::endModule() {
629 assert(CurFn == nullptr);
630 assert(CurMI == nullptr);
632 // If we aren't actually generating debug info (check beginModule -
633 // conditionalized on !DisableDebugInfoPrinting and the presence of the
634 // llvm.dbg.cu metadata node)
635 if (!DwarfInfoSectionSym)
638 // Finalize the debug info for the module.
639 finalizeModuleInfo();
643 // Emit all the DIEs into a debug info section.
646 // Corresponding abbreviations into a abbrev section.
649 // Emit info into a debug aranges section.
650 if (GenerateARangeSection)
653 // Emit info into a debug ranges section.
656 if (useSplitDwarf()) {
659 emitDebugAbbrevDWO();
662 // Emit DWO addresses.
663 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
665 // Emit info into a debug loc section.
668 // Emit info into the dwarf accelerator table sections.
669 if (useDwarfAccelTables()) {
672 emitAccelNamespaces();
676 // Emit the pubnames and pubtypes sections if requested.
677 if (HasDwarfPubSections) {
678 emitDebugPubNames(GenerateGnuPubSections);
679 emitDebugPubTypes(GenerateGnuPubSections);
684 AbstractVariables.clear();
687 // Find abstract variable, if any, associated with Var.
688 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
689 DIVariable &Cleansed) {
690 LLVMContext &Ctx = DV->getContext();
691 // More then one inlined variable corresponds to one abstract variable.
692 // FIXME: This duplication of variables when inlining should probably be
693 // removed. It's done to allow each DIVariable to describe its location
694 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
695 // make it accurate then remove this duplication/cleansing stuff.
696 Cleansed = cleanseInlinedVariable(DV, Ctx);
697 auto I = AbstractVariables.find(Cleansed);
698 if (I != AbstractVariables.end())
699 return I->second.get();
703 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
705 return getExistingAbstractVariable(DV, Cleansed);
708 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
709 LexicalScope *Scope) {
710 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
711 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
712 AbstractVariables[Var] = std::move(AbsDbgVariable);
715 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
716 const MDNode *ScopeNode) {
717 DIVariable Cleansed = DV;
718 if (getExistingAbstractVariable(DV, Cleansed))
721 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
725 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
726 const MDNode *ScopeNode) {
727 DIVariable Cleansed = DV;
728 if (getExistingAbstractVariable(DV, Cleansed))
731 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
732 createAbstractVariable(Cleansed, Scope);
735 // Collect variable information from side table maintained by MMI.
736 void DwarfDebug::collectVariableInfoFromMMITable(
737 SmallPtrSetImpl<const MDNode *> &Processed) {
738 for (const auto &VI : MMI->getVariableDbgInfo()) {
741 Processed.insert(VI.Var);
742 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
744 // If variable scope is not found then skip this variable.
748 DIVariable DV(VI.Var);
749 DIExpression Expr(VI.Expr);
750 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
751 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
752 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
753 ConcreteVariables.push_back(std::move(RegVar));
757 // Get .debug_loc entry for the instruction range starting at MI.
758 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
759 const MDNode *Expr = MI->getDebugExpression();
760 const MDNode *Var = MI->getDebugVariable();
762 assert(MI->getNumOperands() == 4);
763 if (MI->getOperand(0).isReg()) {
764 MachineLocation MLoc;
765 // If the second operand is an immediate, this is a
766 // register-indirect address.
767 if (!MI->getOperand(1).isImm())
768 MLoc.set(MI->getOperand(0).getReg());
770 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
771 return DebugLocEntry::Value(Var, Expr, MLoc);
773 if (MI->getOperand(0).isImm())
774 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
775 if (MI->getOperand(0).isFPImm())
776 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
777 if (MI->getOperand(0).isCImm())
778 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
780 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
783 /// Determine whether two variable pieces overlap.
784 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
785 if (!P1.isBitPiece() || !P2.isBitPiece())
787 unsigned l1 = P1.getBitPieceOffset();
788 unsigned l2 = P2.getBitPieceOffset();
789 unsigned r1 = l1 + P1.getBitPieceSize();
790 unsigned r2 = l2 + P2.getBitPieceSize();
791 // True where [l1,r1[ and [r1,r2[ overlap.
792 return (l1 < r2) && (l2 < r1);
795 /// Build the location list for all DBG_VALUEs in the function that
796 /// describe the same variable. If the ranges of several independent
797 /// pieces of the same variable overlap partially, split them up and
798 /// combine the ranges. The resulting DebugLocEntries are will have
799 /// strict monotonically increasing begin addresses and will never
804 // Ranges History [var, loc, piece ofs size]
805 // 0 | [x, (reg0, piece 0, 32)]
806 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
808 // 3 | [clobber reg0]
809 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
814 // [0-1] [x, (reg0, piece 0, 32)]
815 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
816 // [3-4] [x, (reg1, piece 32, 32)]
817 // [4- ] [x, (mem, piece 0, 64)]
819 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
820 const DbgValueHistoryMap::InstrRanges &Ranges) {
821 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
823 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
824 const MachineInstr *Begin = I->first;
825 const MachineInstr *End = I->second;
826 assert(Begin->isDebugValue() && "Invalid History entry");
828 // Check if a variable is inaccessible in this range.
829 if (Begin->getNumOperands() > 1 &&
830 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
835 // If this piece overlaps with any open ranges, truncate them.
836 DIExpression DIExpr = Begin->getDebugExpression();
837 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
838 [&](DebugLocEntry::Value R) {
839 return piecesOverlap(DIExpr, R.getExpression());
841 OpenRanges.erase(Last, OpenRanges.end());
843 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
844 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
846 const MCSymbol *EndLabel;
848 EndLabel = getLabelAfterInsn(End);
849 else if (std::next(I) == Ranges.end())
850 EndLabel = FunctionEndSym;
852 EndLabel = getLabelBeforeInsn(std::next(I)->first);
853 assert(EndLabel && "Forgot label after instruction ending a range!");
855 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
857 auto Value = getDebugLocValue(Begin);
858 DebugLocEntry Loc(StartLabel, EndLabel, Value);
859 bool couldMerge = false;
861 // If this is a piece, it may belong to the current DebugLocEntry.
862 if (DIExpr.isBitPiece()) {
863 // Add this value to the list of open ranges.
864 OpenRanges.push_back(Value);
866 // Attempt to add the piece to the last entry.
867 if (!DebugLoc.empty())
868 if (DebugLoc.back().MergeValues(Loc))
873 // Need to add a new DebugLocEntry. Add all values from still
874 // valid non-overlapping pieces.
875 if (OpenRanges.size())
876 Loc.addValues(OpenRanges);
878 DebugLoc.push_back(std::move(Loc));
881 // Attempt to coalesce the ranges of two otherwise identical
883 auto CurEntry = DebugLoc.rbegin();
884 auto PrevEntry = std::next(CurEntry);
885 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
889 dbgs() << CurEntry->getValues().size() << " Values:\n";
890 for (auto Value : CurEntry->getValues()) {
891 Value.getVariable()->dump();
892 Value.getExpression()->dump();
900 // Find variables for each lexical scope.
902 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
903 SmallPtrSetImpl<const MDNode *> &Processed) {
904 // Grab the variable info that was squirreled away in the MMI side-table.
905 collectVariableInfoFromMMITable(Processed);
907 for (const auto &I : DbgValues) {
908 DIVariable DV(I.first);
909 if (Processed.count(DV))
912 // Instruction ranges, specifying where DV is accessible.
913 const auto &Ranges = I.second;
917 LexicalScope *Scope = nullptr;
918 if (MDNode *IA = DV.getInlinedAt())
919 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
921 Scope = LScopes.findLexicalScope(DV.getContext());
922 // If variable scope is not found then skip this variable.
926 Processed.insert(DV);
927 const MachineInstr *MInsn = Ranges.front().first;
928 assert(MInsn->isDebugValue() && "History must begin with debug value");
929 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
930 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
931 DbgVariable *RegVar = ConcreteVariables.back().get();
932 InfoHolder.addScopeVariable(Scope, RegVar);
934 // Check if the first DBG_VALUE is valid for the rest of the function.
935 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
938 // Handle multiple DBG_VALUE instructions describing one variable.
939 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
941 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
942 DebugLocList &LocList = DotDebugLocEntries.back();
945 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
947 // Build the location list for this variable.
948 buildLocationList(LocList.List, Ranges);
949 // Finalize the entry by lowering it into a DWARF bytestream.
950 for (auto &Entry : LocList.List)
951 Entry.finalize(*Asm, TypeIdentifierMap);
954 // Collect info for variables that were optimized out.
955 DIArray Variables = SP.getVariables();
956 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
957 DIVariable DV(Variables.getElement(i));
958 assert(DV.isVariable());
959 if (!Processed.insert(DV).second)
961 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
962 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
964 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
965 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
970 // Return Label preceding the instruction.
971 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
972 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
973 assert(Label && "Didn't insert label before instruction");
977 // Return Label immediately following the instruction.
978 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
979 return LabelsAfterInsn.lookup(MI);
982 // Process beginning of an instruction.
983 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
984 assert(CurMI == nullptr);
986 // Check if source location changes, but ignore DBG_VALUE locations.
987 if (!MI->isDebugValue()) {
988 DebugLoc DL = MI->getDebugLoc();
989 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
992 if (DL == PrologEndLoc) {
993 Flags |= DWARF2_FLAG_PROLOGUE_END;
994 PrologEndLoc = DebugLoc();
995 Flags |= DWARF2_FLAG_IS_STMT;
998 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
999 Flags |= DWARF2_FLAG_IS_STMT;
1001 if (!DL.isUnknown()) {
1002 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1003 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1005 recordSourceLine(0, 0, nullptr, 0);
1009 // Insert labels where requested.
1010 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1011 LabelsBeforeInsn.find(MI);
1014 if (I == LabelsBeforeInsn.end())
1017 // Label already assigned.
1022 PrevLabel = MMI->getContext().CreateTempSymbol();
1023 Asm->OutStreamer.EmitLabel(PrevLabel);
1025 I->second = PrevLabel;
1028 // Process end of an instruction.
1029 void DwarfDebug::endInstruction() {
1030 assert(CurMI != nullptr);
1031 // Don't create a new label after DBG_VALUE instructions.
1032 // They don't generate code.
1033 if (!CurMI->isDebugValue())
1034 PrevLabel = nullptr;
1036 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1037 LabelsAfterInsn.find(CurMI);
1041 if (I == LabelsAfterInsn.end())
1044 // Label already assigned.
1048 // We need a label after this instruction.
1050 PrevLabel = MMI->getContext().CreateTempSymbol();
1051 Asm->OutStreamer.EmitLabel(PrevLabel);
1053 I->second = PrevLabel;
1056 // Each LexicalScope has first instruction and last instruction to mark
1057 // beginning and end of a scope respectively. Create an inverse map that list
1058 // scopes starts (and ends) with an instruction. One instruction may start (or
1059 // end) multiple scopes. Ignore scopes that are not reachable.
1060 void DwarfDebug::identifyScopeMarkers() {
1061 SmallVector<LexicalScope *, 4> WorkList;
1062 WorkList.push_back(LScopes.getCurrentFunctionScope());
1063 while (!WorkList.empty()) {
1064 LexicalScope *S = WorkList.pop_back_val();
1066 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1067 if (!Children.empty())
1068 WorkList.append(Children.begin(), Children.end());
1070 if (S->isAbstractScope())
1073 for (const InsnRange &R : S->getRanges()) {
1074 assert(R.first && "InsnRange does not have first instruction!");
1075 assert(R.second && "InsnRange does not have second instruction!");
1076 requestLabelBeforeInsn(R.first);
1077 requestLabelAfterInsn(R.second);
1082 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1083 // First known non-DBG_VALUE and non-frame setup location marks
1084 // the beginning of the function body.
1085 for (const auto &MBB : *MF)
1086 for (const auto &MI : MBB)
1087 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1088 !MI.getDebugLoc().isUnknown()) {
1089 // Did the target forget to set the FrameSetup flag for CFI insns?
1090 assert(!MI.isCFIInstruction() &&
1091 "First non-frame-setup instruction is a CFI instruction.");
1092 return MI.getDebugLoc();
1097 // Gather pre-function debug information. Assumes being called immediately
1098 // after the function entry point has been emitted.
1099 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1102 // If there's no debug info for the function we're not going to do anything.
1103 if (!MMI->hasDebugInfo())
1106 auto DI = FunctionDIs.find(MF->getFunction());
1107 if (DI == FunctionDIs.end())
1110 // Grab the lexical scopes for the function, if we don't have any of those
1111 // then we're not going to be able to do anything.
1112 LScopes.initialize(*MF);
1113 if (LScopes.empty())
1116 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1118 // Make sure that each lexical scope will have a begin/end label.
1119 identifyScopeMarkers();
1121 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1122 // belongs to so that we add to the correct per-cu line table in the
1124 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1125 // FnScope->getScopeNode() and DI->second should represent the same function,
1126 // though they may not be the same MDNode due to inline functions merged in
1127 // LTO where the debug info metadata still differs (either due to distinct
1128 // written differences - two versions of a linkonce_odr function
1129 // written/copied into two separate files, or some sub-optimal metadata that
1130 // isn't structurally identical (see: file path/name info from clang, which
1131 // includes the directory of the cpp file being built, even when the file name
1132 // is absolute (such as an <> lookup header)))
1133 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1134 assert(TheCU && "Unable to find compile unit!");
1135 if (Asm->OutStreamer.hasRawTextSupport())
1136 // Use a single line table if we are generating assembly.
1137 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1139 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1141 // Emit a label for the function so that we have a beginning address.
1142 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1143 // Assumes in correct section after the entry point.
1144 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1146 // Calculate history for local variables.
1147 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1150 // Request labels for the full history.
1151 for (const auto &I : DbgValues) {
1152 const auto &Ranges = I.second;
1156 // The first mention of a function argument gets the FunctionBeginSym
1157 // label, so arguments are visible when breaking at function entry.
1158 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1159 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1160 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1161 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1162 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1163 // Mark all non-overlapping initial pieces.
1164 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1165 DIExpression Piece = I->first->getDebugExpression();
1166 if (std::all_of(Ranges.begin(), I,
1167 [&](DbgValueHistoryMap::InstrRange Pred) {
1168 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1170 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1177 for (const auto &Range : Ranges) {
1178 requestLabelBeforeInsn(Range.first);
1180 requestLabelAfterInsn(Range.second);
1184 PrevInstLoc = DebugLoc();
1185 PrevLabel = FunctionBeginSym;
1187 // Record beginning of function.
1188 PrologEndLoc = findPrologueEndLoc(MF);
1189 if (!PrologEndLoc.isUnknown()) {
1190 DebugLoc FnStartDL =
1191 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1193 // We'd like to list the prologue as "not statements" but GDB behaves
1194 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1195 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1196 FnStartDL.getScope(MF->getFunction()->getContext()),
1197 DWARF2_FLAG_IS_STMT);
1201 // Gather and emit post-function debug information.
1202 void DwarfDebug::endFunction(const MachineFunction *MF) {
1203 assert(CurFn == MF &&
1204 "endFunction should be called with the same function as beginFunction");
1206 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1207 !FunctionDIs.count(MF->getFunction())) {
1208 // If we don't have a lexical scope for this function then there will
1209 // be a hole in the range information. Keep note of this by setting the
1210 // previously used section to nullptr.
1216 // Define end label for subprogram.
1217 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1218 // Assumes in correct section after the entry point.
1219 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1221 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1222 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1224 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1225 DISubprogram SP(FnScope->getScopeNode());
1226 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1228 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1229 collectVariableInfo(TheCU, SP, ProcessedVars);
1231 // Add the range of this function to the list of ranges for the CU.
1232 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1234 // Under -gmlt, skip building the subprogram if there are no inlined
1235 // subroutines inside it.
1236 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1237 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1238 assert(InfoHolder.getScopeVariables().empty());
1239 assert(DbgValues.empty());
1240 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1241 // by a -gmlt CU. Add a test and remove this assertion.
1242 assert(AbstractVariables.empty());
1243 LabelsBeforeInsn.clear();
1244 LabelsAfterInsn.clear();
1245 PrevLabel = nullptr;
1251 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1253 // Construct abstract scopes.
1254 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1255 DISubprogram SP(AScope->getScopeNode());
1256 assert(SP.isSubprogram());
1257 // Collect info for variables that were optimized out.
1258 DIArray Variables = SP.getVariables();
1259 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1260 DIVariable DV(Variables.getElement(i));
1261 assert(DV && DV.isVariable());
1262 if (!ProcessedVars.insert(DV).second)
1264 ensureAbstractVariableIsCreated(DV, DV.getContext());
1265 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1266 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1268 constructAbstractSubprogramScopeDIE(AScope);
1271 TheCU.constructSubprogramScopeDIE(FnScope);
1272 if (auto *SkelCU = TheCU.getSkeleton())
1273 if (!LScopes.getAbstractScopesList().empty())
1274 SkelCU->constructSubprogramScopeDIE(FnScope);
1277 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1278 // DbgVariables except those that are also in AbstractVariables (since they
1279 // can be used cross-function)
1280 InfoHolder.getScopeVariables().clear();
1282 LabelsBeforeInsn.clear();
1283 LabelsAfterInsn.clear();
1284 PrevLabel = nullptr;
1288 // Register a source line with debug info. Returns the unique label that was
1289 // emitted and which provides correspondence to the source line list.
1290 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1295 unsigned Discriminator = 0;
1296 if (DIScope Scope = DIScope(S)) {
1297 assert(Scope.isScope());
1298 Fn = Scope.getFilename();
1299 Dir = Scope.getDirectory();
1300 if (Scope.isLexicalBlockFile())
1301 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1303 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1304 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1305 .getOrCreateSourceID(Fn, Dir);
1307 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1311 //===----------------------------------------------------------------------===//
1313 //===----------------------------------------------------------------------===//
1315 // Emit initial Dwarf sections with a label at the start of each one.
1316 void DwarfDebug::emitSectionLabels() {
1317 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1319 // Dwarf sections base addresses.
1320 DwarfInfoSectionSym =
1321 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1322 if (useSplitDwarf()) {
1323 DwarfInfoDWOSectionSym =
1324 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1325 DwarfTypesDWOSectionSym = emitSectionSym(
1326 Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1328 DwarfAbbrevSectionSym =
1329 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1330 if (useSplitDwarf())
1331 DwarfAbbrevDWOSectionSym = emitSectionSym(
1332 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1333 if (GenerateARangeSection)
1334 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1336 DwarfLineSectionSym =
1337 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1338 if (GenerateGnuPubSections) {
1339 DwarfGnuPubNamesSectionSym =
1340 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1341 DwarfGnuPubTypesSectionSym =
1342 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1343 } else if (HasDwarfPubSections) {
1344 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1345 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1348 DwarfStrSectionSym =
1349 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1350 if (useSplitDwarf()) {
1351 DwarfStrDWOSectionSym =
1352 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1353 DwarfAddrSectionSym =
1354 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1355 DwarfDebugLocSectionSym =
1356 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1358 DwarfDebugLocSectionSym =
1359 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1360 DwarfDebugRangeSectionSym =
1361 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1364 // Recursively emits a debug information entry.
1365 void DwarfDebug::emitDIE(DIE &Die) {
1366 // Get the abbreviation for this DIE.
1367 const DIEAbbrev &Abbrev = Die.getAbbrev();
1369 // Emit the code (index) for the abbreviation.
1370 if (Asm->isVerbose())
1371 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1372 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1373 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1374 dwarf::TagString(Abbrev.getTag()));
1375 Asm->EmitULEB128(Abbrev.getNumber());
1377 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1378 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1380 // Emit the DIE attribute values.
1381 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1382 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1383 dwarf::Form Form = AbbrevData[i].getForm();
1384 assert(Form && "Too many attributes for DIE (check abbreviation)");
1386 if (Asm->isVerbose()) {
1387 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1388 if (Attr == dwarf::DW_AT_accessibility)
1389 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1390 cast<DIEInteger>(Values[i])->getValue()));
1393 // Emit an attribute using the defined form.
1394 Values[i]->EmitValue(Asm, Form);
1397 // Emit the DIE children if any.
1398 if (Abbrev.hasChildren()) {
1399 for (auto &Child : Die.getChildren())
1402 Asm->OutStreamer.AddComment("End Of Children Mark");
1407 // Emit the debug info section.
1408 void DwarfDebug::emitDebugInfo() {
1409 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1411 Holder.emitUnits(DwarfAbbrevSectionSym);
1414 // Emit the abbreviation section.
1415 void DwarfDebug::emitAbbreviations() {
1416 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1418 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1421 // Emit the last address of the section and the end of the line matrix.
1422 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1423 // Define last address of section.
1424 Asm->OutStreamer.AddComment("Extended Op");
1427 Asm->OutStreamer.AddComment("Op size");
1428 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1429 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1430 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1432 Asm->OutStreamer.AddComment("Section end label");
1434 Asm->OutStreamer.EmitSymbolValue(
1435 Asm->GetTempSymbol("section_end", SectionEnd),
1436 Asm->getDataLayout().getPointerSize());
1438 // Mark end of matrix.
1439 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1445 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1446 StringRef TableName, StringRef SymName) {
1447 Accel.FinalizeTable(Asm, TableName);
1448 Asm->OutStreamer.SwitchSection(Section);
1449 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1450 Asm->OutStreamer.EmitLabel(SectionBegin);
1452 // Emit the full data.
1453 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1456 // Emit visible names into a hashed accelerator table section.
1457 void DwarfDebug::emitAccelNames() {
1458 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1459 "Names", "names_begin");
1462 // Emit objective C classes and categories into a hashed accelerator table
1464 void DwarfDebug::emitAccelObjC() {
1465 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1466 "ObjC", "objc_begin");
1469 // Emit namespace dies into a hashed accelerator table.
1470 void DwarfDebug::emitAccelNamespaces() {
1471 emitAccel(AccelNamespace,
1472 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1473 "namespac", "namespac_begin");
1476 // Emit type dies into a hashed accelerator table.
1477 void DwarfDebug::emitAccelTypes() {
1478 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1479 "types", "types_begin");
1482 // Public name handling.
1483 // The format for the various pubnames:
1485 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1486 // for the DIE that is named.
1488 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1489 // into the CU and the index value is computed according to the type of value
1490 // for the DIE that is named.
1492 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1493 // it's the offset within the debug_info/debug_types dwo section, however, the
1494 // reference in the pubname header doesn't change.
1496 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1497 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1499 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1501 // We could have a specification DIE that has our most of our knowledge,
1502 // look for that now.
1503 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1505 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1506 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1507 Linkage = dwarf::GIEL_EXTERNAL;
1508 } else if (Die->findAttribute(dwarf::DW_AT_external))
1509 Linkage = dwarf::GIEL_EXTERNAL;
1511 switch (Die->getTag()) {
1512 case dwarf::DW_TAG_class_type:
1513 case dwarf::DW_TAG_structure_type:
1514 case dwarf::DW_TAG_union_type:
1515 case dwarf::DW_TAG_enumeration_type:
1516 return dwarf::PubIndexEntryDescriptor(
1517 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1518 ? dwarf::GIEL_STATIC
1519 : dwarf::GIEL_EXTERNAL);
1520 case dwarf::DW_TAG_typedef:
1521 case dwarf::DW_TAG_base_type:
1522 case dwarf::DW_TAG_subrange_type:
1523 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1524 case dwarf::DW_TAG_namespace:
1525 return dwarf::GIEK_TYPE;
1526 case dwarf::DW_TAG_subprogram:
1527 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1528 case dwarf::DW_TAG_variable:
1529 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1530 case dwarf::DW_TAG_enumerator:
1531 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1532 dwarf::GIEL_STATIC);
1534 return dwarf::GIEK_NONE;
1538 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1540 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1541 const MCSection *PSec =
1542 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1543 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1545 emitDebugPubSection(GnuStyle, PSec, "Names",
1546 &DwarfCompileUnit::getGlobalNames);
1549 void DwarfDebug::emitDebugPubSection(
1550 bool GnuStyle, const MCSection *PSec, StringRef Name,
1551 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1552 for (const auto &NU : CUMap) {
1553 DwarfCompileUnit *TheU = NU.second;
1555 const auto &Globals = (TheU->*Accessor)();
1557 if (Globals.empty())
1560 if (auto *Skeleton = TheU->getSkeleton())
1562 unsigned ID = TheU->getUniqueID();
1564 // Start the dwarf pubnames section.
1565 Asm->OutStreamer.SwitchSection(PSec);
1568 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1569 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1570 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1571 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1573 Asm->OutStreamer.EmitLabel(BeginLabel);
1575 Asm->OutStreamer.AddComment("DWARF Version");
1576 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1578 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1579 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1581 Asm->OutStreamer.AddComment("Compilation Unit Length");
1582 Asm->EmitInt32(TheU->getLength());
1584 // Emit the pubnames for this compilation unit.
1585 for (const auto &GI : Globals) {
1586 const char *Name = GI.getKeyData();
1587 const DIE *Entity = GI.second;
1589 Asm->OutStreamer.AddComment("DIE offset");
1590 Asm->EmitInt32(Entity->getOffset());
1593 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1594 Asm->OutStreamer.AddComment(
1595 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1596 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1597 Asm->EmitInt8(Desc.toBits());
1600 Asm->OutStreamer.AddComment("External Name");
1601 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1604 Asm->OutStreamer.AddComment("End Mark");
1606 Asm->OutStreamer.EmitLabel(EndLabel);
1610 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1611 const MCSection *PSec =
1612 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1613 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1615 emitDebugPubSection(GnuStyle, PSec, "Types",
1616 &DwarfCompileUnit::getGlobalTypes);
1619 // Emit visible names into a debug str section.
1620 void DwarfDebug::emitDebugStr() {
1621 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1622 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1626 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1627 const DebugLocEntry &Entry) {
1628 auto Comment = Entry.getComments().begin();
1629 auto End = Entry.getComments().end();
1630 for (uint8_t Byte : Entry.getDWARFBytes())
1631 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1634 static void emitDebugLocValue(const AsmPrinter &AP,
1635 const DITypeIdentifierMap &TypeIdentifierMap,
1636 ByteStreamer &Streamer,
1637 const DebugLocEntry::Value &Value,
1638 unsigned PieceOffsetInBits) {
1639 DIVariable DV = Value.getVariable();
1640 DebugLocDwarfExpression DwarfExpr(
1641 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1642 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1644 if (Value.isInt()) {
1645 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1646 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1647 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1648 DwarfExpr.AddSignedConstant(Value.getInt());
1650 DwarfExpr.AddUnsignedConstant(Value.getInt());
1651 } else if (Value.isLocation()) {
1652 MachineLocation Loc = Value.getLoc();
1653 DIExpression Expr = Value.getExpression();
1654 if (!Expr || (Expr.getNumElements() == 0))
1656 AP.EmitDwarfRegOp(Streamer, Loc);
1658 // Complex address entry.
1659 if (Loc.getOffset()) {
1660 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1661 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1663 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1667 // else ... ignore constant fp. There is not any good way to
1668 // to represent them here in dwarf.
1673 void DebugLocEntry::finalize(const AsmPrinter &AP,
1674 const DITypeIdentifierMap &TypeIdentifierMap) {
1675 BufferByteStreamer Streamer(DWARFBytes, Comments);
1676 const DebugLocEntry::Value Value = Values[0];
1677 if (Value.isBitPiece()) {
1678 // Emit all pieces that belong to the same variable and range.
1679 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1680 return P.isBitPiece();
1681 }) && "all values are expected to be pieces");
1682 assert(std::is_sorted(Values.begin(), Values.end()) &&
1683 "pieces are expected to be sorted");
1685 unsigned Offset = 0;
1686 for (auto Piece : Values) {
1687 DIExpression Expr = Piece.getExpression();
1688 unsigned PieceOffset = Expr.getBitPieceOffset();
1689 unsigned PieceSize = Expr.getBitPieceSize();
1690 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1691 if (Offset < PieceOffset) {
1692 // The DWARF spec seriously mandates pieces with no locations for gaps.
1693 DebugLocDwarfExpression Expr(
1694 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1695 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1696 Expr.AddOpPiece(PieceOffset-Offset, 0);
1697 Offset += PieceOffset-Offset;
1699 Offset += PieceSize;
1702 DIVariable Var = Piece.getVariable();
1703 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1704 assert(PieceSize+PieceOffset <= VarSize
1705 && "piece is larger than or outside of variable");
1706 assert(PieceSize != VarSize
1707 && "piece covers entire variable");
1709 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1712 assert(Values.size() == 1 && "only pieces may have >1 value");
1713 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1718 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1719 Asm->OutStreamer.AddComment("Loc expr size");
1720 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1721 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1722 Asm->EmitLabelDifference(end, begin, 2);
1723 Asm->OutStreamer.EmitLabel(begin);
1725 APByteStreamer Streamer(*Asm);
1726 emitDebugLocEntry(Streamer, Entry);
1728 Asm->OutStreamer.EmitLabel(end);
1731 // Emit locations into the debug loc section.
1732 void DwarfDebug::emitDebugLoc() {
1733 // Start the dwarf loc section.
1734 Asm->OutStreamer.SwitchSection(
1735 Asm->getObjFileLowering().getDwarfLocSection());
1736 unsigned char Size = Asm->getDataLayout().getPointerSize();
1737 for (const auto &DebugLoc : DotDebugLocEntries) {
1738 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1739 const DwarfCompileUnit *CU = DebugLoc.CU;
1740 for (const auto &Entry : DebugLoc.List) {
1741 // Set up the range. This range is relative to the entry point of the
1742 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1743 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1744 if (auto *Base = CU->getBaseAddress()) {
1745 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1746 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1748 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1749 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1752 emitDebugLocEntryLocation(Entry);
1754 Asm->OutStreamer.EmitIntValue(0, Size);
1755 Asm->OutStreamer.EmitIntValue(0, Size);
1759 void DwarfDebug::emitDebugLocDWO() {
1760 Asm->OutStreamer.SwitchSection(
1761 Asm->getObjFileLowering().getDwarfLocDWOSection());
1762 for (const auto &DebugLoc : DotDebugLocEntries) {
1763 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1764 for (const auto &Entry : DebugLoc.List) {
1765 // Just always use start_length for now - at least that's one address
1766 // rather than two. We could get fancier and try to, say, reuse an
1767 // address we know we've emitted elsewhere (the start of the function?
1768 // The start of the CU or CU subrange that encloses this range?)
1769 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1770 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1771 Asm->EmitULEB128(idx);
1772 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1774 emitDebugLocEntryLocation(Entry);
1776 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1781 const MCSymbol *Start, *End;
1784 // Emit a debug aranges section, containing a CU lookup for any
1785 // address we can tie back to a CU.
1786 void DwarfDebug::emitDebugARanges() {
1787 // Provides a unique id per text section.
1788 DenseMap<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1790 // Prime section data.
1791 SectionMap[Asm->getObjFileLowering().getTextSection()];
1793 // Filter labels by section.
1794 for (const SymbolCU &SCU : ArangeLabels) {
1795 if (SCU.Sym->isInSection()) {
1796 // Make a note of this symbol and it's section.
1797 const MCSection *Section = &SCU.Sym->getSection();
1798 if (!Section->getKind().isMetadata())
1799 SectionMap[Section].push_back(SCU);
1801 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1802 // appear in the output. This sucks as we rely on sections to build
1803 // arange spans. We can do it without, but it's icky.
1804 SectionMap[nullptr].push_back(SCU);
1808 // Build a list of sections used.
1809 std::vector<const MCSection *> Sections;
1810 for (const auto &it : SectionMap) {
1811 const MCSection *Section = it.first;
1812 Sections.push_back(Section);
1815 // Sort the sections into order.
1816 // This is only done to ensure consistent output order across different runs.
1817 std::sort(Sections.begin(), Sections.end(), SectionSort);
1819 // Add terminating symbols for each section.
1820 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1821 const MCSection *Section = Sections[ID];
1822 MCSymbol *Sym = nullptr;
1825 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1826 // if we know the section name up-front. For user-created sections, the
1827 // resulting label may not be valid to use as a label. (section names can
1828 // use a greater set of characters on some systems)
1829 Sym = Asm->GetTempSymbol("debug_end", ID);
1830 Asm->OutStreamer.SwitchSection(Section);
1831 Asm->OutStreamer.EmitLabel(Sym);
1834 // Insert a final terminator.
1835 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1838 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1840 for (const MCSection *Section : Sections) {
1841 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1842 if (List.size() < 2)
1845 // If we have no section (e.g. common), just write out
1846 // individual spans for each symbol.
1848 for (const SymbolCU &Cur : List) {
1850 Span.Start = Cur.Sym;
1853 Spans[Cur.CU].push_back(Span);
1858 // Sort the symbols by offset within the section.
1859 std::sort(List.begin(), List.end(),
1860 [&](const SymbolCU &A, const SymbolCU &B) {
1861 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1862 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1864 // Symbols with no order assigned should be placed at the end.
1865 // (e.g. section end labels)
1873 // Build spans between each label.
1874 const MCSymbol *StartSym = List[0].Sym;
1875 for (size_t n = 1, e = List.size(); n < e; n++) {
1876 const SymbolCU &Prev = List[n - 1];
1877 const SymbolCU &Cur = List[n];
1879 // Try and build the longest span we can within the same CU.
1880 if (Cur.CU != Prev.CU) {
1882 Span.Start = StartSym;
1884 Spans[Prev.CU].push_back(Span);
1890 // Start the dwarf aranges section.
1891 Asm->OutStreamer.SwitchSection(
1892 Asm->getObjFileLowering().getDwarfARangesSection());
1894 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1896 // Build a list of CUs used.
1897 std::vector<DwarfCompileUnit *> CUs;
1898 for (const auto &it : Spans) {
1899 DwarfCompileUnit *CU = it.first;
1903 // Sort the CU list (again, to ensure consistent output order).
1904 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1905 return A->getUniqueID() < B->getUniqueID();
1908 // Emit an arange table for each CU we used.
1909 for (DwarfCompileUnit *CU : CUs) {
1910 std::vector<ArangeSpan> &List = Spans[CU];
1912 // Describe the skeleton CU's offset and length, not the dwo file's.
1913 if (auto *Skel = CU->getSkeleton())
1916 // Emit size of content not including length itself.
1917 unsigned ContentSize =
1918 sizeof(int16_t) + // DWARF ARange version number
1919 sizeof(int32_t) + // Offset of CU in the .debug_info section
1920 sizeof(int8_t) + // Pointer Size (in bytes)
1921 sizeof(int8_t); // Segment Size (in bytes)
1923 unsigned TupleSize = PtrSize * 2;
1925 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1927 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1929 ContentSize += Padding;
1930 ContentSize += (List.size() + 1) * TupleSize;
1932 // For each compile unit, write the list of spans it covers.
1933 Asm->OutStreamer.AddComment("Length of ARange Set");
1934 Asm->EmitInt32(ContentSize);
1935 Asm->OutStreamer.AddComment("DWARF Arange version number");
1936 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1937 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1938 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1939 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1940 Asm->EmitInt8(PtrSize);
1941 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1944 Asm->OutStreamer.EmitFill(Padding, 0xff);
1946 for (const ArangeSpan &Span : List) {
1947 Asm->EmitLabelReference(Span.Start, PtrSize);
1949 // Calculate the size as being from the span start to it's end.
1951 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1953 // For symbols without an end marker (e.g. common), we
1954 // write a single arange entry containing just that one symbol.
1955 uint64_t Size = SymSize[Span.Start];
1959 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1963 Asm->OutStreamer.AddComment("ARange terminator");
1964 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1965 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1969 // Emit visible names into a debug ranges section.
1970 void DwarfDebug::emitDebugRanges() {
1971 // Start the dwarf ranges section.
1972 Asm->OutStreamer.SwitchSection(
1973 Asm->getObjFileLowering().getDwarfRangesSection());
1975 // Size for our labels.
1976 unsigned char Size = Asm->getDataLayout().getPointerSize();
1978 // Grab the specific ranges for the compile units in the module.
1979 for (const auto &I : CUMap) {
1980 DwarfCompileUnit *TheCU = I.second;
1982 if (auto *Skel = TheCU->getSkeleton())
1985 // Iterate over the misc ranges for the compile units in the module.
1986 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1987 // Emit our symbol so we can find the beginning of the range.
1988 Asm->OutStreamer.EmitLabel(List.getSym());
1990 for (const RangeSpan &Range : List.getRanges()) {
1991 const MCSymbol *Begin = Range.getStart();
1992 const MCSymbol *End = Range.getEnd();
1993 assert(Begin && "Range without a begin symbol?");
1994 assert(End && "Range without an end symbol?");
1995 if (auto *Base = TheCU->getBaseAddress()) {
1996 Asm->EmitLabelDifference(Begin, Base, Size);
1997 Asm->EmitLabelDifference(End, Base, Size);
1999 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2000 Asm->OutStreamer.EmitSymbolValue(End, Size);
2004 // And terminate the list with two 0 values.
2005 Asm->OutStreamer.EmitIntValue(0, Size);
2006 Asm->OutStreamer.EmitIntValue(0, Size);
2011 // DWARF5 Experimental Separate Dwarf emitters.
2013 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2014 std::unique_ptr<DwarfUnit> NewU) {
2015 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2016 U.getCUNode().getSplitDebugFilename());
2018 if (!CompilationDir.empty())
2019 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2021 addGnuPubAttributes(*NewU, Die);
2023 SkeletonHolder.addUnit(std::move(NewU));
2026 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2027 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2028 // DW_AT_addr_base, DW_AT_ranges_base.
2029 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2031 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2032 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2033 DwarfCompileUnit &NewCU = *OwnedUnit;
2034 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2035 DwarfInfoSectionSym);
2037 NewCU.initStmtList(DwarfLineSectionSym);
2039 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2044 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2045 // compile units that would normally be in debug_info.
2046 void DwarfDebug::emitDebugInfoDWO() {
2047 assert(useSplitDwarf() && "No split dwarf debug info?");
2048 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2049 // emit relocations into the dwo file.
2050 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2053 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2054 // abbreviations for the .debug_info.dwo section.
2055 void DwarfDebug::emitDebugAbbrevDWO() {
2056 assert(useSplitDwarf() && "No split dwarf?");
2057 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2060 void DwarfDebug::emitDebugLineDWO() {
2061 assert(useSplitDwarf() && "No split dwarf?");
2062 Asm->OutStreamer.SwitchSection(
2063 Asm->getObjFileLowering().getDwarfLineDWOSection());
2064 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2067 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2068 // string section and is identical in format to traditional .debug_str
2070 void DwarfDebug::emitDebugStrDWO() {
2071 assert(useSplitDwarf() && "No split dwarf?");
2072 const MCSection *OffSec =
2073 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2074 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2078 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2079 if (!useSplitDwarf())
2082 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2083 return &SplitTypeUnitFileTable;
2086 static uint64_t makeTypeSignature(StringRef Identifier) {
2088 Hash.update(Identifier);
2089 // ... take the least significant 8 bytes and return those. Our MD5
2090 // implementation always returns its results in little endian, swap bytes
2092 MD5::MD5Result Result;
2094 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2097 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2098 StringRef Identifier, DIE &RefDie,
2099 DICompositeType CTy) {
2100 // Fast path if we're building some type units and one has already used the
2101 // address pool we know we're going to throw away all this work anyway, so
2102 // don't bother building dependent types.
2103 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2106 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2108 CU.addDIETypeSignature(RefDie, *TU);
2112 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2113 AddrPool.resetUsedFlag();
2115 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2116 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2117 this, &InfoHolder, getDwoLineTable(CU));
2118 DwarfTypeUnit &NewTU = *OwnedUnit;
2119 DIE &UnitDie = NewTU.getUnitDie();
2121 TypeUnitsUnderConstruction.push_back(
2122 std::make_pair(std::move(OwnedUnit), CTy));
2124 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2127 uint64_t Signature = makeTypeSignature(Identifier);
2128 NewTU.setTypeSignature(Signature);
2130 if (useSplitDwarf())
2131 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2133 CU.applyStmtList(UnitDie);
2135 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2138 NewTU.setType(NewTU.createTypeDIE(CTy));
2141 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2142 TypeUnitsUnderConstruction.clear();
2144 // Types referencing entries in the address table cannot be placed in type
2146 if (AddrPool.hasBeenUsed()) {
2148 // Remove all the types built while building this type.
2149 // This is pessimistic as some of these types might not be dependent on
2150 // the type that used an address.
2151 for (const auto &TU : TypeUnitsToAdd)
2152 DwarfTypeUnits.erase(TU.second);
2154 // Construct this type in the CU directly.
2155 // This is inefficient because all the dependent types will be rebuilt
2156 // from scratch, including building them in type units, discovering that
2157 // they depend on addresses, throwing them out and rebuilding them.
2158 CU.constructTypeDIE(RefDie, CTy);
2162 // If the type wasn't dependent on fission addresses, finish adding the type
2163 // and all its dependent types.
2164 for (auto &TU : TypeUnitsToAdd)
2165 InfoHolder.addUnit(std::move(TU.first));
2167 CU.addDIETypeSignature(RefDie, NewTU);
2170 // Accelerator table mutators - add each name along with its companion
2171 // DIE to the proper table while ensuring that the name that we're going
2172 // to reference is in the string table. We do this since the names we
2173 // add may not only be identical to the names in the DIE.
2174 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2175 if (!useDwarfAccelTables())
2177 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2181 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2182 if (!useDwarfAccelTables())
2184 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2188 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2189 if (!useDwarfAccelTables())
2191 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2195 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2196 if (!useDwarfAccelTables())
2198 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),