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 "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MD5.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
52 #define DEBUG_TYPE "dwarfdebug"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
70 cl::desc("Generate dwarf aranges"),
74 enum DefaultOnOff { Default, Enable, Disable };
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
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).getTypeArray();
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), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
177 dwarf::DW_FORM_data4)),
178 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
179 dwarf::DW_FORM_data4)),
180 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
181 dwarf::DW_FORM_data4)),
182 AccelTypes(TypeAtoms) {
184 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
185 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
186 DwarfLineSectionSym = nullptr;
187 DwarfAddrSectionSym = nullptr;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
189 FunctionBeginSym = FunctionEndSym = nullptr;
193 // Turn on accelerator tables for Darwin by default, pubnames by
194 // default for non-Darwin, and handle split dwarf.
195 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
197 if (DwarfAccelTables == Default)
198 HasDwarfAccelTables = IsDarwin;
200 HasDwarfAccelTables = DwarfAccelTables == Enable;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable;
207 if (DwarfPubSections == Default)
208 HasDwarfPubSections = !IsDarwin;
210 HasDwarfPubSections = DwarfPubSections == Enable;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
216 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
221 // Switch to the specified MCSection and emit an assembler
222 // temporary label to it if SymbolStem is specified.
223 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
224 const char *SymbolStem = nullptr) {
225 Asm->OutStreamer.SwitchSection(Section);
229 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
230 Asm->OutStreamer.EmitLabel(TmpSym);
234 static bool isObjCClass(StringRef Name) {
235 return Name.startswith("+") || Name.startswith("-");
238 static bool hasObjCCategory(StringRef Name) {
239 if (!isObjCClass(Name))
242 return Name.find(") ") != StringRef::npos;
245 static void getObjCClassCategory(StringRef In, StringRef &Class,
246 StringRef &Category) {
247 if (!hasObjCCategory(In)) {
248 Class = In.slice(In.find('[') + 1, In.find(' '));
253 Class = In.slice(In.find('[') + 1, In.find('('));
254 Category = In.slice(In.find('[') + 1, In.find(' '));
258 static StringRef getObjCMethodName(StringRef In) {
259 return In.slice(In.find(' ') + 1, In.find(']'));
262 // Helper for sorting sections into a stable output order.
263 static bool SectionSort(const MCSection *A, const MCSection *B) {
264 std::string LA = (A ? A->getLabelBeginName() : "");
265 std::string LB = (B ? B->getLabelBeginName() : "");
269 // Add the various names to the Dwarf accelerator table names.
270 // TODO: Determine whether or not we should add names for programs
271 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
272 // is only slightly different than the lookup of non-standard ObjC names.
273 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
274 if (!SP.isDefinition())
276 addAccelName(SP.getName(), Die);
278 // If the linkage name is different than the name, go ahead and output
279 // that as well into the name table.
280 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
281 addAccelName(SP.getLinkageName(), Die);
283 // If this is an Objective-C selector name add it to the ObjC accelerator
285 if (isObjCClass(SP.getName())) {
286 StringRef Class, Category;
287 getObjCClassCategory(SP.getName(), Class, Category);
288 addAccelObjC(Class, Die);
290 addAccelObjC(Category, Die);
291 // Also add the base method name to the name table.
292 addAccelName(getObjCMethodName(SP.getName()), Die);
296 /// isSubprogramContext - Return true if Context is either a subprogram
297 /// or another context nested inside a subprogram.
298 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
301 DIDescriptor D(Context);
302 if (D.isSubprogram())
305 return isSubprogramContext(resolve(DIType(Context).getContext()));
309 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
310 // and DW_AT_high_pc attributes. If there are global variables in this
311 // scope then create and insert DIEs for these variables.
312 DIE &DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
314 DIE *SPDie = SPCU.getDIE(SP);
316 assert(SPDie && "Unable to find subprogram DIE!");
318 // If we're updating an abstract DIE, then we will be adding the children and
319 // object pointer later on. But what we don't want to do is process the
320 // concrete DIE twice.
321 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
322 // Pick up abstract subprogram DIE.
323 SPDie = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
324 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
326 DISubprogram SPDecl = SP.getFunctionDeclaration();
327 if (!SPDecl.isSubprogram()) {
328 // There is not any need to generate specification DIE for a function
329 // defined at compile unit level. If a function is defined inside another
330 // function then gdb prefers the definition at top level and but does not
331 // expect specification DIE in parent function. So avoid creating
332 // specification DIE for a function defined inside a function.
333 DIScope SPContext = resolve(SP.getContext());
334 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
335 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
336 SPCU.addFlag(*SPDie, dwarf::DW_AT_declaration);
339 DICompositeType SPTy = SP.getType();
340 DIArray Args = SPTy.getTypeArray();
341 uint16_t SPTag = SPTy.getTag();
342 if (SPTag == dwarf::DW_TAG_subroutine_type)
343 SPCU.constructSubprogramArguments(*SPDie, Args);
344 DIE *SPDeclDie = SPDie;
346 &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, SPCU.getUnitDie());
347 SPCU.addDIEEntry(*SPDie, dwarf::DW_AT_specification, *SPDeclDie);
352 attachLowHighPC(SPCU, *SPDie, FunctionBeginSym, FunctionEndSym);
354 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
355 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
356 SPCU.addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
358 // Add name to the name table, we do this here because we're guaranteed
359 // to have concrete versions of our DW_TAG_subprogram nodes.
360 addSubprogramNames(SP, *SPDie);
365 /// Check whether we should create a DIE for the given Scope, return true
366 /// if we don't create a DIE (the corresponding DIE is null).
367 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
368 if (Scope->isAbstractScope())
371 // We don't create a DIE if there is no Range.
372 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
376 if (Ranges.size() > 1)
379 // We don't create a DIE if we have a single Range and the end label
381 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
382 MCSymbol *End = getLabelAfterInsn(RI->second);
386 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
387 dwarf::Attribute A, const MCSymbol *L,
388 const MCSymbol *Sec) {
389 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
390 U.addSectionLabel(D, A, L);
392 U.addSectionDelta(D, A, L, Sec);
395 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
396 const SmallVectorImpl<InsnRange> &Range) {
397 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
398 // emitting it appropriately.
399 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
401 // Under fission, ranges are specified by constant offsets relative to the
402 // CU's DW_AT_GNU_ranges_base.
404 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
405 DwarfDebugRangeSectionSym);
407 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
408 DwarfDebugRangeSectionSym);
410 RangeSpanList List(RangeSym);
411 for (const InsnRange &R : Range) {
412 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
413 List.addRange(std::move(Span));
416 // Add the range list to the set of ranges to be emitted.
417 TheCU.addRangeList(std::move(List));
420 // Construct new DW_TAG_lexical_block for this scope and attach
421 // DW_AT_low_pc/DW_AT_high_pc labels.
423 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
424 LexicalScope *Scope) {
425 if (isLexicalScopeDIENull(Scope))
428 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
429 if (Scope->isAbstractScope())
432 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
434 // If we have multiple ranges, emit them into the range section.
435 if (ScopeRanges.size() > 1) {
436 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
440 // Construct the address range for this DIE.
441 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
442 MCSymbol *Start = getLabelBeforeInsn(RI->first);
443 MCSymbol *End = getLabelAfterInsn(RI->second);
444 assert(End && "End label should not be null!");
446 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
447 assert(End->isDefined() && "Invalid end label for an inlined scope!");
449 attachLowHighPC(TheCU, *ScopeDIE, Start, End);
454 // This scope represents inlined body of a function. Construct DIE to
455 // represent this concrete inlined copy of the function.
457 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
458 LexicalScope *Scope) {
459 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
460 assert(!ScopeRanges.empty() &&
461 "LexicalScope does not have instruction markers!");
463 if (!Scope->getScopeNode())
465 DIScope DS(Scope->getScopeNode());
466 DISubprogram InlinedSP = getDISubprogram(DS);
467 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
469 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
473 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
474 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
476 // If we have multiple ranges, emit them into the range section.
477 if (ScopeRanges.size() > 1)
478 addScopeRangeList(TheCU, *ScopeDIE, ScopeRanges);
480 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
481 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
482 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
484 if (!StartLabel || !EndLabel)
485 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
487 assert(StartLabel->isDefined() &&
488 "Invalid starting label for an inlined scope!");
489 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
491 attachLowHighPC(TheCU, *ScopeDIE, StartLabel, EndLabel);
494 InlinedSubprogramDIEs.insert(OriginDIE);
496 // Add the call site information to the DIE.
497 DILocation DL(Scope->getInlinedAt());
498 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
499 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
500 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
502 // Add name to the name table, we do this here because we're guaranteed
503 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
504 addSubprogramNames(InlinedSP, *ScopeDIE);
509 DIE *DwarfDebug::createScopeChildrenDIE(
510 DwarfCompileUnit &TheCU, LexicalScope *Scope,
511 SmallVectorImpl<std::unique_ptr<DIE>> &Children) {
512 DIE *ObjectPointer = nullptr;
514 // Collect arguments for current function.
515 if (LScopes.isCurrentFunctionScope(Scope)) {
516 for (DbgVariable *ArgDV : CurrentFnArguments)
519 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope()));
520 if (ArgDV->isObjectPointer())
521 ObjectPointer = Children.back().get();
524 // If this is a variadic function, add an unspecified parameter.
525 DISubprogram SP(Scope->getScopeNode());
526 DIArray FnArgs = SP.getType().getTypeArray();
527 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
528 .isUnspecifiedParameter()) {
530 make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
534 // Collect lexical scope children first.
535 for (DbgVariable *DV : ScopeVariables.lookup(Scope)) {
537 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope()));
538 if (DV->isObjectPointer())
539 ObjectPointer = Children.back().get();
541 for (LexicalScope *LS : Scope->getChildren())
542 if (std::unique_ptr<DIE> Nested = constructScopeDIE(TheCU, LS))
543 Children.push_back(std::move(Nested));
544 return ObjectPointer;
547 void DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU, LexicalScope *Scope, DIE &ScopeDIE) {
548 // We create children when the scope DIE is not null.
549 SmallVector<std::unique_ptr<DIE>, 8> Children;
550 if (DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children))
551 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
554 for (auto &I : Children)
555 ScopeDIE.addChild(std::move(I));
558 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU, LexicalScope *Scope) {
559 assert(Scope && Scope->getScopeNode());
560 assert(Scope->isAbstractScope());
561 assert(!Scope->getInlinedAt());
563 DISubprogram Sub(Scope->getScopeNode());
565 ProcessedSPNodes.insert(Sub);
567 if (DIE *ScopeDIE = TheCU.getDIE(Sub)) {
568 AbstractSPDies.insert(std::make_pair(Sub, ScopeDIE));
569 createAndAddScopeChildren(TheCU, Scope, *ScopeDIE);
573 DIE &DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
574 LexicalScope *Scope) {
575 assert(Scope && Scope->getScopeNode());
576 assert(!Scope->getInlinedAt());
577 assert(!Scope->isAbstractScope());
578 assert(DIScope(Scope->getScopeNode()).isSubprogram());
580 DISubprogram Sub(Scope->getScopeNode());
582 ProcessedSPNodes.insert(Sub);
584 DIE &ScopeDIE = updateSubprogramScopeDIE(TheCU, Sub);
586 createAndAddScopeChildren(TheCU, Scope, ScopeDIE);
591 // Construct a DIE for this scope.
592 std::unique_ptr<DIE> DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
593 LexicalScope *Scope) {
594 if (!Scope || !Scope->getScopeNode())
597 DIScope DS(Scope->getScopeNode());
599 assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
600 "Only handle inlined subprograms here, use "
601 "constructSubprogramScopeDIE for non-inlined "
604 SmallVector<std::unique_ptr<DIE>, 8> Children;
606 // We try to create the scope DIE first, then the children DIEs. This will
607 // avoid creating un-used children then removing them later when we find out
608 // the scope DIE is null.
609 std::unique_ptr<DIE> ScopeDIE;
610 if (Scope->getInlinedAt()) {
611 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
614 // We create children when the scope DIE is not null.
615 createScopeChildrenDIE(TheCU, Scope, Children);
617 // Early exit when we know the scope DIE is going to be null.
618 if (isLexicalScopeDIENull(Scope))
621 // We create children here when we know the scope DIE is not going to be
622 // null and the children will be added to the scope DIE.
623 createScopeChildrenDIE(TheCU, Scope, Children);
625 // There is no need to emit empty lexical block DIE.
626 std::pair<ImportedEntityMap::const_iterator,
627 ImportedEntityMap::const_iterator> Range =
628 std::equal_range(ScopesWithImportedEntities.begin(),
629 ScopesWithImportedEntities.end(),
630 std::pair<const MDNode *, const MDNode *>(DS, nullptr),
632 if (Children.empty() && Range.first == Range.second)
634 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
635 assert(ScopeDIE && "Scope DIE should not be null.");
636 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
638 constructImportedEntityDIE(TheCU, i->second, *ScopeDIE);
642 for (auto &I : Children)
643 ScopeDIE->addChild(std::move(I));
648 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
649 if (!GenerateGnuPubSections)
652 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
655 // Create new DwarfCompileUnit for the given metadata node with tag
656 // DW_TAG_compile_unit.
657 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
658 StringRef FN = DIUnit.getFilename();
659 CompilationDir = DIUnit.getDirectory();
661 auto OwnedUnit = make_unique<DwarfCompileUnit>(
662 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
663 DwarfCompileUnit &NewCU = *OwnedUnit;
664 DIE &Die = NewCU.getUnitDie();
665 InfoHolder.addUnit(std::move(OwnedUnit));
667 // LTO with assembly output shares a single line table amongst multiple CUs.
668 // To avoid the compilation directory being ambiguous, let the line table
669 // explicitly describe the directory of all files, never relying on the
670 // compilation directory.
671 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
672 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
673 NewCU.getUniqueID(), CompilationDir);
675 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
676 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
677 DIUnit.getLanguage());
678 NewCU.addString(Die, dwarf::DW_AT_name, FN);
680 if (!useSplitDwarf()) {
681 NewCU.initStmtList(DwarfLineSectionSym);
683 // If we're using split dwarf the compilation dir is going to be in the
684 // skeleton CU and so we don't need to duplicate it here.
685 if (!CompilationDir.empty())
686 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
688 addGnuPubAttributes(NewCU, Die);
691 if (DIUnit.isOptimized())
692 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
694 StringRef Flags = DIUnit.getFlags();
696 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
698 if (unsigned RVer = DIUnit.getRunTimeVersion())
699 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
700 dwarf::DW_FORM_data1, RVer);
705 if (useSplitDwarf()) {
706 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
707 DwarfInfoDWOSectionSym);
708 NewCU.setSkeleton(constructSkeletonCU(NewCU));
710 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
711 DwarfInfoSectionSym);
713 CUMap.insert(std::make_pair(DIUnit, &NewCU));
714 CUDieMap.insert(std::make_pair(&Die, &NewCU));
718 // Construct subprogram DIE.
719 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
721 // FIXME: We should only call this routine once, however, during LTO if a
722 // program is defined in multiple CUs we could end up calling it out of
723 // beginModule as we walk the CUs.
725 DwarfCompileUnit *&CURef = SPMap[N];
731 if (!SP.isDefinition())
732 // This is a method declaration which will be handled while constructing
736 DIE &SubprogramDie = *TheCU.getOrCreateSubprogramDIE(SP);
738 // Expose as a global name.
739 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
742 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
744 DIImportedEntity Module(N);
745 assert(Module.Verify());
746 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
747 constructImportedEntityDIE(TheCU, Module, *D);
750 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
751 const MDNode *N, DIE &Context) {
752 DIImportedEntity Module(N);
753 assert(Module.Verify());
754 return constructImportedEntityDIE(TheCU, Module, Context);
757 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
758 const DIImportedEntity &Module,
760 assert(Module.Verify() &&
761 "Use one of the MDNode * overloads to handle invalid metadata");
762 DIE &IMDie = TheCU.createAndAddDIE(Module.getTag(), Context, Module);
764 DIDescriptor Entity = resolve(Module.getEntity());
765 if (Entity.isNameSpace())
766 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
767 else if (Entity.isSubprogram())
768 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
769 else if (Entity.isType())
770 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
772 EntityDie = TheCU.getDIE(Entity);
773 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
774 Module.getContext().getFilename(),
775 Module.getContext().getDirectory());
776 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, *EntityDie);
777 StringRef Name = Module.getName();
779 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
782 // Emit all Dwarf sections that should come prior to the content. Create
783 // global DIEs and emit initial debug info sections. This is invoked by
784 // the target AsmPrinter.
785 void DwarfDebug::beginModule() {
786 if (DisableDebugInfoPrinting)
789 const Module *M = MMI->getModule();
791 // If module has named metadata anchors then use them, otherwise scan the
792 // module using debug info finder to collect debug info.
793 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
796 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
798 // Emit initial sections so we can reference labels later.
801 SingleCU = CU_Nodes->getNumOperands() == 1;
803 for (MDNode *N : CU_Nodes->operands()) {
804 DICompileUnit CUNode(N);
805 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
806 DIArray ImportedEntities = CUNode.getImportedEntities();
807 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
808 ScopesWithImportedEntities.push_back(std::make_pair(
809 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
810 ImportedEntities.getElement(i)));
811 std::sort(ScopesWithImportedEntities.begin(),
812 ScopesWithImportedEntities.end(), less_first());
813 DIArray GVs = CUNode.getGlobalVariables();
814 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
815 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
816 DIArray SPs = CUNode.getSubprograms();
817 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
818 constructSubprogramDIE(CU, SPs.getElement(i));
819 DIArray EnumTypes = CUNode.getEnumTypes();
820 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
821 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
822 DIArray RetainedTypes = CUNode.getRetainedTypes();
823 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
824 DIType Ty(RetainedTypes.getElement(i));
825 // The retained types array by design contains pointers to
826 // MDNodes rather than DIRefs. Unique them here.
827 DIType UniqueTy(resolve(Ty.getRef()));
828 CU.getOrCreateTypeDIE(UniqueTy);
830 // Emit imported_modules last so that the relevant context is already
832 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
833 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
836 // Tell MMI that we have debug info.
837 MMI->setDebugInfoAvailability(true);
839 // Prime section data.
840 SectionMap[Asm->getObjFileLowering().getTextSection()];
843 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
844 void DwarfDebug::computeInlinedDIEs() {
845 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
846 for (DIE *ISP : InlinedSubprogramDIEs)
847 FirstCU->addUInt(*ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
849 for (const auto &AI : AbstractSPDies) {
850 DIE &ISP = *AI.second;
851 if (InlinedSubprogramDIEs.count(&ISP))
853 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
857 // Collect info for variables that were optimized out.
858 void DwarfDebug::collectDeadVariables() {
859 const Module *M = MMI->getModule();
861 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
862 for (MDNode *N : CU_Nodes->operands()) {
863 DICompileUnit TheCU(N);
864 DIArray Subprograms = TheCU.getSubprograms();
865 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
866 DISubprogram SP(Subprograms.getElement(i));
867 if (ProcessedSPNodes.count(SP) != 0)
869 if (!SP.isSubprogram())
871 if (!SP.isDefinition())
873 DIArray Variables = SP.getVariables();
874 if (Variables.getNumElements() == 0)
877 // Construct subprogram DIE and add variables DIEs.
878 DwarfCompileUnit *SPCU =
879 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
880 assert(SPCU && "Unable to find Compile Unit!");
881 // FIXME: See the comment in constructSubprogramDIE about duplicate
883 constructSubprogramDIE(*SPCU, SP);
884 DIE *SPDIE = SPCU->getDIE(SP);
885 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
886 DIVariable DV(Variables.getElement(vi));
887 if (!DV.isVariable())
889 DbgVariable NewVar(DV, nullptr, this);
890 SPDIE->addChild(SPCU->constructVariableDIE(NewVar, false));
897 void DwarfDebug::finalizeModuleInfo() {
898 // Collect info for variables that were optimized out.
899 collectDeadVariables();
901 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
902 computeInlinedDIEs();
904 // Handle anything that needs to be done on a per-unit basis after
905 // all other generation.
906 for (const auto &TheU : getUnits()) {
907 // Emit DW_AT_containing_type attribute to connect types with their
908 // vtable holding type.
909 TheU->constructContainingTypeDIEs();
911 // Add CU specific attributes if we need to add any.
912 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
913 // If we're splitting the dwarf out now that we've got the entire
914 // CU then add the dwo id to it.
915 DwarfCompileUnit *SkCU =
916 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
917 if (useSplitDwarf()) {
918 // Emit a unique identifier for this CU.
919 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
920 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
921 dwarf::DW_FORM_data8, ID);
922 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
923 dwarf::DW_FORM_data8, ID);
925 // We don't keep track of which addresses are used in which CU so this
926 // is a bit pessimistic under LTO.
927 if (!AddrPool.isEmpty())
928 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
929 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
930 DwarfAddrSectionSym);
931 if (!TheU->getRangeLists().empty())
932 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
933 dwarf::DW_AT_GNU_ranges_base,
934 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
937 // If we have code split among multiple sections or non-contiguous
938 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
939 // remain in the .o file, otherwise add a DW_AT_low_pc.
940 // FIXME: We should use ranges allow reordering of code ala
941 // .subsections_via_symbols in mach-o. This would mean turning on
942 // ranges for all subprogram DIEs for mach-o.
943 DwarfCompileUnit &U =
944 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
945 unsigned NumRanges = TheU->getRanges().size();
948 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
949 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
950 DwarfDebugRangeSectionSym);
952 // A DW_AT_low_pc attribute may also be specified in combination with
953 // DW_AT_ranges to specify the default base address for use in
954 // location lists (see Section 2.6.2) and range lists (see Section
956 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
959 RangeSpan &Range = TheU->getRanges().back();
960 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
962 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
969 // Compute DIE offsets and sizes.
970 InfoHolder.computeSizeAndOffsets();
972 SkeletonHolder.computeSizeAndOffsets();
975 void DwarfDebug::endSections() {
976 // Filter labels by section.
977 for (const SymbolCU &SCU : ArangeLabels) {
978 if (SCU.Sym->isInSection()) {
979 // Make a note of this symbol and it's section.
980 const MCSection *Section = &SCU.Sym->getSection();
981 if (!Section->getKind().isMetadata())
982 SectionMap[Section].push_back(SCU);
984 // Some symbols (e.g. common/bss on mach-o) can have no section but still
985 // appear in the output. This sucks as we rely on sections to build
986 // arange spans. We can do it without, but it's icky.
987 SectionMap[nullptr].push_back(SCU);
991 // Build a list of sections used.
992 std::vector<const MCSection *> Sections;
993 for (const auto &it : SectionMap) {
994 const MCSection *Section = it.first;
995 Sections.push_back(Section);
998 // Sort the sections into order.
999 // This is only done to ensure consistent output order across different runs.
1000 std::sort(Sections.begin(), Sections.end(), SectionSort);
1002 // Add terminating symbols for each section.
1003 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1004 const MCSection *Section = Sections[ID];
1005 MCSymbol *Sym = nullptr;
1008 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1009 // if we know the section name up-front. For user-created sections, the
1010 // resulting label may not be valid to use as a label. (section names can
1011 // use a greater set of characters on some systems)
1012 Sym = Asm->GetTempSymbol("debug_end", ID);
1013 Asm->OutStreamer.SwitchSection(Section);
1014 Asm->OutStreamer.EmitLabel(Sym);
1017 // Insert a final terminator.
1018 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1022 // Emit all Dwarf sections that should come after the content.
1023 void DwarfDebug::endModule() {
1024 assert(CurFn == nullptr);
1025 assert(CurMI == nullptr);
1030 // End any existing sections.
1031 // TODO: Does this need to happen?
1034 // Finalize the debug info for the module.
1035 finalizeModuleInfo();
1039 // Emit all the DIEs into a debug info section.
1042 // Corresponding abbreviations into a abbrev section.
1043 emitAbbreviations();
1045 // Emit info into a debug aranges section.
1046 if (GenerateARangeSection)
1049 // Emit info into a debug ranges section.
1052 if (useSplitDwarf()) {
1055 emitDebugAbbrevDWO();
1057 // Emit DWO addresses.
1058 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1061 // Emit info into a debug loc section.
1064 // Emit info into the dwarf accelerator table sections.
1065 if (useDwarfAccelTables()) {
1068 emitAccelNamespaces();
1072 // Emit the pubnames and pubtypes sections if requested.
1073 if (HasDwarfPubSections) {
1074 emitDebugPubNames(GenerateGnuPubSections);
1075 emitDebugPubTypes(GenerateGnuPubSections);
1081 // Reset these for the next Module if we have one.
1085 // Find abstract variable, if any, associated with Var.
1086 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1087 DebugLoc ScopeLoc) {
1088 LLVMContext &Ctx = DV->getContext();
1089 // More then one inlined variable corresponds to one abstract variable.
1090 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1091 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1093 return AbsDbgVariable;
1095 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1099 AbsDbgVariable = new DbgVariable(Var, nullptr, this);
1100 addScopeVariable(Scope, AbsDbgVariable);
1101 AbstractVariables[Var] = AbsDbgVariable;
1102 return AbsDbgVariable;
1105 // If Var is a current function argument then add it to CurrentFnArguments list.
1106 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1107 if (!LScopes.isCurrentFunctionScope(Scope))
1109 DIVariable DV = Var->getVariable();
1110 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1112 unsigned ArgNo = DV.getArgNumber();
1116 size_t Size = CurrentFnArguments.size();
1118 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1119 // llvm::Function argument size is not good indicator of how many
1120 // arguments does the function have at source level.
1122 CurrentFnArguments.resize(ArgNo * 2);
1123 CurrentFnArguments[ArgNo - 1] = Var;
1127 // Collect variable information from side table maintained by MMI.
1128 void DwarfDebug::collectVariableInfoFromMMITable(
1129 SmallPtrSet<const MDNode *, 16> &Processed) {
1130 for (const auto &VI : MMI->getVariableDbgInfo()) {
1133 Processed.insert(VI.Var);
1134 DIVariable DV(VI.Var);
1135 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1137 // If variable scope is not found then skip this variable.
1141 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1142 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1143 RegVar->setFrameIndex(VI.Slot);
1144 if (!addCurrentFnArgument(RegVar, Scope))
1145 addScopeVariable(Scope, RegVar);
1147 AbsDbgVariable->setFrameIndex(VI.Slot);
1151 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1153 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1154 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1155 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1156 MI->getOperand(0).getReg() &&
1157 (MI->getOperand(1).isImm() ||
1158 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1161 // Get .debug_loc entry for the instruction range starting at MI.
1162 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1163 const MDNode *Var = MI->getDebugVariable();
1165 assert(MI->getNumOperands() == 3);
1166 if (MI->getOperand(0).isReg()) {
1167 MachineLocation MLoc;
1168 // If the second operand is an immediate, this is a
1169 // register-indirect address.
1170 if (!MI->getOperand(1).isImm())
1171 MLoc.set(MI->getOperand(0).getReg());
1173 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1174 return DebugLocEntry::Value(Var, MLoc);
1176 if (MI->getOperand(0).isImm())
1177 return DebugLocEntry::Value(Var, MI->getOperand(0).getImm());
1178 if (MI->getOperand(0).isFPImm())
1179 return DebugLocEntry::Value(Var, MI->getOperand(0).getFPImm());
1180 if (MI->getOperand(0).isCImm())
1181 return DebugLocEntry::Value(Var, MI->getOperand(0).getCImm());
1183 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1186 // Find variables for each lexical scope.
1188 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1189 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1190 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1192 // Grab the variable info that was squirreled away in the MMI side-table.
1193 collectVariableInfoFromMMITable(Processed);
1195 for (const MDNode *Var : UserVariables) {
1196 if (Processed.count(Var))
1199 // History contains relevant DBG_VALUE instructions for Var and instructions
1201 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1202 if (History.empty())
1204 const MachineInstr *MInsn = History.front();
1207 LexicalScope *Scope = nullptr;
1208 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1209 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1210 Scope = LScopes.getCurrentFunctionScope();
1211 else if (MDNode *IA = DV.getInlinedAt())
1212 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1214 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1215 // If variable scope is not found then skip this variable.
1219 Processed.insert(DV);
1220 assert(MInsn->isDebugValue() && "History must begin with debug value");
1221 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1222 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1223 if (!addCurrentFnArgument(RegVar, Scope))
1224 addScopeVariable(Scope, RegVar);
1226 AbsVar->setMInsn(MInsn);
1228 // Simplify ranges that are fully coalesced.
1229 if (History.size() <= 1 ||
1230 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1231 RegVar->setMInsn(MInsn);
1235 // Handle multiple DBG_VALUE instructions describing one variable.
1236 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1238 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1239 DebugLocList &LocList = DotDebugLocEntries.back();
1241 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1242 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1243 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1244 HI = History.begin(),
1247 const MachineInstr *Begin = *HI;
1248 assert(Begin->isDebugValue() && "Invalid History entry");
1250 // Check if DBG_VALUE is truncating a range.
1251 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1252 !Begin->getOperand(0).getReg())
1255 // Compute the range for a register location.
1256 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1257 const MCSymbol *SLabel = nullptr;
1260 // If Begin is the last instruction in History then its value is valid
1261 // until the end of the function.
1262 SLabel = FunctionEndSym;
1264 const MachineInstr *End = HI[1];
1265 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1266 << "\t" << *Begin << "\t" << *End << "\n");
1267 if (End->isDebugValue())
1268 SLabel = getLabelBeforeInsn(End);
1270 // End is a normal instruction clobbering the range.
1271 SLabel = getLabelAfterInsn(End);
1272 assert(SLabel && "Forgot label after clobber instruction");
1277 // The value is valid until the next DBG_VALUE or clobber.
1278 DebugLocEntry Loc(FLabel, SLabel, getDebugLocValue(Begin), TheCU);
1279 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1280 DebugLoc.push_back(std::move(Loc));
1284 // Collect info for variables that were optimized out.
1285 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1286 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1287 DIVariable DV(Variables.getElement(i));
1288 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1290 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1291 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1295 // Return Label preceding the instruction.
1296 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1297 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1298 assert(Label && "Didn't insert label before instruction");
1302 // Return Label immediately following the instruction.
1303 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1304 return LabelsAfterInsn.lookup(MI);
1307 // Process beginning of an instruction.
1308 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1309 assert(CurMI == nullptr);
1311 // Check if source location changes, but ignore DBG_VALUE locations.
1312 if (!MI->isDebugValue()) {
1313 DebugLoc DL = MI->getDebugLoc();
1314 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1317 if (DL == PrologEndLoc) {
1318 Flags |= DWARF2_FLAG_PROLOGUE_END;
1319 PrologEndLoc = DebugLoc();
1321 if (PrologEndLoc.isUnknown())
1322 Flags |= DWARF2_FLAG_IS_STMT;
1324 if (!DL.isUnknown()) {
1325 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1326 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1328 recordSourceLine(0, 0, nullptr, 0);
1332 // Insert labels where requested.
1333 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1334 LabelsBeforeInsn.find(MI);
1337 if (I == LabelsBeforeInsn.end())
1340 // Label already assigned.
1345 PrevLabel = MMI->getContext().CreateTempSymbol();
1346 Asm->OutStreamer.EmitLabel(PrevLabel);
1348 I->second = PrevLabel;
1351 // Process end of an instruction.
1352 void DwarfDebug::endInstruction() {
1353 assert(CurMI != nullptr);
1354 // Don't create a new label after DBG_VALUE instructions.
1355 // They don't generate code.
1356 if (!CurMI->isDebugValue())
1357 PrevLabel = nullptr;
1359 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1360 LabelsAfterInsn.find(CurMI);
1364 if (I == LabelsAfterInsn.end())
1367 // Label already assigned.
1371 // We need a label after this instruction.
1373 PrevLabel = MMI->getContext().CreateTempSymbol();
1374 Asm->OutStreamer.EmitLabel(PrevLabel);
1376 I->second = PrevLabel;
1379 // Each LexicalScope has first instruction and last instruction to mark
1380 // beginning and end of a scope respectively. Create an inverse map that list
1381 // scopes starts (and ends) with an instruction. One instruction may start (or
1382 // end) multiple scopes. Ignore scopes that are not reachable.
1383 void DwarfDebug::identifyScopeMarkers() {
1384 SmallVector<LexicalScope *, 4> WorkList;
1385 WorkList.push_back(LScopes.getCurrentFunctionScope());
1386 while (!WorkList.empty()) {
1387 LexicalScope *S = WorkList.pop_back_val();
1389 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1390 if (!Children.empty())
1391 WorkList.append(Children.begin(), Children.end());
1393 if (S->isAbstractScope())
1396 for (const InsnRange &R : S->getRanges()) {
1397 assert(R.first && "InsnRange does not have first instruction!");
1398 assert(R.second && "InsnRange does not have second instruction!");
1399 requestLabelBeforeInsn(R.first);
1400 requestLabelAfterInsn(R.second);
1405 // Gather pre-function debug information. Assumes being called immediately
1406 // after the function entry point has been emitted.
1407 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1410 // If there's no debug info for the function we're not going to do anything.
1411 if (!MMI->hasDebugInfo())
1414 // Grab the lexical scopes for the function, if we don't have any of those
1415 // then we're not going to be able to do anything.
1416 LScopes.initialize(*MF);
1417 if (LScopes.empty())
1420 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1422 // Make sure that each lexical scope will have a begin/end label.
1423 identifyScopeMarkers();
1425 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1426 // belongs to so that we add to the correct per-cu line table in the
1428 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1429 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1430 assert(TheCU && "Unable to find compile unit!");
1431 if (Asm->OutStreamer.hasRawTextSupport())
1432 // Use a single line table if we are generating assembly.
1433 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1435 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1437 // Emit a label for the function so that we have a beginning address.
1438 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1439 // Assumes in correct section after the entry point.
1440 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1442 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1443 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1444 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1446 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1448 bool AtBlockEntry = true;
1449 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1451 const MachineInstr *MI = II;
1453 if (MI->isDebugValue()) {
1454 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1456 // Keep track of user variables.
1457 const MDNode *Var = MI->getDebugVariable();
1459 // Variable is in a register, we need to check for clobbers.
1460 if (isDbgValueInDefinedReg(MI))
1461 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1463 // Check the history of this variable.
1464 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1465 if (History.empty()) {
1466 UserVariables.push_back(Var);
1467 // The first mention of a function argument gets the FunctionBeginSym
1468 // label, so arguments are visible when breaking at function entry.
1470 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1471 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1472 LabelsBeforeInsn[MI] = FunctionBeginSym;
1474 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1475 const MachineInstr *Prev = History.back();
1476 if (Prev->isDebugValue()) {
1477 // Coalesce identical entries at the end of History.
1478 if (History.size() >= 2 &&
1479 Prev->isIdenticalTo(History[History.size() - 2])) {
1480 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1481 << "\t" << *Prev << "\t"
1482 << *History[History.size() - 2] << "\n");
1486 // Terminate old register assignments that don't reach MI;
1487 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1488 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1489 isDbgValueInDefinedReg(Prev)) {
1490 // Previous register assignment needs to terminate at the end of
1492 MachineBasicBlock::const_iterator LastMI =
1493 PrevMBB->getLastNonDebugInstr();
1494 if (LastMI == PrevMBB->end()) {
1495 // Drop DBG_VALUE for empty range.
1496 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1497 << "\t" << *Prev << "\n");
1499 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1500 // Terminate after LastMI.
1501 History.push_back(LastMI);
1505 History.push_back(MI);
1507 // Not a DBG_VALUE instruction.
1508 if (!MI->isPosition())
1509 AtBlockEntry = false;
1511 // First known non-DBG_VALUE and non-frame setup location marks
1512 // the beginning of the function body.
1513 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1514 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1515 PrologEndLoc = MI->getDebugLoc();
1517 // Check if the instruction clobbers any registers with debug vars.
1518 for (const MachineOperand &MO : MI->operands()) {
1519 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1521 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1524 const MDNode *Var = LiveUserVar[Reg];
1527 // Reg is now clobbered.
1528 LiveUserVar[Reg] = nullptr;
1530 // Was MD last defined by a DBG_VALUE referring to Reg?
1531 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1532 if (HistI == DbgValues.end())
1534 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1535 if (History.empty())
1537 const MachineInstr *Prev = History.back();
1538 // Sanity-check: Register assignments are terminated at the end of
1540 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1542 // Is the variable still in Reg?
1543 if (!isDbgValueInDefinedReg(Prev) ||
1544 Prev->getOperand(0).getReg() != Reg)
1546 // Var is clobbered. Make sure the next instruction gets a label.
1547 History.push_back(MI);
1554 for (auto &I : DbgValues) {
1555 SmallVectorImpl<const MachineInstr *> &History = I.second;
1556 if (History.empty())
1559 // Make sure the final register assignments are terminated.
1560 const MachineInstr *Prev = History.back();
1561 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1562 const MachineBasicBlock *PrevMBB = Prev->getParent();
1563 MachineBasicBlock::const_iterator LastMI =
1564 PrevMBB->getLastNonDebugInstr();
1565 if (LastMI == PrevMBB->end())
1566 // Drop DBG_VALUE for empty range.
1568 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1569 // Terminate after LastMI.
1570 History.push_back(LastMI);
1573 // Request labels for the full history.
1574 for (const MachineInstr *MI : History) {
1575 if (MI->isDebugValue())
1576 requestLabelBeforeInsn(MI);
1578 requestLabelAfterInsn(MI);
1582 PrevInstLoc = DebugLoc();
1583 PrevLabel = FunctionBeginSym;
1585 // Record beginning of function.
1586 if (!PrologEndLoc.isUnknown()) {
1587 DebugLoc FnStartDL =
1588 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1590 FnStartDL.getLine(), FnStartDL.getCol(),
1591 FnStartDL.getScope(MF->getFunction()->getContext()),
1592 // We'd like to list the prologue as "not statements" but GDB behaves
1593 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1594 DWARF2_FLAG_IS_STMT);
1598 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1599 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1600 DIVariable DV = Var->getVariable();
1601 // Variables with positive arg numbers are parameters.
1602 if (unsigned ArgNum = DV.getArgNumber()) {
1603 // Keep all parameters in order at the start of the variable list to ensure
1604 // function types are correct (no out-of-order parameters)
1606 // This could be improved by only doing it for optimized builds (unoptimized
1607 // builds have the right order to begin with), searching from the back (this
1608 // would catch the unoptimized case quickly), or doing a binary search
1609 // rather than linear search.
1610 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1611 while (I != Vars.end()) {
1612 unsigned CurNum = (*I)->getVariable().getArgNumber();
1613 // A local (non-parameter) variable has been found, insert immediately
1617 // A later indexed parameter has been found, insert immediately before it.
1618 if (CurNum > ArgNum)
1622 Vars.insert(I, Var);
1626 Vars.push_back(Var);
1629 // Gather and emit post-function debug information.
1630 void DwarfDebug::endFunction(const MachineFunction *MF) {
1631 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1632 // though the beginFunction may not be called at all.
1633 // We should handle both cases.
1637 assert(CurFn == MF);
1638 assert(CurFn != nullptr);
1640 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1641 // If we don't have a lexical scope for this function then there will
1642 // be a hole in the range information. Keep note of this by setting the
1643 // previously used section to nullptr.
1644 PrevSection = nullptr;
1650 // Define end label for subprogram.
1651 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1652 // Assumes in correct section after the entry point.
1653 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1655 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1656 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1658 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1659 collectVariableInfo(ProcessedVars);
1661 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1662 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1664 // Construct abstract scopes.
1665 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1666 DISubprogram SP(AScope->getScopeNode());
1667 if (SP.isSubprogram()) {
1668 // Collect info for variables that were optimized out.
1669 DIArray Variables = SP.getVariables();
1670 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1671 DIVariable DV(Variables.getElement(i));
1672 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1674 // Check that DbgVariable for DV wasn't created earlier, when
1675 // findAbstractVariable() was called for inlined instance of DV.
1676 LLVMContext &Ctx = DV->getContext();
1677 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1678 if (AbstractVariables.lookup(CleanDV))
1680 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1681 addScopeVariable(Scope, new DbgVariable(DV, nullptr, this));
1684 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1685 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1688 DIE &CurFnDIE = constructSubprogramScopeDIE(TheCU, FnScope);
1689 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1690 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1692 // Add the range of this function to the list of ranges for the CU.
1693 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1694 TheCU.addRange(std::move(Span));
1695 PrevSection = Asm->getCurrentSection();
1699 for (auto &I : ScopeVariables)
1700 DeleteContainerPointers(I.second);
1701 ScopeVariables.clear();
1702 DeleteContainerPointers(CurrentFnArguments);
1703 UserVariables.clear();
1705 AbstractVariables.clear();
1706 LabelsBeforeInsn.clear();
1707 LabelsAfterInsn.clear();
1708 PrevLabel = nullptr;
1712 // Register a source line with debug info. Returns the unique label that was
1713 // emitted and which provides correspondence to the source line list.
1714 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1719 unsigned Discriminator = 0;
1721 DIDescriptor Scope(S);
1723 if (Scope.isCompileUnit()) {
1724 DICompileUnit CU(S);
1725 Fn = CU.getFilename();
1726 Dir = CU.getDirectory();
1727 } else if (Scope.isFile()) {
1729 Fn = F.getFilename();
1730 Dir = F.getDirectory();
1731 } else if (Scope.isSubprogram()) {
1733 Fn = SP.getFilename();
1734 Dir = SP.getDirectory();
1735 } else if (Scope.isLexicalBlockFile()) {
1736 DILexicalBlockFile DBF(S);
1737 Fn = DBF.getFilename();
1738 Dir = DBF.getDirectory();
1739 } else if (Scope.isLexicalBlock()) {
1740 DILexicalBlock DB(S);
1741 Fn = DB.getFilename();
1742 Dir = DB.getDirectory();
1743 Discriminator = DB.getDiscriminator();
1745 llvm_unreachable("Unexpected scope info");
1747 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1748 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1749 .getOrCreateSourceID(Fn, Dir);
1751 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1755 //===----------------------------------------------------------------------===//
1757 //===----------------------------------------------------------------------===//
1759 // Emit initial Dwarf sections with a label at the start of each one.
1760 void DwarfDebug::emitSectionLabels() {
1761 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1763 // Dwarf sections base addresses.
1764 DwarfInfoSectionSym =
1765 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1766 if (useSplitDwarf())
1767 DwarfInfoDWOSectionSym =
1768 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1769 DwarfAbbrevSectionSym =
1770 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1771 if (useSplitDwarf())
1772 DwarfAbbrevDWOSectionSym = emitSectionSym(
1773 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1774 if (GenerateARangeSection)
1775 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1777 DwarfLineSectionSym =
1778 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1779 if (GenerateGnuPubSections) {
1780 DwarfGnuPubNamesSectionSym =
1781 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1782 DwarfGnuPubTypesSectionSym =
1783 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1784 } else if (HasDwarfPubSections) {
1785 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1786 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1789 DwarfStrSectionSym =
1790 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1791 if (useSplitDwarf()) {
1792 DwarfStrDWOSectionSym =
1793 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1794 DwarfAddrSectionSym =
1795 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1796 DwarfDebugLocSectionSym =
1797 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1799 DwarfDebugLocSectionSym =
1800 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1801 DwarfDebugRangeSectionSym =
1802 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1805 // Recursively emits a debug information entry.
1806 void DwarfDebug::emitDIE(DIE &Die) {
1807 // Get the abbreviation for this DIE.
1808 const DIEAbbrev &Abbrev = Die.getAbbrev();
1810 // Emit the code (index) for the abbreviation.
1811 if (Asm->isVerbose())
1812 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1813 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1814 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1815 dwarf::TagString(Abbrev.getTag()));
1816 Asm->EmitULEB128(Abbrev.getNumber());
1818 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1819 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1821 // Emit the DIE attribute values.
1822 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1823 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1824 dwarf::Form Form = AbbrevData[i].getForm();
1825 assert(Form && "Too many attributes for DIE (check abbreviation)");
1827 if (Asm->isVerbose()) {
1828 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1829 if (Attr == dwarf::DW_AT_accessibility)
1830 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1831 cast<DIEInteger>(Values[i])->getValue()));
1834 // Emit an attribute using the defined form.
1835 Values[i]->EmitValue(Asm, Form);
1838 // Emit the DIE children if any.
1839 if (Abbrev.hasChildren()) {
1840 for (auto &Child : Die.getChildren())
1843 Asm->OutStreamer.AddComment("End Of Children Mark");
1848 // Emit the debug info section.
1849 void DwarfDebug::emitDebugInfo() {
1850 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1852 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1855 // Emit the abbreviation section.
1856 void DwarfDebug::emitAbbreviations() {
1857 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1859 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1862 // Emit the last address of the section and the end of the line matrix.
1863 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1864 // Define last address of section.
1865 Asm->OutStreamer.AddComment("Extended Op");
1868 Asm->OutStreamer.AddComment("Op size");
1869 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1870 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1871 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1873 Asm->OutStreamer.AddComment("Section end label");
1875 Asm->OutStreamer.EmitSymbolValue(
1876 Asm->GetTempSymbol("section_end", SectionEnd),
1877 Asm->getDataLayout().getPointerSize());
1879 // Mark end of matrix.
1880 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1886 // Emit visible names into a hashed accelerator table section.
1887 void DwarfDebug::emitAccelNames() {
1888 AccelNames.FinalizeTable(Asm, "Names");
1889 Asm->OutStreamer.SwitchSection(
1890 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1891 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1892 Asm->OutStreamer.EmitLabel(SectionBegin);
1894 // Emit the full data.
1895 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1898 // Emit objective C classes and categories into a hashed accelerator table
1900 void DwarfDebug::emitAccelObjC() {
1901 AccelObjC.FinalizeTable(Asm, "ObjC");
1902 Asm->OutStreamer.SwitchSection(
1903 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1904 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1905 Asm->OutStreamer.EmitLabel(SectionBegin);
1907 // Emit the full data.
1908 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1911 // Emit namespace dies into a hashed accelerator table.
1912 void DwarfDebug::emitAccelNamespaces() {
1913 AccelNamespace.FinalizeTable(Asm, "namespac");
1914 Asm->OutStreamer.SwitchSection(
1915 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1916 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1917 Asm->OutStreamer.EmitLabel(SectionBegin);
1919 // Emit the full data.
1920 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1923 // Emit type dies into a hashed accelerator table.
1924 void DwarfDebug::emitAccelTypes() {
1926 AccelTypes.FinalizeTable(Asm, "types");
1927 Asm->OutStreamer.SwitchSection(
1928 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1929 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1930 Asm->OutStreamer.EmitLabel(SectionBegin);
1932 // Emit the full data.
1933 AccelTypes.Emit(Asm, SectionBegin, &InfoHolder);
1936 // Public name handling.
1937 // The format for the various pubnames:
1939 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1940 // for the DIE that is named.
1942 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1943 // into the CU and the index value is computed according to the type of value
1944 // for the DIE that is named.
1946 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1947 // it's the offset within the debug_info/debug_types dwo section, however, the
1948 // reference in the pubname header doesn't change.
1950 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1951 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1953 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1955 // We could have a specification DIE that has our most of our knowledge,
1956 // look for that now.
1957 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1959 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1960 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1961 Linkage = dwarf::GIEL_EXTERNAL;
1962 } else if (Die->findAttribute(dwarf::DW_AT_external))
1963 Linkage = dwarf::GIEL_EXTERNAL;
1965 switch (Die->getTag()) {
1966 case dwarf::DW_TAG_class_type:
1967 case dwarf::DW_TAG_structure_type:
1968 case dwarf::DW_TAG_union_type:
1969 case dwarf::DW_TAG_enumeration_type:
1970 return dwarf::PubIndexEntryDescriptor(
1971 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1972 ? dwarf::GIEL_STATIC
1973 : dwarf::GIEL_EXTERNAL);
1974 case dwarf::DW_TAG_typedef:
1975 case dwarf::DW_TAG_base_type:
1976 case dwarf::DW_TAG_subrange_type:
1977 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1978 case dwarf::DW_TAG_namespace:
1979 return dwarf::GIEK_TYPE;
1980 case dwarf::DW_TAG_subprogram:
1981 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1982 case dwarf::DW_TAG_constant:
1983 case dwarf::DW_TAG_variable:
1984 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1985 case dwarf::DW_TAG_enumerator:
1986 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1987 dwarf::GIEL_STATIC);
1989 return dwarf::GIEK_NONE;
1993 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1995 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1996 const MCSection *PSec =
1997 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1998 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2000 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2003 void DwarfDebug::emitDebugPubSection(
2004 bool GnuStyle, const MCSection *PSec, StringRef Name,
2005 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2006 for (const auto &NU : CUMap) {
2007 DwarfCompileUnit *TheU = NU.second;
2009 const auto &Globals = (TheU->*Accessor)();
2011 if (Globals.empty())
2014 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2016 unsigned ID = TheU->getUniqueID();
2018 // Start the dwarf pubnames section.
2019 Asm->OutStreamer.SwitchSection(PSec);
2022 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2023 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2024 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2025 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2027 Asm->OutStreamer.EmitLabel(BeginLabel);
2029 Asm->OutStreamer.AddComment("DWARF Version");
2030 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2032 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2033 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2035 Asm->OutStreamer.AddComment("Compilation Unit Length");
2036 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2038 // Emit the pubnames for this compilation unit.
2039 for (const auto &GI : Globals) {
2040 const char *Name = GI.getKeyData();
2041 const DIE *Entity = GI.second;
2043 Asm->OutStreamer.AddComment("DIE offset");
2044 Asm->EmitInt32(Entity->getOffset());
2047 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2048 Asm->OutStreamer.AddComment(
2049 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2050 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2051 Asm->EmitInt8(Desc.toBits());
2054 Asm->OutStreamer.AddComment("External Name");
2055 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2058 Asm->OutStreamer.AddComment("End Mark");
2060 Asm->OutStreamer.EmitLabel(EndLabel);
2064 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2065 const MCSection *PSec =
2066 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2067 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2069 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2072 // Emit visible names into a debug str section.
2073 void DwarfDebug::emitDebugStr() {
2074 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2075 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2078 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2079 const DebugLocEntry &Entry) {
2080 assert(Entry.getValues().size() == 1 &&
2081 "multi-value entries are not supported yet.");
2082 const DebugLocEntry::Value Value = Entry.getValues()[0];
2083 DIVariable DV(Value.getVariable());
2084 if (Value.isInt()) {
2085 DIBasicType BTy(resolve(DV.getType()));
2086 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2087 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2088 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2089 Streamer.EmitSLEB128(Value.getInt());
2091 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2092 Streamer.EmitULEB128(Value.getInt());
2094 } else if (Value.isLocation()) {
2095 MachineLocation Loc = Value.getLoc();
2096 if (!DV.hasComplexAddress())
2098 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2100 // Complex address entry.
2101 unsigned N = DV.getNumAddrElements();
2103 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2104 if (Loc.getOffset()) {
2106 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2107 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2108 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2109 Streamer.EmitSLEB128(DV.getAddrElement(1));
2111 // If first address element is OpPlus then emit
2112 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2113 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2114 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2118 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2121 // Emit remaining complex address elements.
2122 for (; i < N; ++i) {
2123 uint64_t Element = DV.getAddrElement(i);
2124 if (Element == DIBuilder::OpPlus) {
2125 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2126 Streamer.EmitULEB128(DV.getAddrElement(++i));
2127 } else if (Element == DIBuilder::OpDeref) {
2129 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2131 llvm_unreachable("unknown Opcode found in complex address");
2135 // else ... ignore constant fp. There is not any good way to
2136 // to represent them here in dwarf.
2140 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2141 Asm->OutStreamer.AddComment("Loc expr size");
2142 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2143 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2144 Asm->EmitLabelDifference(end, begin, 2);
2145 Asm->OutStreamer.EmitLabel(begin);
2147 APByteStreamer Streamer(*Asm);
2148 emitDebugLocEntry(Streamer, Entry);
2150 Asm->OutStreamer.EmitLabel(end);
2153 // Emit locations into the debug loc section.
2154 void DwarfDebug::emitDebugLoc() {
2155 // Start the dwarf loc section.
2156 Asm->OutStreamer.SwitchSection(
2157 Asm->getObjFileLowering().getDwarfLocSection());
2158 unsigned char Size = Asm->getDataLayout().getPointerSize();
2159 for (const auto &DebugLoc : DotDebugLocEntries) {
2160 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2161 for (const auto &Entry : DebugLoc.List) {
2162 // Set up the range. This range is relative to the entry point of the
2163 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2164 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2165 const DwarfCompileUnit *CU = Entry.getCU();
2166 if (CU->getRanges().size() == 1) {
2167 // Grab the begin symbol from the first range as our base.
2168 const MCSymbol *Base = CU->getRanges()[0].getStart();
2169 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2170 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2172 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2173 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2176 emitDebugLocEntryLocation(Entry);
2178 Asm->OutStreamer.EmitIntValue(0, Size);
2179 Asm->OutStreamer.EmitIntValue(0, Size);
2183 void DwarfDebug::emitDebugLocDWO() {
2184 Asm->OutStreamer.SwitchSection(
2185 Asm->getObjFileLowering().getDwarfLocDWOSection());
2186 for (const auto &DebugLoc : DotDebugLocEntries) {
2187 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2188 for (const auto &Entry : DebugLoc.List) {
2189 // Just always use start_length for now - at least that's one address
2190 // rather than two. We could get fancier and try to, say, reuse an
2191 // address we know we've emitted elsewhere (the start of the function?
2192 // The start of the CU or CU subrange that encloses this range?)
2193 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2194 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2195 Asm->EmitULEB128(idx);
2196 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2198 emitDebugLocEntryLocation(Entry);
2200 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2205 const MCSymbol *Start, *End;
2208 // Emit a debug aranges section, containing a CU lookup for any
2209 // address we can tie back to a CU.
2210 void DwarfDebug::emitDebugARanges() {
2211 // Start the dwarf aranges section.
2212 Asm->OutStreamer.SwitchSection(
2213 Asm->getObjFileLowering().getDwarfARangesSection());
2215 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2219 // Build a list of sections used.
2220 std::vector<const MCSection *> Sections;
2221 for (const auto &it : SectionMap) {
2222 const MCSection *Section = it.first;
2223 Sections.push_back(Section);
2226 // Sort the sections into order.
2227 // This is only done to ensure consistent output order across different runs.
2228 std::sort(Sections.begin(), Sections.end(), SectionSort);
2230 // Build a set of address spans, sorted by CU.
2231 for (const MCSection *Section : Sections) {
2232 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2233 if (List.size() < 2)
2236 // Sort the symbols by offset within the section.
2237 std::sort(List.begin(), List.end(),
2238 [&](const SymbolCU &A, const SymbolCU &B) {
2239 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2240 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2242 // Symbols with no order assigned should be placed at the end.
2243 // (e.g. section end labels)
2251 // If we have no section (e.g. common), just write out
2252 // individual spans for each symbol.
2254 for (const SymbolCU &Cur : List) {
2256 Span.Start = Cur.Sym;
2259 Spans[Cur.CU].push_back(Span);
2262 // Build spans between each label.
2263 const MCSymbol *StartSym = List[0].Sym;
2264 for (size_t n = 1, e = List.size(); n < e; n++) {
2265 const SymbolCU &Prev = List[n - 1];
2266 const SymbolCU &Cur = List[n];
2268 // Try and build the longest span we can within the same CU.
2269 if (Cur.CU != Prev.CU) {
2271 Span.Start = StartSym;
2273 Spans[Prev.CU].push_back(Span);
2280 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2282 // Build a list of CUs used.
2283 std::vector<DwarfCompileUnit *> CUs;
2284 for (const auto &it : Spans) {
2285 DwarfCompileUnit *CU = it.first;
2289 // Sort the CU list (again, to ensure consistent output order).
2290 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2291 return A->getUniqueID() < B->getUniqueID();
2294 // Emit an arange table for each CU we used.
2295 for (DwarfCompileUnit *CU : CUs) {
2296 std::vector<ArangeSpan> &List = Spans[CU];
2298 // Emit size of content not including length itself.
2299 unsigned ContentSize =
2300 sizeof(int16_t) + // DWARF ARange version number
2301 sizeof(int32_t) + // Offset of CU in the .debug_info section
2302 sizeof(int8_t) + // Pointer Size (in bytes)
2303 sizeof(int8_t); // Segment Size (in bytes)
2305 unsigned TupleSize = PtrSize * 2;
2307 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2309 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2311 ContentSize += Padding;
2312 ContentSize += (List.size() + 1) * TupleSize;
2314 // For each compile unit, write the list of spans it covers.
2315 Asm->OutStreamer.AddComment("Length of ARange Set");
2316 Asm->EmitInt32(ContentSize);
2317 Asm->OutStreamer.AddComment("DWARF Arange version number");
2318 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2319 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2320 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2321 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2322 Asm->EmitInt8(PtrSize);
2323 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2326 Asm->OutStreamer.EmitFill(Padding, 0xff);
2328 for (const ArangeSpan &Span : List) {
2329 Asm->EmitLabelReference(Span.Start, PtrSize);
2331 // Calculate the size as being from the span start to it's end.
2333 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2335 // For symbols without an end marker (e.g. common), we
2336 // write a single arange entry containing just that one symbol.
2337 uint64_t Size = SymSize[Span.Start];
2341 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2345 Asm->OutStreamer.AddComment("ARange terminator");
2346 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2347 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2351 // Emit visible names into a debug ranges section.
2352 void DwarfDebug::emitDebugRanges() {
2353 // Start the dwarf ranges section.
2354 Asm->OutStreamer.SwitchSection(
2355 Asm->getObjFileLowering().getDwarfRangesSection());
2357 // Size for our labels.
2358 unsigned char Size = Asm->getDataLayout().getPointerSize();
2360 // Grab the specific ranges for the compile units in the module.
2361 for (const auto &I : CUMap) {
2362 DwarfCompileUnit *TheCU = I.second;
2364 // Iterate over the misc ranges for the compile units in the module.
2365 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2366 // Emit our symbol so we can find the beginning of the range.
2367 Asm->OutStreamer.EmitLabel(List.getSym());
2369 for (const RangeSpan &Range : List.getRanges()) {
2370 const MCSymbol *Begin = Range.getStart();
2371 const MCSymbol *End = Range.getEnd();
2372 assert(Begin && "Range without a begin symbol?");
2373 assert(End && "Range without an end symbol?");
2374 if (TheCU->getRanges().size() == 1) {
2375 // Grab the begin symbol from the first range as our base.
2376 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2377 Asm->EmitLabelDifference(Begin, Base, Size);
2378 Asm->EmitLabelDifference(End, Base, Size);
2380 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2381 Asm->OutStreamer.EmitSymbolValue(End, Size);
2385 // And terminate the list with two 0 values.
2386 Asm->OutStreamer.EmitIntValue(0, Size);
2387 Asm->OutStreamer.EmitIntValue(0, Size);
2390 // Now emit a range for the CU itself.
2391 if (TheCU->getRanges().size() > 1) {
2392 Asm->OutStreamer.EmitLabel(
2393 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2394 for (const RangeSpan &Range : TheCU->getRanges()) {
2395 const MCSymbol *Begin = Range.getStart();
2396 const MCSymbol *End = Range.getEnd();
2397 assert(Begin && "Range without a begin symbol?");
2398 assert(End && "Range without an end symbol?");
2399 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2400 Asm->OutStreamer.EmitSymbolValue(End, Size);
2402 // And terminate the list with two 0 values.
2403 Asm->OutStreamer.EmitIntValue(0, Size);
2404 Asm->OutStreamer.EmitIntValue(0, Size);
2409 // DWARF5 Experimental Separate Dwarf emitters.
2411 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2412 std::unique_ptr<DwarfUnit> NewU) {
2413 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2414 U.getCUNode().getSplitDebugFilename());
2416 if (!CompilationDir.empty())
2417 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2419 addGnuPubAttributes(*NewU, Die);
2421 SkeletonHolder.addUnit(std::move(NewU));
2424 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2425 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2426 // DW_AT_addr_base, DW_AT_ranges_base.
2427 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2429 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2430 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2431 DwarfCompileUnit &NewCU = *OwnedUnit;
2432 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2433 DwarfInfoSectionSym);
2435 NewCU.initStmtList(DwarfLineSectionSym);
2437 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2442 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2444 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2445 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2446 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2448 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), CU, Asm, this,
2450 DwarfTypeUnit &NewTU = *OwnedUnit;
2451 NewTU.setTypeSignature(TU.getTypeSignature());
2452 NewTU.setType(nullptr);
2454 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2456 initSkeletonUnit(TU, NewTU.getUnitDie(), std::move(OwnedUnit));
2460 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2461 // compile units that would normally be in debug_info.
2462 void DwarfDebug::emitDebugInfoDWO() {
2463 assert(useSplitDwarf() && "No split dwarf debug info?");
2464 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2465 // emit relocations into the dwo file.
2466 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2469 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2470 // abbreviations for the .debug_info.dwo section.
2471 void DwarfDebug::emitDebugAbbrevDWO() {
2472 assert(useSplitDwarf() && "No split dwarf?");
2473 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2476 void DwarfDebug::emitDebugLineDWO() {
2477 assert(useSplitDwarf() && "No split dwarf?");
2478 Asm->OutStreamer.SwitchSection(
2479 Asm->getObjFileLowering().getDwarfLineDWOSection());
2480 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2483 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2484 // string section and is identical in format to traditional .debug_str
2486 void DwarfDebug::emitDebugStrDWO() {
2487 assert(useSplitDwarf() && "No split dwarf?");
2488 const MCSection *OffSec =
2489 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2490 const MCSymbol *StrSym = DwarfStrSectionSym;
2491 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2495 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2496 if (!useSplitDwarf())
2499 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2500 return &SplitTypeUnitFileTable;
2503 static uint64_t makeTypeSignature(StringRef Identifier) {
2505 Hash.update(Identifier);
2506 // ... take the least significant 8 bytes and return those. Our MD5
2507 // implementation always returns its results in little endian, swap bytes
2509 MD5::MD5Result Result;
2511 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2514 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2515 StringRef Identifier, DIE &RefDie,
2516 DICompositeType CTy) {
2517 // Fast path if we're building some type units and one has already used the
2518 // address pool we know we're going to throw away all this work anyway, so
2519 // don't bother building dependent types.
2520 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2523 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2525 CU.addDIETypeSignature(RefDie, *TU);
2529 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2530 AddrPool.resetUsedFlag();
2533 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), CU, Asm, this,
2534 &InfoHolder, getDwoLineTable(CU));
2535 DwarfTypeUnit &NewTU = *OwnedUnit;
2536 DIE &UnitDie = NewTU.getUnitDie();
2538 TypeUnitsUnderConstruction.push_back(
2539 std::make_pair(std::move(OwnedUnit), CTy));
2541 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2544 uint64_t Signature = makeTypeSignature(Identifier);
2545 NewTU.setTypeSignature(Signature);
2547 if (!useSplitDwarf())
2548 CU.applyStmtList(UnitDie);
2552 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2553 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2555 NewTU.setType(NewTU.createTypeDIE(CTy));
2558 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2559 TypeUnitsUnderConstruction.clear();
2561 // Types referencing entries in the address table cannot be placed in type
2563 if (AddrPool.hasBeenUsed()) {
2565 // Remove all the types built while building this type.
2566 // This is pessimistic as some of these types might not be dependent on
2567 // the type that used an address.
2568 for (const auto &TU : TypeUnitsToAdd)
2569 DwarfTypeUnits.erase(TU.second);
2571 // Construct this type in the CU directly.
2572 // This is inefficient because all the dependent types will be rebuilt
2573 // from scratch, including building them in type units, discovering that
2574 // they depend on addresses, throwing them out and rebuilding them.
2575 CU.constructTypeDIE(RefDie, CTy);
2579 // If the type wasn't dependent on fission addresses, finish adding the type
2580 // and all its dependent types.
2581 for (auto &TU : TypeUnitsToAdd) {
2582 if (useSplitDwarf())
2583 TU.first->setSkeleton(constructSkeletonTU(*TU.first));
2584 InfoHolder.addUnit(std::move(TU.first));
2587 CU.addDIETypeSignature(RefDie, NewTU);
2590 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE &D,
2591 MCSymbol *Begin, MCSymbol *End) {
2592 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2593 if (DwarfVersion < 4)
2594 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2596 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2599 // Accelerator table mutators - add each name along with its companion
2600 // DIE to the proper table while ensuring that the name that we're going
2601 // to reference is in the string table. We do this since the names we
2602 // add may not only be identical to the names in the DIE.
2603 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2604 if (!useDwarfAccelTables())
2606 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2610 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2611 if (!useDwarfAccelTables())
2613 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2617 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2618 if (!useDwarfAccelTables())
2620 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2624 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2625 if (!useDwarfAccelTables())
2627 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),