1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE &D,
334 dwarf::Attribute A, const MCSymbol *L,
335 const MCSymbol *Sec) {
336 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
337 U.addSectionLabel(D, A, L);
339 U.addSectionDelta(D, A, L, Sec);
342 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE &ScopeDIE,
343 const SmallVectorImpl<InsnRange> &Range) {
344 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
345 // emitting it appropriately.
346 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
348 // Under fission, ranges are specified by constant offsets relative to the
349 // CU's DW_AT_GNU_ranges_base.
351 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
352 DwarfDebugRangeSectionSym);
354 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
355 DwarfDebugRangeSectionSym);
357 RangeSpanList List(RangeSym);
358 for (const InsnRange &R : Range) {
359 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
360 List.addRange(std::move(Span));
363 // Add the range list to the set of ranges to be emitted.
364 TheCU.addRangeList(std::move(List));
367 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
368 const SmallVectorImpl<InsnRange> &Ranges) {
369 assert(!Ranges.empty());
370 if (Ranges.size() == 1)
371 TheCU.attachLowHighPC(Die, getLabelBeforeInsn(Ranges.front().first),
372 getLabelAfterInsn(Ranges.front().second));
374 addScopeRangeList(TheCU, Die, Ranges);
377 // Construct new DW_TAG_lexical_block for this scope and attach
378 // DW_AT_low_pc/DW_AT_high_pc labels.
380 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
381 LexicalScope *Scope) {
382 if (isLexicalScopeDIENull(Scope))
385 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
386 if (Scope->isAbstractScope())
389 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
394 // This scope represents inlined body of a function. Construct DIE to
395 // represent this concrete inlined copy of the function.
397 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
398 LexicalScope *Scope) {
399 assert(Scope->getScopeNode());
400 DIScope DS(Scope->getScopeNode());
401 DISubprogram InlinedSP = getDISubprogram(DS);
402 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
403 // was inlined from another compile unit.
404 DIE *OriginDIE = AbstractSPDies[InlinedSP];
405 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
407 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
408 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
410 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
412 // Add the call site information to the DIE.
413 DILocation DL(Scope->getInlinedAt());
414 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
415 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
416 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
418 // Add name to the name table, we do this here because we're guaranteed
419 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
420 addSubprogramNames(InlinedSP, *ScopeDIE);
425 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
427 const LexicalScope &Scope,
428 DIE *&ObjectPointer) {
429 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
430 if (DV.isObjectPointer())
431 ObjectPointer = Var.get();
435 DIE *DwarfDebug::createScopeChildrenDIE(
436 DwarfCompileUnit &TheCU, LexicalScope *Scope,
437 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
438 unsigned *ChildScopeCount) {
439 DIE *ObjectPointer = nullptr;
441 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
442 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
444 unsigned ChildCountWithoutScopes = Children.size();
446 for (LexicalScope *LS : Scope->getChildren())
447 TheCU.constructScopeDIE(LS, Children);
450 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
452 return ObjectPointer;
455 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
456 LexicalScope *Scope, DIE &ScopeDIE) {
457 // We create children when the scope DIE is not null.
458 SmallVector<std::unique_ptr<DIE>, 8> Children;
459 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
462 for (auto &I : Children)
463 ScopeDIE.addChild(std::move(I));
465 return ObjectPointer;
468 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
469 LexicalScope *Scope) {
470 assert(Scope && Scope->getScopeNode());
471 assert(Scope->isAbstractScope());
472 assert(!Scope->getInlinedAt());
474 DISubprogram SP(Scope->getScopeNode());
476 ProcessedSPNodes.insert(SP);
478 DIE *&AbsDef = AbstractSPDies[SP];
482 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
483 // was inlined from another compile unit.
484 DwarfCompileUnit &SPCU = *SPMap[SP];
487 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
488 // the important distinction that the DIDescriptor is not associated with the
489 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
490 // any). It could be refactored to some common utility function.
491 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
492 ContextDIE = &SPCU.getUnitDie();
493 SPCU.getOrCreateSubprogramDIE(SPDecl);
495 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
497 // Passing null as the associated DIDescriptor because the abstract definition
498 // shouldn't be found by lookup.
499 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
501 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
503 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
504 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
505 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
506 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
509 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
510 LexicalScope *Scope) {
511 assert(Scope && Scope->getScopeNode());
512 assert(!Scope->getInlinedAt());
513 assert(!Scope->isAbstractScope());
514 DISubprogram Sub(Scope->getScopeNode());
516 assert(Sub.isSubprogram());
518 ProcessedSPNodes.insert(Sub);
520 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
522 // Collect arguments for current function.
523 assert(LScopes.isCurrentFunctionScope(Scope));
524 DIE *ObjectPointer = nullptr;
525 for (DbgVariable *ArgDV : CurrentFnArguments)
528 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
530 // If this is a variadic function, add an unspecified parameter.
531 DITypeArray FnArgs = Sub.getType().getTypeArray();
532 // If we have a single element of null, it is a function that returns void.
533 // If we have more than one elements and the last one is null, it is a
534 // variadic function.
535 if (FnArgs.getNumElements() > 1 &&
536 !FnArgs.getElement(FnArgs.getNumElements() - 1))
537 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
539 // Collect lexical scope children first.
540 // ObjectPointer might be a local (non-argument) local variable if it's a
541 // block's synthetic this pointer.
542 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
543 assert(!ObjectPointer && "multiple object pointers can't be described");
544 ObjectPointer = BlockObjPtr;
548 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
551 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
552 if (!GenerateGnuPubSections)
555 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
558 // Create new DwarfCompileUnit for the given metadata node with tag
559 // DW_TAG_compile_unit.
560 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
561 StringRef FN = DIUnit.getFilename();
562 CompilationDir = DIUnit.getDirectory();
564 auto OwnedUnit = make_unique<DwarfCompileUnit>(
565 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
566 DwarfCompileUnit &NewCU = *OwnedUnit;
567 DIE &Die = NewCU.getUnitDie();
568 InfoHolder.addUnit(std::move(OwnedUnit));
570 // LTO with assembly output shares a single line table amongst multiple CUs.
571 // To avoid the compilation directory being ambiguous, let the line table
572 // explicitly describe the directory of all files, never relying on the
573 // compilation directory.
574 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
575 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
576 NewCU.getUniqueID(), CompilationDir);
578 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
579 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
580 DIUnit.getLanguage());
581 NewCU.addString(Die, dwarf::DW_AT_name, FN);
583 if (!useSplitDwarf()) {
584 NewCU.initStmtList(DwarfLineSectionSym);
586 // If we're using split dwarf the compilation dir is going to be in the
587 // skeleton CU and so we don't need to duplicate it here.
588 if (!CompilationDir.empty())
589 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
591 addGnuPubAttributes(NewCU, Die);
594 if (DIUnit.isOptimized())
595 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
597 StringRef Flags = DIUnit.getFlags();
599 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
601 if (unsigned RVer = DIUnit.getRunTimeVersion())
602 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
603 dwarf::DW_FORM_data1, RVer);
608 if (useSplitDwarf()) {
609 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
610 DwarfInfoDWOSectionSym);
611 NewCU.setSkeleton(constructSkeletonCU(NewCU));
613 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
614 DwarfInfoSectionSym);
616 CUMap.insert(std::make_pair(DIUnit, &NewCU));
617 CUDieMap.insert(std::make_pair(&Die, &NewCU));
621 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
623 DIImportedEntity Module(N);
624 assert(Module.Verify());
625 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
626 D->addChild(TheCU.constructImportedEntityDIE(Module));
629 // Emit all Dwarf sections that should come prior to the content. Create
630 // global DIEs and emit initial debug info sections. This is invoked by
631 // the target AsmPrinter.
632 void DwarfDebug::beginModule() {
633 if (DisableDebugInfoPrinting)
636 const Module *M = MMI->getModule();
638 FunctionDIs = makeSubprogramMap(*M);
640 // If module has named metadata anchors then use them, otherwise scan the
641 // module using debug info finder to collect debug info.
642 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
645 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
647 // Emit initial sections so we can reference labels later.
650 SingleCU = CU_Nodes->getNumOperands() == 1;
652 for (MDNode *N : CU_Nodes->operands()) {
653 DICompileUnit CUNode(N);
654 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
655 DIArray ImportedEntities = CUNode.getImportedEntities();
656 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
657 ScopesWithImportedEntities.push_back(std::make_pair(
658 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
659 ImportedEntities.getElement(i)));
660 std::sort(ScopesWithImportedEntities.begin(),
661 ScopesWithImportedEntities.end(), less_first());
662 DIArray GVs = CUNode.getGlobalVariables();
663 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
664 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
665 DIArray SPs = CUNode.getSubprograms();
666 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
667 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
668 DIArray EnumTypes = CUNode.getEnumTypes();
669 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
670 DIType Ty(EnumTypes.getElement(i));
671 // The enum types array by design contains pointers to
672 // MDNodes rather than DIRefs. Unique them here.
673 DIType UniqueTy(resolve(Ty.getRef()));
674 CU.getOrCreateTypeDIE(UniqueTy);
676 DIArray RetainedTypes = CUNode.getRetainedTypes();
677 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
678 DIType Ty(RetainedTypes.getElement(i));
679 // The retained types array by design contains pointers to
680 // MDNodes rather than DIRefs. Unique them here.
681 DIType UniqueTy(resolve(Ty.getRef()));
682 CU.getOrCreateTypeDIE(UniqueTy);
684 // Emit imported_modules last so that the relevant context is already
686 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
687 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
690 // Tell MMI that we have debug info.
691 MMI->setDebugInfoAvailability(true);
693 // Prime section data.
694 SectionMap[Asm->getObjFileLowering().getTextSection()];
697 void DwarfDebug::finishVariableDefinitions() {
698 for (const auto &Var : ConcreteVariables) {
699 DIE *VariableDie = Var->getDIE();
701 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
702 // in the ConcreteVariables list, rather than looking it up again here.
703 // DIE::getUnit isn't simple - it walks parent pointers, etc.
704 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
706 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
707 if (AbsVar && AbsVar->getDIE()) {
708 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
711 Unit->applyVariableAttributes(*Var, *VariableDie);
715 void DwarfDebug::finishSubprogramDefinitions() {
716 const Module *M = MMI->getModule();
718 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
719 for (MDNode *N : CU_Nodes->operands()) {
720 DICompileUnit TheCU(N);
721 // Construct subprogram DIE and add variables DIEs.
722 DwarfCompileUnit *SPCU =
723 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
724 DIArray Subprograms = TheCU.getSubprograms();
725 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
726 DISubprogram SP(Subprograms.getElement(i));
727 // Perhaps the subprogram is in another CU (such as due to comdat
728 // folding, etc), in which case ignore it here.
729 if (SPMap[SP] != SPCU)
731 DIE *D = SPCU->getDIE(SP);
732 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
734 // If this subprogram has an abstract definition, reference that
735 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
737 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
738 // Lazily construct the subprogram if we didn't see either concrete or
739 // inlined versions during codegen. (except in -gmlt ^ where we want
740 // to omit these entirely)
741 D = SPCU->getOrCreateSubprogramDIE(SP);
743 // And attach the attributes
744 SPCU->applySubprogramAttributesToDefinition(SP, *D);
751 // Collect info for variables that were optimized out.
752 void DwarfDebug::collectDeadVariables() {
753 const Module *M = MMI->getModule();
755 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
756 for (MDNode *N : CU_Nodes->operands()) {
757 DICompileUnit TheCU(N);
758 // Construct subprogram DIE and add variables DIEs.
759 DwarfCompileUnit *SPCU =
760 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
761 assert(SPCU && "Unable to find Compile Unit!");
762 DIArray Subprograms = TheCU.getSubprograms();
763 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
764 DISubprogram SP(Subprograms.getElement(i));
765 if (ProcessedSPNodes.count(SP) != 0)
767 assert(SP.isSubprogram() &&
768 "CU's subprogram list contains a non-subprogram");
769 assert(SP.isDefinition() &&
770 "CU's subprogram list contains a subprogram declaration");
771 DIArray Variables = SP.getVariables();
772 if (Variables.getNumElements() == 0)
775 DIE *SPDIE = AbstractSPDies.lookup(SP);
777 SPDIE = SPCU->getDIE(SP);
779 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
780 DIVariable DV(Variables.getElement(vi));
781 assert(DV.isVariable());
782 DbgVariable NewVar(DV, DIExpression(nullptr), this);
783 auto VariableDie = SPCU->constructVariableDIE(NewVar);
784 SPCU->applyVariableAttributes(NewVar, *VariableDie);
785 SPDIE->addChild(std::move(VariableDie));
792 void DwarfDebug::finalizeModuleInfo() {
793 finishSubprogramDefinitions();
795 finishVariableDefinitions();
797 // Collect info for variables that were optimized out.
798 collectDeadVariables();
800 // Handle anything that needs to be done on a per-unit basis after
801 // all other generation.
802 for (const auto &TheU : getUnits()) {
803 // Emit DW_AT_containing_type attribute to connect types with their
804 // vtable holding type.
805 TheU->constructContainingTypeDIEs();
807 // Add CU specific attributes if we need to add any.
808 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
809 // If we're splitting the dwarf out now that we've got the entire
810 // CU then add the dwo id to it.
811 DwarfCompileUnit *SkCU =
812 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
813 if (useSplitDwarf()) {
814 // Emit a unique identifier for this CU.
815 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
816 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
817 dwarf::DW_FORM_data8, ID);
818 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
819 dwarf::DW_FORM_data8, ID);
821 // We don't keep track of which addresses are used in which CU so this
822 // is a bit pessimistic under LTO.
823 if (!AddrPool.isEmpty())
824 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
825 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
826 DwarfAddrSectionSym);
827 if (!TheU->getRangeLists().empty())
828 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
829 dwarf::DW_AT_GNU_ranges_base,
830 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
833 // If we have code split among multiple sections or non-contiguous
834 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
835 // remain in the .o file, otherwise add a DW_AT_low_pc.
836 // FIXME: We should use ranges allow reordering of code ala
837 // .subsections_via_symbols in mach-o. This would mean turning on
838 // ranges for all subprogram DIEs for mach-o.
839 DwarfCompileUnit &U =
840 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
841 unsigned NumRanges = TheU->getRanges().size();
844 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
845 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
846 DwarfDebugRangeSectionSym);
848 // A DW_AT_low_pc attribute may also be specified in combination with
849 // DW_AT_ranges to specify the default base address for use in
850 // location lists (see Section 2.6.2) and range lists (see Section
852 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
855 RangeSpan &Range = TheU->getRanges().back();
856 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
862 // Compute DIE offsets and sizes.
863 InfoHolder.computeSizeAndOffsets();
865 SkeletonHolder.computeSizeAndOffsets();
868 void DwarfDebug::endSections() {
869 // Filter labels by section.
870 for (const SymbolCU &SCU : ArangeLabels) {
871 if (SCU.Sym->isInSection()) {
872 // Make a note of this symbol and it's section.
873 const MCSection *Section = &SCU.Sym->getSection();
874 if (!Section->getKind().isMetadata())
875 SectionMap[Section].push_back(SCU);
877 // Some symbols (e.g. common/bss on mach-o) can have no section but still
878 // appear in the output. This sucks as we rely on sections to build
879 // arange spans. We can do it without, but it's icky.
880 SectionMap[nullptr].push_back(SCU);
884 // Build a list of sections used.
885 std::vector<const MCSection *> Sections;
886 for (const auto &it : SectionMap) {
887 const MCSection *Section = it.first;
888 Sections.push_back(Section);
891 // Sort the sections into order.
892 // This is only done to ensure consistent output order across different runs.
893 std::sort(Sections.begin(), Sections.end(), SectionSort);
895 // Add terminating symbols for each section.
896 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
897 const MCSection *Section = Sections[ID];
898 MCSymbol *Sym = nullptr;
901 // We can't call MCSection::getLabelEndName, as it's only safe to do so
902 // if we know the section name up-front. For user-created sections, the
903 // resulting label may not be valid to use as a label. (section names can
904 // use a greater set of characters on some systems)
905 Sym = Asm->GetTempSymbol("debug_end", ID);
906 Asm->OutStreamer.SwitchSection(Section);
907 Asm->OutStreamer.EmitLabel(Sym);
910 // Insert a final terminator.
911 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
915 // Emit all Dwarf sections that should come after the content.
916 void DwarfDebug::endModule() {
917 assert(CurFn == nullptr);
918 assert(CurMI == nullptr);
923 // End any existing sections.
924 // TODO: Does this need to happen?
927 // Finalize the debug info for the module.
928 finalizeModuleInfo();
932 // Emit all the DIEs into a debug info section.
935 // Corresponding abbreviations into a abbrev section.
938 // Emit info into a debug aranges section.
939 if (GenerateARangeSection)
942 // Emit info into a debug ranges section.
945 if (useSplitDwarf()) {
948 emitDebugAbbrevDWO();
951 // Emit DWO addresses.
952 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
954 // Emit info into a debug loc section.
957 // Emit info into the dwarf accelerator table sections.
958 if (useDwarfAccelTables()) {
961 emitAccelNamespaces();
965 // Emit the pubnames and pubtypes sections if requested.
966 if (HasDwarfPubSections) {
967 emitDebugPubNames(GenerateGnuPubSections);
968 emitDebugPubTypes(GenerateGnuPubSections);
973 AbstractVariables.clear();
975 // Reset these for the next Module if we have one.
979 // Find abstract variable, if any, associated with Var.
980 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
981 DIVariable &Cleansed) {
982 LLVMContext &Ctx = DV->getContext();
983 // More then one inlined variable corresponds to one abstract variable.
984 // FIXME: This duplication of variables when inlining should probably be
985 // removed. It's done to allow each DIVariable to describe its location
986 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
987 // make it accurate then remove this duplication/cleansing stuff.
988 Cleansed = cleanseInlinedVariable(DV, Ctx);
989 auto I = AbstractVariables.find(Cleansed);
990 if (I != AbstractVariables.end())
991 return I->second.get();
995 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
997 return getExistingAbstractVariable(DV, Cleansed);
1000 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1001 LexicalScope *Scope) {
1002 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
1003 addScopeVariable(Scope, AbsDbgVariable.get());
1004 AbstractVariables[Var] = std::move(AbsDbgVariable);
1007 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1008 const MDNode *ScopeNode) {
1009 DIVariable Cleansed = DV;
1010 if (getExistingAbstractVariable(DV, Cleansed))
1013 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1017 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1018 const MDNode *ScopeNode) {
1019 DIVariable Cleansed = DV;
1020 if (getExistingAbstractVariable(DV, Cleansed))
1023 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1024 createAbstractVariable(Cleansed, Scope);
1027 // If Var is a current function argument then add it to CurrentFnArguments list.
1028 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1029 if (!LScopes.isCurrentFunctionScope(Scope))
1031 DIVariable DV = Var->getVariable();
1032 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1034 unsigned ArgNo = DV.getArgNumber();
1038 size_t Size = CurrentFnArguments.size();
1040 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1041 // llvm::Function argument size is not good indicator of how many
1042 // arguments does the function have at source level.
1044 CurrentFnArguments.resize(ArgNo * 2);
1045 assert(!CurrentFnArguments[ArgNo - 1]);
1046 CurrentFnArguments[ArgNo - 1] = Var;
1050 // Collect variable information from side table maintained by MMI.
1051 void DwarfDebug::collectVariableInfoFromMMITable(
1052 SmallPtrSetImpl<const MDNode *> &Processed) {
1053 for (const auto &VI : MMI->getVariableDbgInfo()) {
1056 Processed.insert(VI.Var);
1057 DIVariable DV(VI.Var);
1058 DIExpression Expr(VI.Expr);
1059 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1061 // If variable scope is not found then skip this variable.
1065 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1066 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1067 DbgVariable *RegVar = ConcreteVariables.back().get();
1068 RegVar->setFrameIndex(VI.Slot);
1069 addScopeVariable(Scope, RegVar);
1073 // Get .debug_loc entry for the instruction range starting at MI.
1074 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1075 const MDNode *Expr = MI->getDebugExpression();
1076 const MDNode *Var = MI->getDebugVariable();
1078 assert(MI->getNumOperands() == 4);
1079 if (MI->getOperand(0).isReg()) {
1080 MachineLocation MLoc;
1081 // If the second operand is an immediate, this is a
1082 // register-indirect address.
1083 if (!MI->getOperand(1).isImm())
1084 MLoc.set(MI->getOperand(0).getReg());
1086 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1087 return DebugLocEntry::Value(Var, Expr, MLoc);
1089 if (MI->getOperand(0).isImm())
1090 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1091 if (MI->getOperand(0).isFPImm())
1092 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1093 if (MI->getOperand(0).isCImm())
1094 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1096 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1099 /// Determine whether two variable pieces overlap.
1100 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1101 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1103 unsigned l1 = P1.getPieceOffset();
1104 unsigned l2 = P2.getPieceOffset();
1105 unsigned r1 = l1 + P1.getPieceSize();
1106 unsigned r2 = l2 + P2.getPieceSize();
1107 // True where [l1,r1[ and [r1,r2[ overlap.
1108 return (l1 < r2) && (l2 < r1);
1111 /// Build the location list for all DBG_VALUEs in the function that
1112 /// describe the same variable. If the ranges of several independent
1113 /// pieces of the same variable overlap partially, split them up and
1114 /// combine the ranges. The resulting DebugLocEntries are will have
1115 /// strict monotonically increasing begin addresses and will never
1120 // Ranges History [var, loc, piece ofs size]
1121 // 0 | [x, (reg0, piece 0, 32)]
1122 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1124 // 3 | [clobber reg0]
1125 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1129 // [0-1] [x, (reg0, piece 0, 32)]
1130 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1131 // [3-4] [x, (reg1, piece 32, 32)]
1132 // [4- ] [x, (mem, piece 0, 64)]
1134 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1135 const DbgValueHistoryMap::InstrRanges &Ranges) {
1136 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1138 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1139 const MachineInstr *Begin = I->first;
1140 const MachineInstr *End = I->second;
1141 assert(Begin->isDebugValue() && "Invalid History entry");
1143 // Check if a variable is inaccessible in this range.
1144 if (Begin->getNumOperands() > 1 &&
1145 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1150 // If this piece overlaps with any open ranges, truncate them.
1151 DIExpression DIExpr = Begin->getDebugExpression();
1152 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1153 [&](DebugLocEntry::Value R) {
1154 return piecesOverlap(DIExpr, R.getExpression());
1156 OpenRanges.erase(Last, OpenRanges.end());
1158 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1159 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1161 const MCSymbol *EndLabel;
1163 EndLabel = getLabelAfterInsn(End);
1164 else if (std::next(I) == Ranges.end())
1165 EndLabel = FunctionEndSym;
1167 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1168 assert(EndLabel && "Forgot label after instruction ending a range!");
1170 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1172 auto Value = getDebugLocValue(Begin);
1173 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1174 bool couldMerge = false;
1176 // If this is a piece, it may belong to the current DebugLocEntry.
1177 if (DIExpr.isVariablePiece()) {
1178 // Add this value to the list of open ranges.
1179 OpenRanges.push_back(Value);
1181 // Attempt to add the piece to the last entry.
1182 if (!DebugLoc.empty())
1183 if (DebugLoc.back().MergeValues(Loc))
1188 // Need to add a new DebugLocEntry. Add all values from still
1189 // valid non-overlapping pieces.
1190 if (OpenRanges.size())
1191 Loc.addValues(OpenRanges);
1193 DebugLoc.push_back(std::move(Loc));
1196 // Attempt to coalesce the ranges of two otherwise identical
1198 auto CurEntry = DebugLoc.rbegin();
1199 auto PrevEntry = std::next(CurEntry);
1200 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1201 DebugLoc.pop_back();
1204 dbgs() << CurEntry->getValues().size() << " Values:\n";
1205 for (auto Value : CurEntry->getValues()) {
1206 Value.getVariable()->dump();
1207 Value.getExpression()->dump();
1209 dbgs() << "-----\n";
1215 // Find variables for each lexical scope.
1217 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1218 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1219 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1221 // Grab the variable info that was squirreled away in the MMI side-table.
1222 collectVariableInfoFromMMITable(Processed);
1224 for (const auto &I : DbgValues) {
1225 DIVariable DV(I.first);
1226 if (Processed.count(DV))
1229 // Instruction ranges, specifying where DV is accessible.
1230 const auto &Ranges = I.second;
1234 LexicalScope *Scope = nullptr;
1235 if (MDNode *IA = DV.getInlinedAt()) {
1236 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1237 Scope = LScopes.findInlinedScope(DebugLoc::get(
1238 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1240 Scope = LScopes.findLexicalScope(DV.getContext());
1241 // If variable scope is not found then skip this variable.
1245 Processed.insert(DV);
1246 const MachineInstr *MInsn = Ranges.front().first;
1247 assert(MInsn->isDebugValue() && "History must begin with debug value");
1248 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1249 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1250 DbgVariable *RegVar = ConcreteVariables.back().get();
1251 addScopeVariable(Scope, RegVar);
1253 // Check if the first DBG_VALUE is valid for the rest of the function.
1254 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1257 // Handle multiple DBG_VALUE instructions describing one variable.
1258 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1260 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1261 DebugLocList &LocList = DotDebugLocEntries.back();
1264 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1266 // Build the location list for this variable.
1267 buildLocationList(LocList.List, Ranges);
1270 // Collect info for variables that were optimized out.
1271 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1272 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1273 DIVariable DV(Variables.getElement(i));
1274 assert(DV.isVariable());
1275 if (!Processed.insert(DV))
1277 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1278 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1279 DIExpression NoExpr;
1280 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1281 addScopeVariable(Scope, ConcreteVariables.back().get());
1286 // Return Label preceding the instruction.
1287 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1288 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1289 assert(Label && "Didn't insert label before instruction");
1293 // Return Label immediately following the instruction.
1294 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1295 return LabelsAfterInsn.lookup(MI);
1298 // Process beginning of an instruction.
1299 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1300 assert(CurMI == nullptr);
1302 // Check if source location changes, but ignore DBG_VALUE locations.
1303 if (!MI->isDebugValue()) {
1304 DebugLoc DL = MI->getDebugLoc();
1305 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1308 if (DL == PrologEndLoc) {
1309 Flags |= DWARF2_FLAG_PROLOGUE_END;
1310 PrologEndLoc = DebugLoc();
1312 if (PrologEndLoc.isUnknown())
1313 Flags |= DWARF2_FLAG_IS_STMT;
1315 if (!DL.isUnknown()) {
1316 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1317 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1319 recordSourceLine(0, 0, nullptr, 0);
1323 // Insert labels where requested.
1324 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1325 LabelsBeforeInsn.find(MI);
1328 if (I == LabelsBeforeInsn.end())
1331 // Label already assigned.
1336 PrevLabel = MMI->getContext().CreateTempSymbol();
1337 Asm->OutStreamer.EmitLabel(PrevLabel);
1339 I->second = PrevLabel;
1342 // Process end of an instruction.
1343 void DwarfDebug::endInstruction() {
1344 assert(CurMI != nullptr);
1345 // Don't create a new label after DBG_VALUE instructions.
1346 // They don't generate code.
1347 if (!CurMI->isDebugValue())
1348 PrevLabel = nullptr;
1350 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1351 LabelsAfterInsn.find(CurMI);
1355 if (I == LabelsAfterInsn.end())
1358 // Label already assigned.
1362 // We need a label after this instruction.
1364 PrevLabel = MMI->getContext().CreateTempSymbol();
1365 Asm->OutStreamer.EmitLabel(PrevLabel);
1367 I->second = PrevLabel;
1370 // Each LexicalScope has first instruction and last instruction to mark
1371 // beginning and end of a scope respectively. Create an inverse map that list
1372 // scopes starts (and ends) with an instruction. One instruction may start (or
1373 // end) multiple scopes. Ignore scopes that are not reachable.
1374 void DwarfDebug::identifyScopeMarkers() {
1375 SmallVector<LexicalScope *, 4> WorkList;
1376 WorkList.push_back(LScopes.getCurrentFunctionScope());
1377 while (!WorkList.empty()) {
1378 LexicalScope *S = WorkList.pop_back_val();
1380 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1381 if (!Children.empty())
1382 WorkList.append(Children.begin(), Children.end());
1384 if (S->isAbstractScope())
1387 for (const InsnRange &R : S->getRanges()) {
1388 assert(R.first && "InsnRange does not have first instruction!");
1389 assert(R.second && "InsnRange does not have second instruction!");
1390 requestLabelBeforeInsn(R.first);
1391 requestLabelAfterInsn(R.second);
1396 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1397 // First known non-DBG_VALUE and non-frame setup location marks
1398 // the beginning of the function body.
1399 for (const auto &MBB : *MF)
1400 for (const auto &MI : MBB)
1401 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1402 !MI.getDebugLoc().isUnknown())
1403 return MI.getDebugLoc();
1407 // Gather pre-function debug information. Assumes being called immediately
1408 // after the function entry point has been emitted.
1409 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1412 // If there's no debug info for the function we're not going to do anything.
1413 if (!MMI->hasDebugInfo())
1416 auto DI = FunctionDIs.find(MF->getFunction());
1417 if (DI == FunctionDIs.end())
1420 // Grab the lexical scopes for the function, if we don't have any of those
1421 // then we're not going to be able to do anything.
1422 LScopes.initialize(*MF);
1423 if (LScopes.empty())
1426 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1428 // Make sure that each lexical scope will have a begin/end label.
1429 identifyScopeMarkers();
1431 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1432 // belongs to so that we add to the correct per-cu line table in the
1434 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1435 // FnScope->getScopeNode() and DI->second should represent the same function,
1436 // though they may not be the same MDNode due to inline functions merged in
1437 // LTO where the debug info metadata still differs (either due to distinct
1438 // written differences - two versions of a linkonce_odr function
1439 // written/copied into two separate files, or some sub-optimal metadata that
1440 // isn't structurally identical (see: file path/name info from clang, which
1441 // includes the directory of the cpp file being built, even when the file name
1442 // is absolute (such as an <> lookup header)))
1443 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1444 assert(TheCU && "Unable to find compile unit!");
1445 if (Asm->OutStreamer.hasRawTextSupport())
1446 // Use a single line table if we are generating assembly.
1447 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1449 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1451 // Emit a label for the function so that we have a beginning address.
1452 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1453 // Assumes in correct section after the entry point.
1454 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1456 // Calculate history for local variables.
1457 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1460 // Request labels for the full history.
1461 for (const auto &I : DbgValues) {
1462 const auto &Ranges = I.second;
1466 // The first mention of a function argument gets the FunctionBeginSym
1467 // label, so arguments are visible when breaking at function entry.
1468 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1469 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1470 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1471 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1472 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1473 // Mark all non-overlapping initial pieces.
1474 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1475 DIExpression Piece = I->first->getDebugExpression();
1476 if (std::all_of(Ranges.begin(), I,
1477 [&](DbgValueHistoryMap::InstrRange Pred) {
1478 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1480 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1487 for (const auto &Range : Ranges) {
1488 requestLabelBeforeInsn(Range.first);
1490 requestLabelAfterInsn(Range.second);
1494 PrevInstLoc = DebugLoc();
1495 PrevLabel = FunctionBeginSym;
1497 // Record beginning of function.
1498 PrologEndLoc = findPrologueEndLoc(MF);
1499 if (!PrologEndLoc.isUnknown()) {
1500 DebugLoc FnStartDL =
1501 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1503 FnStartDL.getLine(), FnStartDL.getCol(),
1504 FnStartDL.getScope(MF->getFunction()->getContext()),
1505 // We'd like to list the prologue as "not statements" but GDB behaves
1506 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1507 DWARF2_FLAG_IS_STMT);
1511 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1512 if (addCurrentFnArgument(Var, LS))
1514 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1515 DIVariable DV = Var->getVariable();
1516 // Variables with positive arg numbers are parameters.
1517 if (unsigned ArgNum = DV.getArgNumber()) {
1518 // Keep all parameters in order at the start of the variable list to ensure
1519 // function types are correct (no out-of-order parameters)
1521 // This could be improved by only doing it for optimized builds (unoptimized
1522 // builds have the right order to begin with), searching from the back (this
1523 // would catch the unoptimized case quickly), or doing a binary search
1524 // rather than linear search.
1525 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1526 while (I != Vars.end()) {
1527 unsigned CurNum = (*I)->getVariable().getArgNumber();
1528 // A local (non-parameter) variable has been found, insert immediately
1532 // A later indexed parameter has been found, insert immediately before it.
1533 if (CurNum > ArgNum)
1537 Vars.insert(I, Var);
1541 Vars.push_back(Var);
1544 // Gather and emit post-function debug information.
1545 void DwarfDebug::endFunction(const MachineFunction *MF) {
1546 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1547 // though the beginFunction may not be called at all.
1548 // We should handle both cases.
1552 assert(CurFn == MF);
1553 assert(CurFn != nullptr);
1555 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1556 !FunctionDIs.count(MF->getFunction())) {
1557 // If we don't have a lexical scope for this function then there will
1558 // be a hole in the range information. Keep note of this by setting the
1559 // previously used section to nullptr.
1565 // Define end label for subprogram.
1566 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1567 // Assumes in correct section after the entry point.
1568 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1570 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1571 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1573 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1574 collectVariableInfo(ProcessedVars);
1576 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1577 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1579 // Add the range of this function to the list of ranges for the CU.
1580 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1582 // Under -gmlt, skip building the subprogram if there are no inlined
1583 // subroutines inside it.
1584 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1585 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1586 assert(ScopeVariables.empty());
1587 assert(CurrentFnArguments.empty());
1588 assert(DbgValues.empty());
1589 assert(AbstractVariables.empty());
1590 LabelsBeforeInsn.clear();
1591 LabelsAfterInsn.clear();
1592 PrevLabel = nullptr;
1597 // Construct abstract scopes.
1598 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1599 DISubprogram SP(AScope->getScopeNode());
1600 assert(SP.isSubprogram());
1601 // Collect info for variables that were optimized out.
1602 DIArray Variables = SP.getVariables();
1603 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1604 DIVariable DV(Variables.getElement(i));
1605 assert(DV && DV.isVariable());
1606 if (!ProcessedVars.insert(DV))
1608 ensureAbstractVariableIsCreated(DV, DV.getContext());
1610 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1613 constructSubprogramScopeDIE(TheCU, FnScope);
1616 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1617 // DbgVariables except those that are also in AbstractVariables (since they
1618 // can be used cross-function)
1619 ScopeVariables.clear();
1620 CurrentFnArguments.clear();
1622 LabelsBeforeInsn.clear();
1623 LabelsAfterInsn.clear();
1624 PrevLabel = nullptr;
1628 // Register a source line with debug info. Returns the unique label that was
1629 // emitted and which provides correspondence to the source line list.
1630 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1635 unsigned Discriminator = 0;
1636 if (DIScope Scope = DIScope(S)) {
1637 assert(Scope.isScope());
1638 Fn = Scope.getFilename();
1639 Dir = Scope.getDirectory();
1640 if (Scope.isLexicalBlockFile())
1641 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1643 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1644 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1645 .getOrCreateSourceID(Fn, Dir);
1647 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1651 //===----------------------------------------------------------------------===//
1653 //===----------------------------------------------------------------------===//
1655 // Emit initial Dwarf sections with a label at the start of each one.
1656 void DwarfDebug::emitSectionLabels() {
1657 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1659 // Dwarf sections base addresses.
1660 DwarfInfoSectionSym =
1661 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1662 if (useSplitDwarf()) {
1663 DwarfInfoDWOSectionSym =
1664 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1665 DwarfTypesDWOSectionSym =
1666 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1668 DwarfAbbrevSectionSym =
1669 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1670 if (useSplitDwarf())
1671 DwarfAbbrevDWOSectionSym = emitSectionSym(
1672 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1673 if (GenerateARangeSection)
1674 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1676 DwarfLineSectionSym =
1677 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1678 if (GenerateGnuPubSections) {
1679 DwarfGnuPubNamesSectionSym =
1680 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1681 DwarfGnuPubTypesSectionSym =
1682 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1683 } else if (HasDwarfPubSections) {
1684 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1685 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1688 DwarfStrSectionSym =
1689 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1690 if (useSplitDwarf()) {
1691 DwarfStrDWOSectionSym =
1692 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1693 DwarfAddrSectionSym =
1694 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1695 DwarfDebugLocSectionSym =
1696 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1698 DwarfDebugLocSectionSym =
1699 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1700 DwarfDebugRangeSectionSym =
1701 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1704 // Recursively emits a debug information entry.
1705 void DwarfDebug::emitDIE(DIE &Die) {
1706 // Get the abbreviation for this DIE.
1707 const DIEAbbrev &Abbrev = Die.getAbbrev();
1709 // Emit the code (index) for the abbreviation.
1710 if (Asm->isVerbose())
1711 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1712 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1713 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1714 dwarf::TagString(Abbrev.getTag()));
1715 Asm->EmitULEB128(Abbrev.getNumber());
1717 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1718 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1720 // Emit the DIE attribute values.
1721 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1722 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1723 dwarf::Form Form = AbbrevData[i].getForm();
1724 assert(Form && "Too many attributes for DIE (check abbreviation)");
1726 if (Asm->isVerbose()) {
1727 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1728 if (Attr == dwarf::DW_AT_accessibility)
1729 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1730 cast<DIEInteger>(Values[i])->getValue()));
1733 // Emit an attribute using the defined form.
1734 Values[i]->EmitValue(Asm, Form);
1737 // Emit the DIE children if any.
1738 if (Abbrev.hasChildren()) {
1739 for (auto &Child : Die.getChildren())
1742 Asm->OutStreamer.AddComment("End Of Children Mark");
1747 // Emit the debug info section.
1748 void DwarfDebug::emitDebugInfo() {
1749 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1751 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1754 // Emit the abbreviation section.
1755 void DwarfDebug::emitAbbreviations() {
1756 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1758 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1761 // Emit the last address of the section and the end of the line matrix.
1762 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1763 // Define last address of section.
1764 Asm->OutStreamer.AddComment("Extended Op");
1767 Asm->OutStreamer.AddComment("Op size");
1768 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1769 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1770 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1772 Asm->OutStreamer.AddComment("Section end label");
1774 Asm->OutStreamer.EmitSymbolValue(
1775 Asm->GetTempSymbol("section_end", SectionEnd),
1776 Asm->getDataLayout().getPointerSize());
1778 // Mark end of matrix.
1779 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1785 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1786 StringRef TableName, StringRef SymName) {
1787 Accel.FinalizeTable(Asm, TableName);
1788 Asm->OutStreamer.SwitchSection(Section);
1789 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1790 Asm->OutStreamer.EmitLabel(SectionBegin);
1792 // Emit the full data.
1793 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1796 // Emit visible names into a hashed accelerator table section.
1797 void DwarfDebug::emitAccelNames() {
1798 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1799 "Names", "names_begin");
1802 // Emit objective C classes and categories into a hashed accelerator table
1804 void DwarfDebug::emitAccelObjC() {
1805 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1806 "ObjC", "objc_begin");
1809 // Emit namespace dies into a hashed accelerator table.
1810 void DwarfDebug::emitAccelNamespaces() {
1811 emitAccel(AccelNamespace,
1812 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1813 "namespac", "namespac_begin");
1816 // Emit type dies into a hashed accelerator table.
1817 void DwarfDebug::emitAccelTypes() {
1818 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1819 "types", "types_begin");
1822 // Public name handling.
1823 // The format for the various pubnames:
1825 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1826 // for the DIE that is named.
1828 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1829 // into the CU and the index value is computed according to the type of value
1830 // for the DIE that is named.
1832 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1833 // it's the offset within the debug_info/debug_types dwo section, however, the
1834 // reference in the pubname header doesn't change.
1836 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1837 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1839 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1841 // We could have a specification DIE that has our most of our knowledge,
1842 // look for that now.
1843 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1845 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1846 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1847 Linkage = dwarf::GIEL_EXTERNAL;
1848 } else if (Die->findAttribute(dwarf::DW_AT_external))
1849 Linkage = dwarf::GIEL_EXTERNAL;
1851 switch (Die->getTag()) {
1852 case dwarf::DW_TAG_class_type:
1853 case dwarf::DW_TAG_structure_type:
1854 case dwarf::DW_TAG_union_type:
1855 case dwarf::DW_TAG_enumeration_type:
1856 return dwarf::PubIndexEntryDescriptor(
1857 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1858 ? dwarf::GIEL_STATIC
1859 : dwarf::GIEL_EXTERNAL);
1860 case dwarf::DW_TAG_typedef:
1861 case dwarf::DW_TAG_base_type:
1862 case dwarf::DW_TAG_subrange_type:
1863 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1864 case dwarf::DW_TAG_namespace:
1865 return dwarf::GIEK_TYPE;
1866 case dwarf::DW_TAG_subprogram:
1867 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1868 case dwarf::DW_TAG_constant:
1869 case dwarf::DW_TAG_variable:
1870 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1871 case dwarf::DW_TAG_enumerator:
1872 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1873 dwarf::GIEL_STATIC);
1875 return dwarf::GIEK_NONE;
1879 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1881 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1882 const MCSection *PSec =
1883 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1884 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1886 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1889 void DwarfDebug::emitDebugPubSection(
1890 bool GnuStyle, const MCSection *PSec, StringRef Name,
1891 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1892 for (const auto &NU : CUMap) {
1893 DwarfCompileUnit *TheU = NU.second;
1895 const auto &Globals = (TheU->*Accessor)();
1897 if (Globals.empty())
1900 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1902 unsigned ID = TheU->getUniqueID();
1904 // Start the dwarf pubnames section.
1905 Asm->OutStreamer.SwitchSection(PSec);
1908 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1909 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1910 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1911 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1913 Asm->OutStreamer.EmitLabel(BeginLabel);
1915 Asm->OutStreamer.AddComment("DWARF Version");
1916 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1918 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1919 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1921 Asm->OutStreamer.AddComment("Compilation Unit Length");
1922 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1924 // Emit the pubnames for this compilation unit.
1925 for (const auto &GI : Globals) {
1926 const char *Name = GI.getKeyData();
1927 const DIE *Entity = GI.second;
1929 Asm->OutStreamer.AddComment("DIE offset");
1930 Asm->EmitInt32(Entity->getOffset());
1933 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1934 Asm->OutStreamer.AddComment(
1935 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1936 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1937 Asm->EmitInt8(Desc.toBits());
1940 Asm->OutStreamer.AddComment("External Name");
1941 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1944 Asm->OutStreamer.AddComment("End Mark");
1946 Asm->OutStreamer.EmitLabel(EndLabel);
1950 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1951 const MCSection *PSec =
1952 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1953 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1955 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1958 // Emit visible names into a debug str section.
1959 void DwarfDebug::emitDebugStr() {
1960 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1961 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1964 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1965 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1966 const DITypeIdentifierMap &Map,
1967 ArrayRef<DebugLocEntry::Value> Values) {
1968 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1969 return P.isVariablePiece();
1970 }) && "all values are expected to be pieces");
1971 assert(std::is_sorted(Values.begin(), Values.end()) &&
1972 "pieces are expected to be sorted");
1974 unsigned Offset = 0;
1975 for (auto Piece : Values) {
1976 DIExpression Expr = Piece.getExpression();
1977 unsigned PieceOffset = Expr.getPieceOffset();
1978 unsigned PieceSize = Expr.getPieceSize();
1979 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1980 if (Offset < PieceOffset) {
1981 // The DWARF spec seriously mandates pieces with no locations for gaps.
1982 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1983 Offset += PieceOffset-Offset;
1986 Offset += PieceSize;
1988 const unsigned SizeOfByte = 8;
1990 DIVariable Var = Piece.getVariable();
1991 assert(!Var.isIndirect() && "indirect address for piece");
1992 unsigned VarSize = Var.getSizeInBits(Map);
1993 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1994 && "piece is larger than or outside of variable");
1995 assert(PieceSize*SizeOfByte != VarSize
1996 && "piece covers entire variable");
1998 if (Piece.isLocation() && Piece.getLoc().isReg())
1999 Asm->EmitDwarfRegOpPiece(Streamer,
2001 PieceSize*SizeOfByte);
2003 emitDebugLocValue(Streamer, Piece);
2004 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2010 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2011 const DebugLocEntry &Entry) {
2012 const DebugLocEntry::Value Value = Entry.getValues()[0];
2013 if (Value.isVariablePiece())
2014 // Emit all pieces that belong to the same variable and range.
2015 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2017 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2018 emitDebugLocValue(Streamer, Value);
2021 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2022 const DebugLocEntry::Value &Value) {
2023 DIVariable DV = Value.getVariable();
2025 if (Value.isInt()) {
2026 DIBasicType BTy(resolve(DV.getType()));
2027 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2028 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2029 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2030 Streamer.EmitSLEB128(Value.getInt());
2032 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2033 Streamer.EmitULEB128(Value.getInt());
2035 } else if (Value.isLocation()) {
2036 MachineLocation Loc = Value.getLoc();
2037 DIExpression Expr = Value.getExpression();
2040 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2042 // Complex address entry.
2043 unsigned N = Expr.getNumElements();
2045 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2046 if (Loc.getOffset()) {
2048 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2049 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2050 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2051 Streamer.EmitSLEB128(Expr.getElement(1));
2053 // If first address element is OpPlus then emit
2054 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2055 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2056 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2060 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2063 // Emit remaining complex address elements.
2064 for (; i < N; ++i) {
2065 uint64_t Element = Expr.getElement(i);
2066 if (Element == dwarf::DW_OP_plus) {
2067 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2068 Streamer.EmitULEB128(Expr.getElement(++i));
2069 } else if (Element == dwarf::DW_OP_deref) {
2071 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2072 } else if (Element == dwarf::DW_OP_piece) {
2074 // handled in emitDebugLocEntry.
2076 llvm_unreachable("unknown Opcode found in complex address");
2080 // else ... ignore constant fp. There is not any good way to
2081 // to represent them here in dwarf.
2085 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2086 Asm->OutStreamer.AddComment("Loc expr size");
2087 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2088 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2089 Asm->EmitLabelDifference(end, begin, 2);
2090 Asm->OutStreamer.EmitLabel(begin);
2092 APByteStreamer Streamer(*Asm);
2093 emitDebugLocEntry(Streamer, Entry);
2095 Asm->OutStreamer.EmitLabel(end);
2098 // Emit locations into the debug loc section.
2099 void DwarfDebug::emitDebugLoc() {
2100 // Start the dwarf loc section.
2101 Asm->OutStreamer.SwitchSection(
2102 Asm->getObjFileLowering().getDwarfLocSection());
2103 unsigned char Size = Asm->getDataLayout().getPointerSize();
2104 for (const auto &DebugLoc : DotDebugLocEntries) {
2105 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2106 const DwarfCompileUnit *CU = DebugLoc.CU;
2107 assert(!CU->getRanges().empty());
2108 for (const auto &Entry : DebugLoc.List) {
2109 // Set up the range. This range is relative to the entry point of the
2110 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2111 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2112 if (CU->getRanges().size() == 1) {
2113 // Grab the begin symbol from the first range as our base.
2114 const MCSymbol *Base = CU->getRanges()[0].getStart();
2115 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2116 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2118 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2119 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2122 emitDebugLocEntryLocation(Entry);
2124 Asm->OutStreamer.EmitIntValue(0, Size);
2125 Asm->OutStreamer.EmitIntValue(0, Size);
2129 void DwarfDebug::emitDebugLocDWO() {
2130 Asm->OutStreamer.SwitchSection(
2131 Asm->getObjFileLowering().getDwarfLocDWOSection());
2132 for (const auto &DebugLoc : DotDebugLocEntries) {
2133 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2134 for (const auto &Entry : DebugLoc.List) {
2135 // Just always use start_length for now - at least that's one address
2136 // rather than two. We could get fancier and try to, say, reuse an
2137 // address we know we've emitted elsewhere (the start of the function?
2138 // The start of the CU or CU subrange that encloses this range?)
2139 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2140 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2141 Asm->EmitULEB128(idx);
2142 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2144 emitDebugLocEntryLocation(Entry);
2146 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2151 const MCSymbol *Start, *End;
2154 // Emit a debug aranges section, containing a CU lookup for any
2155 // address we can tie back to a CU.
2156 void DwarfDebug::emitDebugARanges() {
2157 // Start the dwarf aranges section.
2158 Asm->OutStreamer.SwitchSection(
2159 Asm->getObjFileLowering().getDwarfARangesSection());
2161 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2165 // Build a list of sections used.
2166 std::vector<const MCSection *> Sections;
2167 for (const auto &it : SectionMap) {
2168 const MCSection *Section = it.first;
2169 Sections.push_back(Section);
2172 // Sort the sections into order.
2173 // This is only done to ensure consistent output order across different runs.
2174 std::sort(Sections.begin(), Sections.end(), SectionSort);
2176 // Build a set of address spans, sorted by CU.
2177 for (const MCSection *Section : Sections) {
2178 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2179 if (List.size() < 2)
2182 // Sort the symbols by offset within the section.
2183 std::sort(List.begin(), List.end(),
2184 [&](const SymbolCU &A, const SymbolCU &B) {
2185 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2186 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2188 // Symbols with no order assigned should be placed at the end.
2189 // (e.g. section end labels)
2197 // If we have no section (e.g. common), just write out
2198 // individual spans for each symbol.
2200 for (const SymbolCU &Cur : List) {
2202 Span.Start = Cur.Sym;
2205 Spans[Cur.CU].push_back(Span);
2208 // Build spans between each label.
2209 const MCSymbol *StartSym = List[0].Sym;
2210 for (size_t n = 1, e = List.size(); n < e; n++) {
2211 const SymbolCU &Prev = List[n - 1];
2212 const SymbolCU &Cur = List[n];
2214 // Try and build the longest span we can within the same CU.
2215 if (Cur.CU != Prev.CU) {
2217 Span.Start = StartSym;
2219 Spans[Prev.CU].push_back(Span);
2226 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2228 // Build a list of CUs used.
2229 std::vector<DwarfCompileUnit *> CUs;
2230 for (const auto &it : Spans) {
2231 DwarfCompileUnit *CU = it.first;
2235 // Sort the CU list (again, to ensure consistent output order).
2236 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2237 return A->getUniqueID() < B->getUniqueID();
2240 // Emit an arange table for each CU we used.
2241 for (DwarfCompileUnit *CU : CUs) {
2242 std::vector<ArangeSpan> &List = Spans[CU];
2244 // Emit size of content not including length itself.
2245 unsigned ContentSize =
2246 sizeof(int16_t) + // DWARF ARange version number
2247 sizeof(int32_t) + // Offset of CU in the .debug_info section
2248 sizeof(int8_t) + // Pointer Size (in bytes)
2249 sizeof(int8_t); // Segment Size (in bytes)
2251 unsigned TupleSize = PtrSize * 2;
2253 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2255 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2257 ContentSize += Padding;
2258 ContentSize += (List.size() + 1) * TupleSize;
2260 // For each compile unit, write the list of spans it covers.
2261 Asm->OutStreamer.AddComment("Length of ARange Set");
2262 Asm->EmitInt32(ContentSize);
2263 Asm->OutStreamer.AddComment("DWARF Arange version number");
2264 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2265 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2266 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2267 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2268 Asm->EmitInt8(PtrSize);
2269 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2272 Asm->OutStreamer.EmitFill(Padding, 0xff);
2274 for (const ArangeSpan &Span : List) {
2275 Asm->EmitLabelReference(Span.Start, PtrSize);
2277 // Calculate the size as being from the span start to it's end.
2279 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2281 // For symbols without an end marker (e.g. common), we
2282 // write a single arange entry containing just that one symbol.
2283 uint64_t Size = SymSize[Span.Start];
2287 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2291 Asm->OutStreamer.AddComment("ARange terminator");
2292 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2293 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2297 // Emit visible names into a debug ranges section.
2298 void DwarfDebug::emitDebugRanges() {
2299 // Start the dwarf ranges section.
2300 Asm->OutStreamer.SwitchSection(
2301 Asm->getObjFileLowering().getDwarfRangesSection());
2303 // Size for our labels.
2304 unsigned char Size = Asm->getDataLayout().getPointerSize();
2306 // Grab the specific ranges for the compile units in the module.
2307 for (const auto &I : CUMap) {
2308 DwarfCompileUnit *TheCU = I.second;
2310 // Iterate over the misc ranges for the compile units in the module.
2311 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2312 // Emit our symbol so we can find the beginning of the range.
2313 Asm->OutStreamer.EmitLabel(List.getSym());
2315 for (const RangeSpan &Range : List.getRanges()) {
2316 const MCSymbol *Begin = Range.getStart();
2317 const MCSymbol *End = Range.getEnd();
2318 assert(Begin && "Range without a begin symbol?");
2319 assert(End && "Range without an end symbol?");
2320 if (TheCU->getRanges().size() == 1) {
2321 // Grab the begin symbol from the first range as our base.
2322 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2323 Asm->EmitLabelDifference(Begin, Base, Size);
2324 Asm->EmitLabelDifference(End, Base, Size);
2326 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2327 Asm->OutStreamer.EmitSymbolValue(End, Size);
2331 // And terminate the list with two 0 values.
2332 Asm->OutStreamer.EmitIntValue(0, Size);
2333 Asm->OutStreamer.EmitIntValue(0, Size);
2336 // Now emit a range for the CU itself.
2337 if (TheCU->getRanges().size() > 1) {
2338 Asm->OutStreamer.EmitLabel(
2339 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2340 for (const RangeSpan &Range : TheCU->getRanges()) {
2341 const MCSymbol *Begin = Range.getStart();
2342 const MCSymbol *End = Range.getEnd();
2343 assert(Begin && "Range without a begin symbol?");
2344 assert(End && "Range without an end symbol?");
2345 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2346 Asm->OutStreamer.EmitSymbolValue(End, Size);
2348 // And terminate the list with two 0 values.
2349 Asm->OutStreamer.EmitIntValue(0, Size);
2350 Asm->OutStreamer.EmitIntValue(0, Size);
2355 // DWARF5 Experimental Separate Dwarf emitters.
2357 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2358 std::unique_ptr<DwarfUnit> NewU) {
2359 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2360 U.getCUNode().getSplitDebugFilename());
2362 if (!CompilationDir.empty())
2363 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2365 addGnuPubAttributes(*NewU, Die);
2367 SkeletonHolder.addUnit(std::move(NewU));
2370 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2371 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2372 // DW_AT_addr_base, DW_AT_ranges_base.
2373 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2375 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2376 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2377 DwarfCompileUnit &NewCU = *OwnedUnit;
2378 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2379 DwarfInfoSectionSym);
2381 NewCU.initStmtList(DwarfLineSectionSym);
2383 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2388 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2389 // compile units that would normally be in debug_info.
2390 void DwarfDebug::emitDebugInfoDWO() {
2391 assert(useSplitDwarf() && "No split dwarf debug info?");
2392 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2393 // emit relocations into the dwo file.
2394 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2397 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2398 // abbreviations for the .debug_info.dwo section.
2399 void DwarfDebug::emitDebugAbbrevDWO() {
2400 assert(useSplitDwarf() && "No split dwarf?");
2401 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2404 void DwarfDebug::emitDebugLineDWO() {
2405 assert(useSplitDwarf() && "No split dwarf?");
2406 Asm->OutStreamer.SwitchSection(
2407 Asm->getObjFileLowering().getDwarfLineDWOSection());
2408 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2411 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2412 // string section and is identical in format to traditional .debug_str
2414 void DwarfDebug::emitDebugStrDWO() {
2415 assert(useSplitDwarf() && "No split dwarf?");
2416 const MCSection *OffSec =
2417 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2418 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2422 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2423 if (!useSplitDwarf())
2426 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2427 return &SplitTypeUnitFileTable;
2430 static uint64_t makeTypeSignature(StringRef Identifier) {
2432 Hash.update(Identifier);
2433 // ... take the least significant 8 bytes and return those. Our MD5
2434 // implementation always returns its results in little endian, swap bytes
2436 MD5::MD5Result Result;
2438 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2441 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2442 StringRef Identifier, DIE &RefDie,
2443 DICompositeType CTy) {
2444 // Fast path if we're building some type units and one has already used the
2445 // address pool we know we're going to throw away all this work anyway, so
2446 // don't bother building dependent types.
2447 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2450 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2452 CU.addDIETypeSignature(RefDie, *TU);
2456 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2457 AddrPool.resetUsedFlag();
2459 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2460 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2461 this, &InfoHolder, getDwoLineTable(CU));
2462 DwarfTypeUnit &NewTU = *OwnedUnit;
2463 DIE &UnitDie = NewTU.getUnitDie();
2465 TypeUnitsUnderConstruction.push_back(
2466 std::make_pair(std::move(OwnedUnit), CTy));
2468 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2471 uint64_t Signature = makeTypeSignature(Identifier);
2472 NewTU.setTypeSignature(Signature);
2474 if (useSplitDwarf())
2475 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2476 DwarfTypesDWOSectionSym);
2478 CU.applyStmtList(UnitDie);
2480 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2483 NewTU.setType(NewTU.createTypeDIE(CTy));
2486 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2487 TypeUnitsUnderConstruction.clear();
2489 // Types referencing entries in the address table cannot be placed in type
2491 if (AddrPool.hasBeenUsed()) {
2493 // Remove all the types built while building this type.
2494 // This is pessimistic as some of these types might not be dependent on
2495 // the type that used an address.
2496 for (const auto &TU : TypeUnitsToAdd)
2497 DwarfTypeUnits.erase(TU.second);
2499 // Construct this type in the CU directly.
2500 // This is inefficient because all the dependent types will be rebuilt
2501 // from scratch, including building them in type units, discovering that
2502 // they depend on addresses, throwing them out and rebuilding them.
2503 CU.constructTypeDIE(RefDie, CTy);
2507 // If the type wasn't dependent on fission addresses, finish adding the type
2508 // and all its dependent types.
2509 for (auto &TU : TypeUnitsToAdd)
2510 InfoHolder.addUnit(std::move(TU.first));
2512 CU.addDIETypeSignature(RefDie, NewTU);
2515 // Accelerator table mutators - add each name along with its companion
2516 // DIE to the proper table while ensuring that the name that we're going
2517 // to reference is in the string table. We do this since the names we
2518 // add may not only be identical to the names in the DIE.
2519 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2520 if (!useDwarfAccelTables())
2522 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2526 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2527 if (!useDwarfAccelTables())
2529 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2533 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2534 if (!useDwarfAccelTables())
2536 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2540 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2541 if (!useDwarfAccelTables())
2543 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),