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 "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
53 #define DEBUG_TYPE "dwarfdebug"
56 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
57 cl::desc("Disable debug info printing"));
59 static cl::opt<bool> UnknownLocations(
60 "use-unknown-locations", cl::Hidden,
61 cl::desc("Make an absence of debug location information explicit."),
65 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
66 cl::desc("Generate GNU-style pubnames and pubtypes"),
69 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
71 cl::desc("Generate dwarf aranges"),
75 enum DefaultOnOff { Default, Enable, Disable };
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
109 //===----------------------------------------------------------------------===//
111 /// resolve - Look in the DwarfDebug map for the MDNode that
112 /// corresponds to the reference.
113 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
114 return DD->resolve(Ref);
117 bool DbgVariable::isBlockByrefVariable() const {
118 assert(Var.isVariable() && "Invalid complex DbgVariable!");
119 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
123 DIType DbgVariable::getType() const {
124 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
125 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
126 // addresses instead.
127 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
128 /* Byref variables, in Blocks, are declared by the programmer as
129 "SomeType VarName;", but the compiler creates a
130 __Block_byref_x_VarName struct, and gives the variable VarName
131 either the struct, or a pointer to the struct, as its type. This
132 is necessary for various behind-the-scenes things the compiler
133 needs to do with by-reference variables in blocks.
135 However, as far as the original *programmer* is concerned, the
136 variable should still have type 'SomeType', as originally declared.
138 The following function dives into the __Block_byref_x_VarName
139 struct to find the original type of the variable. This will be
140 passed back to the code generating the type for the Debug
141 Information Entry for the variable 'VarName'. 'VarName' will then
142 have the original type 'SomeType' in its debug information.
144 The original type 'SomeType' will be the type of the field named
145 'VarName' inside the __Block_byref_x_VarName struct.
147 NOTE: In order for this to not completely fail on the debugger
148 side, the Debug Information Entry for the variable VarName needs to
149 have a DW_AT_location that tells the debugger how to unwind through
150 the pointers and __Block_byref_x_VarName struct to find the actual
151 value of the variable. The function addBlockByrefType does this. */
153 uint16_t tag = Ty.getTag();
155 if (tag == dwarf::DW_TAG_pointer_type)
156 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
158 DIArray Elements = DICompositeType(subType).getTypeArray();
159 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
160 DIDerivedType DT(Elements.getElement(i));
161 if (getName() == DT.getName())
162 return (resolve(DT.getTypeDerivedFrom()));
168 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
169 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
170 InfoHolder(A, "info_string", DIEValueAllocator),
171 UsedNonDefaultText(false),
172 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
174 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
175 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
176 DwarfAddrSectionSym = 0;
177 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
178 FunctionBeginSym = FunctionEndSym = 0;
182 // Turn on accelerator tables for Darwin by default, pubnames by
183 // default for non-Darwin, and handle split dwarf.
184 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
186 if (DwarfAccelTables == Default)
187 HasDwarfAccelTables = IsDarwin;
189 HasDwarfAccelTables = DwarfAccelTables == Enable;
191 if (SplitDwarf == Default)
192 HasSplitDwarf = false;
194 HasSplitDwarf = SplitDwarf == Enable;
196 if (DwarfPubSections == Default)
197 HasDwarfPubSections = !IsDarwin;
199 HasDwarfPubSections = DwarfPubSections == Enable;
201 DwarfVersion = DwarfVersionNumber
203 : MMI->getModule()->getDwarfVersion();
206 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
211 // Switch to the specified MCSection and emit an assembler
212 // temporary label to it if SymbolStem is specified.
213 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
214 const char *SymbolStem = 0) {
215 Asm->OutStreamer.SwitchSection(Section);
219 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
220 Asm->OutStreamer.EmitLabel(TmpSym);
224 static bool isObjCClass(StringRef Name) {
225 return Name.startswith("+") || Name.startswith("-");
228 static bool hasObjCCategory(StringRef Name) {
229 if (!isObjCClass(Name))
232 return Name.find(") ") != StringRef::npos;
235 static void getObjCClassCategory(StringRef In, StringRef &Class,
236 StringRef &Category) {
237 if (!hasObjCCategory(In)) {
238 Class = In.slice(In.find('[') + 1, In.find(' '));
243 Class = In.slice(In.find('[') + 1, In.find('('));
244 Category = In.slice(In.find('[') + 1, In.find(' '));
248 static StringRef getObjCMethodName(StringRef In) {
249 return In.slice(In.find(' ') + 1, In.find(']'));
252 // Helper for sorting sections into a stable output order.
253 static bool SectionSort(const MCSection *A, const MCSection *B) {
254 std::string LA = (A ? A->getLabelBeginName() : "");
255 std::string LB = (B ? B->getLabelBeginName() : "");
259 // Add the various names to the Dwarf accelerator table names.
260 // TODO: Determine whether or not we should add names for programs
261 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
262 // is only slightly different than the lookup of non-standard ObjC names.
263 static void addSubprogramNames(DwarfUnit &TheU, DISubprogram SP, DIE *Die) {
264 if (!SP.isDefinition())
266 TheU.addAccelName(SP.getName(), Die);
268 // If the linkage name is different than the name, go ahead and output
269 // that as well into the name table.
270 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
271 TheU.addAccelName(SP.getLinkageName(), Die);
273 // If this is an Objective-C selector name add it to the ObjC accelerator
275 if (isObjCClass(SP.getName())) {
276 StringRef Class, Category;
277 getObjCClassCategory(SP.getName(), Class, Category);
278 TheU.addAccelObjC(Class, Die);
280 TheU.addAccelObjC(Category, Die);
281 // Also add the base method name to the name table.
282 TheU.addAccelName(getObjCMethodName(SP.getName()), Die);
286 /// isSubprogramContext - Return true if Context is either a subprogram
287 /// or another context nested inside a subprogram.
288 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
291 DIDescriptor D(Context);
292 if (D.isSubprogram())
295 return isSubprogramContext(resolve(DIType(Context).getContext()));
299 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
300 // and DW_AT_high_pc attributes. If there are global variables in this
301 // scope then create and insert DIEs for these variables.
302 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
304 DIE *SPDie = SPCU.getDIE(SP);
306 assert(SPDie && "Unable to find subprogram DIE!");
308 // If we're updating an abstract DIE, then we will be adding the children and
309 // object pointer later on. But what we don't want to do is process the
310 // concrete DIE twice.
311 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
312 // Pick up abstract subprogram DIE.
313 SPDie = SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
314 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
316 DISubprogram SPDecl = SP.getFunctionDeclaration();
317 if (!SPDecl.isSubprogram()) {
318 // There is not any need to generate specification DIE for a function
319 // defined at compile unit level. If a function is defined inside another
320 // function then gdb prefers the definition at top level and but does not
321 // expect specification DIE in parent function. So avoid creating
322 // specification DIE for a function defined inside a function.
323 DIScope SPContext = resolve(SP.getContext());
324 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
325 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
326 SPCU.addFlag(SPDie, dwarf::DW_AT_declaration);
329 DICompositeType SPTy = SP.getType();
330 DIArray Args = SPTy.getTypeArray();
331 uint16_t SPTag = SPTy.getTag();
332 if (SPTag == dwarf::DW_TAG_subroutine_type)
333 SPCU.constructSubprogramArguments(*SPDie, Args);
334 DIE *SPDeclDie = SPDie;
336 SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
337 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
342 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
344 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
345 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
346 SPCU.addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
348 // Add name to the name table, we do this here because we're guaranteed
349 // to have concrete versions of our DW_TAG_subprogram nodes.
350 addSubprogramNames(SPCU, SP, SPDie);
355 /// Check whether we should create a DIE for the given Scope, return true
356 /// if we don't create a DIE (the corresponding DIE is null).
357 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
358 if (Scope->isAbstractScope())
361 // We don't create a DIE if there is no Range.
362 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
366 if (Ranges.size() > 1)
369 // We don't create a DIE if we have a single Range and the end label
371 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
372 MCSymbol *End = getLabelAfterInsn(RI->second);
376 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE *D,
377 dwarf::Attribute A, const MCSymbol *L,
378 const MCSymbol *Sec) {
379 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
380 U.addSectionLabel(D, A, L);
382 U.addSectionDelta(D, A, L, Sec);
385 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
386 const SmallVectorImpl<InsnRange> &Range) {
387 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
388 // emitting it appropriately.
389 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
391 // Under fission, ranges are specified by constant offsets relative to the
392 // CU's DW_AT_GNU_ranges_base.
394 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
395 DwarfDebugRangeSectionSym);
397 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
398 DwarfDebugRangeSectionSym);
400 RangeSpanList List(RangeSym);
401 for (const InsnRange &R : Range) {
402 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
403 List.addRange(std::move(Span));
406 // Add the range list to the set of ranges to be emitted.
407 TheCU.addRangeList(std::move(List));
410 // Construct new DW_TAG_lexical_block for this scope and attach
411 // DW_AT_low_pc/DW_AT_high_pc labels.
412 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
413 LexicalScope *Scope) {
414 if (isLexicalScopeDIENull(Scope))
417 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
418 if (Scope->isAbstractScope())
421 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
423 // If we have multiple ranges, emit them into the range section.
424 if (ScopeRanges.size() > 1) {
425 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
429 // Construct the address range for this DIE.
430 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
431 MCSymbol *Start = getLabelBeforeInsn(RI->first);
432 MCSymbol *End = getLabelAfterInsn(RI->second);
433 assert(End && "End label should not be null!");
435 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
436 assert(End->isDefined() && "Invalid end label for an inlined scope!");
438 attachLowHighPC(TheCU, ScopeDIE, Start, End);
443 // This scope represents inlined body of a function. Construct DIE to
444 // represent this concrete inlined copy of the function.
445 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
446 LexicalScope *Scope) {
447 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
448 assert(!ScopeRanges.empty() &&
449 "LexicalScope does not have instruction markers!");
451 if (!Scope->getScopeNode())
453 DIScope DS(Scope->getScopeNode());
454 DISubprogram InlinedSP = getDISubprogram(DS);
455 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
457 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
461 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
462 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
464 // If we have multiple ranges, emit them into the range section.
465 if (ScopeRanges.size() > 1)
466 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
468 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
469 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
470 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
472 if (StartLabel == 0 || EndLabel == 0)
473 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
475 assert(StartLabel->isDefined() &&
476 "Invalid starting label for an inlined scope!");
477 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
479 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
482 InlinedSubprogramDIEs.insert(OriginDIE);
484 // Add the call site information to the DIE.
485 DILocation DL(Scope->getInlinedAt());
486 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
487 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
488 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
490 // Add name to the name table, we do this here because we're guaranteed
491 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
492 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
497 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit &TheCU,
499 SmallVectorImpl<DIE *> &Children) {
500 DIE *ObjectPointer = NULL;
502 // Collect arguments for current function.
503 if (LScopes.isCurrentFunctionScope(Scope)) {
504 for (DbgVariable *ArgDV : CurrentFnArguments)
507 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
508 Children.push_back(Arg);
509 if (ArgDV->isObjectPointer())
513 // If this is a variadic function, add an unspecified parameter.
514 DISubprogram SP(Scope->getScopeNode());
515 DIArray FnArgs = SP.getType().getTypeArray();
516 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
517 .isUnspecifiedParameter()) {
518 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
519 Children.push_back(Ellipsis);
523 // Collect lexical scope children first.
524 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
526 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope())) {
527 Children.push_back(Variable);
528 if (DV->isObjectPointer())
529 ObjectPointer = Variable;
531 for (LexicalScope *LS : Scope->getChildren())
532 if (DIE *Nested = constructScopeDIE(TheCU, LS))
533 Children.push_back(Nested);
534 return ObjectPointer;
537 // Construct a DIE for this scope.
538 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
539 LexicalScope *Scope) {
540 if (!Scope || !Scope->getScopeNode())
543 DIScope DS(Scope->getScopeNode());
545 SmallVector<DIE *, 8> Children;
546 DIE *ObjectPointer = NULL;
547 bool ChildrenCreated = false;
549 // We try to create the scope DIE first, then the children DIEs. This will
550 // avoid creating un-used children then removing them later when we find out
551 // the scope DIE is null.
552 DIE *ScopeDIE = NULL;
553 if (Scope->getInlinedAt())
554 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
555 else if (DS.isSubprogram()) {
556 ProcessedSPNodes.insert(DS);
557 if (Scope->isAbstractScope()) {
558 ScopeDIE = TheCU.getDIE(DS);
559 // Note down abstract DIE.
561 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
563 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
565 // Early exit when we know the scope DIE is going to be null.
566 if (isLexicalScopeDIENull(Scope))
569 // We create children here when we know the scope DIE is not going to be
570 // null and the children will be added to the scope DIE.
571 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
572 ChildrenCreated = true;
574 // There is no need to emit empty lexical block DIE.
575 std::pair<ImportedEntityMap::const_iterator,
576 ImportedEntityMap::const_iterator> Range =
578 ScopesWithImportedEntities.begin(),
579 ScopesWithImportedEntities.end(),
580 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
582 if (Children.empty() && Range.first == Range.second)
584 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
585 assert(ScopeDIE && "Scope DIE should not be null.");
586 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
588 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
592 assert(Children.empty() &&
593 "We create children only when the scope DIE is not null.");
596 if (!ChildrenCreated)
597 // We create children when the scope DIE is not null.
598 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
601 for (DIE *I : Children)
602 ScopeDIE->addChild(I);
604 if (DS.isSubprogram() && ObjectPointer != NULL)
605 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
610 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE *D) const {
611 if (!GenerateGnuPubSections)
614 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
617 // Create new DwarfCompileUnit for the given metadata node with tag
618 // DW_TAG_compile_unit.
619 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
620 StringRef FN = DIUnit.getFilename();
621 CompilationDir = DIUnit.getDirectory();
623 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
624 auto OwnedUnit = make_unique<DwarfCompileUnit>(
625 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
626 DwarfCompileUnit &NewCU = *OwnedUnit;
627 InfoHolder.addUnit(std::move(OwnedUnit));
629 // LTO with assembly output shares a single line table amongst multiple CUs.
630 // To avoid the compilation directory being ambiguous, let the line table
631 // explicitly describe the directory of all files, never relying on the
632 // compilation directory.
633 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
634 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
635 NewCU.getUniqueID(), CompilationDir);
637 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
638 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
639 DIUnit.getLanguage());
640 NewCU.addString(Die, dwarf::DW_AT_name, FN);
642 if (!useSplitDwarf()) {
643 NewCU.initStmtList(DwarfLineSectionSym);
645 // If we're using split dwarf the compilation dir is going to be in the
646 // skeleton CU and so we don't need to duplicate it here.
647 if (!CompilationDir.empty())
648 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
650 addGnuPubAttributes(NewCU, Die);
653 if (DIUnit.isOptimized())
654 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
656 StringRef Flags = DIUnit.getFlags();
658 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
660 if (unsigned RVer = DIUnit.getRunTimeVersion())
661 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
662 dwarf::DW_FORM_data1, RVer);
667 if (useSplitDwarf()) {
668 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
669 DwarfInfoDWOSectionSym);
670 NewCU.setSkeleton(constructSkeletonCU(NewCU));
672 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
673 DwarfInfoSectionSym);
675 CUMap.insert(std::make_pair(DIUnit, &NewCU));
676 CUDieMap.insert(std::make_pair(Die, &NewCU));
680 // Construct subprogram DIE.
681 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
683 // FIXME: We should only call this routine once, however, during LTO if a
684 // program is defined in multiple CUs we could end up calling it out of
685 // beginModule as we walk the CUs.
687 DwarfCompileUnit *&CURef = SPMap[N];
693 if (!SP.isDefinition())
694 // This is a method declaration which will be handled while constructing
698 DIE *SubprogramDie = TheCU.getOrCreateSubprogramDIE(SP);
700 // Expose as a global name.
701 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
704 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
706 DIImportedEntity Module(N);
707 assert(Module.Verify());
708 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
709 constructImportedEntityDIE(TheCU, Module, D);
712 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
713 const MDNode *N, DIE *Context) {
714 DIImportedEntity Module(N);
715 assert(Module.Verify());
716 return constructImportedEntityDIE(TheCU, Module, Context);
719 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
720 const DIImportedEntity &Module,
722 assert(Module.Verify() &&
723 "Use one of the MDNode * overloads to handle invalid metadata");
724 assert(Context && "Should always have a context for an imported_module");
725 DIE *IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
727 DIDescriptor Entity = resolve(Module.getEntity());
728 if (Entity.isNameSpace())
729 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
730 else if (Entity.isSubprogram())
731 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
732 else if (Entity.isType())
733 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
735 EntityDie = TheCU.getDIE(Entity);
736 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
737 Module.getContext().getFilename(),
738 Module.getContext().getDirectory());
739 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
740 StringRef Name = Module.getName();
742 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
745 // Emit all Dwarf sections that should come prior to the content. Create
746 // global DIEs and emit initial debug info sections. This is invoked by
747 // the target AsmPrinter.
748 void DwarfDebug::beginModule() {
749 if (DisableDebugInfoPrinting)
752 const Module *M = MMI->getModule();
754 // If module has named metadata anchors then use them, otherwise scan the
755 // module using debug info finder to collect debug info.
756 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
759 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
761 // Emit initial sections so we can reference labels later.
764 SingleCU = CU_Nodes->getNumOperands() == 1;
766 for (MDNode *N : CU_Nodes->operands()) {
767 DICompileUnit CUNode(N);
768 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
769 DIArray ImportedEntities = CUNode.getImportedEntities();
770 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
771 ScopesWithImportedEntities.push_back(std::make_pair(
772 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
773 ImportedEntities.getElement(i)));
774 std::sort(ScopesWithImportedEntities.begin(),
775 ScopesWithImportedEntities.end(), less_first());
776 DIArray GVs = CUNode.getGlobalVariables();
777 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
778 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
779 DIArray SPs = CUNode.getSubprograms();
780 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
781 constructSubprogramDIE(CU, SPs.getElement(i));
782 DIArray EnumTypes = CUNode.getEnumTypes();
783 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
784 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
785 DIArray RetainedTypes = CUNode.getRetainedTypes();
786 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
787 DIType Ty(RetainedTypes.getElement(i));
788 // The retained types array by design contains pointers to
789 // MDNodes rather than DIRefs. Unique them here.
790 DIType UniqueTy(resolve(Ty.getRef()));
791 CU.getOrCreateTypeDIE(UniqueTy);
793 // Emit imported_modules last so that the relevant context is already
795 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
796 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
799 // Tell MMI that we have debug info.
800 MMI->setDebugInfoAvailability(true);
802 // Prime section data.
803 SectionMap[Asm->getObjFileLowering().getTextSection()];
806 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
807 void DwarfDebug::computeInlinedDIEs() {
808 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
809 for (DIE *ISP : InlinedSubprogramDIEs)
810 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
812 for (const auto &AI : AbstractSPDies) {
813 DIE *ISP = AI.second;
814 if (InlinedSubprogramDIEs.count(ISP))
816 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
820 // Collect info for variables that were optimized out.
821 void DwarfDebug::collectDeadVariables() {
822 const Module *M = MMI->getModule();
824 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
825 for (MDNode *N : CU_Nodes->operands()) {
826 DICompileUnit TheCU(N);
827 DIArray Subprograms = TheCU.getSubprograms();
828 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
829 DISubprogram SP(Subprograms.getElement(i));
830 if (ProcessedSPNodes.count(SP) != 0)
832 if (!SP.isSubprogram())
834 if (!SP.isDefinition())
836 DIArray Variables = SP.getVariables();
837 if (Variables.getNumElements() == 0)
840 // Construct subprogram DIE and add variables DIEs.
841 DwarfCompileUnit *SPCU =
842 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
843 assert(SPCU && "Unable to find Compile Unit!");
844 // FIXME: See the comment in constructSubprogramDIE about duplicate
846 constructSubprogramDIE(*SPCU, SP);
847 DIE *SPDIE = SPCU->getDIE(SP);
848 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
849 DIVariable DV(Variables.getElement(vi));
850 if (!DV.isVariable())
852 DbgVariable NewVar(DV, NULL, this);
853 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
854 SPDIE->addChild(VariableDIE);
861 void DwarfDebug::finalizeModuleInfo() {
862 // Collect info for variables that were optimized out.
863 collectDeadVariables();
865 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
866 computeInlinedDIEs();
868 // Handle anything that needs to be done on a per-unit basis after
869 // all other generation.
870 for (const auto &TheU : getUnits()) {
871 // Emit DW_AT_containing_type attribute to connect types with their
872 // vtable holding type.
873 TheU->constructContainingTypeDIEs();
875 // Add CU specific attributes if we need to add any.
876 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
877 // If we're splitting the dwarf out now that we've got the entire
878 // CU then add the dwo id to it.
879 DwarfCompileUnit *SkCU =
880 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
881 if (useSplitDwarf()) {
882 // Emit a unique identifier for this CU.
883 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
884 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
885 dwarf::DW_FORM_data8, ID);
886 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
887 dwarf::DW_FORM_data8, ID);
889 // We don't keep track of which addresses are used in which CU so this
890 // is a bit pessimistic under LTO.
891 if (!InfoHolder.getAddressPool().isEmpty())
892 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
893 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
894 DwarfAddrSectionSym);
895 if (!TheU->getRangeLists().empty())
896 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
897 dwarf::DW_AT_GNU_ranges_base,
898 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
901 // If we have code split among multiple sections or non-contiguous
902 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
903 // remain in the .o file, otherwise add a DW_AT_low_pc.
904 // FIXME: We should use ranges allow reordering of code ala
905 // .subsections_via_symbols in mach-o. This would mean turning on
906 // ranges for all subprogram DIEs for mach-o.
907 DwarfCompileUnit &U =
908 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
909 unsigned NumRanges = TheU->getRanges().size();
912 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
913 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
914 DwarfDebugRangeSectionSym);
916 // A DW_AT_low_pc attribute may also be specified in combination with
917 // DW_AT_ranges to specify the default base address for use in
918 // location lists (see Section 2.6.2) and range lists (see Section
920 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
923 RangeSpan &Range = TheU->getRanges().back();
924 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
926 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
933 // Compute DIE offsets and sizes.
934 InfoHolder.computeSizeAndOffsets();
936 SkeletonHolder.computeSizeAndOffsets();
939 void DwarfDebug::endSections() {
940 // Filter labels by section.
941 for (const SymbolCU &SCU : ArangeLabels) {
942 if (SCU.Sym->isInSection()) {
943 // Make a note of this symbol and it's section.
944 const MCSection *Section = &SCU.Sym->getSection();
945 if (!Section->getKind().isMetadata())
946 SectionMap[Section].push_back(SCU);
948 // Some symbols (e.g. common/bss on mach-o) can have no section but still
949 // appear in the output. This sucks as we rely on sections to build
950 // arange spans. We can do it without, but it's icky.
951 SectionMap[NULL].push_back(SCU);
955 // Build a list of sections used.
956 std::vector<const MCSection *> Sections;
957 for (const auto &it : SectionMap) {
958 const MCSection *Section = it.first;
959 Sections.push_back(Section);
962 // Sort the sections into order.
963 // This is only done to ensure consistent output order across different runs.
964 std::sort(Sections.begin(), Sections.end(), SectionSort);
966 // Add terminating symbols for each section.
967 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
968 const MCSection *Section = Sections[ID];
969 MCSymbol *Sym = NULL;
972 // We can't call MCSection::getLabelEndName, as it's only safe to do so
973 // if we know the section name up-front. For user-created sections, the
974 // resulting label may not be valid to use as a label. (section names can
975 // use a greater set of characters on some systems)
976 Sym = Asm->GetTempSymbol("debug_end", ID);
977 Asm->OutStreamer.SwitchSection(Section);
978 Asm->OutStreamer.EmitLabel(Sym);
981 // Insert a final terminator.
982 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
986 // Emit all Dwarf sections that should come after the content.
987 void DwarfDebug::endModule() {
994 // End any existing sections.
995 // TODO: Does this need to happen?
998 // Finalize the debug info for the module.
999 finalizeModuleInfo();
1003 // Emit all the DIEs into a debug info section.
1006 // Corresponding abbreviations into a abbrev section.
1007 emitAbbreviations();
1009 // Emit info into a debug aranges section.
1010 if (GenerateARangeSection)
1013 // Emit info into a debug ranges section.
1016 if (useSplitDwarf()) {
1019 emitDebugAbbrevDWO();
1021 // Emit DWO addresses.
1022 InfoHolder.getAddressPool().emit(
1023 *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 std::vector<DwarfAccelTable::Atom> Atoms;
1929 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1931 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
1933 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
1934 DwarfAccelTable AT(Atoms);
1935 for (const auto &TheU : getUnits()) {
1936 for (const auto &GI : TheU->getAccelTypes()) {
1937 StringRef Name = GI.getKey();
1938 for (const auto &DI : GI.second)
1939 AT.AddName(Name, DI.first, DI.second);
1943 AT.FinalizeTable(Asm, "types");
1944 Asm->OutStreamer.SwitchSection(
1945 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1946 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1947 Asm->OutStreamer.EmitLabel(SectionBegin);
1949 // Emit the full data.
1950 AT.Emit(Asm, SectionBegin, &InfoHolder);
1953 // Public name handling.
1954 // The format for the various pubnames:
1956 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1957 // for the DIE that is named.
1959 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1960 // into the CU and the index value is computed according to the type of value
1961 // for the DIE that is named.
1963 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1964 // it's the offset within the debug_info/debug_types dwo section, however, the
1965 // reference in the pubname header doesn't change.
1967 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1968 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1970 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1972 // We could have a specification DIE that has our most of our knowledge,
1973 // look for that now.
1974 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1976 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1977 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
1978 Linkage = dwarf::GIEL_EXTERNAL;
1979 } else if (Die->findAttribute(dwarf::DW_AT_external))
1980 Linkage = dwarf::GIEL_EXTERNAL;
1982 switch (Die->getTag()) {
1983 case dwarf::DW_TAG_class_type:
1984 case dwarf::DW_TAG_structure_type:
1985 case dwarf::DW_TAG_union_type:
1986 case dwarf::DW_TAG_enumeration_type:
1987 return dwarf::PubIndexEntryDescriptor(
1988 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1989 ? dwarf::GIEL_STATIC
1990 : dwarf::GIEL_EXTERNAL);
1991 case dwarf::DW_TAG_typedef:
1992 case dwarf::DW_TAG_base_type:
1993 case dwarf::DW_TAG_subrange_type:
1994 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1995 case dwarf::DW_TAG_namespace:
1996 return dwarf::GIEK_TYPE;
1997 case dwarf::DW_TAG_subprogram:
1998 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1999 case dwarf::DW_TAG_constant:
2000 case dwarf::DW_TAG_variable:
2001 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2002 case dwarf::DW_TAG_enumerator:
2003 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2004 dwarf::GIEL_STATIC);
2006 return dwarf::GIEK_NONE;
2010 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2012 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2013 const MCSection *PSec =
2014 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2015 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2017 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2020 void DwarfDebug::emitDebugPubSection(
2021 bool GnuStyle, const MCSection *PSec, StringRef Name,
2022 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2023 for (const auto &NU : CUMap) {
2024 DwarfCompileUnit *TheU = NU.second;
2026 const auto &Globals = (TheU->*Accessor)();
2028 if (Globals.empty())
2031 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2033 unsigned ID = TheU->getUniqueID();
2035 // Start the dwarf pubnames section.
2036 Asm->OutStreamer.SwitchSection(PSec);
2039 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2040 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2041 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2042 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2044 Asm->OutStreamer.EmitLabel(BeginLabel);
2046 Asm->OutStreamer.AddComment("DWARF Version");
2047 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2049 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2050 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2052 Asm->OutStreamer.AddComment("Compilation Unit Length");
2053 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2055 // Emit the pubnames for this compilation unit.
2056 for (const auto &GI : Globals) {
2057 const char *Name = GI.getKeyData();
2058 const DIE *Entity = GI.second;
2060 Asm->OutStreamer.AddComment("DIE offset");
2061 Asm->EmitInt32(Entity->getOffset());
2064 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2065 Asm->OutStreamer.AddComment(
2066 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2067 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2068 Asm->EmitInt8(Desc.toBits());
2071 Asm->OutStreamer.AddComment("External Name");
2072 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2075 Asm->OutStreamer.AddComment("End Mark");
2077 Asm->OutStreamer.EmitLabel(EndLabel);
2081 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2082 const MCSection *PSec =
2083 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2084 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2086 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2089 // Emit visible names into a debug str section.
2090 void DwarfDebug::emitDebugStr() {
2091 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2092 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2095 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2096 const DebugLocEntry &Entry) {
2097 DIVariable DV(Entry.getVariable());
2098 if (Entry.isInt()) {
2099 DIBasicType BTy(resolve(DV.getType()));
2100 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2101 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2102 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2103 Streamer.EmitSLEB128(Entry.getInt());
2105 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2106 Streamer.EmitULEB128(Entry.getInt());
2108 } else if (Entry.isLocation()) {
2109 MachineLocation Loc = Entry.getLoc();
2110 if (!DV.hasComplexAddress())
2112 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2114 // Complex address entry.
2115 unsigned N = DV.getNumAddrElements();
2117 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2118 if (Loc.getOffset()) {
2120 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2121 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2122 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2123 Streamer.EmitSLEB128(DV.getAddrElement(1));
2125 // If first address element is OpPlus then emit
2126 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2127 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2128 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2132 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2135 // Emit remaining complex address elements.
2136 for (; i < N; ++i) {
2137 uint64_t Element = DV.getAddrElement(i);
2138 if (Element == DIBuilder::OpPlus) {
2139 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2140 Streamer.EmitULEB128(DV.getAddrElement(++i));
2141 } else if (Element == DIBuilder::OpDeref) {
2143 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2145 llvm_unreachable("unknown Opcode found in complex address");
2149 // else ... ignore constant fp. There is not any good way to
2150 // to represent them here in dwarf.
2154 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2155 Asm->OutStreamer.AddComment("Loc expr size");
2156 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2157 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2158 Asm->EmitLabelDifference(end, begin, 2);
2159 Asm->OutStreamer.EmitLabel(begin);
2161 APByteStreamer Streamer(*Asm);
2162 emitDebugLocEntry(Streamer, Entry);
2164 Asm->OutStreamer.EmitLabel(end);
2167 // Emit locations into the debug loc section.
2168 void DwarfDebug::emitDebugLoc() {
2169 // Start the dwarf loc section.
2170 Asm->OutStreamer.SwitchSection(
2171 Asm->getObjFileLowering().getDwarfLocSection());
2172 unsigned char Size = Asm->getDataLayout().getPointerSize();
2173 for (const auto &DebugLoc : DotDebugLocEntries) {
2174 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2175 for (const auto &Entry : DebugLoc.List) {
2176 // Set up the range. This range is relative to the entry point of the
2177 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2178 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2179 const DwarfCompileUnit *CU = Entry.getCU();
2180 if (CU->getRanges().size() == 1) {
2181 // Grab the begin symbol from the first range as our base.
2182 const MCSymbol *Base = CU->getRanges()[0].getStart();
2183 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2184 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2186 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2187 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2190 emitDebugLocEntryLocation(Entry);
2192 Asm->OutStreamer.EmitIntValue(0, Size);
2193 Asm->OutStreamer.EmitIntValue(0, Size);
2197 void DwarfDebug::emitDebugLocDWO() {
2198 Asm->OutStreamer.SwitchSection(
2199 Asm->getObjFileLowering().getDwarfLocDWOSection());
2200 for (const auto &DebugLoc : DotDebugLocEntries) {
2201 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2202 for (const auto &Entry : DebugLoc.List) {
2203 // Just always use start_length for now - at least that's one address
2204 // rather than two. We could get fancier and try to, say, reuse an
2205 // address we know we've emitted elsewhere (the start of the function?
2206 // The start of the CU or CU subrange that encloses this range?)
2207 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2208 unsigned idx = InfoHolder.getAddressPool().getIndex(Entry.getBeginSym());
2209 Asm->EmitULEB128(idx);
2210 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2212 emitDebugLocEntryLocation(Entry);
2214 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2219 const MCSymbol *Start, *End;
2222 // Emit a debug aranges section, containing a CU lookup for any
2223 // address we can tie back to a CU.
2224 void DwarfDebug::emitDebugARanges() {
2225 // Start the dwarf aranges section.
2226 Asm->OutStreamer.SwitchSection(
2227 Asm->getObjFileLowering().getDwarfARangesSection());
2229 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2233 // Build a list of sections used.
2234 std::vector<const MCSection *> Sections;
2235 for (const auto &it : SectionMap) {
2236 const MCSection *Section = it.first;
2237 Sections.push_back(Section);
2240 // Sort the sections into order.
2241 // This is only done to ensure consistent output order across different runs.
2242 std::sort(Sections.begin(), Sections.end(), SectionSort);
2244 // Build a set of address spans, sorted by CU.
2245 for (const MCSection *Section : Sections) {
2246 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2247 if (List.size() < 2)
2250 // Sort the symbols by offset within the section.
2251 std::sort(List.begin(), List.end(),
2252 [&](const SymbolCU &A, const SymbolCU &B) {
2253 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2254 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2256 // Symbols with no order assigned should be placed at the end.
2257 // (e.g. section end labels)
2265 // If we have no section (e.g. common), just write out
2266 // individual spans for each symbol.
2267 if (Section == NULL) {
2268 for (const SymbolCU &Cur : List) {
2270 Span.Start = Cur.Sym;
2273 Spans[Cur.CU].push_back(Span);
2276 // Build spans between each label.
2277 const MCSymbol *StartSym = List[0].Sym;
2278 for (size_t n = 1, e = List.size(); n < e; n++) {
2279 const SymbolCU &Prev = List[n - 1];
2280 const SymbolCU &Cur = List[n];
2282 // Try and build the longest span we can within the same CU.
2283 if (Cur.CU != Prev.CU) {
2285 Span.Start = StartSym;
2287 Spans[Prev.CU].push_back(Span);
2294 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2296 // Build a list of CUs used.
2297 std::vector<DwarfCompileUnit *> CUs;
2298 for (const auto &it : Spans) {
2299 DwarfCompileUnit *CU = it.first;
2303 // Sort the CU list (again, to ensure consistent output order).
2304 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2305 return A->getUniqueID() < B->getUniqueID();
2308 // Emit an arange table for each CU we used.
2309 for (DwarfCompileUnit *CU : CUs) {
2310 std::vector<ArangeSpan> &List = Spans[CU];
2312 // Emit size of content not including length itself.
2313 unsigned ContentSize =
2314 sizeof(int16_t) + // DWARF ARange version number
2315 sizeof(int32_t) + // Offset of CU in the .debug_info section
2316 sizeof(int8_t) + // Pointer Size (in bytes)
2317 sizeof(int8_t); // Segment Size (in bytes)
2319 unsigned TupleSize = PtrSize * 2;
2321 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2323 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2325 ContentSize += Padding;
2326 ContentSize += (List.size() + 1) * TupleSize;
2328 // For each compile unit, write the list of spans it covers.
2329 Asm->OutStreamer.AddComment("Length of ARange Set");
2330 Asm->EmitInt32(ContentSize);
2331 Asm->OutStreamer.AddComment("DWARF Arange version number");
2332 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2333 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2334 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2335 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2336 Asm->EmitInt8(PtrSize);
2337 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2340 Asm->OutStreamer.EmitFill(Padding, 0xff);
2342 for (const ArangeSpan &Span : List) {
2343 Asm->EmitLabelReference(Span.Start, PtrSize);
2345 // Calculate the size as being from the span start to it's end.
2347 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2349 // For symbols without an end marker (e.g. common), we
2350 // write a single arange entry containing just that one symbol.
2351 uint64_t Size = SymSize[Span.Start];
2355 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2359 Asm->OutStreamer.AddComment("ARange terminator");
2360 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2361 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2365 // Emit visible names into a debug ranges section.
2366 void DwarfDebug::emitDebugRanges() {
2367 // Start the dwarf ranges section.
2368 Asm->OutStreamer.SwitchSection(
2369 Asm->getObjFileLowering().getDwarfRangesSection());
2371 // Size for our labels.
2372 unsigned char Size = Asm->getDataLayout().getPointerSize();
2374 // Grab the specific ranges for the compile units in the module.
2375 for (const auto &I : CUMap) {
2376 DwarfCompileUnit *TheCU = I.second;
2378 // Emit a symbol so we can find the beginning of our ranges.
2379 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2381 // Iterate over the misc ranges for the compile units in the module.
2382 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2383 // Emit our symbol so we can find the beginning of the range.
2384 Asm->OutStreamer.EmitLabel(List.getSym());
2386 for (const RangeSpan &Range : List.getRanges()) {
2387 const MCSymbol *Begin = Range.getStart();
2388 const MCSymbol *End = Range.getEnd();
2389 assert(Begin && "Range without a begin symbol?");
2390 assert(End && "Range without an end symbol?");
2391 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2392 Asm->OutStreamer.EmitSymbolValue(End, Size);
2395 // And terminate the list with two 0 values.
2396 Asm->OutStreamer.EmitIntValue(0, Size);
2397 Asm->OutStreamer.EmitIntValue(0, Size);
2400 // Now emit a range for the CU itself.
2401 if (TheCU->getRanges().size() > 1) {
2402 Asm->OutStreamer.EmitLabel(
2403 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2404 for (const RangeSpan &Range : TheCU->getRanges()) {
2405 const MCSymbol *Begin = Range.getStart();
2406 const MCSymbol *End = Range.getEnd();
2407 assert(Begin && "Range without a begin symbol?");
2408 assert(End && "Range without an end symbol?");
2409 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2410 Asm->OutStreamer.EmitSymbolValue(End, Size);
2412 // And terminate the list with two 0 values.
2413 Asm->OutStreamer.EmitIntValue(0, Size);
2414 Asm->OutStreamer.EmitIntValue(0, Size);
2419 // DWARF5 Experimental Separate Dwarf emitters.
2421 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE *Die,
2422 std::unique_ptr<DwarfUnit> NewU) {
2423 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2424 U.getCUNode().getSplitDebugFilename());
2426 if (!CompilationDir.empty())
2427 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2429 addGnuPubAttributes(*NewU, Die);
2431 SkeletonHolder.addUnit(std::move(NewU));
2434 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2435 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2436 // DW_AT_addr_base, DW_AT_ranges_base.
2437 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2439 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2440 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2441 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2442 DwarfCompileUnit &NewCU = *OwnedUnit;
2443 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2444 DwarfInfoSectionSym);
2446 NewCU.initStmtList(DwarfLineSectionSym);
2448 initSkeletonUnit(CU, Die, std::move(OwnedUnit));
2453 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2455 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2456 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2457 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2459 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2460 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2461 this, &SkeletonHolder);
2462 DwarfTypeUnit &NewTU = *OwnedUnit;
2463 NewTU.setTypeSignature(TU.getTypeSignature());
2464 NewTU.setType(NULL);
2466 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2468 initSkeletonUnit(TU, Die, std::move(OwnedUnit));
2472 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2473 // compile units that would normally be in debug_info.
2474 void DwarfDebug::emitDebugInfoDWO() {
2475 assert(useSplitDwarf() && "No split dwarf debug info?");
2476 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2477 // emit relocations into the dwo file.
2478 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2481 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2482 // abbreviations for the .debug_info.dwo section.
2483 void DwarfDebug::emitDebugAbbrevDWO() {
2484 assert(useSplitDwarf() && "No split dwarf?");
2485 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2488 void DwarfDebug::emitDebugLineDWO() {
2489 assert(useSplitDwarf() && "No split dwarf?");
2490 Asm->OutStreamer.SwitchSection(
2491 Asm->getObjFileLowering().getDwarfLineDWOSection());
2492 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2495 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2496 // string section and is identical in format to traditional .debug_str
2498 void DwarfDebug::emitDebugStrDWO() {
2499 assert(useSplitDwarf() && "No split dwarf?");
2500 const MCSection *OffSec =
2501 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2502 const MCSymbol *StrSym = DwarfStrSectionSym;
2503 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2507 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2508 if (!useSplitDwarf())
2511 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2512 return &SplitTypeUnitFileTable;
2515 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2516 StringRef Identifier, DIE *RefDie,
2517 DICompositeType CTy) {
2518 // Flag the type unit reference as a declaration so that if it contains
2519 // members (implicit special members, static data member definitions, member
2520 // declarations for definitions in this CU, etc) consumers don't get confused
2521 // and think this is a full definition.
2522 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2524 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2526 CU.addDIETypeSignature(RefDie, *TU);
2530 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2532 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2533 this, &InfoHolder, getDwoLineTable(CU));
2534 DwarfTypeUnit &NewTU = *OwnedUnit;
2536 InfoHolder.addUnit(std::move(OwnedUnit));
2538 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2542 Hash.update(Identifier);
2543 // ... take the least significant 8 bytes and return those. Our MD5
2544 // implementation always returns its results in little endian, swap bytes
2546 MD5::MD5Result Result;
2548 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2549 NewTU.setTypeSignature(Signature);
2550 if (useSplitDwarf())
2551 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2553 CU.applyStmtList(*UnitDie);
2555 NewTU.setType(NewTU.createTypeDIE(CTy));
2559 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2560 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2562 CU.addDIETypeSignature(RefDie, NewTU);
2565 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE *D,
2566 MCSymbol *Begin, MCSymbol *End) {
2567 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2568 if (DwarfVersion < 4)
2569 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2571 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);