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 // LTO with assembly output shares a single line table amongst multiple CUs.
367 // To avoid the compilation directory being ambiguous, let the line table
368 // explicitly describe the directory of all files, never relying on the
369 // compilation directory.
370 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
371 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
372 NewCU.getUniqueID(), CompilationDir);
374 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
375 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
376 DIUnit.getLanguage());
377 NewCU.addString(Die, dwarf::DW_AT_name, FN);
379 if (!useSplitDwarf()) {
380 NewCU.initStmtList(DwarfLineSectionSym);
382 // If we're using split dwarf the compilation dir is going to be in the
383 // skeleton CU and so we don't need to duplicate it here.
384 if (!CompilationDir.empty())
385 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
387 addGnuPubAttributes(NewCU, Die);
390 if (DIUnit.isOptimized())
391 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
393 StringRef Flags = DIUnit.getFlags();
395 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
397 if (unsigned RVer = DIUnit.getRunTimeVersion())
398 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
399 dwarf::DW_FORM_data1, RVer);
401 if (useSplitDwarf()) {
402 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
403 DwarfInfoDWOSectionSym);
404 NewCU.setSkeleton(constructSkeletonCU(NewCU));
406 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
407 DwarfInfoSectionSym);
409 CUMap.insert(std::make_pair(DIUnit, &NewCU));
410 CUDieMap.insert(std::make_pair(&Die, &NewCU));
414 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
416 DIImportedEntity Module(N);
417 assert(Module.Verify());
418 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
419 D->addChild(TheCU.constructImportedEntityDIE(Module));
422 // Emit all Dwarf sections that should come prior to the content. Create
423 // global DIEs and emit initial debug info sections. This is invoked by
424 // the target AsmPrinter.
425 void DwarfDebug::beginModule() {
426 if (DisableDebugInfoPrinting)
429 const Module *M = MMI->getModule();
431 FunctionDIs = makeSubprogramMap(*M);
433 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
436 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
438 // Emit initial sections so we can reference labels later.
441 SingleCU = CU_Nodes->getNumOperands() == 1;
443 for (MDNode *N : CU_Nodes->operands()) {
444 DICompileUnit CUNode(N);
445 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
446 DIArray ImportedEntities = CUNode.getImportedEntities();
447 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
448 ScopesWithImportedEntities.push_back(std::make_pair(
449 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
450 ImportedEntities.getElement(i)));
451 std::sort(ScopesWithImportedEntities.begin(),
452 ScopesWithImportedEntities.end(), less_first());
453 DIArray GVs = CUNode.getGlobalVariables();
454 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
455 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
456 DIArray SPs = CUNode.getSubprograms();
457 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
458 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
459 DIArray EnumTypes = CUNode.getEnumTypes();
460 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
461 DIType Ty(EnumTypes.getElement(i));
462 // The enum types array by design contains pointers to
463 // MDNodes rather than DIRefs. Unique them here.
464 DIType UniqueTy(resolve(Ty.getRef()));
465 CU.getOrCreateTypeDIE(UniqueTy);
467 DIArray RetainedTypes = CUNode.getRetainedTypes();
468 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
469 DIType Ty(RetainedTypes.getElement(i));
470 // The retained types array by design contains pointers to
471 // MDNodes rather than DIRefs. Unique them here.
472 DIType UniqueTy(resolve(Ty.getRef()));
473 CU.getOrCreateTypeDIE(UniqueTy);
475 // Emit imported_modules last so that the relevant context is already
477 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
478 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
481 // Tell MMI that we have debug info.
482 MMI->setDebugInfoAvailability(true);
484 // Prime section data.
485 SectionMap[Asm->getObjFileLowering().getTextSection()];
488 void DwarfDebug::finishVariableDefinitions() {
489 for (const auto &Var : ConcreteVariables) {
490 DIE *VariableDie = Var->getDIE();
492 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
493 // in the ConcreteVariables list, rather than looking it up again here.
494 // DIE::getUnit isn't simple - it walks parent pointers, etc.
495 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
497 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
498 if (AbsVar && AbsVar->getDIE()) {
499 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
502 Unit->applyVariableAttributes(*Var, *VariableDie);
506 void DwarfDebug::finishSubprogramDefinitions() {
507 for (const auto &P : SPMap)
508 P.second->finishSubprogramDefinition(DISubprogram(P.first));
512 // Collect info for variables that were optimized out.
513 void DwarfDebug::collectDeadVariables() {
514 const Module *M = MMI->getModule();
516 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
517 for (MDNode *N : CU_Nodes->operands()) {
518 DICompileUnit TheCU(N);
519 // Construct subprogram DIE and add variables DIEs.
520 DwarfCompileUnit *SPCU =
521 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
522 assert(SPCU && "Unable to find Compile Unit!");
523 DIArray Subprograms = TheCU.getSubprograms();
524 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
525 DISubprogram SP(Subprograms.getElement(i));
526 if (ProcessedSPNodes.count(SP) != 0)
528 assert(SP.isSubprogram() &&
529 "CU's subprogram list contains a non-subprogram");
530 assert(SP.isDefinition() &&
531 "CU's subprogram list contains a subprogram declaration");
532 DIArray Variables = SP.getVariables();
533 if (Variables.getNumElements() == 0)
536 DIE *SPDIE = AbstractSPDies.lookup(SP);
538 SPDIE = SPCU->getDIE(SP);
540 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
541 DIVariable DV(Variables.getElement(vi));
542 assert(DV.isVariable());
543 DbgVariable NewVar(DV, DIExpression(nullptr), this);
544 auto VariableDie = SPCU->constructVariableDIE(NewVar);
545 SPCU->applyVariableAttributes(NewVar, *VariableDie);
546 SPDIE->addChild(std::move(VariableDie));
553 void DwarfDebug::finalizeModuleInfo() {
554 finishSubprogramDefinitions();
556 finishVariableDefinitions();
558 // Collect info for variables that were optimized out.
559 collectDeadVariables();
561 // Handle anything that needs to be done on a per-unit basis after
562 // all other generation.
563 for (const auto &TheU : getUnits()) {
564 // Emit DW_AT_containing_type attribute to connect types with their
565 // vtable holding type.
566 TheU->constructContainingTypeDIEs();
568 // Add CU specific attributes if we need to add any.
569 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
570 // If we're splitting the dwarf out now that we've got the entire
571 // CU then add the dwo id to it.
572 DwarfCompileUnit *SkCU =
573 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
574 if (useSplitDwarf()) {
575 // Emit a unique identifier for this CU.
576 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
577 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
578 dwarf::DW_FORM_data8, ID);
579 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
580 dwarf::DW_FORM_data8, ID);
582 // We don't keep track of which addresses are used in which CU so this
583 // is a bit pessimistic under LTO.
584 if (!AddrPool.isEmpty())
585 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
586 DwarfAddrSectionSym, DwarfAddrSectionSym);
587 if (!TheU->getRangeLists().empty())
588 SkCU->addSectionLabel(
589 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
590 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
593 // If we have code split among multiple sections or non-contiguous
594 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
595 // remain in the .o file, otherwise add a DW_AT_low_pc.
596 // FIXME: We should use ranges allow reordering of code ala
597 // .subsections_via_symbols in mach-o. This would mean turning on
598 // ranges for all subprogram DIEs for mach-o.
599 DwarfCompileUnit &U =
600 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
601 unsigned NumRanges = TheU->getRanges().size();
604 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
605 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
606 DwarfDebugRangeSectionSym);
608 // A DW_AT_low_pc attribute may also be specified in combination with
609 // DW_AT_ranges to specify the default base address for use in
610 // location lists (see Section 2.6.2) and range lists (see Section
612 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
615 RangeSpan &Range = TheU->getRanges().back();
616 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
622 // Compute DIE offsets and sizes.
623 InfoHolder.computeSizeAndOffsets();
625 SkeletonHolder.computeSizeAndOffsets();
628 void DwarfDebug::endSections() {
629 // Filter labels by section.
630 for (const SymbolCU &SCU : ArangeLabels) {
631 if (SCU.Sym->isInSection()) {
632 // Make a note of this symbol and it's section.
633 const MCSection *Section = &SCU.Sym->getSection();
634 if (!Section->getKind().isMetadata())
635 SectionMap[Section].push_back(SCU);
637 // Some symbols (e.g. common/bss on mach-o) can have no section but still
638 // appear in the output. This sucks as we rely on sections to build
639 // arange spans. We can do it without, but it's icky.
640 SectionMap[nullptr].push_back(SCU);
644 // Build a list of sections used.
645 std::vector<const MCSection *> Sections;
646 for (const auto &it : SectionMap) {
647 const MCSection *Section = it.first;
648 Sections.push_back(Section);
651 // Sort the sections into order.
652 // This is only done to ensure consistent output order across different runs.
653 std::sort(Sections.begin(), Sections.end(), SectionSort);
655 // Add terminating symbols for each section.
656 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
657 const MCSection *Section = Sections[ID];
658 MCSymbol *Sym = nullptr;
661 // We can't call MCSection::getLabelEndName, as it's only safe to do so
662 // if we know the section name up-front. For user-created sections, the
663 // resulting label may not be valid to use as a label. (section names can
664 // use a greater set of characters on some systems)
665 Sym = Asm->GetTempSymbol("debug_end", ID);
666 Asm->OutStreamer.SwitchSection(Section);
667 Asm->OutStreamer.EmitLabel(Sym);
670 // Insert a final terminator.
671 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
675 // Emit all Dwarf sections that should come after the content.
676 void DwarfDebug::endModule() {
677 assert(CurFn == nullptr);
678 assert(CurMI == nullptr);
680 // If we aren't actually generating debug info (check beginModule -
681 // conditionalized on !DisableDebugInfoPrinting and the presence of the
682 // llvm.dbg.cu metadata node)
683 if (!DwarfInfoSectionSym)
686 // End any existing sections.
687 // TODO: Does this need to happen?
690 // Finalize the debug info for the module.
691 finalizeModuleInfo();
695 // Emit all the DIEs into a debug info section.
698 // Corresponding abbreviations into a abbrev section.
701 // Emit info into a debug aranges section.
702 if (GenerateARangeSection)
705 // Emit info into a debug ranges section.
708 if (useSplitDwarf()) {
711 emitDebugAbbrevDWO();
714 // Emit DWO addresses.
715 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
717 // Emit info into a debug loc section.
720 // Emit info into the dwarf accelerator table sections.
721 if (useDwarfAccelTables()) {
724 emitAccelNamespaces();
728 // Emit the pubnames and pubtypes sections if requested.
729 if (HasDwarfPubSections) {
730 emitDebugPubNames(GenerateGnuPubSections);
731 emitDebugPubTypes(GenerateGnuPubSections);
736 AbstractVariables.clear();
739 // Find abstract variable, if any, associated with Var.
740 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
741 DIVariable &Cleansed) {
742 LLVMContext &Ctx = DV->getContext();
743 // More then one inlined variable corresponds to one abstract variable.
744 // FIXME: This duplication of variables when inlining should probably be
745 // removed. It's done to allow each DIVariable to describe its location
746 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
747 // make it accurate then remove this duplication/cleansing stuff.
748 Cleansed = cleanseInlinedVariable(DV, Ctx);
749 auto I = AbstractVariables.find(Cleansed);
750 if (I != AbstractVariables.end())
751 return I->second.get();
755 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
757 return getExistingAbstractVariable(DV, Cleansed);
760 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
761 LexicalScope *Scope) {
762 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
763 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
764 AbstractVariables[Var] = std::move(AbsDbgVariable);
767 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
768 const MDNode *ScopeNode) {
769 DIVariable Cleansed = DV;
770 if (getExistingAbstractVariable(DV, Cleansed))
773 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
777 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
778 const MDNode *ScopeNode) {
779 DIVariable Cleansed = DV;
780 if (getExistingAbstractVariable(DV, Cleansed))
783 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
784 createAbstractVariable(Cleansed, Scope);
787 // Collect variable information from side table maintained by MMI.
788 void DwarfDebug::collectVariableInfoFromMMITable(
789 SmallPtrSetImpl<const MDNode *> &Processed) {
790 for (const auto &VI : MMI->getVariableDbgInfo()) {
793 Processed.insert(VI.Var);
794 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
796 // If variable scope is not found then skip this variable.
800 DIVariable DV(VI.Var);
801 DIExpression Expr(VI.Expr);
802 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
803 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
804 DbgVariable *RegVar = ConcreteVariables.back().get();
805 RegVar->setFrameIndex(VI.Slot);
806 InfoHolder.addScopeVariable(Scope, RegVar);
810 // Get .debug_loc entry for the instruction range starting at MI.
811 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
812 const MDNode *Expr = MI->getDebugExpression();
813 const MDNode *Var = MI->getDebugVariable();
815 assert(MI->getNumOperands() == 4);
816 if (MI->getOperand(0).isReg()) {
817 MachineLocation MLoc;
818 // If the second operand is an immediate, this is a
819 // register-indirect address.
820 if (!MI->getOperand(1).isImm())
821 MLoc.set(MI->getOperand(0).getReg());
823 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
824 return DebugLocEntry::Value(Var, Expr, MLoc);
826 if (MI->getOperand(0).isImm())
827 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
828 if (MI->getOperand(0).isFPImm())
829 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
830 if (MI->getOperand(0).isCImm())
831 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
833 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
836 /// Determine whether two variable pieces overlap.
837 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
838 if (!P1.isVariablePiece() || !P2.isVariablePiece())
840 unsigned l1 = P1.getPieceOffset();
841 unsigned l2 = P2.getPieceOffset();
842 unsigned r1 = l1 + P1.getPieceSize();
843 unsigned r2 = l2 + P2.getPieceSize();
844 // True where [l1,r1[ and [r1,r2[ overlap.
845 return (l1 < r2) && (l2 < r1);
848 /// Build the location list for all DBG_VALUEs in the function that
849 /// describe the same variable. If the ranges of several independent
850 /// pieces of the same variable overlap partially, split them up and
851 /// combine the ranges. The resulting DebugLocEntries are will have
852 /// strict monotonically increasing begin addresses and will never
857 // Ranges History [var, loc, piece ofs size]
858 // 0 | [x, (reg0, piece 0, 32)]
859 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
861 // 3 | [clobber reg0]
862 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
866 // [0-1] [x, (reg0, piece 0, 32)]
867 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
868 // [3-4] [x, (reg1, piece 32, 32)]
869 // [4- ] [x, (mem, piece 0, 64)]
871 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
872 const DbgValueHistoryMap::InstrRanges &Ranges) {
873 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
875 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
876 const MachineInstr *Begin = I->first;
877 const MachineInstr *End = I->second;
878 assert(Begin->isDebugValue() && "Invalid History entry");
880 // Check if a variable is inaccessible in this range.
881 if (Begin->getNumOperands() > 1 &&
882 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
887 // If this piece overlaps with any open ranges, truncate them.
888 DIExpression DIExpr = Begin->getDebugExpression();
889 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
890 [&](DebugLocEntry::Value R) {
891 return piecesOverlap(DIExpr, R.getExpression());
893 OpenRanges.erase(Last, OpenRanges.end());
895 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
896 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
898 const MCSymbol *EndLabel;
900 EndLabel = getLabelAfterInsn(End);
901 else if (std::next(I) == Ranges.end())
902 EndLabel = FunctionEndSym;
904 EndLabel = getLabelBeforeInsn(std::next(I)->first);
905 assert(EndLabel && "Forgot label after instruction ending a range!");
907 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
909 auto Value = getDebugLocValue(Begin);
910 DebugLocEntry Loc(StartLabel, EndLabel, Value);
911 bool couldMerge = false;
913 // If this is a piece, it may belong to the current DebugLocEntry.
914 if (DIExpr.isVariablePiece()) {
915 // Add this value to the list of open ranges.
916 OpenRanges.push_back(Value);
918 // Attempt to add the piece to the last entry.
919 if (!DebugLoc.empty())
920 if (DebugLoc.back().MergeValues(Loc))
925 // Need to add a new DebugLocEntry. Add all values from still
926 // valid non-overlapping pieces.
927 if (OpenRanges.size())
928 Loc.addValues(OpenRanges);
930 DebugLoc.push_back(std::move(Loc));
933 // Attempt to coalesce the ranges of two otherwise identical
935 auto CurEntry = DebugLoc.rbegin();
936 auto PrevEntry = std::next(CurEntry);
937 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
941 dbgs() << CurEntry->getValues().size() << " Values:\n";
942 for (auto Value : CurEntry->getValues()) {
943 Value.getVariable()->dump();
944 Value.getExpression()->dump();
952 // Find variables for each lexical scope.
954 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
955 SmallPtrSetImpl<const MDNode *> &Processed) {
956 // Grab the variable info that was squirreled away in the MMI side-table.
957 collectVariableInfoFromMMITable(Processed);
959 for (const auto &I : DbgValues) {
960 DIVariable DV(I.first);
961 if (Processed.count(DV))
964 // Instruction ranges, specifying where DV is accessible.
965 const auto &Ranges = I.second;
969 LexicalScope *Scope = nullptr;
970 if (MDNode *IA = DV.getInlinedAt()) {
971 DebugLoc DL = DebugLoc::getFromDILocation(IA);
972 Scope = LScopes.findInlinedScope(DebugLoc::get(
973 DL.getLine(), DL.getCol(), DV.getContext(), IA));
975 Scope = LScopes.findLexicalScope(DV.getContext());
976 // If variable scope is not found then skip this variable.
980 Processed.insert(DV);
981 const MachineInstr *MInsn = Ranges.front().first;
982 assert(MInsn->isDebugValue() && "History must begin with debug value");
983 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
984 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
985 DbgVariable *RegVar = ConcreteVariables.back().get();
986 InfoHolder.addScopeVariable(Scope, RegVar);
988 // Check if the first DBG_VALUE is valid for the rest of the function.
989 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
992 // Handle multiple DBG_VALUE instructions describing one variable.
993 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
995 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
996 DebugLocList &LocList = DotDebugLocEntries.back();
999 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1001 // Build the location list for this variable.
1002 buildLocationList(LocList.List, Ranges);
1005 // Collect info for variables that were optimized out.
1006 DIArray Variables = SP.getVariables();
1007 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1008 DIVariable DV(Variables.getElement(i));
1009 assert(DV.isVariable());
1010 if (!Processed.insert(DV))
1012 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1013 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1014 DIExpression NoExpr;
1015 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1016 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
1021 // Return Label preceding the instruction.
1022 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1023 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1024 assert(Label && "Didn't insert label before instruction");
1028 // Return Label immediately following the instruction.
1029 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1030 return LabelsAfterInsn.lookup(MI);
1033 // Process beginning of an instruction.
1034 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1035 assert(CurMI == nullptr);
1037 // Check if source location changes, but ignore DBG_VALUE locations.
1038 if (!MI->isDebugValue()) {
1039 DebugLoc DL = MI->getDebugLoc();
1040 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1043 if (DL == PrologEndLoc) {
1044 Flags |= DWARF2_FLAG_PROLOGUE_END;
1045 PrologEndLoc = DebugLoc();
1047 if (PrologEndLoc.isUnknown())
1048 Flags |= DWARF2_FLAG_IS_STMT;
1050 if (!DL.isUnknown()) {
1051 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1052 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1054 recordSourceLine(0, 0, nullptr, 0);
1058 // Insert labels where requested.
1059 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1060 LabelsBeforeInsn.find(MI);
1063 if (I == LabelsBeforeInsn.end())
1066 // Label already assigned.
1071 PrevLabel = MMI->getContext().CreateTempSymbol();
1072 Asm->OutStreamer.EmitLabel(PrevLabel);
1074 I->second = PrevLabel;
1077 // Process end of an instruction.
1078 void DwarfDebug::endInstruction() {
1079 assert(CurMI != nullptr);
1080 // Don't create a new label after DBG_VALUE instructions.
1081 // They don't generate code.
1082 if (!CurMI->isDebugValue())
1083 PrevLabel = nullptr;
1085 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1086 LabelsAfterInsn.find(CurMI);
1090 if (I == LabelsAfterInsn.end())
1093 // Label already assigned.
1097 // We need a label after this instruction.
1099 PrevLabel = MMI->getContext().CreateTempSymbol();
1100 Asm->OutStreamer.EmitLabel(PrevLabel);
1102 I->second = PrevLabel;
1105 // Each LexicalScope has first instruction and last instruction to mark
1106 // beginning and end of a scope respectively. Create an inverse map that list
1107 // scopes starts (and ends) with an instruction. One instruction may start (or
1108 // end) multiple scopes. Ignore scopes that are not reachable.
1109 void DwarfDebug::identifyScopeMarkers() {
1110 SmallVector<LexicalScope *, 4> WorkList;
1111 WorkList.push_back(LScopes.getCurrentFunctionScope());
1112 while (!WorkList.empty()) {
1113 LexicalScope *S = WorkList.pop_back_val();
1115 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1116 if (!Children.empty())
1117 WorkList.append(Children.begin(), Children.end());
1119 if (S->isAbstractScope())
1122 for (const InsnRange &R : S->getRanges()) {
1123 assert(R.first && "InsnRange does not have first instruction!");
1124 assert(R.second && "InsnRange does not have second instruction!");
1125 requestLabelBeforeInsn(R.first);
1126 requestLabelAfterInsn(R.second);
1131 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1132 // First known non-DBG_VALUE and non-frame setup location marks
1133 // the beginning of the function body.
1134 for (const auto &MBB : *MF)
1135 for (const auto &MI : MBB)
1136 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1137 !MI.getDebugLoc().isUnknown())
1138 return MI.getDebugLoc();
1142 // Gather pre-function debug information. Assumes being called immediately
1143 // after the function entry point has been emitted.
1144 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1147 // If there's no debug info for the function we're not going to do anything.
1148 if (!MMI->hasDebugInfo())
1151 auto DI = FunctionDIs.find(MF->getFunction());
1152 if (DI == FunctionDIs.end())
1155 // Grab the lexical scopes for the function, if we don't have any of those
1156 // then we're not going to be able to do anything.
1157 LScopes.initialize(*MF);
1158 if (LScopes.empty())
1161 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1163 // Make sure that each lexical scope will have a begin/end label.
1164 identifyScopeMarkers();
1166 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1167 // belongs to so that we add to the correct per-cu line table in the
1169 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1170 // FnScope->getScopeNode() and DI->second should represent the same function,
1171 // though they may not be the same MDNode due to inline functions merged in
1172 // LTO where the debug info metadata still differs (either due to distinct
1173 // written differences - two versions of a linkonce_odr function
1174 // written/copied into two separate files, or some sub-optimal metadata that
1175 // isn't structurally identical (see: file path/name info from clang, which
1176 // includes the directory of the cpp file being built, even when the file name
1177 // is absolute (such as an <> lookup header)))
1178 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1179 assert(TheCU && "Unable to find compile unit!");
1180 if (Asm->OutStreamer.hasRawTextSupport())
1181 // Use a single line table if we are generating assembly.
1182 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1184 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1186 // Emit a label for the function so that we have a beginning address.
1187 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1188 // Assumes in correct section after the entry point.
1189 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1191 // Calculate history for local variables.
1192 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1195 // Request labels for the full history.
1196 for (const auto &I : DbgValues) {
1197 const auto &Ranges = I.second;
1201 // The first mention of a function argument gets the FunctionBeginSym
1202 // label, so arguments are visible when breaking at function entry.
1203 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1204 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1205 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1206 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1207 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1208 // Mark all non-overlapping initial pieces.
1209 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1210 DIExpression Piece = I->first->getDebugExpression();
1211 if (std::all_of(Ranges.begin(), I,
1212 [&](DbgValueHistoryMap::InstrRange Pred) {
1213 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1215 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1222 for (const auto &Range : Ranges) {
1223 requestLabelBeforeInsn(Range.first);
1225 requestLabelAfterInsn(Range.second);
1229 PrevInstLoc = DebugLoc();
1230 PrevLabel = FunctionBeginSym;
1232 // Record beginning of function.
1233 PrologEndLoc = findPrologueEndLoc(MF);
1234 if (!PrologEndLoc.isUnknown()) {
1235 DebugLoc FnStartDL =
1236 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1238 FnStartDL.getLine(), FnStartDL.getCol(),
1239 FnStartDL.getScope(MF->getFunction()->getContext()),
1240 // We'd like to list the prologue as "not statements" but GDB behaves
1241 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1242 DWARF2_FLAG_IS_STMT);
1246 // Gather and emit post-function debug information.
1247 void DwarfDebug::endFunction(const MachineFunction *MF) {
1248 assert(CurFn == MF &&
1249 "endFunction should be called with the same function as beginFunction");
1251 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1252 !FunctionDIs.count(MF->getFunction())) {
1253 // If we don't have a lexical scope for this function then there will
1254 // be a hole in the range information. Keep note of this by setting the
1255 // previously used section to nullptr.
1261 // Define end label for subprogram.
1262 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1263 // Assumes in correct section after the entry point.
1264 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1266 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1267 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1269 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1270 DISubprogram SP(FnScope->getScopeNode());
1271 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1273 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1274 collectVariableInfo(TheCU, SP, ProcessedVars);
1276 // Add the range of this function to the list of ranges for the CU.
1277 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1279 // Under -gmlt, skip building the subprogram if there are no inlined
1280 // subroutines inside it.
1281 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1282 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1283 assert(InfoHolder.getScopeVariables().empty());
1284 assert(DbgValues.empty());
1285 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1286 // by a -gmlt CU. Add a test and remove this assertion.
1287 assert(AbstractVariables.empty());
1288 LabelsBeforeInsn.clear();
1289 LabelsAfterInsn.clear();
1290 PrevLabel = nullptr;
1296 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1298 // Construct abstract scopes.
1299 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1300 DISubprogram SP(AScope->getScopeNode());
1301 assert(SP.isSubprogram());
1302 // Collect info for variables that were optimized out.
1303 DIArray Variables = SP.getVariables();
1304 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1305 DIVariable DV(Variables.getElement(i));
1306 assert(DV && DV.isVariable());
1307 if (!ProcessedVars.insert(DV))
1309 ensureAbstractVariableIsCreated(DV, DV.getContext());
1310 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1311 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1313 constructAbstractSubprogramScopeDIE(AScope);
1316 TheCU.constructSubprogramScopeDIE(FnScope);
1319 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1320 // DbgVariables except those that are also in AbstractVariables (since they
1321 // can be used cross-function)
1322 InfoHolder.getScopeVariables().clear();
1324 LabelsBeforeInsn.clear();
1325 LabelsAfterInsn.clear();
1326 PrevLabel = nullptr;
1330 // Register a source line with debug info. Returns the unique label that was
1331 // emitted and which provides correspondence to the source line list.
1332 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1337 unsigned Discriminator = 0;
1338 if (DIScope Scope = DIScope(S)) {
1339 assert(Scope.isScope());
1340 Fn = Scope.getFilename();
1341 Dir = Scope.getDirectory();
1342 if (Scope.isLexicalBlockFile())
1343 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1345 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1346 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1347 .getOrCreateSourceID(Fn, Dir);
1349 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1353 //===----------------------------------------------------------------------===//
1355 //===----------------------------------------------------------------------===//
1357 // Emit initial Dwarf sections with a label at the start of each one.
1358 void DwarfDebug::emitSectionLabels() {
1359 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1361 // Dwarf sections base addresses.
1362 DwarfInfoSectionSym =
1363 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1364 if (useSplitDwarf()) {
1365 DwarfInfoDWOSectionSym =
1366 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1367 DwarfTypesDWOSectionSym =
1368 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1370 DwarfAbbrevSectionSym =
1371 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1372 if (useSplitDwarf())
1373 DwarfAbbrevDWOSectionSym = emitSectionSym(
1374 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1375 if (GenerateARangeSection)
1376 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1378 DwarfLineSectionSym =
1379 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1380 if (GenerateGnuPubSections) {
1381 DwarfGnuPubNamesSectionSym =
1382 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1383 DwarfGnuPubTypesSectionSym =
1384 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1385 } else if (HasDwarfPubSections) {
1386 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1387 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1390 DwarfStrSectionSym =
1391 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1392 if (useSplitDwarf()) {
1393 DwarfStrDWOSectionSym =
1394 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1395 DwarfAddrSectionSym =
1396 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1397 DwarfDebugLocSectionSym =
1398 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1400 DwarfDebugLocSectionSym =
1401 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1402 DwarfDebugRangeSectionSym =
1403 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1406 // Recursively emits a debug information entry.
1407 void DwarfDebug::emitDIE(DIE &Die) {
1408 // Get the abbreviation for this DIE.
1409 const DIEAbbrev &Abbrev = Die.getAbbrev();
1411 // Emit the code (index) for the abbreviation.
1412 if (Asm->isVerbose())
1413 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1414 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1415 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1416 dwarf::TagString(Abbrev.getTag()));
1417 Asm->EmitULEB128(Abbrev.getNumber());
1419 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1420 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1422 // Emit the DIE attribute values.
1423 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1424 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1425 dwarf::Form Form = AbbrevData[i].getForm();
1426 assert(Form && "Too many attributes for DIE (check abbreviation)");
1428 if (Asm->isVerbose()) {
1429 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1430 if (Attr == dwarf::DW_AT_accessibility)
1431 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1432 cast<DIEInteger>(Values[i])->getValue()));
1435 // Emit an attribute using the defined form.
1436 Values[i]->EmitValue(Asm, Form);
1439 // Emit the DIE children if any.
1440 if (Abbrev.hasChildren()) {
1441 for (auto &Child : Die.getChildren())
1444 Asm->OutStreamer.AddComment("End Of Children Mark");
1449 // Emit the debug info section.
1450 void DwarfDebug::emitDebugInfo() {
1451 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1453 Holder.emitUnits(DwarfAbbrevSectionSym);
1456 // Emit the abbreviation section.
1457 void DwarfDebug::emitAbbreviations() {
1458 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1460 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1463 // Emit the last address of the section and the end of the line matrix.
1464 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1465 // Define last address of section.
1466 Asm->OutStreamer.AddComment("Extended Op");
1469 Asm->OutStreamer.AddComment("Op size");
1470 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1471 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1472 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1474 Asm->OutStreamer.AddComment("Section end label");
1476 Asm->OutStreamer.EmitSymbolValue(
1477 Asm->GetTempSymbol("section_end", SectionEnd),
1478 Asm->getDataLayout().getPointerSize());
1480 // Mark end of matrix.
1481 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1487 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1488 StringRef TableName, StringRef SymName) {
1489 Accel.FinalizeTable(Asm, TableName);
1490 Asm->OutStreamer.SwitchSection(Section);
1491 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1492 Asm->OutStreamer.EmitLabel(SectionBegin);
1494 // Emit the full data.
1495 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1498 // Emit visible names into a hashed accelerator table section.
1499 void DwarfDebug::emitAccelNames() {
1500 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1501 "Names", "names_begin");
1504 // Emit objective C classes and categories into a hashed accelerator table
1506 void DwarfDebug::emitAccelObjC() {
1507 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1508 "ObjC", "objc_begin");
1511 // Emit namespace dies into a hashed accelerator table.
1512 void DwarfDebug::emitAccelNamespaces() {
1513 emitAccel(AccelNamespace,
1514 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1515 "namespac", "namespac_begin");
1518 // Emit type dies into a hashed accelerator table.
1519 void DwarfDebug::emitAccelTypes() {
1520 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1521 "types", "types_begin");
1524 // Public name handling.
1525 // The format for the various pubnames:
1527 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1528 // for the DIE that is named.
1530 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1531 // into the CU and the index value is computed according to the type of value
1532 // for the DIE that is named.
1534 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1535 // it's the offset within the debug_info/debug_types dwo section, however, the
1536 // reference in the pubname header doesn't change.
1538 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1539 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1541 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1543 // We could have a specification DIE that has our most of our knowledge,
1544 // look for that now.
1545 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1547 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1548 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1549 Linkage = dwarf::GIEL_EXTERNAL;
1550 } else if (Die->findAttribute(dwarf::DW_AT_external))
1551 Linkage = dwarf::GIEL_EXTERNAL;
1553 switch (Die->getTag()) {
1554 case dwarf::DW_TAG_class_type:
1555 case dwarf::DW_TAG_structure_type:
1556 case dwarf::DW_TAG_union_type:
1557 case dwarf::DW_TAG_enumeration_type:
1558 return dwarf::PubIndexEntryDescriptor(
1559 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1560 ? dwarf::GIEL_STATIC
1561 : dwarf::GIEL_EXTERNAL);
1562 case dwarf::DW_TAG_typedef:
1563 case dwarf::DW_TAG_base_type:
1564 case dwarf::DW_TAG_subrange_type:
1565 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1566 case dwarf::DW_TAG_namespace:
1567 return dwarf::GIEK_TYPE;
1568 case dwarf::DW_TAG_subprogram:
1569 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1570 case dwarf::DW_TAG_constant:
1571 case dwarf::DW_TAG_variable:
1572 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1573 case dwarf::DW_TAG_enumerator:
1574 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1575 dwarf::GIEL_STATIC);
1577 return dwarf::GIEK_NONE;
1581 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1583 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1584 const MCSection *PSec =
1585 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1586 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1588 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1591 void DwarfDebug::emitDebugPubSection(
1592 bool GnuStyle, const MCSection *PSec, StringRef Name,
1593 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1594 for (const auto &NU : CUMap) {
1595 DwarfCompileUnit *TheU = NU.second;
1597 const auto &Globals = (TheU->*Accessor)();
1599 if (Globals.empty())
1602 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1604 unsigned ID = TheU->getUniqueID();
1606 // Start the dwarf pubnames section.
1607 Asm->OutStreamer.SwitchSection(PSec);
1610 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1611 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1612 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1613 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1615 Asm->OutStreamer.EmitLabel(BeginLabel);
1617 Asm->OutStreamer.AddComment("DWARF Version");
1618 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1620 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1621 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1623 Asm->OutStreamer.AddComment("Compilation Unit Length");
1624 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1626 // Emit the pubnames for this compilation unit.
1627 for (const auto &GI : Globals) {
1628 const char *Name = GI.getKeyData();
1629 const DIE *Entity = GI.second;
1631 Asm->OutStreamer.AddComment("DIE offset");
1632 Asm->EmitInt32(Entity->getOffset());
1635 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1636 Asm->OutStreamer.AddComment(
1637 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1638 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1639 Asm->EmitInt8(Desc.toBits());
1642 Asm->OutStreamer.AddComment("External Name");
1643 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1646 Asm->OutStreamer.AddComment("End Mark");
1648 Asm->OutStreamer.EmitLabel(EndLabel);
1652 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1653 const MCSection *PSec =
1654 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1655 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1657 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1660 // Emit visible names into a debug str section.
1661 void DwarfDebug::emitDebugStr() {
1662 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1663 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1666 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1667 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1668 const DITypeIdentifierMap &Map,
1669 ArrayRef<DebugLocEntry::Value> Values) {
1670 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1671 return P.isVariablePiece();
1672 }) && "all values are expected to be pieces");
1673 assert(std::is_sorted(Values.begin(), Values.end()) &&
1674 "pieces are expected to be sorted");
1676 unsigned Offset = 0;
1677 for (auto Piece : Values) {
1678 DIExpression Expr = Piece.getExpression();
1679 unsigned PieceOffset = Expr.getPieceOffset();
1680 unsigned PieceSize = Expr.getPieceSize();
1681 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1682 if (Offset < PieceOffset) {
1683 // The DWARF spec seriously mandates pieces with no locations for gaps.
1684 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1685 Offset += PieceOffset-Offset;
1688 Offset += PieceSize;
1690 const unsigned SizeOfByte = 8;
1692 DIVariable Var = Piece.getVariable();
1693 assert(!Var.isIndirect() && "indirect address for piece");
1694 unsigned VarSize = Var.getSizeInBits(Map);
1695 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1696 && "piece is larger than or outside of variable");
1697 assert(PieceSize*SizeOfByte != VarSize
1698 && "piece covers entire variable");
1700 if (Piece.isLocation() && Piece.getLoc().isReg())
1701 Asm->EmitDwarfRegOpPiece(Streamer,
1703 PieceSize*SizeOfByte);
1705 emitDebugLocValue(Streamer, Piece);
1706 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1712 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1713 const DebugLocEntry &Entry) {
1714 const DebugLocEntry::Value Value = Entry.getValues()[0];
1715 if (Value.isVariablePiece())
1716 // Emit all pieces that belong to the same variable and range.
1717 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1719 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1720 emitDebugLocValue(Streamer, Value);
1723 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1724 const DebugLocEntry::Value &Value) {
1725 DIVariable DV = Value.getVariable();
1727 if (Value.isInt()) {
1728 DIBasicType BTy(resolve(DV.getType()));
1729 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1730 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1731 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1732 Streamer.EmitSLEB128(Value.getInt());
1734 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1735 Streamer.EmitULEB128(Value.getInt());
1737 } else if (Value.isLocation()) {
1738 MachineLocation Loc = Value.getLoc();
1739 DIExpression Expr = Value.getExpression();
1742 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1744 // Complex address entry.
1745 unsigned N = Expr.getNumElements();
1747 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1748 if (Loc.getOffset()) {
1750 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1751 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1752 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1753 Streamer.EmitSLEB128(Expr.getElement(1));
1755 // If first address element is OpPlus then emit
1756 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1757 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1758 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1762 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1765 // Emit remaining complex address elements.
1766 for (; i < N; ++i) {
1767 uint64_t Element = Expr.getElement(i);
1768 if (Element == dwarf::DW_OP_plus) {
1769 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1770 Streamer.EmitULEB128(Expr.getElement(++i));
1771 } else if (Element == dwarf::DW_OP_deref) {
1773 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1774 } else if (Element == dwarf::DW_OP_piece) {
1776 // handled in emitDebugLocEntry.
1778 llvm_unreachable("unknown Opcode found in complex address");
1782 // else ... ignore constant fp. There is not any good way to
1783 // to represent them here in dwarf.
1787 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1788 Asm->OutStreamer.AddComment("Loc expr size");
1789 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1790 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1791 Asm->EmitLabelDifference(end, begin, 2);
1792 Asm->OutStreamer.EmitLabel(begin);
1794 APByteStreamer Streamer(*Asm);
1795 emitDebugLocEntry(Streamer, Entry);
1797 Asm->OutStreamer.EmitLabel(end);
1800 // Emit locations into the debug loc section.
1801 void DwarfDebug::emitDebugLoc() {
1802 // Start the dwarf loc section.
1803 Asm->OutStreamer.SwitchSection(
1804 Asm->getObjFileLowering().getDwarfLocSection());
1805 unsigned char Size = Asm->getDataLayout().getPointerSize();
1806 for (const auto &DebugLoc : DotDebugLocEntries) {
1807 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1808 const DwarfCompileUnit *CU = DebugLoc.CU;
1809 assert(!CU->getRanges().empty());
1810 for (const auto &Entry : DebugLoc.List) {
1811 // Set up the range. This range is relative to the entry point of the
1812 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1813 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1814 if (CU->getRanges().size() == 1) {
1815 // Grab the begin symbol from the first range as our base.
1816 const MCSymbol *Base = CU->getRanges()[0].getStart();
1817 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1818 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1820 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1821 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1824 emitDebugLocEntryLocation(Entry);
1826 Asm->OutStreamer.EmitIntValue(0, Size);
1827 Asm->OutStreamer.EmitIntValue(0, Size);
1831 void DwarfDebug::emitDebugLocDWO() {
1832 Asm->OutStreamer.SwitchSection(
1833 Asm->getObjFileLowering().getDwarfLocDWOSection());
1834 for (const auto &DebugLoc : DotDebugLocEntries) {
1835 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1836 for (const auto &Entry : DebugLoc.List) {
1837 // Just always use start_length for now - at least that's one address
1838 // rather than two. We could get fancier and try to, say, reuse an
1839 // address we know we've emitted elsewhere (the start of the function?
1840 // The start of the CU or CU subrange that encloses this range?)
1841 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1842 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1843 Asm->EmitULEB128(idx);
1844 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1846 emitDebugLocEntryLocation(Entry);
1848 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1853 const MCSymbol *Start, *End;
1856 // Emit a debug aranges section, containing a CU lookup for any
1857 // address we can tie back to a CU.
1858 void DwarfDebug::emitDebugARanges() {
1859 // Start the dwarf aranges section.
1860 Asm->OutStreamer.SwitchSection(
1861 Asm->getObjFileLowering().getDwarfARangesSection());
1863 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1867 // Build a list of sections used.
1868 std::vector<const MCSection *> Sections;
1869 for (const auto &it : SectionMap) {
1870 const MCSection *Section = it.first;
1871 Sections.push_back(Section);
1874 // Sort the sections into order.
1875 // This is only done to ensure consistent output order across different runs.
1876 std::sort(Sections.begin(), Sections.end(), SectionSort);
1878 // Build a set of address spans, sorted by CU.
1879 for (const MCSection *Section : Sections) {
1880 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1881 if (List.size() < 2)
1884 // Sort the symbols by offset within the section.
1885 std::sort(List.begin(), List.end(),
1886 [&](const SymbolCU &A, const SymbolCU &B) {
1887 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1888 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1890 // Symbols with no order assigned should be placed at the end.
1891 // (e.g. section end labels)
1899 // If we have no section (e.g. common), just write out
1900 // individual spans for each symbol.
1902 for (const SymbolCU &Cur : List) {
1904 Span.Start = Cur.Sym;
1907 Spans[Cur.CU].push_back(Span);
1910 // Build spans between each label.
1911 const MCSymbol *StartSym = List[0].Sym;
1912 for (size_t n = 1, e = List.size(); n < e; n++) {
1913 const SymbolCU &Prev = List[n - 1];
1914 const SymbolCU &Cur = List[n];
1916 // Try and build the longest span we can within the same CU.
1917 if (Cur.CU != Prev.CU) {
1919 Span.Start = StartSym;
1921 Spans[Prev.CU].push_back(Span);
1928 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1930 // Build a list of CUs used.
1931 std::vector<DwarfCompileUnit *> CUs;
1932 for (const auto &it : Spans) {
1933 DwarfCompileUnit *CU = it.first;
1937 // Sort the CU list (again, to ensure consistent output order).
1938 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1939 return A->getUniqueID() < B->getUniqueID();
1942 // Emit an arange table for each CU we used.
1943 for (DwarfCompileUnit *CU : CUs) {
1944 std::vector<ArangeSpan> &List = Spans[CU];
1946 // Emit size of content not including length itself.
1947 unsigned ContentSize =
1948 sizeof(int16_t) + // DWARF ARange version number
1949 sizeof(int32_t) + // Offset of CU in the .debug_info section
1950 sizeof(int8_t) + // Pointer Size (in bytes)
1951 sizeof(int8_t); // Segment Size (in bytes)
1953 unsigned TupleSize = PtrSize * 2;
1955 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1957 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1959 ContentSize += Padding;
1960 ContentSize += (List.size() + 1) * TupleSize;
1962 // For each compile unit, write the list of spans it covers.
1963 Asm->OutStreamer.AddComment("Length of ARange Set");
1964 Asm->EmitInt32(ContentSize);
1965 Asm->OutStreamer.AddComment("DWARF Arange version number");
1966 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1967 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1968 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
1969 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1970 Asm->EmitInt8(PtrSize);
1971 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1974 Asm->OutStreamer.EmitFill(Padding, 0xff);
1976 for (const ArangeSpan &Span : List) {
1977 Asm->EmitLabelReference(Span.Start, PtrSize);
1979 // Calculate the size as being from the span start to it's end.
1981 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1983 // For symbols without an end marker (e.g. common), we
1984 // write a single arange entry containing just that one symbol.
1985 uint64_t Size = SymSize[Span.Start];
1989 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1993 Asm->OutStreamer.AddComment("ARange terminator");
1994 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1995 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1999 // Emit visible names into a debug ranges section.
2000 void DwarfDebug::emitDebugRanges() {
2001 // Start the dwarf ranges section.
2002 Asm->OutStreamer.SwitchSection(
2003 Asm->getObjFileLowering().getDwarfRangesSection());
2005 // Size for our labels.
2006 unsigned char Size = Asm->getDataLayout().getPointerSize();
2008 // Grab the specific ranges for the compile units in the module.
2009 for (const auto &I : CUMap) {
2010 DwarfCompileUnit *TheCU = I.second;
2012 // Iterate over the misc ranges for the compile units in the module.
2013 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2014 // Emit our symbol so we can find the beginning of the range.
2015 Asm->OutStreamer.EmitLabel(List.getSym());
2017 for (const RangeSpan &Range : List.getRanges()) {
2018 const MCSymbol *Begin = Range.getStart();
2019 const MCSymbol *End = Range.getEnd();
2020 assert(Begin && "Range without a begin symbol?");
2021 assert(End && "Range without an end symbol?");
2022 if (TheCU->getRanges().size() == 1) {
2023 // Grab the begin symbol from the first range as our base.
2024 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2025 Asm->EmitLabelDifference(Begin, Base, Size);
2026 Asm->EmitLabelDifference(End, Base, Size);
2028 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2029 Asm->OutStreamer.EmitSymbolValue(End, Size);
2033 // And terminate the list with two 0 values.
2034 Asm->OutStreamer.EmitIntValue(0, Size);
2035 Asm->OutStreamer.EmitIntValue(0, Size);
2038 // Now emit a range for the CU itself.
2039 if (TheCU->getRanges().size() > 1) {
2040 Asm->OutStreamer.EmitLabel(
2041 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2042 for (const RangeSpan &Range : TheCU->getRanges()) {
2043 const MCSymbol *Begin = Range.getStart();
2044 const MCSymbol *End = Range.getEnd();
2045 assert(Begin && "Range without a begin symbol?");
2046 assert(End && "Range without an end symbol?");
2047 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2048 Asm->OutStreamer.EmitSymbolValue(End, Size);
2050 // And terminate the list with two 0 values.
2051 Asm->OutStreamer.EmitIntValue(0, Size);
2052 Asm->OutStreamer.EmitIntValue(0, Size);
2057 // DWARF5 Experimental Separate Dwarf emitters.
2059 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2060 std::unique_ptr<DwarfUnit> NewU) {
2061 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2062 U.getCUNode().getSplitDebugFilename());
2064 if (!CompilationDir.empty())
2065 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2067 addGnuPubAttributes(*NewU, Die);
2069 SkeletonHolder.addUnit(std::move(NewU));
2072 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2073 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2074 // DW_AT_addr_base, DW_AT_ranges_base.
2075 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2077 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2078 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2079 DwarfCompileUnit &NewCU = *OwnedUnit;
2080 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2081 DwarfInfoSectionSym);
2083 NewCU.initStmtList(DwarfLineSectionSym);
2085 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2090 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2091 // compile units that would normally be in debug_info.
2092 void DwarfDebug::emitDebugInfoDWO() {
2093 assert(useSplitDwarf() && "No split dwarf debug info?");
2094 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2095 // emit relocations into the dwo file.
2096 InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2099 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2100 // abbreviations for the .debug_info.dwo section.
2101 void DwarfDebug::emitDebugAbbrevDWO() {
2102 assert(useSplitDwarf() && "No split dwarf?");
2103 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2106 void DwarfDebug::emitDebugLineDWO() {
2107 assert(useSplitDwarf() && "No split dwarf?");
2108 Asm->OutStreamer.SwitchSection(
2109 Asm->getObjFileLowering().getDwarfLineDWOSection());
2110 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2113 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2114 // string section and is identical in format to traditional .debug_str
2116 void DwarfDebug::emitDebugStrDWO() {
2117 assert(useSplitDwarf() && "No split dwarf?");
2118 const MCSection *OffSec =
2119 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2120 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2124 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2125 if (!useSplitDwarf())
2128 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2129 return &SplitTypeUnitFileTable;
2132 static uint64_t makeTypeSignature(StringRef Identifier) {
2134 Hash.update(Identifier);
2135 // ... take the least significant 8 bytes and return those. Our MD5
2136 // implementation always returns its results in little endian, swap bytes
2138 MD5::MD5Result Result;
2140 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2143 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2144 StringRef Identifier, DIE &RefDie,
2145 DICompositeType CTy) {
2146 // Fast path if we're building some type units and one has already used the
2147 // address pool we know we're going to throw away all this work anyway, so
2148 // don't bother building dependent types.
2149 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2152 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2154 CU.addDIETypeSignature(RefDie, *TU);
2158 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2159 AddrPool.resetUsedFlag();
2161 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2162 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2163 this, &InfoHolder, getDwoLineTable(CU));
2164 DwarfTypeUnit &NewTU = *OwnedUnit;
2165 DIE &UnitDie = NewTU.getUnitDie();
2167 TypeUnitsUnderConstruction.push_back(
2168 std::make_pair(std::move(OwnedUnit), CTy));
2170 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2173 uint64_t Signature = makeTypeSignature(Identifier);
2174 NewTU.setTypeSignature(Signature);
2176 if (useSplitDwarf())
2177 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2178 DwarfTypesDWOSectionSym);
2180 CU.applyStmtList(UnitDie);
2182 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2185 NewTU.setType(NewTU.createTypeDIE(CTy));
2188 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2189 TypeUnitsUnderConstruction.clear();
2191 // Types referencing entries in the address table cannot be placed in type
2193 if (AddrPool.hasBeenUsed()) {
2195 // Remove all the types built while building this type.
2196 // This is pessimistic as some of these types might not be dependent on
2197 // the type that used an address.
2198 for (const auto &TU : TypeUnitsToAdd)
2199 DwarfTypeUnits.erase(TU.second);
2201 // Construct this type in the CU directly.
2202 // This is inefficient because all the dependent types will be rebuilt
2203 // from scratch, including building them in type units, discovering that
2204 // they depend on addresses, throwing them out and rebuilding them.
2205 CU.constructTypeDIE(RefDie, CTy);
2209 // If the type wasn't dependent on fission addresses, finish adding the type
2210 // and all its dependent types.
2211 for (auto &TU : TypeUnitsToAdd)
2212 InfoHolder.addUnit(std::move(TU.first));
2214 CU.addDIETypeSignature(RefDie, NewTU);
2217 // Accelerator table mutators - add each name along with its companion
2218 // DIE to the proper table while ensuring that the name that we're going
2219 // to reference is in the string table. We do this since the names we
2220 // add may not only be identical to the names in the DIE.
2221 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2222 if (!useDwarfAccelTables())
2224 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2228 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2229 if (!useDwarfAccelTables())
2231 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2235 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2236 if (!useDwarfAccelTables())
2238 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2242 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2243 if (!useDwarfAccelTables())
2245 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),