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"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.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 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
173 InfoHolder(A, *this, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
334 assert(Scope && Scope->getScopeNode());
335 assert(Scope->isAbstractScope());
336 assert(!Scope->getInlinedAt());
338 const MDNode *SP = Scope->getScopeNode();
340 ProcessedSPNodes.insert(SP);
342 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
343 // was inlined from another compile unit.
344 SPMap[SP]->constructAbstractSubprogramScopeDIE(Scope);
347 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
348 if (!GenerateGnuPubSections)
351 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
354 // Create new DwarfCompileUnit for the given metadata node with tag
355 // DW_TAG_compile_unit.
356 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
357 StringRef FN = DIUnit.getFilename();
358 CompilationDir = DIUnit.getDirectory();
360 auto OwnedUnit = make_unique<DwarfCompileUnit>(
361 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
362 DwarfCompileUnit &NewCU = *OwnedUnit;
363 DIE &Die = NewCU.getUnitDie();
364 InfoHolder.addUnit(std::move(OwnedUnit));
366 NewCU.setSkeleton(constructSkeletonCU(NewCU));
368 // LTO with assembly output shares a single line table amongst multiple CUs.
369 // To avoid the compilation directory being ambiguous, let the line table
370 // explicitly describe the directory of all files, never relying on the
371 // compilation directory.
372 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
373 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
374 NewCU.getUniqueID(), CompilationDir);
376 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
377 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
378 DIUnit.getLanguage());
379 NewCU.addString(Die, dwarf::DW_AT_name, FN);
381 if (!useSplitDwarf()) {
382 NewCU.initStmtList(DwarfLineSectionSym);
384 // If we're using split dwarf the compilation dir is going to be in the
385 // skeleton CU and so we don't need to duplicate it here.
386 if (!CompilationDir.empty())
387 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
389 addGnuPubAttributes(NewCU, Die);
392 if (DIUnit.isOptimized())
393 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
395 StringRef Flags = DIUnit.getFlags();
397 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
399 if (unsigned RVer = DIUnit.getRunTimeVersion())
400 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
401 dwarf::DW_FORM_data1, RVer);
404 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
405 DwarfInfoDWOSectionSym);
407 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
408 DwarfInfoSectionSym);
410 CUMap.insert(std::make_pair(DIUnit, &NewCU));
411 CUDieMap.insert(std::make_pair(&Die, &NewCU));
415 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
417 DIImportedEntity Module(N);
418 assert(Module.Verify());
419 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
420 D->addChild(TheCU.constructImportedEntityDIE(Module));
423 // Emit all Dwarf sections that should come prior to the content. Create
424 // global DIEs and emit initial debug info sections. This is invoked by
425 // the target AsmPrinter.
426 void DwarfDebug::beginModule() {
427 if (DisableDebugInfoPrinting)
430 const Module *M = MMI->getModule();
432 FunctionDIs = makeSubprogramMap(*M);
434 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
437 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
439 // Emit initial sections so we can reference labels later.
442 SingleCU = CU_Nodes->getNumOperands() == 1;
444 for (MDNode *N : CU_Nodes->operands()) {
445 DICompileUnit CUNode(N);
446 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
447 DIArray ImportedEntities = CUNode.getImportedEntities();
448 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
449 ScopesWithImportedEntities.push_back(std::make_pair(
450 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
451 ImportedEntities.getElement(i)));
452 std::sort(ScopesWithImportedEntities.begin(),
453 ScopesWithImportedEntities.end(), less_first());
454 DIArray GVs = CUNode.getGlobalVariables();
455 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
456 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
457 DIArray SPs = CUNode.getSubprograms();
458 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
459 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
460 DIArray EnumTypes = CUNode.getEnumTypes();
461 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
462 DIType Ty(EnumTypes.getElement(i));
463 // The enum types array by design contains pointers to
464 // MDNodes rather than DIRefs. Unique them here.
465 DIType UniqueTy(resolve(Ty.getRef()));
466 CU.getOrCreateTypeDIE(UniqueTy);
468 DIArray RetainedTypes = CUNode.getRetainedTypes();
469 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
470 DIType Ty(RetainedTypes.getElement(i));
471 // The retained types array by design contains pointers to
472 // MDNodes rather than DIRefs. Unique them here.
473 DIType UniqueTy(resolve(Ty.getRef()));
474 CU.getOrCreateTypeDIE(UniqueTy);
476 // Emit imported_modules last so that the relevant context is already
478 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
479 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
482 // Tell MMI that we have debug info.
483 MMI->setDebugInfoAvailability(true);
485 // Prime section data.
486 SectionMap[Asm->getObjFileLowering().getTextSection()];
489 void DwarfDebug::finishVariableDefinitions() {
490 for (const auto &Var : ConcreteVariables) {
491 DIE *VariableDie = Var->getDIE();
493 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
494 // in the ConcreteVariables list, rather than looking it up again here.
495 // DIE::getUnit isn't simple - it walks parent pointers, etc.
496 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
498 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
499 if (AbsVar && AbsVar->getDIE()) {
500 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
503 Unit->applyVariableAttributes(*Var, *VariableDie);
507 void DwarfDebug::finishSubprogramDefinitions() {
508 for (const auto &P : SPMap)
509 P.second->finishSubprogramDefinition(DISubprogram(P.first));
513 // Collect info for variables that were optimized out.
514 void DwarfDebug::collectDeadVariables() {
515 const Module *M = MMI->getModule();
517 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
518 for (MDNode *N : CU_Nodes->operands()) {
519 DICompileUnit TheCU(N);
520 // Construct subprogram DIE and add variables DIEs.
521 DwarfCompileUnit *SPCU =
522 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
523 assert(SPCU && "Unable to find Compile Unit!");
524 DIArray Subprograms = TheCU.getSubprograms();
525 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
526 DISubprogram SP(Subprograms.getElement(i));
527 if (ProcessedSPNodes.count(SP) != 0)
529 SPCU->collectDeadVariables(SP);
535 void DwarfDebug::finalizeModuleInfo() {
536 finishSubprogramDefinitions();
538 finishVariableDefinitions();
540 // Collect info for variables that were optimized out.
541 collectDeadVariables();
543 // Handle anything that needs to be done on a per-unit basis after
544 // all other generation.
545 for (const auto &P : CUMap) {
546 auto &TheCU = *P.second;
547 // Emit DW_AT_containing_type attribute to connect types with their
548 // vtable holding type.
549 TheCU.constructContainingTypeDIEs();
551 // Add CU specific attributes if we need to add any.
552 // If we're splitting the dwarf out now that we've got the entire
553 // CU then add the dwo id to it.
554 auto *SkCU = TheCU.getSkeleton();
555 if (useSplitDwarf()) {
556 // Emit a unique identifier for this CU.
557 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
558 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
559 dwarf::DW_FORM_data8, ID);
560 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
561 dwarf::DW_FORM_data8, ID);
563 // We don't keep track of which addresses are used in which CU so this
564 // is a bit pessimistic under LTO.
565 if (!AddrPool.isEmpty())
566 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
567 DwarfAddrSectionSym, DwarfAddrSectionSym);
568 if (!TheCU.getRangeLists().empty())
569 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
570 DwarfDebugRangeSectionSym,
571 DwarfDebugRangeSectionSym);
574 // If we have code split among multiple sections or non-contiguous
575 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
576 // remain in the .o file, otherwise add a DW_AT_low_pc.
577 // FIXME: We should use ranges allow reordering of code ala
578 // .subsections_via_symbols in mach-o. This would mean turning on
579 // ranges for all subprogram DIEs for mach-o.
580 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
581 unsigned NumRanges = TheCU.getRanges().size();
584 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
585 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
586 DwarfDebugRangeSectionSym);
588 // A DW_AT_low_pc attribute may also be specified in combination with
589 // DW_AT_ranges to specify the default base address for use in
590 // location lists (see Section 2.6.2) and range lists (see Section
592 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
594 const RangeSpan &Range = TheCU.getRanges().back();
595 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
600 // Compute DIE offsets and sizes.
601 InfoHolder.computeSizeAndOffsets();
603 SkeletonHolder.computeSizeAndOffsets();
606 void DwarfDebug::endSections() {
607 // Filter labels by section.
608 for (const SymbolCU &SCU : ArangeLabels) {
609 if (SCU.Sym->isInSection()) {
610 // Make a note of this symbol and it's section.
611 const MCSection *Section = &SCU.Sym->getSection();
612 if (!Section->getKind().isMetadata())
613 SectionMap[Section].push_back(SCU);
615 // Some symbols (e.g. common/bss on mach-o) can have no section but still
616 // appear in the output. This sucks as we rely on sections to build
617 // arange spans. We can do it without, but it's icky.
618 SectionMap[nullptr].push_back(SCU);
622 // Build a list of sections used.
623 std::vector<const MCSection *> Sections;
624 for (const auto &it : SectionMap) {
625 const MCSection *Section = it.first;
626 Sections.push_back(Section);
629 // Sort the sections into order.
630 // This is only done to ensure consistent output order across different runs.
631 std::sort(Sections.begin(), Sections.end(), SectionSort);
633 // Add terminating symbols for each section.
634 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
635 const MCSection *Section = Sections[ID];
636 MCSymbol *Sym = nullptr;
639 // We can't call MCSection::getLabelEndName, as it's only safe to do so
640 // if we know the section name up-front. For user-created sections, the
641 // resulting label may not be valid to use as a label. (section names can
642 // use a greater set of characters on some systems)
643 Sym = Asm->GetTempSymbol("debug_end", ID);
644 Asm->OutStreamer.SwitchSection(Section);
645 Asm->OutStreamer.EmitLabel(Sym);
648 // Insert a final terminator.
649 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
653 // Emit all Dwarf sections that should come after the content.
654 void DwarfDebug::endModule() {
655 assert(CurFn == nullptr);
656 assert(CurMI == nullptr);
658 // If we aren't actually generating debug info (check beginModule -
659 // conditionalized on !DisableDebugInfoPrinting and the presence of the
660 // llvm.dbg.cu metadata node)
661 if (!DwarfInfoSectionSym)
664 // End any existing sections.
665 // TODO: Does this need to happen?
668 // Finalize the debug info for the module.
669 finalizeModuleInfo();
673 // Emit all the DIEs into a debug info section.
676 // Corresponding abbreviations into a abbrev section.
679 // Emit info into a debug aranges section.
680 if (GenerateARangeSection)
683 // Emit info into a debug ranges section.
686 if (useSplitDwarf()) {
689 emitDebugAbbrevDWO();
692 // Emit DWO addresses.
693 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
695 // Emit info into a debug loc section.
698 // Emit info into the dwarf accelerator table sections.
699 if (useDwarfAccelTables()) {
702 emitAccelNamespaces();
706 // Emit the pubnames and pubtypes sections if requested.
707 if (HasDwarfPubSections) {
708 emitDebugPubNames(GenerateGnuPubSections);
709 emitDebugPubTypes(GenerateGnuPubSections);
714 AbstractVariables.clear();
717 // Find abstract variable, if any, associated with Var.
718 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
719 DIVariable &Cleansed) {
720 LLVMContext &Ctx = DV->getContext();
721 // More then one inlined variable corresponds to one abstract variable.
722 // FIXME: This duplication of variables when inlining should probably be
723 // removed. It's done to allow each DIVariable to describe its location
724 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
725 // make it accurate then remove this duplication/cleansing stuff.
726 Cleansed = cleanseInlinedVariable(DV, Ctx);
727 auto I = AbstractVariables.find(Cleansed);
728 if (I != AbstractVariables.end())
729 return I->second.get();
733 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
735 return getExistingAbstractVariable(DV, Cleansed);
738 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
739 LexicalScope *Scope) {
740 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
741 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
742 AbstractVariables[Var] = std::move(AbsDbgVariable);
745 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
746 const MDNode *ScopeNode) {
747 DIVariable Cleansed = DV;
748 if (getExistingAbstractVariable(DV, Cleansed))
751 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
755 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
756 const MDNode *ScopeNode) {
757 DIVariable Cleansed = DV;
758 if (getExistingAbstractVariable(DV, Cleansed))
761 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
762 createAbstractVariable(Cleansed, Scope);
765 // Collect variable information from side table maintained by MMI.
766 void DwarfDebug::collectVariableInfoFromMMITable(
767 SmallPtrSetImpl<const MDNode *> &Processed) {
768 for (const auto &VI : MMI->getVariableDbgInfo()) {
771 Processed.insert(VI.Var);
772 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
774 // If variable scope is not found then skip this variable.
778 DIVariable DV(VI.Var);
779 DIExpression Expr(VI.Expr);
780 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
781 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
782 DbgVariable *RegVar = ConcreteVariables.back().get();
783 RegVar->setFrameIndex(VI.Slot);
784 InfoHolder.addScopeVariable(Scope, RegVar);
788 // Get .debug_loc entry for the instruction range starting at MI.
789 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
790 const MDNode *Expr = MI->getDebugExpression();
791 const MDNode *Var = MI->getDebugVariable();
793 assert(MI->getNumOperands() == 4);
794 if (MI->getOperand(0).isReg()) {
795 MachineLocation MLoc;
796 // If the second operand is an immediate, this is a
797 // register-indirect address.
798 if (!MI->getOperand(1).isImm())
799 MLoc.set(MI->getOperand(0).getReg());
801 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
802 return DebugLocEntry::Value(Var, Expr, MLoc);
804 if (MI->getOperand(0).isImm())
805 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
806 if (MI->getOperand(0).isFPImm())
807 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
808 if (MI->getOperand(0).isCImm())
809 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
811 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
814 /// Determine whether two variable pieces overlap.
815 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
816 if (!P1.isVariablePiece() || !P2.isVariablePiece())
818 unsigned l1 = P1.getPieceOffset();
819 unsigned l2 = P2.getPieceOffset();
820 unsigned r1 = l1 + P1.getPieceSize();
821 unsigned r2 = l2 + P2.getPieceSize();
822 // True where [l1,r1[ and [r1,r2[ overlap.
823 return (l1 < r2) && (l2 < r1);
826 /// Build the location list for all DBG_VALUEs in the function that
827 /// describe the same variable. If the ranges of several independent
828 /// pieces of the same variable overlap partially, split them up and
829 /// combine the ranges. The resulting DebugLocEntries are will have
830 /// strict monotonically increasing begin addresses and will never
835 // Ranges History [var, loc, piece ofs size]
836 // 0 | [x, (reg0, piece 0, 32)]
837 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
839 // 3 | [clobber reg0]
840 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
844 // [0-1] [x, (reg0, piece 0, 32)]
845 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
846 // [3-4] [x, (reg1, piece 32, 32)]
847 // [4- ] [x, (mem, piece 0, 64)]
849 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
850 const DbgValueHistoryMap::InstrRanges &Ranges) {
851 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
853 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
854 const MachineInstr *Begin = I->first;
855 const MachineInstr *End = I->second;
856 assert(Begin->isDebugValue() && "Invalid History entry");
858 // Check if a variable is inaccessible in this range.
859 if (Begin->getNumOperands() > 1 &&
860 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
865 // If this piece overlaps with any open ranges, truncate them.
866 DIExpression DIExpr = Begin->getDebugExpression();
867 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
868 [&](DebugLocEntry::Value R) {
869 return piecesOverlap(DIExpr, R.getExpression());
871 OpenRanges.erase(Last, OpenRanges.end());
873 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
874 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
876 const MCSymbol *EndLabel;
878 EndLabel = getLabelAfterInsn(End);
879 else if (std::next(I) == Ranges.end())
880 EndLabel = FunctionEndSym;
882 EndLabel = getLabelBeforeInsn(std::next(I)->first);
883 assert(EndLabel && "Forgot label after instruction ending a range!");
885 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
887 auto Value = getDebugLocValue(Begin);
888 DebugLocEntry Loc(StartLabel, EndLabel, Value);
889 bool couldMerge = false;
891 // If this is a piece, it may belong to the current DebugLocEntry.
892 if (DIExpr.isVariablePiece()) {
893 // Add this value to the list of open ranges.
894 OpenRanges.push_back(Value);
896 // Attempt to add the piece to the last entry.
897 if (!DebugLoc.empty())
898 if (DebugLoc.back().MergeValues(Loc))
903 // Need to add a new DebugLocEntry. Add all values from still
904 // valid non-overlapping pieces.
905 if (OpenRanges.size())
906 Loc.addValues(OpenRanges);
908 DebugLoc.push_back(std::move(Loc));
911 // Attempt to coalesce the ranges of two otherwise identical
913 auto CurEntry = DebugLoc.rbegin();
914 auto PrevEntry = std::next(CurEntry);
915 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
919 dbgs() << CurEntry->getValues().size() << " Values:\n";
920 for (auto Value : CurEntry->getValues()) {
921 Value.getVariable()->dump();
922 Value.getExpression()->dump();
930 // Find variables for each lexical scope.
932 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
933 SmallPtrSetImpl<const MDNode *> &Processed) {
934 // Grab the variable info that was squirreled away in the MMI side-table.
935 collectVariableInfoFromMMITable(Processed);
937 for (const auto &I : DbgValues) {
938 DIVariable DV(I.first);
939 if (Processed.count(DV))
942 // Instruction ranges, specifying where DV is accessible.
943 const auto &Ranges = I.second;
947 LexicalScope *Scope = nullptr;
948 if (MDNode *IA = DV.getInlinedAt()) {
949 DebugLoc DL = DebugLoc::getFromDILocation(IA);
950 Scope = LScopes.findInlinedScope(DebugLoc::get(
951 DL.getLine(), DL.getCol(), DV.getContext(), IA));
953 Scope = LScopes.findLexicalScope(DV.getContext());
954 // If variable scope is not found then skip this variable.
958 Processed.insert(DV);
959 const MachineInstr *MInsn = Ranges.front().first;
960 assert(MInsn->isDebugValue() && "History must begin with debug value");
961 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
962 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
963 DbgVariable *RegVar = ConcreteVariables.back().get();
964 InfoHolder.addScopeVariable(Scope, RegVar);
966 // Check if the first DBG_VALUE is valid for the rest of the function.
967 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
970 // Handle multiple DBG_VALUE instructions describing one variable.
971 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
973 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
974 DebugLocList &LocList = DotDebugLocEntries.back();
977 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
979 // Build the location list for this variable.
980 buildLocationList(LocList.List, Ranges);
983 // Collect info for variables that were optimized out.
984 DIArray Variables = SP.getVariables();
985 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
986 DIVariable DV(Variables.getElement(i));
987 assert(DV.isVariable());
988 if (!Processed.insert(DV))
990 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
991 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
993 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
994 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
999 // Return Label preceding the instruction.
1000 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1001 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1002 assert(Label && "Didn't insert label before instruction");
1006 // Return Label immediately following the instruction.
1007 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1008 return LabelsAfterInsn.lookup(MI);
1011 // Process beginning of an instruction.
1012 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1013 assert(CurMI == nullptr);
1015 // Check if source location changes, but ignore DBG_VALUE locations.
1016 if (!MI->isDebugValue()) {
1017 DebugLoc DL = MI->getDebugLoc();
1018 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1021 if (DL == PrologEndLoc) {
1022 Flags |= DWARF2_FLAG_PROLOGUE_END;
1023 PrologEndLoc = DebugLoc();
1025 if (PrologEndLoc.isUnknown())
1026 Flags |= DWARF2_FLAG_IS_STMT;
1028 if (!DL.isUnknown()) {
1029 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1030 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1032 recordSourceLine(0, 0, nullptr, 0);
1036 // Insert labels where requested.
1037 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1038 LabelsBeforeInsn.find(MI);
1041 if (I == LabelsBeforeInsn.end())
1044 // Label already assigned.
1049 PrevLabel = MMI->getContext().CreateTempSymbol();
1050 Asm->OutStreamer.EmitLabel(PrevLabel);
1052 I->second = PrevLabel;
1055 // Process end of an instruction.
1056 void DwarfDebug::endInstruction() {
1057 assert(CurMI != nullptr);
1058 // Don't create a new label after DBG_VALUE instructions.
1059 // They don't generate code.
1060 if (!CurMI->isDebugValue())
1061 PrevLabel = nullptr;
1063 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1064 LabelsAfterInsn.find(CurMI);
1068 if (I == LabelsAfterInsn.end())
1071 // Label already assigned.
1075 // We need a label after this instruction.
1077 PrevLabel = MMI->getContext().CreateTempSymbol();
1078 Asm->OutStreamer.EmitLabel(PrevLabel);
1080 I->second = PrevLabel;
1083 // Each LexicalScope has first instruction and last instruction to mark
1084 // beginning and end of a scope respectively. Create an inverse map that list
1085 // scopes starts (and ends) with an instruction. One instruction may start (or
1086 // end) multiple scopes. Ignore scopes that are not reachable.
1087 void DwarfDebug::identifyScopeMarkers() {
1088 SmallVector<LexicalScope *, 4> WorkList;
1089 WorkList.push_back(LScopes.getCurrentFunctionScope());
1090 while (!WorkList.empty()) {
1091 LexicalScope *S = WorkList.pop_back_val();
1093 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1094 if (!Children.empty())
1095 WorkList.append(Children.begin(), Children.end());
1097 if (S->isAbstractScope())
1100 for (const InsnRange &R : S->getRanges()) {
1101 assert(R.first && "InsnRange does not have first instruction!");
1102 assert(R.second && "InsnRange does not have second instruction!");
1103 requestLabelBeforeInsn(R.first);
1104 requestLabelAfterInsn(R.second);
1109 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1110 // First known non-DBG_VALUE and non-frame setup location marks
1111 // the beginning of the function body.
1112 for (const auto &MBB : *MF)
1113 for (const auto &MI : MBB)
1114 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1115 !MI.getDebugLoc().isUnknown())
1116 return MI.getDebugLoc();
1120 // Gather pre-function debug information. Assumes being called immediately
1121 // after the function entry point has been emitted.
1122 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1125 // If there's no debug info for the function we're not going to do anything.
1126 if (!MMI->hasDebugInfo())
1129 auto DI = FunctionDIs.find(MF->getFunction());
1130 if (DI == FunctionDIs.end())
1133 // Grab the lexical scopes for the function, if we don't have any of those
1134 // then we're not going to be able to do anything.
1135 LScopes.initialize(*MF);
1136 if (LScopes.empty())
1139 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1141 // Make sure that each lexical scope will have a begin/end label.
1142 identifyScopeMarkers();
1144 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1145 // belongs to so that we add to the correct per-cu line table in the
1147 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1148 // FnScope->getScopeNode() and DI->second should represent the same function,
1149 // though they may not be the same MDNode due to inline functions merged in
1150 // LTO where the debug info metadata still differs (either due to distinct
1151 // written differences - two versions of a linkonce_odr function
1152 // written/copied into two separate files, or some sub-optimal metadata that
1153 // isn't structurally identical (see: file path/name info from clang, which
1154 // includes the directory of the cpp file being built, even when the file name
1155 // is absolute (such as an <> lookup header)))
1156 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1157 assert(TheCU && "Unable to find compile unit!");
1158 if (Asm->OutStreamer.hasRawTextSupport())
1159 // Use a single line table if we are generating assembly.
1160 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1162 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1164 // Emit a label for the function so that we have a beginning address.
1165 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1166 // Assumes in correct section after the entry point.
1167 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1169 // Calculate history for local variables.
1170 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1173 // Request labels for the full history.
1174 for (const auto &I : DbgValues) {
1175 const auto &Ranges = I.second;
1179 // The first mention of a function argument gets the FunctionBeginSym
1180 // label, so arguments are visible when breaking at function entry.
1181 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1182 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1183 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1184 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1185 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1186 // Mark all non-overlapping initial pieces.
1187 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1188 DIExpression Piece = I->first->getDebugExpression();
1189 if (std::all_of(Ranges.begin(), I,
1190 [&](DbgValueHistoryMap::InstrRange Pred) {
1191 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1193 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1200 for (const auto &Range : Ranges) {
1201 requestLabelBeforeInsn(Range.first);
1203 requestLabelAfterInsn(Range.second);
1207 PrevInstLoc = DebugLoc();
1208 PrevLabel = FunctionBeginSym;
1210 // Record beginning of function.
1211 PrologEndLoc = findPrologueEndLoc(MF);
1212 if (!PrologEndLoc.isUnknown()) {
1213 DebugLoc FnStartDL =
1214 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1216 FnStartDL.getLine(), FnStartDL.getCol(),
1217 FnStartDL.getScope(MF->getFunction()->getContext()),
1218 // We'd like to list the prologue as "not statements" but GDB behaves
1219 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1220 DWARF2_FLAG_IS_STMT);
1224 // Gather and emit post-function debug information.
1225 void DwarfDebug::endFunction(const MachineFunction *MF) {
1226 assert(CurFn == MF &&
1227 "endFunction should be called with the same function as beginFunction");
1229 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1230 !FunctionDIs.count(MF->getFunction())) {
1231 // If we don't have a lexical scope for this function then there will
1232 // be a hole in the range information. Keep note of this by setting the
1233 // previously used section to nullptr.
1239 // Define end label for subprogram.
1240 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1241 // Assumes in correct section after the entry point.
1242 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1244 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1245 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1247 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1248 DISubprogram SP(FnScope->getScopeNode());
1249 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1251 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1252 collectVariableInfo(TheCU, SP, ProcessedVars);
1254 // Add the range of this function to the list of ranges for the CU.
1255 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1257 // Under -gmlt, skip building the subprogram if there are no inlined
1258 // subroutines inside it.
1259 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1260 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1261 assert(InfoHolder.getScopeVariables().empty());
1262 assert(DbgValues.empty());
1263 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1264 // by a -gmlt CU. Add a test and remove this assertion.
1265 assert(AbstractVariables.empty());
1266 LabelsBeforeInsn.clear();
1267 LabelsAfterInsn.clear();
1268 PrevLabel = nullptr;
1274 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1276 // Construct abstract scopes.
1277 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1278 DISubprogram SP(AScope->getScopeNode());
1279 assert(SP.isSubprogram());
1280 // Collect info for variables that were optimized out.
1281 DIArray Variables = SP.getVariables();
1282 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1283 DIVariable DV(Variables.getElement(i));
1284 assert(DV && DV.isVariable());
1285 if (!ProcessedVars.insert(DV))
1287 ensureAbstractVariableIsCreated(DV, DV.getContext());
1288 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1289 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1291 constructAbstractSubprogramScopeDIE(AScope);
1294 TheCU.constructSubprogramScopeDIE(FnScope);
1297 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1298 // DbgVariables except those that are also in AbstractVariables (since they
1299 // can be used cross-function)
1300 InfoHolder.getScopeVariables().clear();
1302 LabelsBeforeInsn.clear();
1303 LabelsAfterInsn.clear();
1304 PrevLabel = nullptr;
1308 // Register a source line with debug info. Returns the unique label that was
1309 // emitted and which provides correspondence to the source line list.
1310 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1315 unsigned Discriminator = 0;
1316 if (DIScope Scope = DIScope(S)) {
1317 assert(Scope.isScope());
1318 Fn = Scope.getFilename();
1319 Dir = Scope.getDirectory();
1320 if (Scope.isLexicalBlockFile())
1321 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1323 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1324 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1325 .getOrCreateSourceID(Fn, Dir);
1327 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1331 //===----------------------------------------------------------------------===//
1333 //===----------------------------------------------------------------------===//
1335 // Emit initial Dwarf sections with a label at the start of each one.
1336 void DwarfDebug::emitSectionLabels() {
1337 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1339 // Dwarf sections base addresses.
1340 DwarfInfoSectionSym =
1341 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1342 if (useSplitDwarf()) {
1343 DwarfInfoDWOSectionSym =
1344 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1345 DwarfTypesDWOSectionSym =
1346 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1348 DwarfAbbrevSectionSym =
1349 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1350 if (useSplitDwarf())
1351 DwarfAbbrevDWOSectionSym = emitSectionSym(
1352 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1353 if (GenerateARangeSection)
1354 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1356 DwarfLineSectionSym =
1357 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1358 if (GenerateGnuPubSections) {
1359 DwarfGnuPubNamesSectionSym =
1360 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1361 DwarfGnuPubTypesSectionSym =
1362 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1363 } else if (HasDwarfPubSections) {
1364 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1365 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1368 DwarfStrSectionSym =
1369 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1370 if (useSplitDwarf()) {
1371 DwarfStrDWOSectionSym =
1372 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1373 DwarfAddrSectionSym =
1374 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1375 DwarfDebugLocSectionSym =
1376 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1378 DwarfDebugLocSectionSym =
1379 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1380 DwarfDebugRangeSectionSym =
1381 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1384 // Recursively emits a debug information entry.
1385 void DwarfDebug::emitDIE(DIE &Die) {
1386 // Get the abbreviation for this DIE.
1387 const DIEAbbrev &Abbrev = Die.getAbbrev();
1389 // Emit the code (index) for the abbreviation.
1390 if (Asm->isVerbose())
1391 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1392 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1393 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1394 dwarf::TagString(Abbrev.getTag()));
1395 Asm->EmitULEB128(Abbrev.getNumber());
1397 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1398 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1400 // Emit the DIE attribute values.
1401 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1402 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1403 dwarf::Form Form = AbbrevData[i].getForm();
1404 assert(Form && "Too many attributes for DIE (check abbreviation)");
1406 if (Asm->isVerbose()) {
1407 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1408 if (Attr == dwarf::DW_AT_accessibility)
1409 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1410 cast<DIEInteger>(Values[i])->getValue()));
1413 // Emit an attribute using the defined form.
1414 Values[i]->EmitValue(Asm, Form);
1417 // Emit the DIE children if any.
1418 if (Abbrev.hasChildren()) {
1419 for (auto &Child : Die.getChildren())
1422 Asm->OutStreamer.AddComment("End Of Children Mark");
1427 // Emit the debug info section.
1428 void DwarfDebug::emitDebugInfo() {
1429 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1431 Holder.emitUnits(DwarfAbbrevSectionSym);
1434 // Emit the abbreviation section.
1435 void DwarfDebug::emitAbbreviations() {
1436 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1438 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1441 // Emit the last address of the section and the end of the line matrix.
1442 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1443 // Define last address of section.
1444 Asm->OutStreamer.AddComment("Extended Op");
1447 Asm->OutStreamer.AddComment("Op size");
1448 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1449 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1450 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1452 Asm->OutStreamer.AddComment("Section end label");
1454 Asm->OutStreamer.EmitSymbolValue(
1455 Asm->GetTempSymbol("section_end", SectionEnd),
1456 Asm->getDataLayout().getPointerSize());
1458 // Mark end of matrix.
1459 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1465 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1466 StringRef TableName, StringRef SymName) {
1467 Accel.FinalizeTable(Asm, TableName);
1468 Asm->OutStreamer.SwitchSection(Section);
1469 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1470 Asm->OutStreamer.EmitLabel(SectionBegin);
1472 // Emit the full data.
1473 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1476 // Emit visible names into a hashed accelerator table section.
1477 void DwarfDebug::emitAccelNames() {
1478 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1479 "Names", "names_begin");
1482 // Emit objective C classes and categories into a hashed accelerator table
1484 void DwarfDebug::emitAccelObjC() {
1485 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1486 "ObjC", "objc_begin");
1489 // Emit namespace dies into a hashed accelerator table.
1490 void DwarfDebug::emitAccelNamespaces() {
1491 emitAccel(AccelNamespace,
1492 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1493 "namespac", "namespac_begin");
1496 // Emit type dies into a hashed accelerator table.
1497 void DwarfDebug::emitAccelTypes() {
1498 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1499 "types", "types_begin");
1502 // Public name handling.
1503 // The format for the various pubnames:
1505 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1506 // for the DIE that is named.
1508 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1509 // into the CU and the index value is computed according to the type of value
1510 // for the DIE that is named.
1512 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1513 // it's the offset within the debug_info/debug_types dwo section, however, the
1514 // reference in the pubname header doesn't change.
1516 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1517 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1519 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1521 // We could have a specification DIE that has our most of our knowledge,
1522 // look for that now.
1523 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1525 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1526 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1527 Linkage = dwarf::GIEL_EXTERNAL;
1528 } else if (Die->findAttribute(dwarf::DW_AT_external))
1529 Linkage = dwarf::GIEL_EXTERNAL;
1531 switch (Die->getTag()) {
1532 case dwarf::DW_TAG_class_type:
1533 case dwarf::DW_TAG_structure_type:
1534 case dwarf::DW_TAG_union_type:
1535 case dwarf::DW_TAG_enumeration_type:
1536 return dwarf::PubIndexEntryDescriptor(
1537 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1538 ? dwarf::GIEL_STATIC
1539 : dwarf::GIEL_EXTERNAL);
1540 case dwarf::DW_TAG_typedef:
1541 case dwarf::DW_TAG_base_type:
1542 case dwarf::DW_TAG_subrange_type:
1543 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1544 case dwarf::DW_TAG_namespace:
1545 return dwarf::GIEK_TYPE;
1546 case dwarf::DW_TAG_subprogram:
1547 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1548 case dwarf::DW_TAG_constant:
1549 case dwarf::DW_TAG_variable:
1550 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1551 case dwarf::DW_TAG_enumerator:
1552 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1553 dwarf::GIEL_STATIC);
1555 return dwarf::GIEK_NONE;
1559 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1561 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1562 const MCSection *PSec =
1563 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1564 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1566 emitDebugPubSection(GnuStyle, PSec, "Names",
1567 &DwarfCompileUnit::getGlobalNames);
1570 void DwarfDebug::emitDebugPubSection(
1571 bool GnuStyle, const MCSection *PSec, StringRef Name,
1572 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1573 for (const auto &NU : CUMap) {
1574 DwarfCompileUnit *TheU = NU.second;
1576 const auto &Globals = (TheU->*Accessor)();
1578 if (Globals.empty())
1581 if (auto *Skeleton = TheU->getSkeleton())
1583 unsigned ID = TheU->getUniqueID();
1585 // Start the dwarf pubnames section.
1586 Asm->OutStreamer.SwitchSection(PSec);
1589 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1590 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1591 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1592 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1594 Asm->OutStreamer.EmitLabel(BeginLabel);
1596 Asm->OutStreamer.AddComment("DWARF Version");
1597 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1599 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1600 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1602 Asm->OutStreamer.AddComment("Compilation Unit Length");
1603 Asm->EmitInt32(TheU->getLength());
1605 // Emit the pubnames for this compilation unit.
1606 for (const auto &GI : Globals) {
1607 const char *Name = GI.getKeyData();
1608 const DIE *Entity = GI.second;
1610 Asm->OutStreamer.AddComment("DIE offset");
1611 Asm->EmitInt32(Entity->getOffset());
1614 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1615 Asm->OutStreamer.AddComment(
1616 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1617 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1618 Asm->EmitInt8(Desc.toBits());
1621 Asm->OutStreamer.AddComment("External Name");
1622 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1625 Asm->OutStreamer.AddComment("End Mark");
1627 Asm->OutStreamer.EmitLabel(EndLabel);
1631 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1632 const MCSection *PSec =
1633 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1634 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1636 emitDebugPubSection(GnuStyle, PSec, "Types",
1637 &DwarfCompileUnit::getGlobalTypes);
1640 // Emit visible names into a debug str section.
1641 void DwarfDebug::emitDebugStr() {
1642 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1643 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1646 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1647 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1648 const DITypeIdentifierMap &Map,
1649 ArrayRef<DebugLocEntry::Value> Values) {
1650 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1651 return P.isVariablePiece();
1652 }) && "all values are expected to be pieces");
1653 assert(std::is_sorted(Values.begin(), Values.end()) &&
1654 "pieces are expected to be sorted");
1656 unsigned Offset = 0;
1657 for (auto Piece : Values) {
1658 DIExpression Expr = Piece.getExpression();
1659 unsigned PieceOffset = Expr.getPieceOffset();
1660 unsigned PieceSize = Expr.getPieceSize();
1661 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1662 if (Offset < PieceOffset) {
1663 // The DWARF spec seriously mandates pieces with no locations for gaps.
1664 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1665 Offset += PieceOffset-Offset;
1668 Offset += PieceSize;
1670 const unsigned SizeOfByte = 8;
1672 DIVariable Var = Piece.getVariable();
1673 assert(!Var.isIndirect() && "indirect address for piece");
1674 unsigned VarSize = Var.getSizeInBits(Map);
1675 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1676 && "piece is larger than or outside of variable");
1677 assert(PieceSize*SizeOfByte != VarSize
1678 && "piece covers entire variable");
1680 if (Piece.isLocation() && Piece.getLoc().isReg())
1681 Asm->EmitDwarfRegOpPiece(Streamer,
1683 PieceSize*SizeOfByte);
1685 emitDebugLocValue(Streamer, Piece);
1686 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1692 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1693 const DebugLocEntry &Entry) {
1694 const DebugLocEntry::Value Value = Entry.getValues()[0];
1695 if (Value.isVariablePiece())
1696 // Emit all pieces that belong to the same variable and range.
1697 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1699 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1700 emitDebugLocValue(Streamer, Value);
1703 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1704 const DebugLocEntry::Value &Value) {
1705 DIVariable DV = Value.getVariable();
1707 if (Value.isInt()) {
1708 DIBasicType BTy(resolve(DV.getType()));
1709 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1710 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1711 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1712 Streamer.EmitSLEB128(Value.getInt());
1714 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1715 Streamer.EmitULEB128(Value.getInt());
1717 } else if (Value.isLocation()) {
1718 MachineLocation Loc = Value.getLoc();
1719 DIExpression Expr = Value.getExpression();
1722 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1724 // Complex address entry.
1725 unsigned N = Expr.getNumElements();
1727 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1728 if (Loc.getOffset()) {
1730 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1731 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1732 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1733 Streamer.EmitSLEB128(Expr.getElement(1));
1735 // If first address element is OpPlus then emit
1736 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1737 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1738 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1742 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1745 // Emit remaining complex address elements.
1746 for (; i < N; ++i) {
1747 uint64_t Element = Expr.getElement(i);
1748 if (Element == dwarf::DW_OP_plus) {
1749 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1750 Streamer.EmitULEB128(Expr.getElement(++i));
1751 } else if (Element == dwarf::DW_OP_deref) {
1753 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1754 } else if (Element == dwarf::DW_OP_piece) {
1756 // handled in emitDebugLocEntry.
1758 llvm_unreachable("unknown Opcode found in complex address");
1762 // else ... ignore constant fp. There is not any good way to
1763 // to represent them here in dwarf.
1767 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1768 Asm->OutStreamer.AddComment("Loc expr size");
1769 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1770 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1771 Asm->EmitLabelDifference(end, begin, 2);
1772 Asm->OutStreamer.EmitLabel(begin);
1774 APByteStreamer Streamer(*Asm);
1775 emitDebugLocEntry(Streamer, Entry);
1777 Asm->OutStreamer.EmitLabel(end);
1780 // Emit locations into the debug loc section.
1781 void DwarfDebug::emitDebugLoc() {
1782 // Start the dwarf loc section.
1783 Asm->OutStreamer.SwitchSection(
1784 Asm->getObjFileLowering().getDwarfLocSection());
1785 unsigned char Size = Asm->getDataLayout().getPointerSize();
1786 for (const auto &DebugLoc : DotDebugLocEntries) {
1787 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1788 const DwarfCompileUnit *CU = DebugLoc.CU;
1789 assert(!CU->getRanges().empty());
1790 for (const auto &Entry : DebugLoc.List) {
1791 // Set up the range. This range is relative to the entry point of the
1792 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1793 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1794 if (CU->getRanges().size() == 1) {
1795 // Grab the begin symbol from the first range as our base.
1796 const MCSymbol *Base = CU->getRanges()[0].getStart();
1797 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1798 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1800 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1801 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1804 emitDebugLocEntryLocation(Entry);
1806 Asm->OutStreamer.EmitIntValue(0, Size);
1807 Asm->OutStreamer.EmitIntValue(0, Size);
1811 void DwarfDebug::emitDebugLocDWO() {
1812 Asm->OutStreamer.SwitchSection(
1813 Asm->getObjFileLowering().getDwarfLocDWOSection());
1814 for (const auto &DebugLoc : DotDebugLocEntries) {
1815 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1816 for (const auto &Entry : DebugLoc.List) {
1817 // Just always use start_length for now - at least that's one address
1818 // rather than two. We could get fancier and try to, say, reuse an
1819 // address we know we've emitted elsewhere (the start of the function?
1820 // The start of the CU or CU subrange that encloses this range?)
1821 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1822 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1823 Asm->EmitULEB128(idx);
1824 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1826 emitDebugLocEntryLocation(Entry);
1828 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1833 const MCSymbol *Start, *End;
1836 // Emit a debug aranges section, containing a CU lookup for any
1837 // address we can tie back to a CU.
1838 void DwarfDebug::emitDebugARanges() {
1839 // Start the dwarf aranges section.
1840 Asm->OutStreamer.SwitchSection(
1841 Asm->getObjFileLowering().getDwarfARangesSection());
1843 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1847 // Build a list of sections used.
1848 std::vector<const MCSection *> Sections;
1849 for (const auto &it : SectionMap) {
1850 const MCSection *Section = it.first;
1851 Sections.push_back(Section);
1854 // Sort the sections into order.
1855 // This is only done to ensure consistent output order across different runs.
1856 std::sort(Sections.begin(), Sections.end(), SectionSort);
1858 // Build a set of address spans, sorted by CU.
1859 for (const MCSection *Section : Sections) {
1860 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1861 if (List.size() < 2)
1864 // Sort the symbols by offset within the section.
1865 std::sort(List.begin(), List.end(),
1866 [&](const SymbolCU &A, const SymbolCU &B) {
1867 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1868 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1870 // Symbols with no order assigned should be placed at the end.
1871 // (e.g. section end labels)
1879 // If we have no section (e.g. common), just write out
1880 // individual spans for each symbol.
1882 for (const SymbolCU &Cur : List) {
1884 Span.Start = Cur.Sym;
1887 Spans[Cur.CU].push_back(Span);
1890 // Build spans between each label.
1891 const MCSymbol *StartSym = List[0].Sym;
1892 for (size_t n = 1, e = List.size(); n < e; n++) {
1893 const SymbolCU &Prev = List[n - 1];
1894 const SymbolCU &Cur = List[n];
1896 // Try and build the longest span we can within the same CU.
1897 if (Cur.CU != Prev.CU) {
1899 Span.Start = StartSym;
1901 Spans[Prev.CU].push_back(Span);
1908 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1910 // Build a list of CUs used.
1911 std::vector<DwarfCompileUnit *> CUs;
1912 for (const auto &it : Spans) {
1913 DwarfCompileUnit *CU = it.first;
1917 // Sort the CU list (again, to ensure consistent output order).
1918 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1919 return A->getUniqueID() < B->getUniqueID();
1922 // Emit an arange table for each CU we used.
1923 for (DwarfCompileUnit *CU : CUs) {
1924 std::vector<ArangeSpan> &List = Spans[CU];
1926 // Describe the skeleton CU's offset and length, not the dwo file's.
1927 if (auto *Skel = CU->getSkeleton())
1930 // Emit size of content not including length itself.
1931 unsigned ContentSize =
1932 sizeof(int16_t) + // DWARF ARange version number
1933 sizeof(int32_t) + // Offset of CU in the .debug_info section
1934 sizeof(int8_t) + // Pointer Size (in bytes)
1935 sizeof(int8_t); // Segment Size (in bytes)
1937 unsigned TupleSize = PtrSize * 2;
1939 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1941 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1943 ContentSize += Padding;
1944 ContentSize += (List.size() + 1) * TupleSize;
1946 // For each compile unit, write the list of spans it covers.
1947 Asm->OutStreamer.AddComment("Length of ARange Set");
1948 Asm->EmitInt32(ContentSize);
1949 Asm->OutStreamer.AddComment("DWARF Arange version number");
1950 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1951 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1952 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1953 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1954 Asm->EmitInt8(PtrSize);
1955 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1958 Asm->OutStreamer.EmitFill(Padding, 0xff);
1960 for (const ArangeSpan &Span : List) {
1961 Asm->EmitLabelReference(Span.Start, PtrSize);
1963 // Calculate the size as being from the span start to it's end.
1965 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1967 // For symbols without an end marker (e.g. common), we
1968 // write a single arange entry containing just that one symbol.
1969 uint64_t Size = SymSize[Span.Start];
1973 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1977 Asm->OutStreamer.AddComment("ARange terminator");
1978 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1979 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1983 // Emit visible names into a debug ranges section.
1984 void DwarfDebug::emitDebugRanges() {
1985 // Start the dwarf ranges section.
1986 Asm->OutStreamer.SwitchSection(
1987 Asm->getObjFileLowering().getDwarfRangesSection());
1989 // Size for our labels.
1990 unsigned char Size = Asm->getDataLayout().getPointerSize();
1992 // Grab the specific ranges for the compile units in the module.
1993 for (const auto &I : CUMap) {
1994 DwarfCompileUnit *TheCU = I.second;
1996 // Iterate over the misc ranges for the compile units in the module.
1997 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1998 // Emit our symbol so we can find the beginning of the range.
1999 Asm->OutStreamer.EmitLabel(List.getSym());
2001 for (const RangeSpan &Range : List.getRanges()) {
2002 const MCSymbol *Begin = Range.getStart();
2003 const MCSymbol *End = Range.getEnd();
2004 assert(Begin && "Range without a begin symbol?");
2005 assert(End && "Range without an end symbol?");
2006 if (TheCU->getRanges().size() == 1) {
2007 // Grab the begin symbol from the first range as our base.
2008 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2009 Asm->EmitLabelDifference(Begin, Base, Size);
2010 Asm->EmitLabelDifference(End, Base, Size);
2012 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2013 Asm->OutStreamer.EmitSymbolValue(End, Size);
2017 // And terminate the list with two 0 values.
2018 Asm->OutStreamer.EmitIntValue(0, Size);
2019 Asm->OutStreamer.EmitIntValue(0, Size);
2022 // Now emit a range for the CU itself.
2023 if (TheCU->getRanges().size() > 1) {
2024 Asm->OutStreamer.EmitLabel(
2025 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2026 for (const RangeSpan &Range : TheCU->getRanges()) {
2027 const MCSymbol *Begin = Range.getStart();
2028 const MCSymbol *End = Range.getEnd();
2029 assert(Begin && "Range without a begin symbol?");
2030 assert(End && "Range without an end symbol?");
2031 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2032 Asm->OutStreamer.EmitSymbolValue(End, Size);
2034 // And terminate the list with two 0 values.
2035 Asm->OutStreamer.EmitIntValue(0, Size);
2036 Asm->OutStreamer.EmitIntValue(0, Size);
2041 // DWARF5 Experimental Separate Dwarf emitters.
2043 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2044 std::unique_ptr<DwarfUnit> NewU) {
2045 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2046 U.getCUNode().getSplitDebugFilename());
2048 if (!CompilationDir.empty())
2049 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2051 addGnuPubAttributes(*NewU, Die);
2053 SkeletonHolder.addUnit(std::move(NewU));
2056 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2057 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2058 // DW_AT_addr_base, DW_AT_ranges_base.
2059 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2061 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2062 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2063 DwarfCompileUnit &NewCU = *OwnedUnit;
2064 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2065 DwarfInfoSectionSym);
2067 NewCU.initStmtList(DwarfLineSectionSym);
2069 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2074 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2075 // compile units that would normally be in debug_info.
2076 void DwarfDebug::emitDebugInfoDWO() {
2077 assert(useSplitDwarf() && "No split dwarf debug info?");
2078 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2079 // emit relocations into the dwo file.
2080 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2083 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2084 // abbreviations for the .debug_info.dwo section.
2085 void DwarfDebug::emitDebugAbbrevDWO() {
2086 assert(useSplitDwarf() && "No split dwarf?");
2087 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2090 void DwarfDebug::emitDebugLineDWO() {
2091 assert(useSplitDwarf() && "No split dwarf?");
2092 Asm->OutStreamer.SwitchSection(
2093 Asm->getObjFileLowering().getDwarfLineDWOSection());
2094 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2097 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2098 // string section and is identical in format to traditional .debug_str
2100 void DwarfDebug::emitDebugStrDWO() {
2101 assert(useSplitDwarf() && "No split dwarf?");
2102 const MCSection *OffSec =
2103 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2104 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2108 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2109 if (!useSplitDwarf())
2112 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2113 return &SplitTypeUnitFileTable;
2116 static uint64_t makeTypeSignature(StringRef Identifier) {
2118 Hash.update(Identifier);
2119 // ... take the least significant 8 bytes and return those. Our MD5
2120 // implementation always returns its results in little endian, swap bytes
2122 MD5::MD5Result Result;
2124 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2127 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2128 StringRef Identifier, DIE &RefDie,
2129 DICompositeType CTy) {
2130 // Fast path if we're building some type units and one has already used the
2131 // address pool we know we're going to throw away all this work anyway, so
2132 // don't bother building dependent types.
2133 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2136 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2138 CU.addDIETypeSignature(RefDie, *TU);
2142 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2143 AddrPool.resetUsedFlag();
2145 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2146 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2147 this, &InfoHolder, getDwoLineTable(CU));
2148 DwarfTypeUnit &NewTU = *OwnedUnit;
2149 DIE &UnitDie = NewTU.getUnitDie();
2151 TypeUnitsUnderConstruction.push_back(
2152 std::make_pair(std::move(OwnedUnit), CTy));
2154 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2157 uint64_t Signature = makeTypeSignature(Identifier);
2158 NewTU.setTypeSignature(Signature);
2160 if (useSplitDwarf())
2161 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2163 CU.applyStmtList(UnitDie);
2165 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2168 NewTU.setType(NewTU.createTypeDIE(CTy));
2171 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2172 TypeUnitsUnderConstruction.clear();
2174 // Types referencing entries in the address table cannot be placed in type
2176 if (AddrPool.hasBeenUsed()) {
2178 // Remove all the types built while building this type.
2179 // This is pessimistic as some of these types might not be dependent on
2180 // the type that used an address.
2181 for (const auto &TU : TypeUnitsToAdd)
2182 DwarfTypeUnits.erase(TU.second);
2184 // Construct this type in the CU directly.
2185 // This is inefficient because all the dependent types will be rebuilt
2186 // from scratch, including building them in type units, discovering that
2187 // they depend on addresses, throwing them out and rebuilding them.
2188 CU.constructTypeDIE(RefDie, CTy);
2192 // If the type wasn't dependent on fission addresses, finish adding the type
2193 // and all its dependent types.
2194 for (auto &TU : TypeUnitsToAdd)
2195 InfoHolder.addUnit(std::move(TU.first));
2197 CU.addDIETypeSignature(RefDie, NewTU);
2200 // Accelerator table mutators - add each name along with its companion
2201 // DIE to the proper table while ensuring that the name that we're going
2202 // to reference is in the string table. We do this since the names we
2203 // add may not only be identical to the names in the DIE.
2204 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2205 if (!useDwarfAccelTables())
2207 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2211 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2212 if (!useDwarfAccelTables())
2214 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2218 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2219 if (!useDwarfAccelTables())
2221 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2225 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2226 if (!useDwarfAccelTables())
2228 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),