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 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
335 if (auto *SkelCU = CU.getSkeleton())
339 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
340 assert(Scope && Scope->getScopeNode());
341 assert(Scope->isAbstractScope());
342 assert(!Scope->getInlinedAt());
344 const MDNode *SP = Scope->getScopeNode();
346 ProcessedSPNodes.insert(SP);
348 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
349 // was inlined from another compile unit.
350 auto &CU = SPMap[SP];
351 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
352 CU.constructAbstractSubprogramScopeDIE(Scope);
356 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
357 if (!GenerateGnuPubSections)
360 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
363 // Create new DwarfCompileUnit for the given metadata node with tag
364 // DW_TAG_compile_unit.
365 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
366 StringRef FN = DIUnit.getFilename();
367 CompilationDir = DIUnit.getDirectory();
369 auto OwnedUnit = make_unique<DwarfCompileUnit>(
370 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
371 DwarfCompileUnit &NewCU = *OwnedUnit;
372 DIE &Die = NewCU.getUnitDie();
373 InfoHolder.addUnit(std::move(OwnedUnit));
375 NewCU.setSkeleton(constructSkeletonCU(NewCU));
377 // LTO with assembly output shares a single line table amongst multiple CUs.
378 // To avoid the compilation directory being ambiguous, let the line table
379 // explicitly describe the directory of all files, never relying on the
380 // compilation directory.
381 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
382 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
383 NewCU.getUniqueID(), CompilationDir);
385 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
386 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
387 DIUnit.getLanguage());
388 NewCU.addString(Die, dwarf::DW_AT_name, FN);
390 if (!useSplitDwarf()) {
391 NewCU.initStmtList(DwarfLineSectionSym);
393 // If we're using split dwarf the compilation dir is going to be in the
394 // skeleton CU and so we don't need to duplicate it here.
395 if (!CompilationDir.empty())
396 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
398 addGnuPubAttributes(NewCU, Die);
401 if (DIUnit.isOptimized())
402 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
404 StringRef Flags = DIUnit.getFlags();
406 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
408 if (unsigned RVer = DIUnit.getRunTimeVersion())
409 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
410 dwarf::DW_FORM_data1, RVer);
413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
414 DwarfInfoDWOSectionSym);
416 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
417 DwarfInfoSectionSym);
419 CUMap.insert(std::make_pair(DIUnit, &NewCU));
420 CUDieMap.insert(std::make_pair(&Die, &NewCU));
424 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
426 DIImportedEntity Module(N);
427 assert(Module.Verify());
428 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
429 D->addChild(TheCU.constructImportedEntityDIE(Module));
432 // Emit all Dwarf sections that should come prior to the content. Create
433 // global DIEs and emit initial debug info sections. This is invoked by
434 // the target AsmPrinter.
435 void DwarfDebug::beginModule() {
436 if (DisableDebugInfoPrinting)
439 const Module *M = MMI->getModule();
441 FunctionDIs = makeSubprogramMap(*M);
443 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
446 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
448 // Emit initial sections so we can reference labels later.
451 SingleCU = CU_Nodes->getNumOperands() == 1;
453 for (MDNode *N : CU_Nodes->operands()) {
454 DICompileUnit CUNode(N);
455 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
456 DIArray ImportedEntities = CUNode.getImportedEntities();
457 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
458 ScopesWithImportedEntities.push_back(std::make_pair(
459 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
460 ImportedEntities.getElement(i)));
461 std::sort(ScopesWithImportedEntities.begin(),
462 ScopesWithImportedEntities.end(), less_first());
463 DIArray GVs = CUNode.getGlobalVariables();
464 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
465 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
466 DIArray SPs = CUNode.getSubprograms();
467 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
468 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
469 DIArray EnumTypes = CUNode.getEnumTypes();
470 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
471 DIType Ty(EnumTypes.getElement(i));
472 // The enum types array by design contains pointers to
473 // MDNodes rather than DIRefs. Unique them here.
474 DIType UniqueTy(resolve(Ty.getRef()));
475 CU.getOrCreateTypeDIE(UniqueTy);
477 DIArray RetainedTypes = CUNode.getRetainedTypes();
478 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
479 DIType Ty(RetainedTypes.getElement(i));
480 // The retained types array by design contains pointers to
481 // MDNodes rather than DIRefs. Unique them here.
482 DIType UniqueTy(resolve(Ty.getRef()));
483 CU.getOrCreateTypeDIE(UniqueTy);
485 // Emit imported_modules last so that the relevant context is already
487 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
488 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
491 // Tell MMI that we have debug info.
492 MMI->setDebugInfoAvailability(true);
494 // Prime section data.
495 SectionMap[Asm->getObjFileLowering().getTextSection()];
498 void DwarfDebug::finishVariableDefinitions() {
499 for (const auto &Var : ConcreteVariables) {
500 DIE *VariableDie = Var->getDIE();
502 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
503 // in the ConcreteVariables list, rather than looking it up again here.
504 // DIE::getUnit isn't simple - it walks parent pointers, etc.
505 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
507 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
508 if (AbsVar && AbsVar->getDIE()) {
509 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
512 Unit->applyVariableAttributes(*Var, *VariableDie);
516 void DwarfDebug::finishSubprogramDefinitions() {
517 for (const auto &P : SPMap)
518 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
519 CU.finishSubprogramDefinition(DISubprogram(P.first));
524 // Collect info for variables that were optimized out.
525 void DwarfDebug::collectDeadVariables() {
526 const Module *M = MMI->getModule();
528 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
529 for (MDNode *N : CU_Nodes->operands()) {
530 DICompileUnit TheCU(N);
531 // Construct subprogram DIE and add variables DIEs.
532 DwarfCompileUnit *SPCU =
533 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
534 assert(SPCU && "Unable to find Compile Unit!");
535 DIArray Subprograms = TheCU.getSubprograms();
536 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
537 DISubprogram SP(Subprograms.getElement(i));
538 if (ProcessedSPNodes.count(SP) != 0)
540 SPCU->collectDeadVariables(SP);
546 void DwarfDebug::finalizeModuleInfo() {
547 finishSubprogramDefinitions();
549 finishVariableDefinitions();
551 // Collect info for variables that were optimized out.
552 collectDeadVariables();
554 // Handle anything that needs to be done on a per-unit basis after
555 // all other generation.
556 for (const auto &P : CUMap) {
557 auto &TheCU = *P.second;
558 // Emit DW_AT_containing_type attribute to connect types with their
559 // vtable holding type.
560 TheCU.constructContainingTypeDIEs();
562 // Add CU specific attributes if we need to add any.
563 // If we're splitting the dwarf out now that we've got the entire
564 // CU then add the dwo id to it.
565 auto *SkCU = TheCU.getSkeleton();
566 if (useSplitDwarf()) {
567 // Emit a unique identifier for this CU.
568 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
569 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
570 dwarf::DW_FORM_data8, ID);
571 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
572 dwarf::DW_FORM_data8, ID);
574 // We don't keep track of which addresses are used in which CU so this
575 // is a bit pessimistic under LTO.
576 if (!AddrPool.isEmpty())
577 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
578 DwarfAddrSectionSym, DwarfAddrSectionSym);
579 if (!SkCU->getRangeLists().empty())
580 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
581 DwarfDebugRangeSectionSym,
582 DwarfDebugRangeSectionSym);
585 // If we have code split among multiple sections or non-contiguous
586 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
587 // remain in the .o file, otherwise add a DW_AT_low_pc.
588 // FIXME: We should use ranges allow reordering of code ala
589 // .subsections_via_symbols in mach-o. This would mean turning on
590 // ranges for all subprogram DIEs for mach-o.
591 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
592 if (unsigned NumRanges = TheCU.getRanges().size()) {
594 // A DW_AT_low_pc attribute may also be specified in combination with
595 // DW_AT_ranges to specify the default base address for use in
596 // location lists (see Section 2.6.2) and range lists (see Section
598 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
600 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
601 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
605 // Compute DIE offsets and sizes.
606 InfoHolder.computeSizeAndOffsets();
608 SkeletonHolder.computeSizeAndOffsets();
611 void DwarfDebug::endSections() {
612 // Filter labels by section.
613 for (const SymbolCU &SCU : ArangeLabels) {
614 if (SCU.Sym->isInSection()) {
615 // Make a note of this symbol and it's section.
616 const MCSection *Section = &SCU.Sym->getSection();
617 if (!Section->getKind().isMetadata())
618 SectionMap[Section].push_back(SCU);
620 // Some symbols (e.g. common/bss on mach-o) can have no section but still
621 // appear in the output. This sucks as we rely on sections to build
622 // arange spans. We can do it without, but it's icky.
623 SectionMap[nullptr].push_back(SCU);
627 // Build a list of sections used.
628 std::vector<const MCSection *> Sections;
629 for (const auto &it : SectionMap) {
630 const MCSection *Section = it.first;
631 Sections.push_back(Section);
634 // Sort the sections into order.
635 // This is only done to ensure consistent output order across different runs.
636 std::sort(Sections.begin(), Sections.end(), SectionSort);
638 // Add terminating symbols for each section.
639 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
640 const MCSection *Section = Sections[ID];
641 MCSymbol *Sym = nullptr;
644 // We can't call MCSection::getLabelEndName, as it's only safe to do so
645 // if we know the section name up-front. For user-created sections, the
646 // resulting label may not be valid to use as a label. (section names can
647 // use a greater set of characters on some systems)
648 Sym = Asm->GetTempSymbol("debug_end", ID);
649 Asm->OutStreamer.SwitchSection(Section);
650 Asm->OutStreamer.EmitLabel(Sym);
653 // Insert a final terminator.
654 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
658 // Emit all Dwarf sections that should come after the content.
659 void DwarfDebug::endModule() {
660 assert(CurFn == nullptr);
661 assert(CurMI == nullptr);
663 // If we aren't actually generating debug info (check beginModule -
664 // conditionalized on !DisableDebugInfoPrinting and the presence of the
665 // llvm.dbg.cu metadata node)
666 if (!DwarfInfoSectionSym)
669 // End any existing sections.
670 // TODO: Does this need to happen?
673 // Finalize the debug info for the module.
674 finalizeModuleInfo();
678 // Emit all the DIEs into a debug info section.
681 // Corresponding abbreviations into a abbrev section.
684 // Emit info into a debug aranges section.
685 if (GenerateARangeSection)
688 // Emit info into a debug ranges section.
691 if (useSplitDwarf()) {
694 emitDebugAbbrevDWO();
697 // Emit DWO addresses.
698 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
700 // Emit info into a debug loc section.
703 // Emit info into the dwarf accelerator table sections.
704 if (useDwarfAccelTables()) {
707 emitAccelNamespaces();
711 // Emit the pubnames and pubtypes sections if requested.
712 if (HasDwarfPubSections) {
713 emitDebugPubNames(GenerateGnuPubSections);
714 emitDebugPubTypes(GenerateGnuPubSections);
719 AbstractVariables.clear();
722 // Find abstract variable, if any, associated with Var.
723 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
724 DIVariable &Cleansed) {
725 LLVMContext &Ctx = DV->getContext();
726 // More then one inlined variable corresponds to one abstract variable.
727 // FIXME: This duplication of variables when inlining should probably be
728 // removed. It's done to allow each DIVariable to describe its location
729 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
730 // make it accurate then remove this duplication/cleansing stuff.
731 Cleansed = cleanseInlinedVariable(DV, Ctx);
732 auto I = AbstractVariables.find(Cleansed);
733 if (I != AbstractVariables.end())
734 return I->second.get();
738 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
740 return getExistingAbstractVariable(DV, Cleansed);
743 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
744 LexicalScope *Scope) {
745 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
746 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
747 AbstractVariables[Var] = std::move(AbsDbgVariable);
750 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
751 const MDNode *ScopeNode) {
752 DIVariable Cleansed = DV;
753 if (getExistingAbstractVariable(DV, Cleansed))
756 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
760 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
761 const MDNode *ScopeNode) {
762 DIVariable Cleansed = DV;
763 if (getExistingAbstractVariable(DV, Cleansed))
766 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
767 createAbstractVariable(Cleansed, Scope);
770 // Collect variable information from side table maintained by MMI.
771 void DwarfDebug::collectVariableInfoFromMMITable(
772 SmallPtrSetImpl<const MDNode *> &Processed) {
773 for (const auto &VI : MMI->getVariableDbgInfo()) {
776 Processed.insert(VI.Var);
777 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
779 // If variable scope is not found then skip this variable.
783 DIVariable DV(VI.Var);
784 DIExpression Expr(VI.Expr);
785 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
786 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
787 DbgVariable *RegVar = ConcreteVariables.back().get();
788 RegVar->setFrameIndex(VI.Slot);
789 InfoHolder.addScopeVariable(Scope, RegVar);
793 // Get .debug_loc entry for the instruction range starting at MI.
794 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
795 const MDNode *Expr = MI->getDebugExpression();
796 const MDNode *Var = MI->getDebugVariable();
798 assert(MI->getNumOperands() == 4);
799 if (MI->getOperand(0).isReg()) {
800 MachineLocation MLoc;
801 // If the second operand is an immediate, this is a
802 // register-indirect address.
803 if (!MI->getOperand(1).isImm())
804 MLoc.set(MI->getOperand(0).getReg());
806 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
807 return DebugLocEntry::Value(Var, Expr, MLoc);
809 if (MI->getOperand(0).isImm())
810 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
811 if (MI->getOperand(0).isFPImm())
812 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
813 if (MI->getOperand(0).isCImm())
814 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
816 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
819 /// Determine whether two variable pieces overlap.
820 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
821 if (!P1.isVariablePiece() || !P2.isVariablePiece())
823 unsigned l1 = P1.getPieceOffset();
824 unsigned l2 = P2.getPieceOffset();
825 unsigned r1 = l1 + P1.getPieceSize();
826 unsigned r2 = l2 + P2.getPieceSize();
827 // True where [l1,r1[ and [r1,r2[ overlap.
828 return (l1 < r2) && (l2 < r1);
831 /// Build the location list for all DBG_VALUEs in the function that
832 /// describe the same variable. If the ranges of several independent
833 /// pieces of the same variable overlap partially, split them up and
834 /// combine the ranges. The resulting DebugLocEntries are will have
835 /// strict monotonically increasing begin addresses and will never
840 // Ranges History [var, loc, piece ofs size]
841 // 0 | [x, (reg0, piece 0, 32)]
842 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
844 // 3 | [clobber reg0]
845 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
849 // [0-1] [x, (reg0, piece 0, 32)]
850 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
851 // [3-4] [x, (reg1, piece 32, 32)]
852 // [4- ] [x, (mem, piece 0, 64)]
854 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
855 const DbgValueHistoryMap::InstrRanges &Ranges) {
856 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
858 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
859 const MachineInstr *Begin = I->first;
860 const MachineInstr *End = I->second;
861 assert(Begin->isDebugValue() && "Invalid History entry");
863 // Check if a variable is inaccessible in this range.
864 if (Begin->getNumOperands() > 1 &&
865 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
870 // If this piece overlaps with any open ranges, truncate them.
871 DIExpression DIExpr = Begin->getDebugExpression();
872 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
873 [&](DebugLocEntry::Value R) {
874 return piecesOverlap(DIExpr, R.getExpression());
876 OpenRanges.erase(Last, OpenRanges.end());
878 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
879 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
881 const MCSymbol *EndLabel;
883 EndLabel = getLabelAfterInsn(End);
884 else if (std::next(I) == Ranges.end())
885 EndLabel = FunctionEndSym;
887 EndLabel = getLabelBeforeInsn(std::next(I)->first);
888 assert(EndLabel && "Forgot label after instruction ending a range!");
890 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
892 auto Value = getDebugLocValue(Begin);
893 DebugLocEntry Loc(StartLabel, EndLabel, Value);
894 bool couldMerge = false;
896 // If this is a piece, it may belong to the current DebugLocEntry.
897 if (DIExpr.isVariablePiece()) {
898 // Add this value to the list of open ranges.
899 OpenRanges.push_back(Value);
901 // Attempt to add the piece to the last entry.
902 if (!DebugLoc.empty())
903 if (DebugLoc.back().MergeValues(Loc))
908 // Need to add a new DebugLocEntry. Add all values from still
909 // valid non-overlapping pieces.
910 if (OpenRanges.size())
911 Loc.addValues(OpenRanges);
913 DebugLoc.push_back(std::move(Loc));
916 // Attempt to coalesce the ranges of two otherwise identical
918 auto CurEntry = DebugLoc.rbegin();
919 auto PrevEntry = std::next(CurEntry);
920 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
924 dbgs() << CurEntry->getValues().size() << " Values:\n";
925 for (auto Value : CurEntry->getValues()) {
926 Value.getVariable()->dump();
927 Value.getExpression()->dump();
935 // Find variables for each lexical scope.
937 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
938 SmallPtrSetImpl<const MDNode *> &Processed) {
939 // Grab the variable info that was squirreled away in the MMI side-table.
940 collectVariableInfoFromMMITable(Processed);
942 for (const auto &I : DbgValues) {
943 DIVariable DV(I.first);
944 if (Processed.count(DV))
947 // Instruction ranges, specifying where DV is accessible.
948 const auto &Ranges = I.second;
952 LexicalScope *Scope = nullptr;
953 if (MDNode *IA = DV.getInlinedAt()) {
954 DebugLoc DL = DebugLoc::getFromDILocation(IA);
955 Scope = LScopes.findInlinedScope(DebugLoc::get(
956 DL.getLine(), DL.getCol(), DV.getContext(), IA));
958 Scope = LScopes.findLexicalScope(DV.getContext());
959 // If variable scope is not found then skip this variable.
963 Processed.insert(DV);
964 const MachineInstr *MInsn = Ranges.front().first;
965 assert(MInsn->isDebugValue() && "History must begin with debug value");
966 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
967 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
968 DbgVariable *RegVar = ConcreteVariables.back().get();
969 InfoHolder.addScopeVariable(Scope, RegVar);
971 // Check if the first DBG_VALUE is valid for the rest of the function.
972 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
975 // Handle multiple DBG_VALUE instructions describing one variable.
976 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
978 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
979 DebugLocList &LocList = DotDebugLocEntries.back();
982 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
984 // Build the location list for this variable.
985 buildLocationList(LocList.List, Ranges);
988 // Collect info for variables that were optimized out.
989 DIArray Variables = SP.getVariables();
990 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
991 DIVariable DV(Variables.getElement(i));
992 assert(DV.isVariable());
993 if (!Processed.insert(DV).second)
995 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
996 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
998 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
999 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
1004 // Return Label preceding the instruction.
1005 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1006 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1007 assert(Label && "Didn't insert label before instruction");
1011 // Return Label immediately following the instruction.
1012 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1013 return LabelsAfterInsn.lookup(MI);
1016 // Process beginning of an instruction.
1017 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1018 assert(CurMI == nullptr);
1020 // Check if source location changes, but ignore DBG_VALUE locations.
1021 if (!MI->isDebugValue()) {
1022 DebugLoc DL = MI->getDebugLoc();
1023 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1026 if (DL == PrologEndLoc) {
1027 Flags |= DWARF2_FLAG_PROLOGUE_END;
1028 PrologEndLoc = DebugLoc();
1030 if (PrologEndLoc.isUnknown())
1031 Flags |= DWARF2_FLAG_IS_STMT;
1033 if (!DL.isUnknown()) {
1034 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1035 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1037 recordSourceLine(0, 0, nullptr, 0);
1041 // Insert labels where requested.
1042 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1043 LabelsBeforeInsn.find(MI);
1046 if (I == LabelsBeforeInsn.end())
1049 // Label already assigned.
1054 PrevLabel = MMI->getContext().CreateTempSymbol();
1055 Asm->OutStreamer.EmitLabel(PrevLabel);
1057 I->second = PrevLabel;
1060 // Process end of an instruction.
1061 void DwarfDebug::endInstruction() {
1062 assert(CurMI != nullptr);
1063 // Don't create a new label after DBG_VALUE instructions.
1064 // They don't generate code.
1065 if (!CurMI->isDebugValue())
1066 PrevLabel = nullptr;
1068 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1069 LabelsAfterInsn.find(CurMI);
1073 if (I == LabelsAfterInsn.end())
1076 // Label already assigned.
1080 // We need a label after this instruction.
1082 PrevLabel = MMI->getContext().CreateTempSymbol();
1083 Asm->OutStreamer.EmitLabel(PrevLabel);
1085 I->second = PrevLabel;
1088 // Each LexicalScope has first instruction and last instruction to mark
1089 // beginning and end of a scope respectively. Create an inverse map that list
1090 // scopes starts (and ends) with an instruction. One instruction may start (or
1091 // end) multiple scopes. Ignore scopes that are not reachable.
1092 void DwarfDebug::identifyScopeMarkers() {
1093 SmallVector<LexicalScope *, 4> WorkList;
1094 WorkList.push_back(LScopes.getCurrentFunctionScope());
1095 while (!WorkList.empty()) {
1096 LexicalScope *S = WorkList.pop_back_val();
1098 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1099 if (!Children.empty())
1100 WorkList.append(Children.begin(), Children.end());
1102 if (S->isAbstractScope())
1105 for (const InsnRange &R : S->getRanges()) {
1106 assert(R.first && "InsnRange does not have first instruction!");
1107 assert(R.second && "InsnRange does not have second instruction!");
1108 requestLabelBeforeInsn(R.first);
1109 requestLabelAfterInsn(R.second);
1114 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1115 // First known non-DBG_VALUE and non-frame setup location marks
1116 // the beginning of the function body.
1117 for (const auto &MBB : *MF)
1118 for (const auto &MI : MBB)
1119 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1120 !MI.getDebugLoc().isUnknown()) {
1121 // Did the target forget to set the FrameSetup flag for CFI insns?
1122 assert(!MI.isCFIInstruction() &&
1123 "First non-frame-setup instruction is a CFI instruction.");
1124 return MI.getDebugLoc();
1129 // Gather pre-function debug information. Assumes being called immediately
1130 // after the function entry point has been emitted.
1131 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1134 // If there's no debug info for the function we're not going to do anything.
1135 if (!MMI->hasDebugInfo())
1138 auto DI = FunctionDIs.find(MF->getFunction());
1139 if (DI == FunctionDIs.end())
1142 // Grab the lexical scopes for the function, if we don't have any of those
1143 // then we're not going to be able to do anything.
1144 LScopes.initialize(*MF);
1145 if (LScopes.empty())
1148 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1150 // Make sure that each lexical scope will have a begin/end label.
1151 identifyScopeMarkers();
1153 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1154 // belongs to so that we add to the correct per-cu line table in the
1156 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1157 // FnScope->getScopeNode() and DI->second should represent the same function,
1158 // though they may not be the same MDNode due to inline functions merged in
1159 // LTO where the debug info metadata still differs (either due to distinct
1160 // written differences - two versions of a linkonce_odr function
1161 // written/copied into two separate files, or some sub-optimal metadata that
1162 // isn't structurally identical (see: file path/name info from clang, which
1163 // includes the directory of the cpp file being built, even when the file name
1164 // is absolute (such as an <> lookup header)))
1165 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1166 assert(TheCU && "Unable to find compile unit!");
1167 if (Asm->OutStreamer.hasRawTextSupport())
1168 // Use a single line table if we are generating assembly.
1169 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1171 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1173 // Emit a label for the function so that we have a beginning address.
1174 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1175 // Assumes in correct section after the entry point.
1176 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1178 // Calculate history for local variables.
1179 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1182 // Request labels for the full history.
1183 for (const auto &I : DbgValues) {
1184 const auto &Ranges = I.second;
1188 // The first mention of a function argument gets the FunctionBeginSym
1189 // label, so arguments are visible when breaking at function entry.
1190 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1191 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1192 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1193 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1194 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1195 // Mark all non-overlapping initial pieces.
1196 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1197 DIExpression Piece = I->first->getDebugExpression();
1198 if (std::all_of(Ranges.begin(), I,
1199 [&](DbgValueHistoryMap::InstrRange Pred) {
1200 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1202 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1209 for (const auto &Range : Ranges) {
1210 requestLabelBeforeInsn(Range.first);
1212 requestLabelAfterInsn(Range.second);
1216 PrevInstLoc = DebugLoc();
1217 PrevLabel = FunctionBeginSym;
1219 // Record beginning of function.
1220 PrologEndLoc = findPrologueEndLoc(MF);
1221 if (!PrologEndLoc.isUnknown()) {
1222 DebugLoc FnStartDL =
1223 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1225 FnStartDL.getLine(), FnStartDL.getCol(),
1226 FnStartDL.getScope(MF->getFunction()->getContext()),
1227 // We'd like to list the prologue as "not statements" but GDB behaves
1228 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1229 DWARF2_FLAG_IS_STMT);
1233 // Gather and emit post-function debug information.
1234 void DwarfDebug::endFunction(const MachineFunction *MF) {
1235 assert(CurFn == MF &&
1236 "endFunction should be called with the same function as beginFunction");
1238 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1239 !FunctionDIs.count(MF->getFunction())) {
1240 // If we don't have a lexical scope for this function then there will
1241 // be a hole in the range information. Keep note of this by setting the
1242 // previously used section to nullptr.
1248 // Define end label for subprogram.
1249 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1250 // Assumes in correct section after the entry point.
1251 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1253 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1254 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1256 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1257 DISubprogram SP(FnScope->getScopeNode());
1258 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1260 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1261 collectVariableInfo(TheCU, SP, ProcessedVars);
1263 // Add the range of this function to the list of ranges for the CU.
1264 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1266 // Under -gmlt, skip building the subprogram if there are no inlined
1267 // subroutines inside it.
1268 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1269 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1270 assert(InfoHolder.getScopeVariables().empty());
1271 assert(DbgValues.empty());
1272 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1273 // by a -gmlt CU. Add a test and remove this assertion.
1274 assert(AbstractVariables.empty());
1275 LabelsBeforeInsn.clear();
1276 LabelsAfterInsn.clear();
1277 PrevLabel = nullptr;
1283 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1285 // Construct abstract scopes.
1286 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1287 DISubprogram SP(AScope->getScopeNode());
1288 assert(SP.isSubprogram());
1289 // Collect info for variables that were optimized out.
1290 DIArray Variables = SP.getVariables();
1291 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1292 DIVariable DV(Variables.getElement(i));
1293 assert(DV && DV.isVariable());
1294 if (!ProcessedVars.insert(DV).second)
1296 ensureAbstractVariableIsCreated(DV, DV.getContext());
1297 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1298 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1300 constructAbstractSubprogramScopeDIE(AScope);
1303 TheCU.constructSubprogramScopeDIE(FnScope);
1304 if (auto *SkelCU = TheCU.getSkeleton())
1305 if (!LScopes.getAbstractScopesList().empty())
1306 SkelCU->constructSubprogramScopeDIE(FnScope);
1309 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1310 // DbgVariables except those that are also in AbstractVariables (since they
1311 // can be used cross-function)
1312 InfoHolder.getScopeVariables().clear();
1314 LabelsBeforeInsn.clear();
1315 LabelsAfterInsn.clear();
1316 PrevLabel = nullptr;
1320 // Register a source line with debug info. Returns the unique label that was
1321 // emitted and which provides correspondence to the source line list.
1322 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1327 unsigned Discriminator = 0;
1328 if (DIScope Scope = DIScope(S)) {
1329 assert(Scope.isScope());
1330 Fn = Scope.getFilename();
1331 Dir = Scope.getDirectory();
1332 if (Scope.isLexicalBlockFile())
1333 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1335 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1336 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1337 .getOrCreateSourceID(Fn, Dir);
1339 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1343 //===----------------------------------------------------------------------===//
1345 //===----------------------------------------------------------------------===//
1347 // Emit initial Dwarf sections with a label at the start of each one.
1348 void DwarfDebug::emitSectionLabels() {
1349 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1351 // Dwarf sections base addresses.
1352 DwarfInfoSectionSym =
1353 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1354 if (useSplitDwarf()) {
1355 DwarfInfoDWOSectionSym =
1356 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1357 DwarfTypesDWOSectionSym =
1358 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1360 DwarfAbbrevSectionSym =
1361 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1362 if (useSplitDwarf())
1363 DwarfAbbrevDWOSectionSym = emitSectionSym(
1364 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1365 if (GenerateARangeSection)
1366 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1368 DwarfLineSectionSym =
1369 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1370 if (GenerateGnuPubSections) {
1371 DwarfGnuPubNamesSectionSym =
1372 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1373 DwarfGnuPubTypesSectionSym =
1374 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1375 } else if (HasDwarfPubSections) {
1376 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1377 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1380 DwarfStrSectionSym =
1381 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1382 if (useSplitDwarf()) {
1383 DwarfStrDWOSectionSym =
1384 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1385 DwarfAddrSectionSym =
1386 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1387 DwarfDebugLocSectionSym =
1388 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1390 DwarfDebugLocSectionSym =
1391 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1392 DwarfDebugRangeSectionSym =
1393 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1396 // Recursively emits a debug information entry.
1397 void DwarfDebug::emitDIE(DIE &Die) {
1398 // Get the abbreviation for this DIE.
1399 const DIEAbbrev &Abbrev = Die.getAbbrev();
1401 // Emit the code (index) for the abbreviation.
1402 if (Asm->isVerbose())
1403 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1404 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1405 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1406 dwarf::TagString(Abbrev.getTag()));
1407 Asm->EmitULEB128(Abbrev.getNumber());
1409 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1410 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1412 // Emit the DIE attribute values.
1413 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1414 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1415 dwarf::Form Form = AbbrevData[i].getForm();
1416 assert(Form && "Too many attributes for DIE (check abbreviation)");
1418 if (Asm->isVerbose()) {
1419 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1420 if (Attr == dwarf::DW_AT_accessibility)
1421 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1422 cast<DIEInteger>(Values[i])->getValue()));
1425 // Emit an attribute using the defined form.
1426 Values[i]->EmitValue(Asm, Form);
1429 // Emit the DIE children if any.
1430 if (Abbrev.hasChildren()) {
1431 for (auto &Child : Die.getChildren())
1434 Asm->OutStreamer.AddComment("End Of Children Mark");
1439 // Emit the debug info section.
1440 void DwarfDebug::emitDebugInfo() {
1441 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1443 Holder.emitUnits(DwarfAbbrevSectionSym);
1446 // Emit the abbreviation section.
1447 void DwarfDebug::emitAbbreviations() {
1448 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1450 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1453 // Emit the last address of the section and the end of the line matrix.
1454 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1455 // Define last address of section.
1456 Asm->OutStreamer.AddComment("Extended Op");
1459 Asm->OutStreamer.AddComment("Op size");
1460 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1461 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1462 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1464 Asm->OutStreamer.AddComment("Section end label");
1466 Asm->OutStreamer.EmitSymbolValue(
1467 Asm->GetTempSymbol("section_end", SectionEnd),
1468 Asm->getDataLayout().getPointerSize());
1470 // Mark end of matrix.
1471 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1477 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1478 StringRef TableName, StringRef SymName) {
1479 Accel.FinalizeTable(Asm, TableName);
1480 Asm->OutStreamer.SwitchSection(Section);
1481 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1482 Asm->OutStreamer.EmitLabel(SectionBegin);
1484 // Emit the full data.
1485 Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1488 // Emit visible names into a hashed accelerator table section.
1489 void DwarfDebug::emitAccelNames() {
1490 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1491 "Names", "names_begin");
1494 // Emit objective C classes and categories into a hashed accelerator table
1496 void DwarfDebug::emitAccelObjC() {
1497 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1498 "ObjC", "objc_begin");
1501 // Emit namespace dies into a hashed accelerator table.
1502 void DwarfDebug::emitAccelNamespaces() {
1503 emitAccel(AccelNamespace,
1504 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1505 "namespac", "namespac_begin");
1508 // Emit type dies into a hashed accelerator table.
1509 void DwarfDebug::emitAccelTypes() {
1510 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1511 "types", "types_begin");
1514 // Public name handling.
1515 // The format for the various pubnames:
1517 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1518 // for the DIE that is named.
1520 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1521 // into the CU and the index value is computed according to the type of value
1522 // for the DIE that is named.
1524 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1525 // it's the offset within the debug_info/debug_types dwo section, however, the
1526 // reference in the pubname header doesn't change.
1528 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1529 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1531 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1533 // We could have a specification DIE that has our most of our knowledge,
1534 // look for that now.
1535 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1537 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1538 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1539 Linkage = dwarf::GIEL_EXTERNAL;
1540 } else if (Die->findAttribute(dwarf::DW_AT_external))
1541 Linkage = dwarf::GIEL_EXTERNAL;
1543 switch (Die->getTag()) {
1544 case dwarf::DW_TAG_class_type:
1545 case dwarf::DW_TAG_structure_type:
1546 case dwarf::DW_TAG_union_type:
1547 case dwarf::DW_TAG_enumeration_type:
1548 return dwarf::PubIndexEntryDescriptor(
1549 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1550 ? dwarf::GIEL_STATIC
1551 : dwarf::GIEL_EXTERNAL);
1552 case dwarf::DW_TAG_typedef:
1553 case dwarf::DW_TAG_base_type:
1554 case dwarf::DW_TAG_subrange_type:
1555 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1556 case dwarf::DW_TAG_namespace:
1557 return dwarf::GIEK_TYPE;
1558 case dwarf::DW_TAG_subprogram:
1559 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1560 case dwarf::DW_TAG_constant:
1561 case dwarf::DW_TAG_variable:
1562 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1563 case dwarf::DW_TAG_enumerator:
1564 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1565 dwarf::GIEL_STATIC);
1567 return dwarf::GIEK_NONE;
1571 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1573 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1574 const MCSection *PSec =
1575 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1576 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1578 emitDebugPubSection(GnuStyle, PSec, "Names",
1579 &DwarfCompileUnit::getGlobalNames);
1582 void DwarfDebug::emitDebugPubSection(
1583 bool GnuStyle, const MCSection *PSec, StringRef Name,
1584 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1585 for (const auto &NU : CUMap) {
1586 DwarfCompileUnit *TheU = NU.second;
1588 const auto &Globals = (TheU->*Accessor)();
1590 if (Globals.empty())
1593 if (auto *Skeleton = TheU->getSkeleton())
1595 unsigned ID = TheU->getUniqueID();
1597 // Start the dwarf pubnames section.
1598 Asm->OutStreamer.SwitchSection(PSec);
1601 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1602 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1603 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1604 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1606 Asm->OutStreamer.EmitLabel(BeginLabel);
1608 Asm->OutStreamer.AddComment("DWARF Version");
1609 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1611 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1612 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1614 Asm->OutStreamer.AddComment("Compilation Unit Length");
1615 Asm->EmitInt32(TheU->getLength());
1617 // Emit the pubnames for this compilation unit.
1618 for (const auto &GI : Globals) {
1619 const char *Name = GI.getKeyData();
1620 const DIE *Entity = GI.second;
1622 Asm->OutStreamer.AddComment("DIE offset");
1623 Asm->EmitInt32(Entity->getOffset());
1626 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1627 Asm->OutStreamer.AddComment(
1628 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1629 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1630 Asm->EmitInt8(Desc.toBits());
1633 Asm->OutStreamer.AddComment("External Name");
1634 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1637 Asm->OutStreamer.AddComment("End Mark");
1639 Asm->OutStreamer.EmitLabel(EndLabel);
1643 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1644 const MCSection *PSec =
1645 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1646 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1648 emitDebugPubSection(GnuStyle, PSec, "Types",
1649 &DwarfCompileUnit::getGlobalTypes);
1652 // Emit visible names into a debug str section.
1653 void DwarfDebug::emitDebugStr() {
1654 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1655 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1658 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1659 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1660 const DITypeIdentifierMap &Map,
1661 ArrayRef<DebugLocEntry::Value> Values) {
1662 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1663 return P.isVariablePiece();
1664 }) && "all values are expected to be pieces");
1665 assert(std::is_sorted(Values.begin(), Values.end()) &&
1666 "pieces are expected to be sorted");
1668 unsigned Offset = 0;
1669 for (auto Piece : Values) {
1670 DIExpression Expr = Piece.getExpression();
1671 unsigned PieceOffset = Expr.getPieceOffset();
1672 unsigned PieceSize = Expr.getPieceSize();
1673 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1674 if (Offset < PieceOffset) {
1675 // The DWARF spec seriously mandates pieces with no locations for gaps.
1676 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1677 Offset += PieceOffset-Offset;
1680 Offset += PieceSize;
1682 const unsigned SizeOfByte = 8;
1684 DIVariable Var = Piece.getVariable();
1685 assert(!Var.isIndirect() && "indirect address for piece");
1686 unsigned VarSize = Var.getSizeInBits(Map);
1687 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1688 && "piece is larger than or outside of variable");
1689 assert(PieceSize*SizeOfByte != VarSize
1690 && "piece covers entire variable");
1692 if (Piece.isLocation() && Piece.getLoc().isReg())
1693 Asm->EmitDwarfRegOpPiece(Streamer,
1695 PieceSize*SizeOfByte);
1697 emitDebugLocValue(Streamer, Piece);
1698 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1704 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1705 const DebugLocEntry &Entry) {
1706 const DebugLocEntry::Value Value = Entry.getValues()[0];
1707 if (Value.isVariablePiece())
1708 // Emit all pieces that belong to the same variable and range.
1709 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1711 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1712 emitDebugLocValue(Streamer, Value);
1715 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1716 const DebugLocEntry::Value &Value) {
1717 DIVariable DV = Value.getVariable();
1719 if (Value.isInt()) {
1720 DIBasicType BTy(resolve(DV.getType()));
1721 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1722 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1723 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1724 Streamer.EmitSLEB128(Value.getInt());
1726 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1727 Streamer.EmitULEB128(Value.getInt());
1729 // The proper way to describe a constant value is
1730 // DW_OP_constu <const>, DW_OP_stack_value.
1731 // Unfortunately, DW_OP_stack_value was not available until DWARF-4,
1732 // so we will continue to generate DW_OP_constu <const> for DWARF-2
1733 // and DWARF-3. Technically, this is incorrect since DW_OP_const <const>
1734 // actually describes a value at a constant addess, not a constant value.
1735 // However, in the past there was no better way to describe a constant
1736 // value, so the producers and consumers started to rely on heuristics
1737 // to disambiguate the value vs. location status of the expression.
1738 // See PR21176 for more details.
1739 if (getDwarfVersion() >= 4)
1740 Streamer.EmitInt8(dwarf::DW_OP_stack_value, "DW_OP_stack_value");
1741 } else if (Value.isLocation()) {
1742 MachineLocation Loc = Value.getLoc();
1743 DIExpression Expr = Value.getExpression();
1746 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1748 // Complex address entry.
1749 unsigned N = Expr.getNumElements();
1751 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1752 if (Loc.getOffset()) {
1754 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1755 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1756 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1757 Streamer.EmitSLEB128(Expr.getElement(1));
1759 // If first address element is OpPlus then emit
1760 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1761 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1762 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1766 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1769 // Emit remaining complex address elements.
1770 for (; i < N; ++i) {
1771 uint64_t Element = Expr.getElement(i);
1772 if (Element == dwarf::DW_OP_plus) {
1773 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1774 Streamer.EmitULEB128(Expr.getElement(++i));
1775 } else if (Element == dwarf::DW_OP_deref) {
1777 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1778 } else if (Element == dwarf::DW_OP_piece) {
1780 // handled in emitDebugLocEntry.
1782 llvm_unreachable("unknown Opcode found in complex address");
1786 // else ... ignore constant fp. There is not any good way to
1787 // to represent them here in dwarf.
1791 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1792 Asm->OutStreamer.AddComment("Loc expr size");
1793 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1794 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1795 Asm->EmitLabelDifference(end, begin, 2);
1796 Asm->OutStreamer.EmitLabel(begin);
1798 APByteStreamer Streamer(*Asm);
1799 emitDebugLocEntry(Streamer, Entry);
1801 Asm->OutStreamer.EmitLabel(end);
1804 // Emit locations into the debug loc section.
1805 void DwarfDebug::emitDebugLoc() {
1806 // Start the dwarf loc section.
1807 Asm->OutStreamer.SwitchSection(
1808 Asm->getObjFileLowering().getDwarfLocSection());
1809 unsigned char Size = Asm->getDataLayout().getPointerSize();
1810 for (const auto &DebugLoc : DotDebugLocEntries) {
1811 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1812 const DwarfCompileUnit *CU = DebugLoc.CU;
1813 for (const auto &Entry : DebugLoc.List) {
1814 // Set up the range. This range is relative to the entry point of the
1815 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1816 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1817 if (auto *Base = CU->getBaseAddress()) {
1818 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1819 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1821 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1822 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1825 emitDebugLocEntryLocation(Entry);
1827 Asm->OutStreamer.EmitIntValue(0, Size);
1828 Asm->OutStreamer.EmitIntValue(0, Size);
1832 void DwarfDebug::emitDebugLocDWO() {
1833 Asm->OutStreamer.SwitchSection(
1834 Asm->getObjFileLowering().getDwarfLocDWOSection());
1835 for (const auto &DebugLoc : DotDebugLocEntries) {
1836 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1837 for (const auto &Entry : DebugLoc.List) {
1838 // Just always use start_length for now - at least that's one address
1839 // rather than two. We could get fancier and try to, say, reuse an
1840 // address we know we've emitted elsewhere (the start of the function?
1841 // The start of the CU or CU subrange that encloses this range?)
1842 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1843 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1844 Asm->EmitULEB128(idx);
1845 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1847 emitDebugLocEntryLocation(Entry);
1849 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1854 const MCSymbol *Start, *End;
1857 // Emit a debug aranges section, containing a CU lookup for any
1858 // address we can tie back to a CU.
1859 void DwarfDebug::emitDebugARanges() {
1860 // Start the dwarf aranges section.
1861 Asm->OutStreamer.SwitchSection(
1862 Asm->getObjFileLowering().getDwarfARangesSection());
1864 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1868 // Build a list of sections used.
1869 std::vector<const MCSection *> Sections;
1870 for (const auto &it : SectionMap) {
1871 const MCSection *Section = it.first;
1872 Sections.push_back(Section);
1875 // Sort the sections into order.
1876 // This is only done to ensure consistent output order across different runs.
1877 std::sort(Sections.begin(), Sections.end(), SectionSort);
1879 // Build a set of address spans, sorted by CU.
1880 for (const MCSection *Section : Sections) {
1881 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1882 if (List.size() < 2)
1885 // Sort the symbols by offset within the section.
1886 std::sort(List.begin(), List.end(),
1887 [&](const SymbolCU &A, const SymbolCU &B) {
1888 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1889 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1891 // Symbols with no order assigned should be placed at the end.
1892 // (e.g. section end labels)
1900 // If we have no section (e.g. common), just write out
1901 // individual spans for each symbol.
1903 for (const SymbolCU &Cur : List) {
1905 Span.Start = Cur.Sym;
1908 Spans[Cur.CU].push_back(Span);
1911 // Build spans between each label.
1912 const MCSymbol *StartSym = List[0].Sym;
1913 for (size_t n = 1, e = List.size(); n < e; n++) {
1914 const SymbolCU &Prev = List[n - 1];
1915 const SymbolCU &Cur = List[n];
1917 // Try and build the longest span we can within the same CU.
1918 if (Cur.CU != Prev.CU) {
1920 Span.Start = StartSym;
1922 Spans[Prev.CU].push_back(Span);
1929 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1931 // Build a list of CUs used.
1932 std::vector<DwarfCompileUnit *> CUs;
1933 for (const auto &it : Spans) {
1934 DwarfCompileUnit *CU = it.first;
1938 // Sort the CU list (again, to ensure consistent output order).
1939 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1940 return A->getUniqueID() < B->getUniqueID();
1943 // Emit an arange table for each CU we used.
1944 for (DwarfCompileUnit *CU : CUs) {
1945 std::vector<ArangeSpan> &List = Spans[CU];
1947 // Describe the skeleton CU's offset and length, not the dwo file's.
1948 if (auto *Skel = CU->getSkeleton())
1951 // Emit size of content not including length itself.
1952 unsigned ContentSize =
1953 sizeof(int16_t) + // DWARF ARange version number
1954 sizeof(int32_t) + // Offset of CU in the .debug_info section
1955 sizeof(int8_t) + // Pointer Size (in bytes)
1956 sizeof(int8_t); // Segment Size (in bytes)
1958 unsigned TupleSize = PtrSize * 2;
1960 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1962 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1964 ContentSize += Padding;
1965 ContentSize += (List.size() + 1) * TupleSize;
1967 // For each compile unit, write the list of spans it covers.
1968 Asm->OutStreamer.AddComment("Length of ARange Set");
1969 Asm->EmitInt32(ContentSize);
1970 Asm->OutStreamer.AddComment("DWARF Arange version number");
1971 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1972 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1973 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1974 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1975 Asm->EmitInt8(PtrSize);
1976 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1979 Asm->OutStreamer.EmitFill(Padding, 0xff);
1981 for (const ArangeSpan &Span : List) {
1982 Asm->EmitLabelReference(Span.Start, PtrSize);
1984 // Calculate the size as being from the span start to it's end.
1986 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1988 // For symbols without an end marker (e.g. common), we
1989 // write a single arange entry containing just that one symbol.
1990 uint64_t Size = SymSize[Span.Start];
1994 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1998 Asm->OutStreamer.AddComment("ARange terminator");
1999 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2000 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2004 // Emit visible names into a debug ranges section.
2005 void DwarfDebug::emitDebugRanges() {
2006 // Start the dwarf ranges section.
2007 Asm->OutStreamer.SwitchSection(
2008 Asm->getObjFileLowering().getDwarfRangesSection());
2010 // Size for our labels.
2011 unsigned char Size = Asm->getDataLayout().getPointerSize();
2013 // Grab the specific ranges for the compile units in the module.
2014 for (const auto &I : CUMap) {
2015 DwarfCompileUnit *TheCU = I.second;
2017 if (auto *Skel = TheCU->getSkeleton())
2020 // Iterate over the misc ranges for the compile units in the module.
2021 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2022 // Emit our symbol so we can find the beginning of the range.
2023 Asm->OutStreamer.EmitLabel(List.getSym());
2025 for (const RangeSpan &Range : List.getRanges()) {
2026 const MCSymbol *Begin = Range.getStart();
2027 const MCSymbol *End = Range.getEnd();
2028 assert(Begin && "Range without a begin symbol?");
2029 assert(End && "Range without an end symbol?");
2030 if (auto *Base = TheCU->getBaseAddress()) {
2031 Asm->EmitLabelDifference(Begin, Base, Size);
2032 Asm->EmitLabelDifference(End, Base, Size);
2034 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2035 Asm->OutStreamer.EmitSymbolValue(End, Size);
2039 // And terminate the list with two 0 values.
2040 Asm->OutStreamer.EmitIntValue(0, Size);
2041 Asm->OutStreamer.EmitIntValue(0, Size);
2046 // DWARF5 Experimental Separate Dwarf emitters.
2048 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2049 std::unique_ptr<DwarfUnit> NewU) {
2050 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2051 U.getCUNode().getSplitDebugFilename());
2053 if (!CompilationDir.empty())
2054 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2056 addGnuPubAttributes(*NewU, Die);
2058 SkeletonHolder.addUnit(std::move(NewU));
2061 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2062 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2063 // DW_AT_addr_base, DW_AT_ranges_base.
2064 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2066 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2067 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2068 DwarfCompileUnit &NewCU = *OwnedUnit;
2069 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2070 DwarfInfoSectionSym);
2072 NewCU.initStmtList(DwarfLineSectionSym);
2074 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2079 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2080 // compile units that would normally be in debug_info.
2081 void DwarfDebug::emitDebugInfoDWO() {
2082 assert(useSplitDwarf() && "No split dwarf debug info?");
2083 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2084 // emit relocations into the dwo file.
2085 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2088 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2089 // abbreviations for the .debug_info.dwo section.
2090 void DwarfDebug::emitDebugAbbrevDWO() {
2091 assert(useSplitDwarf() && "No split dwarf?");
2092 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2095 void DwarfDebug::emitDebugLineDWO() {
2096 assert(useSplitDwarf() && "No split dwarf?");
2097 Asm->OutStreamer.SwitchSection(
2098 Asm->getObjFileLowering().getDwarfLineDWOSection());
2099 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2102 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2103 // string section and is identical in format to traditional .debug_str
2105 void DwarfDebug::emitDebugStrDWO() {
2106 assert(useSplitDwarf() && "No split dwarf?");
2107 const MCSection *OffSec =
2108 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2109 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2113 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2114 if (!useSplitDwarf())
2117 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2118 return &SplitTypeUnitFileTable;
2121 static uint64_t makeTypeSignature(StringRef Identifier) {
2123 Hash.update(Identifier);
2124 // ... take the least significant 8 bytes and return those. Our MD5
2125 // implementation always returns its results in little endian, swap bytes
2127 MD5::MD5Result Result;
2129 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2132 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2133 StringRef Identifier, DIE &RefDie,
2134 DICompositeType CTy) {
2135 // Fast path if we're building some type units and one has already used the
2136 // address pool we know we're going to throw away all this work anyway, so
2137 // don't bother building dependent types.
2138 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2141 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2143 CU.addDIETypeSignature(RefDie, *TU);
2147 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2148 AddrPool.resetUsedFlag();
2150 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2151 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2152 this, &InfoHolder, getDwoLineTable(CU));
2153 DwarfTypeUnit &NewTU = *OwnedUnit;
2154 DIE &UnitDie = NewTU.getUnitDie();
2156 TypeUnitsUnderConstruction.push_back(
2157 std::make_pair(std::move(OwnedUnit), CTy));
2159 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2162 uint64_t Signature = makeTypeSignature(Identifier);
2163 NewTU.setTypeSignature(Signature);
2165 if (useSplitDwarf())
2166 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2168 CU.applyStmtList(UnitDie);
2170 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2173 NewTU.setType(NewTU.createTypeDIE(CTy));
2176 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2177 TypeUnitsUnderConstruction.clear();
2179 // Types referencing entries in the address table cannot be placed in type
2181 if (AddrPool.hasBeenUsed()) {
2183 // Remove all the types built while building this type.
2184 // This is pessimistic as some of these types might not be dependent on
2185 // the type that used an address.
2186 for (const auto &TU : TypeUnitsToAdd)
2187 DwarfTypeUnits.erase(TU.second);
2189 // Construct this type in the CU directly.
2190 // This is inefficient because all the dependent types will be rebuilt
2191 // from scratch, including building them in type units, discovering that
2192 // they depend on addresses, throwing them out and rebuilding them.
2193 CU.constructTypeDIE(RefDie, CTy);
2197 // If the type wasn't dependent on fission addresses, finish adding the type
2198 // and all its dependent types.
2199 for (auto &TU : TypeUnitsToAdd)
2200 InfoHolder.addUnit(std::move(TU.first));
2202 CU.addDIETypeSignature(RefDie, NewTU);
2205 // Accelerator table mutators - add each name along with its companion
2206 // DIE to the proper table while ensuring that the name that we're going
2207 // to reference is in the string table. We do this since the names we
2208 // add may not only be identical to the names in the DIE.
2209 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2210 if (!useDwarfAccelTables())
2212 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2216 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2217 if (!useDwarfAccelTables())
2219 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2223 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2224 if (!useDwarfAccelTables())
2226 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2230 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2231 if (!useDwarfAccelTables())
2233 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),