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());
122 DIType DbgVariable::getType() const {
123 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
124 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
125 // addresses instead.
126 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
127 /* Byref variables, in Blocks, are declared by the programmer as
128 "SomeType VarName;", but the compiler creates a
129 __Block_byref_x_VarName struct, and gives the variable VarName
130 either the struct, or a pointer to the struct, as its type. This
131 is necessary for various behind-the-scenes things the compiler
132 needs to do with by-reference variables in blocks.
134 However, as far as the original *programmer* is concerned, the
135 variable should still have type 'SomeType', as originally declared.
137 The following function dives into the __Block_byref_x_VarName
138 struct to find the original type of the variable. This will be
139 passed back to the code generating the type for the Debug
140 Information Entry for the variable 'VarName'. 'VarName' will then
141 have the original type 'SomeType' in its debug information.
143 The original type 'SomeType' will be the type of the field named
144 'VarName' inside the __Block_byref_x_VarName struct.
146 NOTE: In order for this to not completely fail on the debugger
147 side, the Debug Information Entry for the variable VarName needs to
148 have a DW_AT_location that tells the debugger how to unwind through
149 the pointers and __Block_byref_x_VarName struct to find the actual
150 value of the variable. The function addBlockByrefType does this. */
152 uint16_t tag = Ty.getTag();
154 if (tag == dwarf::DW_TAG_pointer_type)
155 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
157 DIArray Elements = DICompositeType(subType).getTypeArray();
158 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
159 DIDerivedType DT(Elements.getElement(i));
160 if (getName() == DT.getName())
161 return (resolve(DT.getTypeDerivedFrom()));
167 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
168 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
169 InfoHolder(A, "info_string", DIEValueAllocator),
170 UsedNonDefaultText(false),
171 SkeletonHolder(A, "skel_string", DIEValueAllocator),
172 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
173 dwarf::DW_FORM_data4)) {
175 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
176 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
177 DwarfAddrSectionSym = 0;
178 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
179 FunctionBeginSym = FunctionEndSym = 0;
183 // Turn on accelerator tables for Darwin by default, pubnames by
184 // default for non-Darwin, and handle split dwarf.
185 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
187 if (DwarfAccelTables == Default)
188 HasDwarfAccelTables = IsDarwin;
190 HasDwarfAccelTables = DwarfAccelTables == Enable;
192 if (SplitDwarf == Default)
193 HasSplitDwarf = false;
195 HasSplitDwarf = SplitDwarf == Enable;
197 if (DwarfPubSections == Default)
198 HasDwarfPubSections = !IsDarwin;
200 HasDwarfPubSections = DwarfPubSections == Enable;
202 DwarfVersion = DwarfVersionNumber
204 : MMI->getModule()->getDwarfVersion();
207 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
212 // Switch to the specified MCSection and emit an assembler
213 // temporary label to it if SymbolStem is specified.
214 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
215 const char *SymbolStem = 0) {
216 Asm->OutStreamer.SwitchSection(Section);
220 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
221 Asm->OutStreamer.EmitLabel(TmpSym);
225 static bool isObjCClass(StringRef Name) {
226 return Name.startswith("+") || Name.startswith("-");
229 static bool hasObjCCategory(StringRef Name) {
230 if (!isObjCClass(Name))
233 return Name.find(") ") != StringRef::npos;
236 static void getObjCClassCategory(StringRef In, StringRef &Class,
237 StringRef &Category) {
238 if (!hasObjCCategory(In)) {
239 Class = In.slice(In.find('[') + 1, In.find(' '));
244 Class = In.slice(In.find('[') + 1, In.find('('));
245 Category = In.slice(In.find('[') + 1, In.find(' '));
249 static StringRef getObjCMethodName(StringRef In) {
250 return In.slice(In.find(' ') + 1, In.find(']'));
253 // Helper for sorting sections into a stable output order.
254 static bool SectionSort(const MCSection *A, const MCSection *B) {
255 std::string LA = (A ? A->getLabelBeginName() : "");
256 std::string LB = (B ? B->getLabelBeginName() : "");
260 // Add the various names to the Dwarf accelerator table names.
261 // TODO: Determine whether or not we should add names for programs
262 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
263 // is only slightly different than the lookup of non-standard ObjC names.
264 void DwarfDebug::addSubprogramNames(DwarfUnit &TheU, DISubprogram SP, DIE *Die) {
265 if (!SP.isDefinition())
267 addAccelName(SP.getName(), Die);
269 // If the linkage name is different than the name, go ahead and output
270 // that as well into the name table.
271 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
272 addAccelName(SP.getLinkageName(), Die);
274 // If this is an Objective-C selector name add it to the ObjC accelerator
276 if (isObjCClass(SP.getName())) {
277 StringRef Class, Category;
278 getObjCClassCategory(SP.getName(), Class, Category);
279 TheU.addAccelObjC(Class, Die);
281 TheU.addAccelObjC(Category, Die);
282 // Also add the base method name to the name table.
283 addAccelName(getObjCMethodName(SP.getName()), Die);
287 /// isSubprogramContext - Return true if Context is either a subprogram
288 /// or another context nested inside a subprogram.
289 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
292 DIDescriptor D(Context);
293 if (D.isSubprogram())
296 return isSubprogramContext(resolve(DIType(Context).getContext()));
300 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
301 // and DW_AT_high_pc attributes. If there are global variables in this
302 // scope then create and insert DIEs for these variables.
303 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
305 DIE *SPDie = SPCU.getDIE(SP);
307 assert(SPDie && "Unable to find subprogram DIE!");
309 // If we're updating an abstract DIE, then we will be adding the children and
310 // object pointer later on. But what we don't want to do is process the
311 // concrete DIE twice.
312 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
313 // Pick up abstract subprogram DIE.
314 SPDie = SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
315 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
317 DISubprogram SPDecl = SP.getFunctionDeclaration();
318 if (!SPDecl.isSubprogram()) {
319 // There is not any need to generate specification DIE for a function
320 // defined at compile unit level. If a function is defined inside another
321 // function then gdb prefers the definition at top level and but does not
322 // expect specification DIE in parent function. So avoid creating
323 // specification DIE for a function defined inside a function.
324 DIScope SPContext = resolve(SP.getContext());
325 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
326 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
327 SPCU.addFlag(SPDie, dwarf::DW_AT_declaration);
330 DICompositeType SPTy = SP.getType();
331 DIArray Args = SPTy.getTypeArray();
332 uint16_t SPTag = SPTy.getTag();
333 if (SPTag == dwarf::DW_TAG_subroutine_type)
334 SPCU.constructSubprogramArguments(*SPDie, Args);
335 DIE *SPDeclDie = SPDie;
337 SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
338 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
343 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
345 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
346 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
347 SPCU.addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
349 // Add name to the name table, we do this here because we're guaranteed
350 // to have concrete versions of our DW_TAG_subprogram nodes.
351 addSubprogramNames(SPCU, SP, SPDie);
356 /// Check whether we should create a DIE for the given Scope, return true
357 /// if we don't create a DIE (the corresponding DIE is null).
358 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
359 if (Scope->isAbstractScope())
362 // We don't create a DIE if there is no Range.
363 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
367 if (Ranges.size() > 1)
370 // We don't create a DIE if we have a single Range and the end label
372 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
373 MCSymbol *End = getLabelAfterInsn(RI->second);
377 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE *D,
378 dwarf::Attribute A, const MCSymbol *L,
379 const MCSymbol *Sec) {
380 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
381 U.addSectionLabel(D, A, L);
383 U.addSectionDelta(D, A, L, Sec);
386 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
387 const SmallVectorImpl<InsnRange> &Range) {
388 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
389 // emitting it appropriately.
390 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
392 // Under fission, ranges are specified by constant offsets relative to the
393 // CU's DW_AT_GNU_ranges_base.
395 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
396 DwarfDebugRangeSectionSym);
398 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
399 DwarfDebugRangeSectionSym);
401 RangeSpanList List(RangeSym);
402 for (const InsnRange &R : Range) {
403 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
404 List.addRange(std::move(Span));
407 // Add the range list to the set of ranges to be emitted.
408 TheCU.addRangeList(std::move(List));
411 // Construct new DW_TAG_lexical_block for this scope and attach
412 // DW_AT_low_pc/DW_AT_high_pc labels.
413 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
414 LexicalScope *Scope) {
415 if (isLexicalScopeDIENull(Scope))
418 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
419 if (Scope->isAbstractScope())
422 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
424 // If we have multiple ranges, emit them into the range section.
425 if (ScopeRanges.size() > 1) {
426 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
430 // Construct the address range for this DIE.
431 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
432 MCSymbol *Start = getLabelBeforeInsn(RI->first);
433 MCSymbol *End = getLabelAfterInsn(RI->second);
434 assert(End && "End label should not be null!");
436 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
437 assert(End->isDefined() && "Invalid end label for an inlined scope!");
439 attachLowHighPC(TheCU, ScopeDIE, Start, End);
444 // This scope represents inlined body of a function. Construct DIE to
445 // represent this concrete inlined copy of the function.
446 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
447 LexicalScope *Scope) {
448 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
449 assert(!ScopeRanges.empty() &&
450 "LexicalScope does not have instruction markers!");
452 if (!Scope->getScopeNode())
454 DIScope DS(Scope->getScopeNode());
455 DISubprogram InlinedSP = getDISubprogram(DS);
456 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
458 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
462 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
463 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
465 // If we have multiple ranges, emit them into the range section.
466 if (ScopeRanges.size() > 1)
467 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
469 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
470 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
471 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
473 if (StartLabel == 0 || EndLabel == 0)
474 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
476 assert(StartLabel->isDefined() &&
477 "Invalid starting label for an inlined scope!");
478 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
480 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
483 InlinedSubprogramDIEs.insert(OriginDIE);
485 // Add the call site information to the DIE.
486 DILocation DL(Scope->getInlinedAt());
487 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
488 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
489 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
491 // Add name to the name table, we do this here because we're guaranteed
492 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
493 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
498 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit &TheCU,
500 SmallVectorImpl<DIE *> &Children) {
501 DIE *ObjectPointer = NULL;
503 // Collect arguments for current function.
504 if (LScopes.isCurrentFunctionScope(Scope)) {
505 for (DbgVariable *ArgDV : CurrentFnArguments)
508 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
509 Children.push_back(Arg);
510 if (ArgDV->isObjectPointer())
514 // If this is a variadic function, add an unspecified parameter.
515 DISubprogram SP(Scope->getScopeNode());
516 DIArray FnArgs = SP.getType().getTypeArray();
517 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
518 .isUnspecifiedParameter()) {
519 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
520 Children.push_back(Ellipsis);
524 // Collect lexical scope children first.
525 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
527 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope())) {
528 Children.push_back(Variable);
529 if (DV->isObjectPointer())
530 ObjectPointer = Variable;
532 for (LexicalScope *LS : Scope->getChildren())
533 if (DIE *Nested = constructScopeDIE(TheCU, LS))
534 Children.push_back(Nested);
535 return ObjectPointer;
538 // Construct a DIE for this scope.
539 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
540 LexicalScope *Scope) {
541 if (!Scope || !Scope->getScopeNode())
544 DIScope DS(Scope->getScopeNode());
546 SmallVector<DIE *, 8> Children;
547 DIE *ObjectPointer = NULL;
548 bool ChildrenCreated = false;
550 // We try to create the scope DIE first, then the children DIEs. This will
551 // avoid creating un-used children then removing them later when we find out
552 // the scope DIE is null.
553 DIE *ScopeDIE = NULL;
554 if (Scope->getInlinedAt())
555 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
556 else if (DS.isSubprogram()) {
557 ProcessedSPNodes.insert(DS);
558 if (Scope->isAbstractScope()) {
559 ScopeDIE = TheCU.getDIE(DS);
560 // Note down abstract DIE.
562 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
564 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
566 // Early exit when we know the scope DIE is going to be null.
567 if (isLexicalScopeDIENull(Scope))
570 // We create children here when we know the scope DIE is not going to be
571 // null and the children will be added to the scope DIE.
572 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
573 ChildrenCreated = true;
575 // There is no need to emit empty lexical block DIE.
576 std::pair<ImportedEntityMap::const_iterator,
577 ImportedEntityMap::const_iterator> Range =
579 ScopesWithImportedEntities.begin(),
580 ScopesWithImportedEntities.end(),
581 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
583 if (Children.empty() && Range.first == Range.second)
585 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
586 assert(ScopeDIE && "Scope DIE should not be null.");
587 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
589 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
593 assert(Children.empty() &&
594 "We create children only when the scope DIE is not null.");
597 if (!ChildrenCreated)
598 // We create children when the scope DIE is not null.
599 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
602 for (DIE *I : Children)
603 ScopeDIE->addChild(I);
605 if (DS.isSubprogram() && ObjectPointer != NULL)
606 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
611 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE *D) const {
612 if (!GenerateGnuPubSections)
615 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
618 // Create new DwarfCompileUnit for the given metadata node with tag
619 // DW_TAG_compile_unit.
620 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
621 StringRef FN = DIUnit.getFilename();
622 CompilationDir = DIUnit.getDirectory();
624 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
625 auto OwnedUnit = make_unique<DwarfCompileUnit>(
626 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
627 DwarfCompileUnit &NewCU = *OwnedUnit;
628 InfoHolder.addUnit(std::move(OwnedUnit));
630 // LTO with assembly output shares a single line table amongst multiple CUs.
631 // To avoid the compilation directory being ambiguous, let the line table
632 // explicitly describe the directory of all files, never relying on the
633 // compilation directory.
634 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
635 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
636 NewCU.getUniqueID(), CompilationDir);
638 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
639 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
640 DIUnit.getLanguage());
641 NewCU.addString(Die, dwarf::DW_AT_name, FN);
643 if (!useSplitDwarf()) {
644 NewCU.initStmtList(DwarfLineSectionSym);
646 // If we're using split dwarf the compilation dir is going to be in the
647 // skeleton CU and so we don't need to duplicate it here.
648 if (!CompilationDir.empty())
649 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
651 addGnuPubAttributes(NewCU, Die);
654 if (DIUnit.isOptimized())
655 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
657 StringRef Flags = DIUnit.getFlags();
659 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
661 if (unsigned RVer = DIUnit.getRunTimeVersion())
662 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
663 dwarf::DW_FORM_data1, RVer);
668 if (useSplitDwarf()) {
669 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
670 DwarfInfoDWOSectionSym);
671 NewCU.setSkeleton(constructSkeletonCU(NewCU));
673 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
674 DwarfInfoSectionSym);
676 CUMap.insert(std::make_pair(DIUnit, &NewCU));
677 CUDieMap.insert(std::make_pair(Die, &NewCU));
681 // Construct subprogram DIE.
682 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
684 // FIXME: We should only call this routine once, however, during LTO if a
685 // program is defined in multiple CUs we could end up calling it out of
686 // beginModule as we walk the CUs.
688 DwarfCompileUnit *&CURef = SPMap[N];
694 if (!SP.isDefinition())
695 // This is a method declaration which will be handled while constructing
699 DIE *SubprogramDie = TheCU.getOrCreateSubprogramDIE(SP);
701 // Expose as a global name.
702 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
705 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
707 DIImportedEntity Module(N);
708 assert(Module.Verify());
709 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
710 constructImportedEntityDIE(TheCU, Module, D);
713 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
714 const MDNode *N, DIE *Context) {
715 DIImportedEntity Module(N);
716 assert(Module.Verify());
717 return constructImportedEntityDIE(TheCU, Module, Context);
720 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
721 const DIImportedEntity &Module,
723 assert(Module.Verify() &&
724 "Use one of the MDNode * overloads to handle invalid metadata");
725 assert(Context && "Should always have a context for an imported_module");
726 DIE *IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
728 DIDescriptor Entity = resolve(Module.getEntity());
729 if (Entity.isNameSpace())
730 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
731 else if (Entity.isSubprogram())
732 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
733 else if (Entity.isType())
734 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
736 EntityDie = TheCU.getDIE(Entity);
737 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
738 Module.getContext().getFilename(),
739 Module.getContext().getDirectory());
740 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
741 StringRef Name = Module.getName();
743 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
746 // Emit all Dwarf sections that should come prior to the content. Create
747 // global DIEs and emit initial debug info sections. This is invoked by
748 // the target AsmPrinter.
749 void DwarfDebug::beginModule() {
750 if (DisableDebugInfoPrinting)
753 const Module *M = MMI->getModule();
755 // If module has named metadata anchors then use them, otherwise scan the
756 // module using debug info finder to collect debug info.
757 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
760 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
762 // Emit initial sections so we can reference labels later.
765 SingleCU = CU_Nodes->getNumOperands() == 1;
767 for (MDNode *N : CU_Nodes->operands()) {
768 DICompileUnit CUNode(N);
769 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
770 DIArray ImportedEntities = CUNode.getImportedEntities();
771 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
772 ScopesWithImportedEntities.push_back(std::make_pair(
773 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
774 ImportedEntities.getElement(i)));
775 std::sort(ScopesWithImportedEntities.begin(),
776 ScopesWithImportedEntities.end(), less_first());
777 DIArray GVs = CUNode.getGlobalVariables();
778 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
779 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
780 DIArray SPs = CUNode.getSubprograms();
781 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
782 constructSubprogramDIE(CU, SPs.getElement(i));
783 DIArray EnumTypes = CUNode.getEnumTypes();
784 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
785 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
786 DIArray RetainedTypes = CUNode.getRetainedTypes();
787 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
788 DIType Ty(RetainedTypes.getElement(i));
789 // The retained types array by design contains pointers to
790 // MDNodes rather than DIRefs. Unique them here.
791 DIType UniqueTy(resolve(Ty.getRef()));
792 CU.getOrCreateTypeDIE(UniqueTy);
794 // Emit imported_modules last so that the relevant context is already
796 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
797 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
800 // Tell MMI that we have debug info.
801 MMI->setDebugInfoAvailability(true);
803 // Prime section data.
804 SectionMap[Asm->getObjFileLowering().getTextSection()];
807 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
808 void DwarfDebug::computeInlinedDIEs() {
809 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
810 for (DIE *ISP : InlinedSubprogramDIEs)
811 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
813 for (const auto &AI : AbstractSPDies) {
814 DIE *ISP = AI.second;
815 if (InlinedSubprogramDIEs.count(ISP))
817 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
821 // Collect info for variables that were optimized out.
822 void DwarfDebug::collectDeadVariables() {
823 const Module *M = MMI->getModule();
825 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
826 for (MDNode *N : CU_Nodes->operands()) {
827 DICompileUnit TheCU(N);
828 DIArray Subprograms = TheCU.getSubprograms();
829 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
830 DISubprogram SP(Subprograms.getElement(i));
831 if (ProcessedSPNodes.count(SP) != 0)
833 if (!SP.isSubprogram())
835 if (!SP.isDefinition())
837 DIArray Variables = SP.getVariables();
838 if (Variables.getNumElements() == 0)
841 // Construct subprogram DIE and add variables DIEs.
842 DwarfCompileUnit *SPCU =
843 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
844 assert(SPCU && "Unable to find Compile Unit!");
845 // FIXME: See the comment in constructSubprogramDIE about duplicate
847 constructSubprogramDIE(*SPCU, SP);
848 DIE *SPDIE = SPCU->getDIE(SP);
849 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
850 DIVariable DV(Variables.getElement(vi));
851 if (!DV.isVariable())
853 DbgVariable NewVar(DV, NULL, this);
854 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
855 SPDIE->addChild(VariableDIE);
862 void DwarfDebug::finalizeModuleInfo() {
863 // Collect info for variables that were optimized out.
864 collectDeadVariables();
866 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
867 computeInlinedDIEs();
869 // Handle anything that needs to be done on a per-unit basis after
870 // all other generation.
871 for (const auto &TheU : getUnits()) {
872 // Emit DW_AT_containing_type attribute to connect types with their
873 // vtable holding type.
874 TheU->constructContainingTypeDIEs();
876 // Add CU specific attributes if we need to add any.
877 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
878 // If we're splitting the dwarf out now that we've got the entire
879 // CU then add the dwo id to it.
880 DwarfCompileUnit *SkCU =
881 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
882 if (useSplitDwarf()) {
883 // Emit a unique identifier for this CU.
884 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
885 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
886 dwarf::DW_FORM_data8, ID);
887 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
888 dwarf::DW_FORM_data8, ID);
890 // We don't keep track of which addresses are used in which CU so this
891 // is a bit pessimistic under LTO.
892 if (!AddrPool.isEmpty())
893 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
894 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
895 DwarfAddrSectionSym);
896 if (!TheU->getRangeLists().empty())
897 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
898 dwarf::DW_AT_GNU_ranges_base,
899 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
902 // If we have code split among multiple sections or non-contiguous
903 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
904 // remain in the .o file, otherwise add a DW_AT_low_pc.
905 // FIXME: We should use ranges allow reordering of code ala
906 // .subsections_via_symbols in mach-o. This would mean turning on
907 // ranges for all subprogram DIEs for mach-o.
908 DwarfCompileUnit &U =
909 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
910 unsigned NumRanges = TheU->getRanges().size();
913 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
914 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
915 DwarfDebugRangeSectionSym);
917 // A DW_AT_low_pc attribute may also be specified in combination with
918 // DW_AT_ranges to specify the default base address for use in
919 // location lists (see Section 2.6.2) and range lists (see Section
921 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
924 RangeSpan &Range = TheU->getRanges().back();
925 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
927 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
934 // Compute DIE offsets and sizes.
935 InfoHolder.computeSizeAndOffsets();
937 SkeletonHolder.computeSizeAndOffsets();
940 void DwarfDebug::endSections() {
941 // Filter labels by section.
942 for (const SymbolCU &SCU : ArangeLabels) {
943 if (SCU.Sym->isInSection()) {
944 // Make a note of this symbol and it's section.
945 const MCSection *Section = &SCU.Sym->getSection();
946 if (!Section->getKind().isMetadata())
947 SectionMap[Section].push_back(SCU);
949 // Some symbols (e.g. common/bss on mach-o) can have no section but still
950 // appear in the output. This sucks as we rely on sections to build
951 // arange spans. We can do it without, but it's icky.
952 SectionMap[NULL].push_back(SCU);
956 // Build a list of sections used.
957 std::vector<const MCSection *> Sections;
958 for (const auto &it : SectionMap) {
959 const MCSection *Section = it.first;
960 Sections.push_back(Section);
963 // Sort the sections into order.
964 // This is only done to ensure consistent output order across different runs.
965 std::sort(Sections.begin(), Sections.end(), SectionSort);
967 // Add terminating symbols for each section.
968 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
969 const MCSection *Section = Sections[ID];
970 MCSymbol *Sym = NULL;
973 // We can't call MCSection::getLabelEndName, as it's only safe to do so
974 // if we know the section name up-front. For user-created sections, the
975 // resulting label may not be valid to use as a label. (section names can
976 // use a greater set of characters on some systems)
977 Sym = Asm->GetTempSymbol("debug_end", ID);
978 Asm->OutStreamer.SwitchSection(Section);
979 Asm->OutStreamer.EmitLabel(Sym);
982 // Insert a final terminator.
983 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
987 // Emit all Dwarf sections that should come after the content.
988 void DwarfDebug::endModule() {
995 // End any existing sections.
996 // TODO: Does this need to happen?
999 // Finalize the debug info for the module.
1000 finalizeModuleInfo();
1004 // Emit all the DIEs into a debug info section.
1007 // Corresponding abbreviations into a abbrev section.
1008 emitAbbreviations();
1010 // Emit info into a debug aranges section.
1011 if (GenerateARangeSection)
1014 // Emit info into a debug ranges section.
1017 if (useSplitDwarf()) {
1020 emitDebugAbbrevDWO();
1022 // Emit DWO addresses.
1023 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1026 // Emit info into a debug loc section.
1029 // Emit info into the dwarf accelerator table sections.
1030 if (useDwarfAccelTables()) {
1033 emitAccelNamespaces();
1037 // Emit the pubnames and pubtypes sections if requested.
1038 if (HasDwarfPubSections) {
1039 emitDebugPubNames(GenerateGnuPubSections);
1040 emitDebugPubTypes(GenerateGnuPubSections);
1046 // Reset these for the next Module if we have one.
1050 // Find abstract variable, if any, associated with Var.
1051 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1052 DebugLoc ScopeLoc) {
1053 LLVMContext &Ctx = DV->getContext();
1054 // More then one inlined variable corresponds to one abstract variable.
1055 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1056 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1058 return AbsDbgVariable;
1060 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1064 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1065 addScopeVariable(Scope, AbsDbgVariable);
1066 AbstractVariables[Var] = AbsDbgVariable;
1067 return AbsDbgVariable;
1070 // If Var is a current function argument then add it to CurrentFnArguments list.
1071 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1072 if (!LScopes.isCurrentFunctionScope(Scope))
1074 DIVariable DV = Var->getVariable();
1075 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1077 unsigned ArgNo = DV.getArgNumber();
1081 size_t Size = CurrentFnArguments.size();
1083 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1084 // llvm::Function argument size is not good indicator of how many
1085 // arguments does the function have at source level.
1087 CurrentFnArguments.resize(ArgNo * 2);
1088 CurrentFnArguments[ArgNo - 1] = Var;
1092 // Collect variable information from side table maintained by MMI.
1093 void DwarfDebug::collectVariableInfoFromMMITable(
1094 SmallPtrSet<const MDNode *, 16> &Processed) {
1095 for (const auto &VI : MMI->getVariableDbgInfo()) {
1098 Processed.insert(VI.Var);
1099 DIVariable DV(VI.Var);
1100 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1102 // If variable scope is not found then skip this variable.
1106 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1107 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1108 RegVar->setFrameIndex(VI.Slot);
1109 if (!addCurrentFnArgument(RegVar, Scope))
1110 addScopeVariable(Scope, RegVar);
1112 AbsDbgVariable->setFrameIndex(VI.Slot);
1116 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1118 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1119 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1120 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1121 MI->getOperand(0).getReg() &&
1122 (MI->getOperand(1).isImm() ||
1123 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1126 // Get .debug_loc entry for the instruction range starting at MI.
1127 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1128 const MCSymbol *FLabel,
1129 const MCSymbol *SLabel,
1130 const MachineInstr *MI,
1131 DwarfCompileUnit *Unit) {
1132 const MDNode *Var = MI->getDebugVariable();
1134 assert(MI->getNumOperands() == 3);
1135 if (MI->getOperand(0).isReg()) {
1136 MachineLocation MLoc;
1137 // If the second operand is an immediate, this is a
1138 // register-indirect address.
1139 if (!MI->getOperand(1).isImm())
1140 MLoc.set(MI->getOperand(0).getReg());
1142 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1143 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1145 if (MI->getOperand(0).isImm())
1146 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1147 if (MI->getOperand(0).isFPImm())
1148 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1150 if (MI->getOperand(0).isCImm())
1151 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1154 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1157 // Find variables for each lexical scope.
1159 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1161 // Grab the variable info that was squirreled away in the MMI side-table.
1162 collectVariableInfoFromMMITable(Processed);
1164 for (const MDNode *Var : UserVariables) {
1165 if (Processed.count(Var))
1168 // History contains relevant DBG_VALUE instructions for Var and instructions
1170 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1171 if (History.empty())
1173 const MachineInstr *MInsn = History.front();
1176 LexicalScope *Scope = NULL;
1177 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1178 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1179 Scope = LScopes.getCurrentFunctionScope();
1180 else if (MDNode *IA = DV.getInlinedAt())
1181 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1183 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1184 // If variable scope is not found then skip this variable.
1188 Processed.insert(DV);
1189 assert(MInsn->isDebugValue() && "History must begin with debug value");
1190 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1191 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1192 if (!addCurrentFnArgument(RegVar, Scope))
1193 addScopeVariable(Scope, RegVar);
1195 AbsVar->setMInsn(MInsn);
1197 // Simplify ranges that are fully coalesced.
1198 if (History.size() <= 1 ||
1199 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1200 RegVar->setMInsn(MInsn);
1204 // Handle multiple DBG_VALUE instructions describing one variable.
1205 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1207 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1208 DebugLocList &LocList = DotDebugLocEntries.back();
1210 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1211 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1212 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1213 HI = History.begin(),
1216 const MachineInstr *Begin = *HI;
1217 assert(Begin->isDebugValue() && "Invalid History entry");
1219 // Check if DBG_VALUE is truncating a range.
1220 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1221 !Begin->getOperand(0).getReg())
1224 // Compute the range for a register location.
1225 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1226 const MCSymbol *SLabel = 0;
1229 // If Begin is the last instruction in History then its value is valid
1230 // until the end of the function.
1231 SLabel = FunctionEndSym;
1233 const MachineInstr *End = HI[1];
1234 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1235 << "\t" << *Begin << "\t" << *End << "\n");
1236 if (End->isDebugValue())
1237 SLabel = getLabelBeforeInsn(End);
1239 // End is a normal instruction clobbering the range.
1240 SLabel = getLabelAfterInsn(End);
1241 assert(SLabel && "Forgot label after clobber instruction");
1246 // The value is valid until the next DBG_VALUE or clobber.
1247 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1248 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1249 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1250 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1251 DebugLoc.push_back(std::move(Loc));
1255 // Collect info for variables that were optimized out.
1256 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1257 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1258 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1259 DIVariable DV(Variables.getElement(i));
1260 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1262 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1263 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1267 // Return Label preceding the instruction.
1268 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1269 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1270 assert(Label && "Didn't insert label before instruction");
1274 // Return Label immediately following the instruction.
1275 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1276 return LabelsAfterInsn.lookup(MI);
1279 // Process beginning of an instruction.
1280 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1283 // Check if source location changes, but ignore DBG_VALUE locations.
1284 if (!MI->isDebugValue()) {
1285 DebugLoc DL = MI->getDebugLoc();
1286 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1289 if (DL == PrologEndLoc) {
1290 Flags |= DWARF2_FLAG_PROLOGUE_END;
1291 PrologEndLoc = DebugLoc();
1293 if (PrologEndLoc.isUnknown())
1294 Flags |= DWARF2_FLAG_IS_STMT;
1296 if (!DL.isUnknown()) {
1297 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1298 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1300 recordSourceLine(0, 0, 0, 0);
1304 // Insert labels where requested.
1305 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1306 LabelsBeforeInsn.find(MI);
1309 if (I == LabelsBeforeInsn.end())
1312 // Label already assigned.
1317 PrevLabel = MMI->getContext().CreateTempSymbol();
1318 Asm->OutStreamer.EmitLabel(PrevLabel);
1320 I->second = PrevLabel;
1323 // Process end of an instruction.
1324 void DwarfDebug::endInstruction() {
1326 // Don't create a new label after DBG_VALUE instructions.
1327 // They don't generate code.
1328 if (!CurMI->isDebugValue())
1331 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1332 LabelsAfterInsn.find(CurMI);
1336 if (I == LabelsAfterInsn.end())
1339 // Label already assigned.
1343 // We need a label after this instruction.
1345 PrevLabel = MMI->getContext().CreateTempSymbol();
1346 Asm->OutStreamer.EmitLabel(PrevLabel);
1348 I->second = PrevLabel;
1351 // Each LexicalScope has first instruction and last instruction to mark
1352 // beginning and end of a scope respectively. Create an inverse map that list
1353 // scopes starts (and ends) with an instruction. One instruction may start (or
1354 // end) multiple scopes. Ignore scopes that are not reachable.
1355 void DwarfDebug::identifyScopeMarkers() {
1356 SmallVector<LexicalScope *, 4> WorkList;
1357 WorkList.push_back(LScopes.getCurrentFunctionScope());
1358 while (!WorkList.empty()) {
1359 LexicalScope *S = WorkList.pop_back_val();
1361 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1362 if (!Children.empty())
1363 WorkList.append(Children.begin(), Children.end());
1365 if (S->isAbstractScope())
1368 for (const InsnRange &R : S->getRanges()) {
1369 assert(R.first && "InsnRange does not have first instruction!");
1370 assert(R.second && "InsnRange does not have second instruction!");
1371 requestLabelBeforeInsn(R.first);
1372 requestLabelAfterInsn(R.second);
1377 // Gather pre-function debug information. Assumes being called immediately
1378 // after the function entry point has been emitted.
1379 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1382 // If there's no debug info for the function we're not going to do anything.
1383 if (!MMI->hasDebugInfo())
1386 // Grab the lexical scopes for the function, if we don't have any of those
1387 // then we're not going to be able to do anything.
1388 LScopes.initialize(*MF);
1389 if (LScopes.empty())
1392 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1394 // Make sure that each lexical scope will have a begin/end label.
1395 identifyScopeMarkers();
1397 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1398 // belongs to so that we add to the correct per-cu line table in the
1400 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1401 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1402 assert(TheCU && "Unable to find compile unit!");
1403 if (Asm->OutStreamer.hasRawTextSupport())
1404 // Use a single line table if we are generating assembly.
1405 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1407 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1409 // Emit a label for the function so that we have a beginning address.
1410 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1411 // Assumes in correct section after the entry point.
1412 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1414 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1415 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1416 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1418 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1420 bool AtBlockEntry = true;
1421 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1423 const MachineInstr *MI = II;
1425 if (MI->isDebugValue()) {
1426 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1428 // Keep track of user variables.
1429 const MDNode *Var = MI->getDebugVariable();
1431 // Variable is in a register, we need to check for clobbers.
1432 if (isDbgValueInDefinedReg(MI))
1433 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1435 // Check the history of this variable.
1436 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1437 if (History.empty()) {
1438 UserVariables.push_back(Var);
1439 // The first mention of a function argument gets the FunctionBeginSym
1440 // label, so arguments are visible when breaking at function entry.
1442 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1443 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1444 LabelsBeforeInsn[MI] = FunctionBeginSym;
1446 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1447 const MachineInstr *Prev = History.back();
1448 if (Prev->isDebugValue()) {
1449 // Coalesce identical entries at the end of History.
1450 if (History.size() >= 2 &&
1451 Prev->isIdenticalTo(History[History.size() - 2])) {
1452 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1453 << "\t" << *Prev << "\t"
1454 << *History[History.size() - 2] << "\n");
1458 // Terminate old register assignments that don't reach MI;
1459 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1460 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1461 isDbgValueInDefinedReg(Prev)) {
1462 // Previous register assignment needs to terminate at the end of
1464 MachineBasicBlock::const_iterator LastMI =
1465 PrevMBB->getLastNonDebugInstr();
1466 if (LastMI == PrevMBB->end()) {
1467 // Drop DBG_VALUE for empty range.
1468 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1469 << "\t" << *Prev << "\n");
1471 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1472 // Terminate after LastMI.
1473 History.push_back(LastMI);
1477 History.push_back(MI);
1479 // Not a DBG_VALUE instruction.
1480 if (!MI->isPosition())
1481 AtBlockEntry = false;
1483 // First known non-DBG_VALUE and non-frame setup location marks
1484 // the beginning of the function body.
1485 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1486 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1487 PrologEndLoc = MI->getDebugLoc();
1489 // Check if the instruction clobbers any registers with debug vars.
1490 for (const MachineOperand &MO : MI->operands()) {
1491 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1493 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1496 const MDNode *Var = LiveUserVar[Reg];
1499 // Reg is now clobbered.
1500 LiveUserVar[Reg] = 0;
1502 // Was MD last defined by a DBG_VALUE referring to Reg?
1503 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1504 if (HistI == DbgValues.end())
1506 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1507 if (History.empty())
1509 const MachineInstr *Prev = History.back();
1510 // Sanity-check: Register assignments are terminated at the end of
1512 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1514 // Is the variable still in Reg?
1515 if (!isDbgValueInDefinedReg(Prev) ||
1516 Prev->getOperand(0).getReg() != Reg)
1518 // Var is clobbered. Make sure the next instruction gets a label.
1519 History.push_back(MI);
1526 for (auto &I : DbgValues) {
1527 SmallVectorImpl<const MachineInstr *> &History = I.second;
1528 if (History.empty())
1531 // Make sure the final register assignments are terminated.
1532 const MachineInstr *Prev = History.back();
1533 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1534 const MachineBasicBlock *PrevMBB = Prev->getParent();
1535 MachineBasicBlock::const_iterator LastMI =
1536 PrevMBB->getLastNonDebugInstr();
1537 if (LastMI == PrevMBB->end())
1538 // Drop DBG_VALUE for empty range.
1540 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1541 // Terminate after LastMI.
1542 History.push_back(LastMI);
1545 // Request labels for the full history.
1546 for (const MachineInstr *MI : History) {
1547 if (MI->isDebugValue())
1548 requestLabelBeforeInsn(MI);
1550 requestLabelAfterInsn(MI);
1554 PrevInstLoc = DebugLoc();
1555 PrevLabel = FunctionBeginSym;
1557 // Record beginning of function.
1558 if (!PrologEndLoc.isUnknown()) {
1559 DebugLoc FnStartDL =
1560 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1562 FnStartDL.getLine(), FnStartDL.getCol(),
1563 FnStartDL.getScope(MF->getFunction()->getContext()),
1564 // We'd like to list the prologue as "not statements" but GDB behaves
1565 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1566 DWARF2_FLAG_IS_STMT);
1570 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1571 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1572 DIVariable DV = Var->getVariable();
1573 // Variables with positive arg numbers are parameters.
1574 if (unsigned ArgNum = DV.getArgNumber()) {
1575 // Keep all parameters in order at the start of the variable list to ensure
1576 // function types are correct (no out-of-order parameters)
1578 // This could be improved by only doing it for optimized builds (unoptimized
1579 // builds have the right order to begin with), searching from the back (this
1580 // would catch the unoptimized case quickly), or doing a binary search
1581 // rather than linear search.
1582 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1583 while (I != Vars.end()) {
1584 unsigned CurNum = (*I)->getVariable().getArgNumber();
1585 // A local (non-parameter) variable has been found, insert immediately
1589 // A later indexed parameter has been found, insert immediately before it.
1590 if (CurNum > ArgNum)
1594 Vars.insert(I, Var);
1598 Vars.push_back(Var);
1601 // Gather and emit post-function debug information.
1602 void DwarfDebug::endFunction(const MachineFunction *MF) {
1603 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1604 // though the beginFunction may not be called at all.
1605 // We should handle both cases.
1609 assert(CurFn == MF);
1612 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1613 // If we don't have a lexical scope for this function then there will
1614 // be a hole in the range information. Keep note of this by setting the
1615 // previously used section to nullptr.
1616 PrevSection = nullptr;
1622 // Define end label for subprogram.
1623 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1624 // Assumes in correct section after the entry point.
1625 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1627 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1628 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1630 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1631 collectVariableInfo(ProcessedVars);
1633 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1634 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1636 // Construct abstract scopes.
1637 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1638 DISubprogram SP(AScope->getScopeNode());
1639 if (SP.isSubprogram()) {
1640 // Collect info for variables that were optimized out.
1641 DIArray Variables = SP.getVariables();
1642 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1643 DIVariable DV(Variables.getElement(i));
1644 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1646 // Check that DbgVariable for DV wasn't created earlier, when
1647 // findAbstractVariable() was called for inlined instance of DV.
1648 LLVMContext &Ctx = DV->getContext();
1649 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1650 if (AbstractVariables.lookup(CleanDV))
1652 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1653 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1656 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1657 constructScopeDIE(TheCU, AScope);
1660 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1661 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1662 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1664 // Add the range of this function to the list of ranges for the CU.
1665 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1666 TheCU.addRange(std::move(Span));
1667 PrevSection = Asm->getCurrentSection();
1671 for (auto &I : ScopeVariables)
1672 DeleteContainerPointers(I.second);
1673 ScopeVariables.clear();
1674 DeleteContainerPointers(CurrentFnArguments);
1675 UserVariables.clear();
1677 AbstractVariables.clear();
1678 LabelsBeforeInsn.clear();
1679 LabelsAfterInsn.clear();
1684 // Register a source line with debug info. Returns the unique label that was
1685 // emitted and which provides correspondence to the source line list.
1686 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1691 unsigned Discriminator = 0;
1693 DIDescriptor Scope(S);
1695 if (Scope.isCompileUnit()) {
1696 DICompileUnit CU(S);
1697 Fn = CU.getFilename();
1698 Dir = CU.getDirectory();
1699 } else if (Scope.isFile()) {
1701 Fn = F.getFilename();
1702 Dir = F.getDirectory();
1703 } else if (Scope.isSubprogram()) {
1705 Fn = SP.getFilename();
1706 Dir = SP.getDirectory();
1707 } else if (Scope.isLexicalBlockFile()) {
1708 DILexicalBlockFile DBF(S);
1709 Fn = DBF.getFilename();
1710 Dir = DBF.getDirectory();
1711 } else if (Scope.isLexicalBlock()) {
1712 DILexicalBlock DB(S);
1713 Fn = DB.getFilename();
1714 Dir = DB.getDirectory();
1715 Discriminator = DB.getDiscriminator();
1717 llvm_unreachable("Unexpected scope info");
1719 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1720 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1721 .getOrCreateSourceID(Fn, Dir);
1723 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1727 //===----------------------------------------------------------------------===//
1729 //===----------------------------------------------------------------------===//
1731 // Emit initial Dwarf sections with a label at the start of each one.
1732 void DwarfDebug::emitSectionLabels() {
1733 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1735 // Dwarf sections base addresses.
1736 DwarfInfoSectionSym =
1737 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1738 if (useSplitDwarf())
1739 DwarfInfoDWOSectionSym =
1740 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1741 DwarfAbbrevSectionSym =
1742 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1743 if (useSplitDwarf())
1744 DwarfAbbrevDWOSectionSym = emitSectionSym(
1745 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1746 if (GenerateARangeSection)
1747 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1749 DwarfLineSectionSym =
1750 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1751 if (GenerateGnuPubSections) {
1752 DwarfGnuPubNamesSectionSym =
1753 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1754 DwarfGnuPubTypesSectionSym =
1755 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1756 } else if (HasDwarfPubSections) {
1757 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1758 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1761 DwarfStrSectionSym =
1762 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1763 if (useSplitDwarf()) {
1764 DwarfStrDWOSectionSym =
1765 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1766 DwarfAddrSectionSym =
1767 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1768 DwarfDebugLocSectionSym =
1769 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1771 DwarfDebugLocSectionSym =
1772 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1773 DwarfDebugRangeSectionSym =
1774 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1777 // Recursively emits a debug information entry.
1778 void DwarfDebug::emitDIE(DIE &Die) {
1779 // Get the abbreviation for this DIE.
1780 const DIEAbbrev &Abbrev = Die.getAbbrev();
1782 // Emit the code (index) for the abbreviation.
1783 if (Asm->isVerbose())
1784 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1785 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1786 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1787 dwarf::TagString(Abbrev.getTag()));
1788 Asm->EmitULEB128(Abbrev.getNumber());
1790 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1791 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1793 // Emit the DIE attribute values.
1794 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1795 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1796 dwarf::Form Form = AbbrevData[i].getForm();
1797 assert(Form && "Too many attributes for DIE (check abbreviation)");
1799 if (Asm->isVerbose()) {
1800 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1801 if (Attr == dwarf::DW_AT_accessibility)
1802 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1803 cast<DIEInteger>(Values[i])->getValue()));
1806 // Emit an attribute using the defined form.
1807 Values[i]->EmitValue(Asm, Form);
1810 // Emit the DIE children if any.
1811 if (Abbrev.hasChildren()) {
1812 for (auto &Child : Die.getChildren())
1815 Asm->OutStreamer.AddComment("End Of Children Mark");
1820 // Emit the debug info section.
1821 void DwarfDebug::emitDebugInfo() {
1822 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1824 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1827 // Emit the abbreviation section.
1828 void DwarfDebug::emitAbbreviations() {
1829 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1831 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1834 // Emit the last address of the section and the end of the line matrix.
1835 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1836 // Define last address of section.
1837 Asm->OutStreamer.AddComment("Extended Op");
1840 Asm->OutStreamer.AddComment("Op size");
1841 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1842 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1843 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1845 Asm->OutStreamer.AddComment("Section end label");
1847 Asm->OutStreamer.EmitSymbolValue(
1848 Asm->GetTempSymbol("section_end", SectionEnd),
1849 Asm->getDataLayout().getPointerSize());
1851 // Mark end of matrix.
1852 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1858 // Emit visible names into a hashed accelerator table section.
1859 void DwarfDebug::emitAccelNames() {
1861 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1862 for (const auto &TheU : getUnits()) {
1863 for (const auto &GI : TheU->getAccelNames()) {
1864 StringRef Name = GI.getKey();
1865 for (const DIE *D : GI.second)
1866 AT.AddName(Name, D);
1870 AT.FinalizeTable(Asm, "Names");
1871 Asm->OutStreamer.SwitchSection(
1872 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1873 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1874 Asm->OutStreamer.EmitLabel(SectionBegin);
1876 // Emit the full data.
1877 AT.Emit(Asm, SectionBegin, &InfoHolder);
1880 // Emit objective C classes and categories into a hashed accelerator table
1882 void DwarfDebug::emitAccelObjC() {
1884 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1885 for (const auto &TheU : getUnits()) {
1886 for (const auto &GI : TheU->getAccelObjC()) {
1887 StringRef Name = GI.getKey();
1888 for (const DIE *D : GI.second)
1889 AT.AddName(Name, D);
1893 AT.FinalizeTable(Asm, "ObjC");
1894 Asm->OutStreamer.SwitchSection(
1895 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1896 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1897 Asm->OutStreamer.EmitLabel(SectionBegin);
1899 // Emit the full data.
1900 AT.Emit(Asm, SectionBegin, &InfoHolder);
1903 // Emit namespace dies into a hashed accelerator table.
1904 void DwarfDebug::emitAccelNamespaces() {
1906 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1907 for (const auto &TheU : getUnits()) {
1908 for (const auto &GI : TheU->getAccelNamespace()) {
1909 StringRef Name = GI.getKey();
1910 for (const DIE *D : GI.second)
1911 AT.AddName(Name, D);
1915 AT.FinalizeTable(Asm, "namespac");
1916 Asm->OutStreamer.SwitchSection(
1917 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1918 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1919 Asm->OutStreamer.EmitLabel(SectionBegin);
1921 // Emit the full data.
1922 AT.Emit(Asm, SectionBegin, &InfoHolder);
1925 // Emit type dies into a hashed accelerator table.
1926 void DwarfDebug::emitAccelTypes() {
1927 DwarfAccelTable::Atom Atoms[] = {
1928 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
1929 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
1930 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
1931 DwarfAccelTable AT(Atoms);
1932 for (const auto &TheU : getUnits()) {
1933 for (const auto &GI : TheU->getAccelTypes()) {
1934 StringRef Name = GI.getKey();
1935 for (const auto &DI : GI.second)
1936 AT.AddName(Name, DI.first, DI.second);
1940 AT.FinalizeTable(Asm, "types");
1941 Asm->OutStreamer.SwitchSection(
1942 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1943 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1944 Asm->OutStreamer.EmitLabel(SectionBegin);
1946 // Emit the full data.
1947 AT.Emit(Asm, SectionBegin, &InfoHolder);
1950 // Public name handling.
1951 // The format for the various pubnames:
1953 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1954 // for the DIE that is named.
1956 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1957 // into the CU and the index value is computed according to the type of value
1958 // for the DIE that is named.
1960 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1961 // it's the offset within the debug_info/debug_types dwo section, however, the
1962 // reference in the pubname header doesn't change.
1964 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1965 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1967 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1969 // We could have a specification DIE that has our most of our knowledge,
1970 // look for that now.
1971 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1973 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1974 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
1975 Linkage = dwarf::GIEL_EXTERNAL;
1976 } else if (Die->findAttribute(dwarf::DW_AT_external))
1977 Linkage = dwarf::GIEL_EXTERNAL;
1979 switch (Die->getTag()) {
1980 case dwarf::DW_TAG_class_type:
1981 case dwarf::DW_TAG_structure_type:
1982 case dwarf::DW_TAG_union_type:
1983 case dwarf::DW_TAG_enumeration_type:
1984 return dwarf::PubIndexEntryDescriptor(
1985 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1986 ? dwarf::GIEL_STATIC
1987 : dwarf::GIEL_EXTERNAL);
1988 case dwarf::DW_TAG_typedef:
1989 case dwarf::DW_TAG_base_type:
1990 case dwarf::DW_TAG_subrange_type:
1991 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1992 case dwarf::DW_TAG_namespace:
1993 return dwarf::GIEK_TYPE;
1994 case dwarf::DW_TAG_subprogram:
1995 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1996 case dwarf::DW_TAG_constant:
1997 case dwarf::DW_TAG_variable:
1998 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1999 case dwarf::DW_TAG_enumerator:
2000 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2001 dwarf::GIEL_STATIC);
2003 return dwarf::GIEK_NONE;
2007 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2009 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2010 const MCSection *PSec =
2011 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2012 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2014 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2017 void DwarfDebug::emitDebugPubSection(
2018 bool GnuStyle, const MCSection *PSec, StringRef Name,
2019 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2020 for (const auto &NU : CUMap) {
2021 DwarfCompileUnit *TheU = NU.second;
2023 const auto &Globals = (TheU->*Accessor)();
2025 if (Globals.empty())
2028 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2030 unsigned ID = TheU->getUniqueID();
2032 // Start the dwarf pubnames section.
2033 Asm->OutStreamer.SwitchSection(PSec);
2036 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2037 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2038 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2039 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2041 Asm->OutStreamer.EmitLabel(BeginLabel);
2043 Asm->OutStreamer.AddComment("DWARF Version");
2044 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2046 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2047 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2049 Asm->OutStreamer.AddComment("Compilation Unit Length");
2050 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2052 // Emit the pubnames for this compilation unit.
2053 for (const auto &GI : Globals) {
2054 const char *Name = GI.getKeyData();
2055 const DIE *Entity = GI.second;
2057 Asm->OutStreamer.AddComment("DIE offset");
2058 Asm->EmitInt32(Entity->getOffset());
2061 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2062 Asm->OutStreamer.AddComment(
2063 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2064 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2065 Asm->EmitInt8(Desc.toBits());
2068 Asm->OutStreamer.AddComment("External Name");
2069 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2072 Asm->OutStreamer.AddComment("End Mark");
2074 Asm->OutStreamer.EmitLabel(EndLabel);
2078 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2079 const MCSection *PSec =
2080 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2081 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2083 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2086 // Emit visible names into a debug str section.
2087 void DwarfDebug::emitDebugStr() {
2088 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2089 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2092 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2093 const DebugLocEntry &Entry) {
2094 DIVariable DV(Entry.getVariable());
2095 if (Entry.isInt()) {
2096 DIBasicType BTy(resolve(DV.getType()));
2097 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2098 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2099 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2100 Streamer.EmitSLEB128(Entry.getInt());
2102 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2103 Streamer.EmitULEB128(Entry.getInt());
2105 } else if (Entry.isLocation()) {
2106 MachineLocation Loc = Entry.getLoc();
2107 if (!DV.hasComplexAddress())
2109 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2111 // Complex address entry.
2112 unsigned N = DV.getNumAddrElements();
2114 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2115 if (Loc.getOffset()) {
2117 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2118 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2119 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2120 Streamer.EmitSLEB128(DV.getAddrElement(1));
2122 // If first address element is OpPlus then emit
2123 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2124 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2125 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2129 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2132 // Emit remaining complex address elements.
2133 for (; i < N; ++i) {
2134 uint64_t Element = DV.getAddrElement(i);
2135 if (Element == DIBuilder::OpPlus) {
2136 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2137 Streamer.EmitULEB128(DV.getAddrElement(++i));
2138 } else if (Element == DIBuilder::OpDeref) {
2140 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2142 llvm_unreachable("unknown Opcode found in complex address");
2146 // else ... ignore constant fp. There is not any good way to
2147 // to represent them here in dwarf.
2151 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2152 Asm->OutStreamer.AddComment("Loc expr size");
2153 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2154 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2155 Asm->EmitLabelDifference(end, begin, 2);
2156 Asm->OutStreamer.EmitLabel(begin);
2158 APByteStreamer Streamer(*Asm);
2159 emitDebugLocEntry(Streamer, Entry);
2161 Asm->OutStreamer.EmitLabel(end);
2164 // Emit locations into the debug loc section.
2165 void DwarfDebug::emitDebugLoc() {
2166 // Start the dwarf loc section.
2167 Asm->OutStreamer.SwitchSection(
2168 Asm->getObjFileLowering().getDwarfLocSection());
2169 unsigned char Size = Asm->getDataLayout().getPointerSize();
2170 for (const auto &DebugLoc : DotDebugLocEntries) {
2171 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2172 for (const auto &Entry : DebugLoc.List) {
2173 // Set up the range. This range is relative to the entry point of the
2174 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2175 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2176 const DwarfCompileUnit *CU = Entry.getCU();
2177 if (CU->getRanges().size() == 1) {
2178 // Grab the begin symbol from the first range as our base.
2179 const MCSymbol *Base = CU->getRanges()[0].getStart();
2180 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2181 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2183 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2184 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2187 emitDebugLocEntryLocation(Entry);
2189 Asm->OutStreamer.EmitIntValue(0, Size);
2190 Asm->OutStreamer.EmitIntValue(0, Size);
2194 void DwarfDebug::emitDebugLocDWO() {
2195 Asm->OutStreamer.SwitchSection(
2196 Asm->getObjFileLowering().getDwarfLocDWOSection());
2197 for (const auto &DebugLoc : DotDebugLocEntries) {
2198 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2199 for (const auto &Entry : DebugLoc.List) {
2200 // Just always use start_length for now - at least that's one address
2201 // rather than two. We could get fancier and try to, say, reuse an
2202 // address we know we've emitted elsewhere (the start of the function?
2203 // The start of the CU or CU subrange that encloses this range?)
2204 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2205 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2206 Asm->EmitULEB128(idx);
2207 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2209 emitDebugLocEntryLocation(Entry);
2211 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2216 const MCSymbol *Start, *End;
2219 // Emit a debug aranges section, containing a CU lookup for any
2220 // address we can tie back to a CU.
2221 void DwarfDebug::emitDebugARanges() {
2222 // Start the dwarf aranges section.
2223 Asm->OutStreamer.SwitchSection(
2224 Asm->getObjFileLowering().getDwarfARangesSection());
2226 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2230 // Build a list of sections used.
2231 std::vector<const MCSection *> Sections;
2232 for (const auto &it : SectionMap) {
2233 const MCSection *Section = it.first;
2234 Sections.push_back(Section);
2237 // Sort the sections into order.
2238 // This is only done to ensure consistent output order across different runs.
2239 std::sort(Sections.begin(), Sections.end(), SectionSort);
2241 // Build a set of address spans, sorted by CU.
2242 for (const MCSection *Section : Sections) {
2243 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2244 if (List.size() < 2)
2247 // Sort the symbols by offset within the section.
2248 std::sort(List.begin(), List.end(),
2249 [&](const SymbolCU &A, const SymbolCU &B) {
2250 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2251 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2253 // Symbols with no order assigned should be placed at the end.
2254 // (e.g. section end labels)
2262 // If we have no section (e.g. common), just write out
2263 // individual spans for each symbol.
2264 if (Section == NULL) {
2265 for (const SymbolCU &Cur : List) {
2267 Span.Start = Cur.Sym;
2270 Spans[Cur.CU].push_back(Span);
2273 // Build spans between each label.
2274 const MCSymbol *StartSym = List[0].Sym;
2275 for (size_t n = 1, e = List.size(); n < e; n++) {
2276 const SymbolCU &Prev = List[n - 1];
2277 const SymbolCU &Cur = List[n];
2279 // Try and build the longest span we can within the same CU.
2280 if (Cur.CU != Prev.CU) {
2282 Span.Start = StartSym;
2284 Spans[Prev.CU].push_back(Span);
2291 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2293 // Build a list of CUs used.
2294 std::vector<DwarfCompileUnit *> CUs;
2295 for (const auto &it : Spans) {
2296 DwarfCompileUnit *CU = it.first;
2300 // Sort the CU list (again, to ensure consistent output order).
2301 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2302 return A->getUniqueID() < B->getUniqueID();
2305 // Emit an arange table for each CU we used.
2306 for (DwarfCompileUnit *CU : CUs) {
2307 std::vector<ArangeSpan> &List = Spans[CU];
2309 // Emit size of content not including length itself.
2310 unsigned ContentSize =
2311 sizeof(int16_t) + // DWARF ARange version number
2312 sizeof(int32_t) + // Offset of CU in the .debug_info section
2313 sizeof(int8_t) + // Pointer Size (in bytes)
2314 sizeof(int8_t); // Segment Size (in bytes)
2316 unsigned TupleSize = PtrSize * 2;
2318 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2320 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2322 ContentSize += Padding;
2323 ContentSize += (List.size() + 1) * TupleSize;
2325 // For each compile unit, write the list of spans it covers.
2326 Asm->OutStreamer.AddComment("Length of ARange Set");
2327 Asm->EmitInt32(ContentSize);
2328 Asm->OutStreamer.AddComment("DWARF Arange version number");
2329 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2330 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2331 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2332 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2333 Asm->EmitInt8(PtrSize);
2334 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2337 Asm->OutStreamer.EmitFill(Padding, 0xff);
2339 for (const ArangeSpan &Span : List) {
2340 Asm->EmitLabelReference(Span.Start, PtrSize);
2342 // Calculate the size as being from the span start to it's end.
2344 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2346 // For symbols without an end marker (e.g. common), we
2347 // write a single arange entry containing just that one symbol.
2348 uint64_t Size = SymSize[Span.Start];
2352 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2356 Asm->OutStreamer.AddComment("ARange terminator");
2357 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2358 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2362 // Emit visible names into a debug ranges section.
2363 void DwarfDebug::emitDebugRanges() {
2364 // Start the dwarf ranges section.
2365 Asm->OutStreamer.SwitchSection(
2366 Asm->getObjFileLowering().getDwarfRangesSection());
2368 // Size for our labels.
2369 unsigned char Size = Asm->getDataLayout().getPointerSize();
2371 // Grab the specific ranges for the compile units in the module.
2372 for (const auto &I : CUMap) {
2373 DwarfCompileUnit *TheCU = I.second;
2375 // Emit a symbol so we can find the beginning of our ranges.
2376 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2378 // Iterate over the misc ranges for the compile units in the module.
2379 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2380 // Emit our symbol so we can find the beginning of the range.
2381 Asm->OutStreamer.EmitLabel(List.getSym());
2383 for (const RangeSpan &Range : List.getRanges()) {
2384 const MCSymbol *Begin = Range.getStart();
2385 const MCSymbol *End = Range.getEnd();
2386 assert(Begin && "Range without a begin symbol?");
2387 assert(End && "Range without an end symbol?");
2388 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2389 Asm->OutStreamer.EmitSymbolValue(End, Size);
2392 // And terminate the list with two 0 values.
2393 Asm->OutStreamer.EmitIntValue(0, Size);
2394 Asm->OutStreamer.EmitIntValue(0, Size);
2397 // Now emit a range for the CU itself.
2398 if (TheCU->getRanges().size() > 1) {
2399 Asm->OutStreamer.EmitLabel(
2400 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2401 for (const RangeSpan &Range : TheCU->getRanges()) {
2402 const MCSymbol *Begin = Range.getStart();
2403 const MCSymbol *End = Range.getEnd();
2404 assert(Begin && "Range without a begin symbol?");
2405 assert(End && "Range without an end symbol?");
2406 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2407 Asm->OutStreamer.EmitSymbolValue(End, Size);
2409 // And terminate the list with two 0 values.
2410 Asm->OutStreamer.EmitIntValue(0, Size);
2411 Asm->OutStreamer.EmitIntValue(0, Size);
2416 // DWARF5 Experimental Separate Dwarf emitters.
2418 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE *Die,
2419 std::unique_ptr<DwarfUnit> NewU) {
2420 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2421 U.getCUNode().getSplitDebugFilename());
2423 if (!CompilationDir.empty())
2424 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2426 addGnuPubAttributes(*NewU, Die);
2428 SkeletonHolder.addUnit(std::move(NewU));
2431 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2432 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2433 // DW_AT_addr_base, DW_AT_ranges_base.
2434 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2436 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2437 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2438 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2439 DwarfCompileUnit &NewCU = *OwnedUnit;
2440 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2441 DwarfInfoSectionSym);
2443 NewCU.initStmtList(DwarfLineSectionSym);
2445 initSkeletonUnit(CU, Die, std::move(OwnedUnit));
2450 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2452 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2453 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2454 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2456 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2457 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2458 this, &SkeletonHolder);
2459 DwarfTypeUnit &NewTU = *OwnedUnit;
2460 NewTU.setTypeSignature(TU.getTypeSignature());
2461 NewTU.setType(NULL);
2463 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2465 initSkeletonUnit(TU, Die, std::move(OwnedUnit));
2469 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2470 // compile units that would normally be in debug_info.
2471 void DwarfDebug::emitDebugInfoDWO() {
2472 assert(useSplitDwarf() && "No split dwarf debug info?");
2473 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2474 // emit relocations into the dwo file.
2475 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2478 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2479 // abbreviations for the .debug_info.dwo section.
2480 void DwarfDebug::emitDebugAbbrevDWO() {
2481 assert(useSplitDwarf() && "No split dwarf?");
2482 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2485 void DwarfDebug::emitDebugLineDWO() {
2486 assert(useSplitDwarf() && "No split dwarf?");
2487 Asm->OutStreamer.SwitchSection(
2488 Asm->getObjFileLowering().getDwarfLineDWOSection());
2489 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2492 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2493 // string section and is identical in format to traditional .debug_str
2495 void DwarfDebug::emitDebugStrDWO() {
2496 assert(useSplitDwarf() && "No split dwarf?");
2497 const MCSection *OffSec =
2498 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2499 const MCSymbol *StrSym = DwarfStrSectionSym;
2500 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2504 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2505 if (!useSplitDwarf())
2508 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2509 return &SplitTypeUnitFileTable;
2512 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2513 StringRef Identifier, DIE *RefDie,
2514 DICompositeType CTy) {
2515 // Flag the type unit reference as a declaration so that if it contains
2516 // members (implicit special members, static data member definitions, member
2517 // declarations for definitions in this CU, etc) consumers don't get confused
2518 // and think this is a full definition.
2519 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2521 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2523 CU.addDIETypeSignature(RefDie, *TU);
2527 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2529 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2530 this, &InfoHolder, getDwoLineTable(CU));
2531 DwarfTypeUnit &NewTU = *OwnedUnit;
2533 InfoHolder.addUnit(std::move(OwnedUnit));
2535 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2539 Hash.update(Identifier);
2540 // ... take the least significant 8 bytes and return those. Our MD5
2541 // implementation always returns its results in little endian, swap bytes
2543 MD5::MD5Result Result;
2545 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2546 NewTU.setTypeSignature(Signature);
2547 if (useSplitDwarf())
2548 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2550 CU.applyStmtList(*UnitDie);
2552 NewTU.setType(NewTU.createTypeDIE(CTy));
2556 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2557 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2559 CU.addDIETypeSignature(RefDie, NewTU);
2562 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE *D,
2563 MCSymbol *Begin, MCSymbol *End) {
2564 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2565 if (DwarfVersion < 4)
2566 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2568 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2571 // Accelerator table mutators - add each name along with its companion
2572 // DIE to the proper table while ensuring that the name that we're going
2573 // to reference is in the string table. We do this since the names we
2574 // add may not only be identical to the names in the DIE.
2575 void DwarfDebug::addAccelName(StringRef Name, const DIE *Die) {
2576 if (!useDwarfAccelTables())
2578 InfoHolder.getStringPoolEntry(Name);
2579 AccelNames.AddName(Name, Die);