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 void DwarfDebug::attachRangesOrLowHighPC(DwarfCompileUnit &TheCU, DIE &Die,
334 const SmallVectorImpl<InsnRange> &Ranges) {
335 assert(!Ranges.empty());
336 if (Ranges.size() == 1)
337 TheCU.attachLowHighPC(Die, getLabelBeforeInsn(Ranges.front().first),
338 getLabelAfterInsn(Ranges.front().second));
340 TheCU.addScopeRangeList(Die, Ranges);
343 // Construct new DW_TAG_lexical_block for this scope and attach
344 // DW_AT_low_pc/DW_AT_high_pc labels.
346 DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
347 LexicalScope *Scope) {
348 if (isLexicalScopeDIENull(Scope))
351 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
352 if (Scope->isAbstractScope())
355 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
360 // This scope represents inlined body of a function. Construct DIE to
361 // represent this concrete inlined copy of the function.
363 DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
364 LexicalScope *Scope) {
365 assert(Scope->getScopeNode());
366 DIScope DS(Scope->getScopeNode());
367 DISubprogram InlinedSP = getDISubprogram(DS);
368 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
369 // was inlined from another compile unit.
370 DIE *OriginDIE = AbstractSPDies[InlinedSP];
371 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
373 auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
374 TheCU.addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
376 attachRangesOrLowHighPC(TheCU, *ScopeDIE, Scope->getRanges());
378 // Add the call site information to the DIE.
379 DILocation DL(Scope->getInlinedAt());
380 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
381 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
382 TheCU.addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
384 // Add name to the name table, we do this here because we're guaranteed
385 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
386 addSubprogramNames(InlinedSP, *ScopeDIE);
391 static std::unique_ptr<DIE> constructVariableDIE(DwarfCompileUnit &TheCU,
393 const LexicalScope &Scope,
394 DIE *&ObjectPointer) {
395 auto Var = TheCU.constructVariableDIE(DV, Scope.isAbstractScope());
396 if (DV.isObjectPointer())
397 ObjectPointer = Var.get();
401 DIE *DwarfDebug::createScopeChildrenDIE(
402 DwarfCompileUnit &TheCU, LexicalScope *Scope,
403 SmallVectorImpl<std::unique_ptr<DIE>> &Children,
404 unsigned *ChildScopeCount) {
405 DIE *ObjectPointer = nullptr;
407 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
408 Children.push_back(constructVariableDIE(TheCU, *DV, *Scope, ObjectPointer));
410 unsigned ChildCountWithoutScopes = Children.size();
412 for (LexicalScope *LS : Scope->getChildren())
413 TheCU.constructScopeDIE(LS, Children);
416 *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
418 return ObjectPointer;
421 DIE *DwarfDebug::createAndAddScopeChildren(DwarfCompileUnit &TheCU,
422 LexicalScope *Scope, DIE &ScopeDIE) {
423 // We create children when the scope DIE is not null.
424 SmallVector<std::unique_ptr<DIE>, 8> Children;
425 DIE *ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
428 for (auto &I : Children)
429 ScopeDIE.addChild(std::move(I));
431 return ObjectPointer;
434 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &TheCU,
435 LexicalScope *Scope) {
436 assert(Scope && Scope->getScopeNode());
437 assert(Scope->isAbstractScope());
438 assert(!Scope->getInlinedAt());
440 DISubprogram SP(Scope->getScopeNode());
442 ProcessedSPNodes.insert(SP);
444 DIE *&AbsDef = AbstractSPDies[SP];
448 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
449 // was inlined from another compile unit.
450 DwarfCompileUnit &SPCU = *SPMap[SP];
453 // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
454 // the important distinction that the DIDescriptor is not associated with the
455 // DIE (since the DIDescriptor will be associated with the concrete DIE, if
456 // any). It could be refactored to some common utility function.
457 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
458 ContextDIE = &SPCU.getUnitDie();
459 SPCU.getOrCreateSubprogramDIE(SPDecl);
461 ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
463 // Passing null as the associated DIDescriptor because the abstract definition
464 // shouldn't be found by lookup.
465 AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
467 SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
469 if (TheCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
470 SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
471 if (DIE *ObjectPointer = createAndAddScopeChildren(SPCU, Scope, *AbsDef))
472 SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
475 void DwarfDebug::constructSubprogramScopeDIE(DwarfCompileUnit &TheCU,
476 LexicalScope *Scope) {
477 assert(Scope && Scope->getScopeNode());
478 assert(!Scope->getInlinedAt());
479 assert(!Scope->isAbstractScope());
480 DISubprogram Sub(Scope->getScopeNode());
482 assert(Sub.isSubprogram());
484 ProcessedSPNodes.insert(Sub);
486 DIE &ScopeDIE = TheCU.updateSubprogramScopeDIE(Sub);
488 // Collect arguments for current function.
489 assert(LScopes.isCurrentFunctionScope(Scope));
490 DIE *ObjectPointer = nullptr;
491 for (DbgVariable *ArgDV : CurrentFnArguments)
494 constructVariableDIE(TheCU, *ArgDV, *Scope, ObjectPointer));
496 // If this is a variadic function, add an unspecified parameter.
497 DITypeArray FnArgs = Sub.getType().getTypeArray();
498 // If we have a single element of null, it is a function that returns void.
499 // If we have more than one elements and the last one is null, it is a
500 // variadic function.
501 if (FnArgs.getNumElements() > 1 &&
502 !FnArgs.getElement(FnArgs.getNumElements() - 1))
503 ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
505 // Collect lexical scope children first.
506 // ObjectPointer might be a local (non-argument) local variable if it's a
507 // block's synthetic this pointer.
508 if (DIE *BlockObjPtr = createAndAddScopeChildren(TheCU, Scope, ScopeDIE)) {
509 assert(!ObjectPointer && "multiple object pointers can't be described");
510 ObjectPointer = BlockObjPtr;
514 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
517 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
518 if (!GenerateGnuPubSections)
521 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
524 // Create new DwarfCompileUnit for the given metadata node with tag
525 // DW_TAG_compile_unit.
526 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
527 StringRef FN = DIUnit.getFilename();
528 CompilationDir = DIUnit.getDirectory();
530 auto OwnedUnit = make_unique<DwarfCompileUnit>(
531 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
532 DwarfCompileUnit &NewCU = *OwnedUnit;
533 DIE &Die = NewCU.getUnitDie();
534 InfoHolder.addUnit(std::move(OwnedUnit));
536 // LTO with assembly output shares a single line table amongst multiple CUs.
537 // To avoid the compilation directory being ambiguous, let the line table
538 // explicitly describe the directory of all files, never relying on the
539 // compilation directory.
540 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
541 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
542 NewCU.getUniqueID(), CompilationDir);
544 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
545 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
546 DIUnit.getLanguage());
547 NewCU.addString(Die, dwarf::DW_AT_name, FN);
549 if (!useSplitDwarf()) {
550 NewCU.initStmtList(DwarfLineSectionSym);
552 // If we're using split dwarf the compilation dir is going to be in the
553 // skeleton CU and so we don't need to duplicate it here.
554 if (!CompilationDir.empty())
555 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
557 addGnuPubAttributes(NewCU, Die);
560 if (DIUnit.isOptimized())
561 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
563 StringRef Flags = DIUnit.getFlags();
565 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
567 if (unsigned RVer = DIUnit.getRunTimeVersion())
568 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
569 dwarf::DW_FORM_data1, RVer);
574 if (useSplitDwarf()) {
575 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
576 DwarfInfoDWOSectionSym);
577 NewCU.setSkeleton(constructSkeletonCU(NewCU));
579 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
580 DwarfInfoSectionSym);
582 CUMap.insert(std::make_pair(DIUnit, &NewCU));
583 CUDieMap.insert(std::make_pair(&Die, &NewCU));
587 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
589 DIImportedEntity Module(N);
590 assert(Module.Verify());
591 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
592 D->addChild(TheCU.constructImportedEntityDIE(Module));
595 // Emit all Dwarf sections that should come prior to the content. Create
596 // global DIEs and emit initial debug info sections. This is invoked by
597 // the target AsmPrinter.
598 void DwarfDebug::beginModule() {
599 if (DisableDebugInfoPrinting)
602 const Module *M = MMI->getModule();
604 FunctionDIs = makeSubprogramMap(*M);
606 // If module has named metadata anchors then use them, otherwise scan the
607 // module using debug info finder to collect debug info.
608 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
611 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
613 // Emit initial sections so we can reference labels later.
616 SingleCU = CU_Nodes->getNumOperands() == 1;
618 for (MDNode *N : CU_Nodes->operands()) {
619 DICompileUnit CUNode(N);
620 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
621 DIArray ImportedEntities = CUNode.getImportedEntities();
622 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
623 ScopesWithImportedEntities.push_back(std::make_pair(
624 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
625 ImportedEntities.getElement(i)));
626 std::sort(ScopesWithImportedEntities.begin(),
627 ScopesWithImportedEntities.end(), less_first());
628 DIArray GVs = CUNode.getGlobalVariables();
629 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
630 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
631 DIArray SPs = CUNode.getSubprograms();
632 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
633 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
634 DIArray EnumTypes = CUNode.getEnumTypes();
635 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
636 DIType Ty(EnumTypes.getElement(i));
637 // The enum types array by design contains pointers to
638 // MDNodes rather than DIRefs. Unique them here.
639 DIType UniqueTy(resolve(Ty.getRef()));
640 CU.getOrCreateTypeDIE(UniqueTy);
642 DIArray RetainedTypes = CUNode.getRetainedTypes();
643 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
644 DIType Ty(RetainedTypes.getElement(i));
645 // The retained types array by design contains pointers to
646 // MDNodes rather than DIRefs. Unique them here.
647 DIType UniqueTy(resolve(Ty.getRef()));
648 CU.getOrCreateTypeDIE(UniqueTy);
650 // Emit imported_modules last so that the relevant context is already
652 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
653 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
656 // Tell MMI that we have debug info.
657 MMI->setDebugInfoAvailability(true);
659 // Prime section data.
660 SectionMap[Asm->getObjFileLowering().getTextSection()];
663 void DwarfDebug::finishVariableDefinitions() {
664 for (const auto &Var : ConcreteVariables) {
665 DIE *VariableDie = Var->getDIE();
667 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
668 // in the ConcreteVariables list, rather than looking it up again here.
669 // DIE::getUnit isn't simple - it walks parent pointers, etc.
670 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
672 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
673 if (AbsVar && AbsVar->getDIE()) {
674 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
677 Unit->applyVariableAttributes(*Var, *VariableDie);
681 void DwarfDebug::finishSubprogramDefinitions() {
682 const Module *M = MMI->getModule();
684 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
685 for (MDNode *N : CU_Nodes->operands()) {
686 DICompileUnit TheCU(N);
687 // Construct subprogram DIE and add variables DIEs.
688 DwarfCompileUnit *SPCU =
689 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
690 DIArray Subprograms = TheCU.getSubprograms();
691 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
692 DISubprogram SP(Subprograms.getElement(i));
693 // Perhaps the subprogram is in another CU (such as due to comdat
694 // folding, etc), in which case ignore it here.
695 if (SPMap[SP] != SPCU)
697 DIE *D = SPCU->getDIE(SP);
698 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
700 // If this subprogram has an abstract definition, reference that
701 SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
703 if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
704 // Lazily construct the subprogram if we didn't see either concrete or
705 // inlined versions during codegen. (except in -gmlt ^ where we want
706 // to omit these entirely)
707 D = SPCU->getOrCreateSubprogramDIE(SP);
709 // And attach the attributes
710 SPCU->applySubprogramAttributesToDefinition(SP, *D);
717 // Collect info for variables that were optimized out.
718 void DwarfDebug::collectDeadVariables() {
719 const Module *M = MMI->getModule();
721 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
722 for (MDNode *N : CU_Nodes->operands()) {
723 DICompileUnit TheCU(N);
724 // Construct subprogram DIE and add variables DIEs.
725 DwarfCompileUnit *SPCU =
726 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
727 assert(SPCU && "Unable to find Compile Unit!");
728 DIArray Subprograms = TheCU.getSubprograms();
729 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
730 DISubprogram SP(Subprograms.getElement(i));
731 if (ProcessedSPNodes.count(SP) != 0)
733 assert(SP.isSubprogram() &&
734 "CU's subprogram list contains a non-subprogram");
735 assert(SP.isDefinition() &&
736 "CU's subprogram list contains a subprogram declaration");
737 DIArray Variables = SP.getVariables();
738 if (Variables.getNumElements() == 0)
741 DIE *SPDIE = AbstractSPDies.lookup(SP);
743 SPDIE = SPCU->getDIE(SP);
745 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
746 DIVariable DV(Variables.getElement(vi));
747 assert(DV.isVariable());
748 DbgVariable NewVar(DV, DIExpression(nullptr), this);
749 auto VariableDie = SPCU->constructVariableDIE(NewVar);
750 SPCU->applyVariableAttributes(NewVar, *VariableDie);
751 SPDIE->addChild(std::move(VariableDie));
758 void DwarfDebug::finalizeModuleInfo() {
759 finishSubprogramDefinitions();
761 finishVariableDefinitions();
763 // Collect info for variables that were optimized out.
764 collectDeadVariables();
766 // Handle anything that needs to be done on a per-unit basis after
767 // all other generation.
768 for (const auto &TheU : getUnits()) {
769 // Emit DW_AT_containing_type attribute to connect types with their
770 // vtable holding type.
771 TheU->constructContainingTypeDIEs();
773 // Add CU specific attributes if we need to add any.
774 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
775 // If we're splitting the dwarf out now that we've got the entire
776 // CU then add the dwo id to it.
777 DwarfCompileUnit *SkCU =
778 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
779 if (useSplitDwarf()) {
780 // Emit a unique identifier for this CU.
781 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
782 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
783 dwarf::DW_FORM_data8, ID);
784 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
785 dwarf::DW_FORM_data8, ID);
787 // We don't keep track of which addresses are used in which CU so this
788 // is a bit pessimistic under LTO.
789 if (!AddrPool.isEmpty())
790 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
791 DwarfAddrSectionSym, DwarfAddrSectionSym);
792 if (!TheU->getRangeLists().empty())
793 SkCU->addSectionLabel(
794 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
795 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
798 // If we have code split among multiple sections or non-contiguous
799 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
800 // remain in the .o file, otherwise add a DW_AT_low_pc.
801 // FIXME: We should use ranges allow reordering of code ala
802 // .subsections_via_symbols in mach-o. This would mean turning on
803 // ranges for all subprogram DIEs for mach-o.
804 DwarfCompileUnit &U =
805 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
806 unsigned NumRanges = TheU->getRanges().size();
809 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
810 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
811 DwarfDebugRangeSectionSym);
813 // A DW_AT_low_pc attribute may also be specified in combination with
814 // DW_AT_ranges to specify the default base address for use in
815 // location lists (see Section 2.6.2) and range lists (see Section
817 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
820 RangeSpan &Range = TheU->getRanges().back();
821 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
827 // Compute DIE offsets and sizes.
828 InfoHolder.computeSizeAndOffsets();
830 SkeletonHolder.computeSizeAndOffsets();
833 void DwarfDebug::endSections() {
834 // Filter labels by section.
835 for (const SymbolCU &SCU : ArangeLabels) {
836 if (SCU.Sym->isInSection()) {
837 // Make a note of this symbol and it's section.
838 const MCSection *Section = &SCU.Sym->getSection();
839 if (!Section->getKind().isMetadata())
840 SectionMap[Section].push_back(SCU);
842 // Some symbols (e.g. common/bss on mach-o) can have no section but still
843 // appear in the output. This sucks as we rely on sections to build
844 // arange spans. We can do it without, but it's icky.
845 SectionMap[nullptr].push_back(SCU);
849 // Build a list of sections used.
850 std::vector<const MCSection *> Sections;
851 for (const auto &it : SectionMap) {
852 const MCSection *Section = it.first;
853 Sections.push_back(Section);
856 // Sort the sections into order.
857 // This is only done to ensure consistent output order across different runs.
858 std::sort(Sections.begin(), Sections.end(), SectionSort);
860 // Add terminating symbols for each section.
861 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
862 const MCSection *Section = Sections[ID];
863 MCSymbol *Sym = nullptr;
866 // We can't call MCSection::getLabelEndName, as it's only safe to do so
867 // if we know the section name up-front. For user-created sections, the
868 // resulting label may not be valid to use as a label. (section names can
869 // use a greater set of characters on some systems)
870 Sym = Asm->GetTempSymbol("debug_end", ID);
871 Asm->OutStreamer.SwitchSection(Section);
872 Asm->OutStreamer.EmitLabel(Sym);
875 // Insert a final terminator.
876 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
880 // Emit all Dwarf sections that should come after the content.
881 void DwarfDebug::endModule() {
882 assert(CurFn == nullptr);
883 assert(CurMI == nullptr);
888 // End any existing sections.
889 // TODO: Does this need to happen?
892 // Finalize the debug info for the module.
893 finalizeModuleInfo();
897 // Emit all the DIEs into a debug info section.
900 // Corresponding abbreviations into a abbrev section.
903 // Emit info into a debug aranges section.
904 if (GenerateARangeSection)
907 // Emit info into a debug ranges section.
910 if (useSplitDwarf()) {
913 emitDebugAbbrevDWO();
916 // Emit DWO addresses.
917 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
919 // Emit info into a debug loc section.
922 // Emit info into the dwarf accelerator table sections.
923 if (useDwarfAccelTables()) {
926 emitAccelNamespaces();
930 // Emit the pubnames and pubtypes sections if requested.
931 if (HasDwarfPubSections) {
932 emitDebugPubNames(GenerateGnuPubSections);
933 emitDebugPubTypes(GenerateGnuPubSections);
938 AbstractVariables.clear();
940 // Reset these for the next Module if we have one.
944 // Find abstract variable, if any, associated with Var.
945 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
946 DIVariable &Cleansed) {
947 LLVMContext &Ctx = DV->getContext();
948 // More then one inlined variable corresponds to one abstract variable.
949 // FIXME: This duplication of variables when inlining should probably be
950 // removed. It's done to allow each DIVariable to describe its location
951 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
952 // make it accurate then remove this duplication/cleansing stuff.
953 Cleansed = cleanseInlinedVariable(DV, Ctx);
954 auto I = AbstractVariables.find(Cleansed);
955 if (I != AbstractVariables.end())
956 return I->second.get();
960 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
962 return getExistingAbstractVariable(DV, Cleansed);
965 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
966 LexicalScope *Scope) {
967 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
968 addScopeVariable(Scope, AbsDbgVariable.get());
969 AbstractVariables[Var] = std::move(AbsDbgVariable);
972 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
973 const MDNode *ScopeNode) {
974 DIVariable Cleansed = DV;
975 if (getExistingAbstractVariable(DV, Cleansed))
978 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
982 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
983 const MDNode *ScopeNode) {
984 DIVariable Cleansed = DV;
985 if (getExistingAbstractVariable(DV, Cleansed))
988 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
989 createAbstractVariable(Cleansed, Scope);
992 // If Var is a current function argument then add it to CurrentFnArguments list.
993 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
994 if (!LScopes.isCurrentFunctionScope(Scope))
996 DIVariable DV = Var->getVariable();
997 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
999 unsigned ArgNo = DV.getArgNumber();
1003 size_t Size = CurrentFnArguments.size();
1005 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1006 // llvm::Function argument size is not good indicator of how many
1007 // arguments does the function have at source level.
1009 CurrentFnArguments.resize(ArgNo * 2);
1010 assert(!CurrentFnArguments[ArgNo - 1]);
1011 CurrentFnArguments[ArgNo - 1] = Var;
1015 // Collect variable information from side table maintained by MMI.
1016 void DwarfDebug::collectVariableInfoFromMMITable(
1017 SmallPtrSetImpl<const MDNode *> &Processed) {
1018 for (const auto &VI : MMI->getVariableDbgInfo()) {
1021 Processed.insert(VI.Var);
1022 DIVariable DV(VI.Var);
1023 DIExpression Expr(VI.Expr);
1024 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1026 // If variable scope is not found then skip this variable.
1030 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1031 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1032 DbgVariable *RegVar = ConcreteVariables.back().get();
1033 RegVar->setFrameIndex(VI.Slot);
1034 addScopeVariable(Scope, RegVar);
1038 // Get .debug_loc entry for the instruction range starting at MI.
1039 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1040 const MDNode *Expr = MI->getDebugExpression();
1041 const MDNode *Var = MI->getDebugVariable();
1043 assert(MI->getNumOperands() == 4);
1044 if (MI->getOperand(0).isReg()) {
1045 MachineLocation MLoc;
1046 // If the second operand is an immediate, this is a
1047 // register-indirect address.
1048 if (!MI->getOperand(1).isImm())
1049 MLoc.set(MI->getOperand(0).getReg());
1051 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1052 return DebugLocEntry::Value(Var, Expr, MLoc);
1054 if (MI->getOperand(0).isImm())
1055 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1056 if (MI->getOperand(0).isFPImm())
1057 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1058 if (MI->getOperand(0).isCImm())
1059 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1061 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1064 /// Determine whether two variable pieces overlap.
1065 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1066 if (!P1.isVariablePiece() || !P2.isVariablePiece())
1068 unsigned l1 = P1.getPieceOffset();
1069 unsigned l2 = P2.getPieceOffset();
1070 unsigned r1 = l1 + P1.getPieceSize();
1071 unsigned r2 = l2 + P2.getPieceSize();
1072 // True where [l1,r1[ and [r1,r2[ overlap.
1073 return (l1 < r2) && (l2 < r1);
1076 /// Build the location list for all DBG_VALUEs in the function that
1077 /// describe the same variable. If the ranges of several independent
1078 /// pieces of the same variable overlap partially, split them up and
1079 /// combine the ranges. The resulting DebugLocEntries are will have
1080 /// strict monotonically increasing begin addresses and will never
1085 // Ranges History [var, loc, piece ofs size]
1086 // 0 | [x, (reg0, piece 0, 32)]
1087 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1089 // 3 | [clobber reg0]
1090 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1094 // [0-1] [x, (reg0, piece 0, 32)]
1095 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
1096 // [3-4] [x, (reg1, piece 32, 32)]
1097 // [4- ] [x, (mem, piece 0, 64)]
1099 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1100 const DbgValueHistoryMap::InstrRanges &Ranges) {
1101 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1103 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1104 const MachineInstr *Begin = I->first;
1105 const MachineInstr *End = I->second;
1106 assert(Begin->isDebugValue() && "Invalid History entry");
1108 // Check if a variable is inaccessible in this range.
1109 if (Begin->getNumOperands() > 1 &&
1110 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1115 // If this piece overlaps with any open ranges, truncate them.
1116 DIExpression DIExpr = Begin->getDebugExpression();
1117 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1118 [&](DebugLocEntry::Value R) {
1119 return piecesOverlap(DIExpr, R.getExpression());
1121 OpenRanges.erase(Last, OpenRanges.end());
1123 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1124 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1126 const MCSymbol *EndLabel;
1128 EndLabel = getLabelAfterInsn(End);
1129 else if (std::next(I) == Ranges.end())
1130 EndLabel = FunctionEndSym;
1132 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1133 assert(EndLabel && "Forgot label after instruction ending a range!");
1135 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1137 auto Value = getDebugLocValue(Begin);
1138 DebugLocEntry Loc(StartLabel, EndLabel, Value);
1139 bool couldMerge = false;
1141 // If this is a piece, it may belong to the current DebugLocEntry.
1142 if (DIExpr.isVariablePiece()) {
1143 // Add this value to the list of open ranges.
1144 OpenRanges.push_back(Value);
1146 // Attempt to add the piece to the last entry.
1147 if (!DebugLoc.empty())
1148 if (DebugLoc.back().MergeValues(Loc))
1153 // Need to add a new DebugLocEntry. Add all values from still
1154 // valid non-overlapping pieces.
1155 if (OpenRanges.size())
1156 Loc.addValues(OpenRanges);
1158 DebugLoc.push_back(std::move(Loc));
1161 // Attempt to coalesce the ranges of two otherwise identical
1163 auto CurEntry = DebugLoc.rbegin();
1164 auto PrevEntry = std::next(CurEntry);
1165 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1166 DebugLoc.pop_back();
1169 dbgs() << CurEntry->getValues().size() << " Values:\n";
1170 for (auto Value : CurEntry->getValues()) {
1171 Value.getVariable()->dump();
1172 Value.getExpression()->dump();
1174 dbgs() << "-----\n";
1180 // Find variables for each lexical scope.
1182 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1183 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1184 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1186 // Grab the variable info that was squirreled away in the MMI side-table.
1187 collectVariableInfoFromMMITable(Processed);
1189 for (const auto &I : DbgValues) {
1190 DIVariable DV(I.first);
1191 if (Processed.count(DV))
1194 // Instruction ranges, specifying where DV is accessible.
1195 const auto &Ranges = I.second;
1199 LexicalScope *Scope = nullptr;
1200 if (MDNode *IA = DV.getInlinedAt()) {
1201 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1202 Scope = LScopes.findInlinedScope(DebugLoc::get(
1203 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1205 Scope = LScopes.findLexicalScope(DV.getContext());
1206 // If variable scope is not found then skip this variable.
1210 Processed.insert(DV);
1211 const MachineInstr *MInsn = Ranges.front().first;
1212 assert(MInsn->isDebugValue() && "History must begin with debug value");
1213 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1214 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1215 DbgVariable *RegVar = ConcreteVariables.back().get();
1216 addScopeVariable(Scope, RegVar);
1218 // Check if the first DBG_VALUE is valid for the rest of the function.
1219 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1222 // Handle multiple DBG_VALUE instructions describing one variable.
1223 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1225 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1226 DebugLocList &LocList = DotDebugLocEntries.back();
1229 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1231 // Build the location list for this variable.
1232 buildLocationList(LocList.List, Ranges);
1235 // Collect info for variables that were optimized out.
1236 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1237 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1238 DIVariable DV(Variables.getElement(i));
1239 assert(DV.isVariable());
1240 if (!Processed.insert(DV))
1242 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1243 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1244 DIExpression NoExpr;
1245 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1246 addScopeVariable(Scope, ConcreteVariables.back().get());
1251 // Return Label preceding the instruction.
1252 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1253 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1254 assert(Label && "Didn't insert label before instruction");
1258 // Return Label immediately following the instruction.
1259 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1260 return LabelsAfterInsn.lookup(MI);
1263 // Process beginning of an instruction.
1264 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1265 assert(CurMI == nullptr);
1267 // Check if source location changes, but ignore DBG_VALUE locations.
1268 if (!MI->isDebugValue()) {
1269 DebugLoc DL = MI->getDebugLoc();
1270 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1273 if (DL == PrologEndLoc) {
1274 Flags |= DWARF2_FLAG_PROLOGUE_END;
1275 PrologEndLoc = DebugLoc();
1277 if (PrologEndLoc.isUnknown())
1278 Flags |= DWARF2_FLAG_IS_STMT;
1280 if (!DL.isUnknown()) {
1281 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1282 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1284 recordSourceLine(0, 0, nullptr, 0);
1288 // Insert labels where requested.
1289 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1290 LabelsBeforeInsn.find(MI);
1293 if (I == LabelsBeforeInsn.end())
1296 // Label already assigned.
1301 PrevLabel = MMI->getContext().CreateTempSymbol();
1302 Asm->OutStreamer.EmitLabel(PrevLabel);
1304 I->second = PrevLabel;
1307 // Process end of an instruction.
1308 void DwarfDebug::endInstruction() {
1309 assert(CurMI != nullptr);
1310 // Don't create a new label after DBG_VALUE instructions.
1311 // They don't generate code.
1312 if (!CurMI->isDebugValue())
1313 PrevLabel = nullptr;
1315 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1316 LabelsAfterInsn.find(CurMI);
1320 if (I == LabelsAfterInsn.end())
1323 // Label already assigned.
1327 // We need a label after this instruction.
1329 PrevLabel = MMI->getContext().CreateTempSymbol();
1330 Asm->OutStreamer.EmitLabel(PrevLabel);
1332 I->second = PrevLabel;
1335 // Each LexicalScope has first instruction and last instruction to mark
1336 // beginning and end of a scope respectively. Create an inverse map that list
1337 // scopes starts (and ends) with an instruction. One instruction may start (or
1338 // end) multiple scopes. Ignore scopes that are not reachable.
1339 void DwarfDebug::identifyScopeMarkers() {
1340 SmallVector<LexicalScope *, 4> WorkList;
1341 WorkList.push_back(LScopes.getCurrentFunctionScope());
1342 while (!WorkList.empty()) {
1343 LexicalScope *S = WorkList.pop_back_val();
1345 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1346 if (!Children.empty())
1347 WorkList.append(Children.begin(), Children.end());
1349 if (S->isAbstractScope())
1352 for (const InsnRange &R : S->getRanges()) {
1353 assert(R.first && "InsnRange does not have first instruction!");
1354 assert(R.second && "InsnRange does not have second instruction!");
1355 requestLabelBeforeInsn(R.first);
1356 requestLabelAfterInsn(R.second);
1361 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1362 // First known non-DBG_VALUE and non-frame setup location marks
1363 // the beginning of the function body.
1364 for (const auto &MBB : *MF)
1365 for (const auto &MI : MBB)
1366 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1367 !MI.getDebugLoc().isUnknown())
1368 return MI.getDebugLoc();
1372 // Gather pre-function debug information. Assumes being called immediately
1373 // after the function entry point has been emitted.
1374 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1377 // If there's no debug info for the function we're not going to do anything.
1378 if (!MMI->hasDebugInfo())
1381 auto DI = FunctionDIs.find(MF->getFunction());
1382 if (DI == FunctionDIs.end())
1385 // Grab the lexical scopes for the function, if we don't have any of those
1386 // then we're not going to be able to do anything.
1387 LScopes.initialize(*MF);
1388 if (LScopes.empty())
1391 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1393 // Make sure that each lexical scope will have a begin/end label.
1394 identifyScopeMarkers();
1396 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1397 // belongs to so that we add to the correct per-cu line table in the
1399 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1400 // FnScope->getScopeNode() and DI->second should represent the same function,
1401 // though they may not be the same MDNode due to inline functions merged in
1402 // LTO where the debug info metadata still differs (either due to distinct
1403 // written differences - two versions of a linkonce_odr function
1404 // written/copied into two separate files, or some sub-optimal metadata that
1405 // isn't structurally identical (see: file path/name info from clang, which
1406 // includes the directory of the cpp file being built, even when the file name
1407 // is absolute (such as an <> lookup header)))
1408 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1409 assert(TheCU && "Unable to find compile unit!");
1410 if (Asm->OutStreamer.hasRawTextSupport())
1411 // Use a single line table if we are generating assembly.
1412 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1414 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1416 // Emit a label for the function so that we have a beginning address.
1417 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1418 // Assumes in correct section after the entry point.
1419 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1421 // Calculate history for local variables.
1422 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1425 // Request labels for the full history.
1426 for (const auto &I : DbgValues) {
1427 const auto &Ranges = I.second;
1431 // The first mention of a function argument gets the FunctionBeginSym
1432 // label, so arguments are visible when breaking at function entry.
1433 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1434 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1435 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1436 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1437 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1438 // Mark all non-overlapping initial pieces.
1439 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1440 DIExpression Piece = I->first->getDebugExpression();
1441 if (std::all_of(Ranges.begin(), I,
1442 [&](DbgValueHistoryMap::InstrRange Pred) {
1443 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1445 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1452 for (const auto &Range : Ranges) {
1453 requestLabelBeforeInsn(Range.first);
1455 requestLabelAfterInsn(Range.second);
1459 PrevInstLoc = DebugLoc();
1460 PrevLabel = FunctionBeginSym;
1462 // Record beginning of function.
1463 PrologEndLoc = findPrologueEndLoc(MF);
1464 if (!PrologEndLoc.isUnknown()) {
1465 DebugLoc FnStartDL =
1466 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1468 FnStartDL.getLine(), FnStartDL.getCol(),
1469 FnStartDL.getScope(MF->getFunction()->getContext()),
1470 // We'd like to list the prologue as "not statements" but GDB behaves
1471 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1472 DWARF2_FLAG_IS_STMT);
1476 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1477 if (addCurrentFnArgument(Var, LS))
1479 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1480 DIVariable DV = Var->getVariable();
1481 // Variables with positive arg numbers are parameters.
1482 if (unsigned ArgNum = DV.getArgNumber()) {
1483 // Keep all parameters in order at the start of the variable list to ensure
1484 // function types are correct (no out-of-order parameters)
1486 // This could be improved by only doing it for optimized builds (unoptimized
1487 // builds have the right order to begin with), searching from the back (this
1488 // would catch the unoptimized case quickly), or doing a binary search
1489 // rather than linear search.
1490 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1491 while (I != Vars.end()) {
1492 unsigned CurNum = (*I)->getVariable().getArgNumber();
1493 // A local (non-parameter) variable has been found, insert immediately
1497 // A later indexed parameter has been found, insert immediately before it.
1498 if (CurNum > ArgNum)
1502 Vars.insert(I, Var);
1506 Vars.push_back(Var);
1509 // Gather and emit post-function debug information.
1510 void DwarfDebug::endFunction(const MachineFunction *MF) {
1511 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1512 // though the beginFunction may not be called at all.
1513 // We should handle both cases.
1517 assert(CurFn == MF);
1518 assert(CurFn != nullptr);
1520 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1521 !FunctionDIs.count(MF->getFunction())) {
1522 // If we don't have a lexical scope for this function then there will
1523 // be a hole in the range information. Keep note of this by setting the
1524 // previously used section to nullptr.
1530 // Define end label for subprogram.
1531 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1532 // Assumes in correct section after the entry point.
1533 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1535 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1536 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1538 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1539 collectVariableInfo(ProcessedVars);
1541 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1542 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1544 // Add the range of this function to the list of ranges for the CU.
1545 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1547 // Under -gmlt, skip building the subprogram if there are no inlined
1548 // subroutines inside it.
1549 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1550 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1551 assert(ScopeVariables.empty());
1552 assert(CurrentFnArguments.empty());
1553 assert(DbgValues.empty());
1554 assert(AbstractVariables.empty());
1555 LabelsBeforeInsn.clear();
1556 LabelsAfterInsn.clear();
1557 PrevLabel = nullptr;
1562 // Construct abstract scopes.
1563 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1564 DISubprogram SP(AScope->getScopeNode());
1565 assert(SP.isSubprogram());
1566 // Collect info for variables that were optimized out.
1567 DIArray Variables = SP.getVariables();
1568 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1569 DIVariable DV(Variables.getElement(i));
1570 assert(DV && DV.isVariable());
1571 if (!ProcessedVars.insert(DV))
1573 ensureAbstractVariableIsCreated(DV, DV.getContext());
1575 constructAbstractSubprogramScopeDIE(TheCU, AScope);
1578 constructSubprogramScopeDIE(TheCU, FnScope);
1581 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1582 // DbgVariables except those that are also in AbstractVariables (since they
1583 // can be used cross-function)
1584 ScopeVariables.clear();
1585 CurrentFnArguments.clear();
1587 LabelsBeforeInsn.clear();
1588 LabelsAfterInsn.clear();
1589 PrevLabel = nullptr;
1593 // Register a source line with debug info. Returns the unique label that was
1594 // emitted and which provides correspondence to the source line list.
1595 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1600 unsigned Discriminator = 0;
1601 if (DIScope Scope = DIScope(S)) {
1602 assert(Scope.isScope());
1603 Fn = Scope.getFilename();
1604 Dir = Scope.getDirectory();
1605 if (Scope.isLexicalBlockFile())
1606 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1608 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1609 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1610 .getOrCreateSourceID(Fn, Dir);
1612 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1616 //===----------------------------------------------------------------------===//
1618 //===----------------------------------------------------------------------===//
1620 // Emit initial Dwarf sections with a label at the start of each one.
1621 void DwarfDebug::emitSectionLabels() {
1622 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1624 // Dwarf sections base addresses.
1625 DwarfInfoSectionSym =
1626 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1627 if (useSplitDwarf()) {
1628 DwarfInfoDWOSectionSym =
1629 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1630 DwarfTypesDWOSectionSym =
1631 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1633 DwarfAbbrevSectionSym =
1634 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1635 if (useSplitDwarf())
1636 DwarfAbbrevDWOSectionSym = emitSectionSym(
1637 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1638 if (GenerateARangeSection)
1639 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1641 DwarfLineSectionSym =
1642 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1643 if (GenerateGnuPubSections) {
1644 DwarfGnuPubNamesSectionSym =
1645 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1646 DwarfGnuPubTypesSectionSym =
1647 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1648 } else if (HasDwarfPubSections) {
1649 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1650 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1653 DwarfStrSectionSym =
1654 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1655 if (useSplitDwarf()) {
1656 DwarfStrDWOSectionSym =
1657 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1658 DwarfAddrSectionSym =
1659 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1660 DwarfDebugLocSectionSym =
1661 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1663 DwarfDebugLocSectionSym =
1664 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1665 DwarfDebugRangeSectionSym =
1666 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1669 // Recursively emits a debug information entry.
1670 void DwarfDebug::emitDIE(DIE &Die) {
1671 // Get the abbreviation for this DIE.
1672 const DIEAbbrev &Abbrev = Die.getAbbrev();
1674 // Emit the code (index) for the abbreviation.
1675 if (Asm->isVerbose())
1676 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1677 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1678 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1679 dwarf::TagString(Abbrev.getTag()));
1680 Asm->EmitULEB128(Abbrev.getNumber());
1682 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1683 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1685 // Emit the DIE attribute values.
1686 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1687 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1688 dwarf::Form Form = AbbrevData[i].getForm();
1689 assert(Form && "Too many attributes for DIE (check abbreviation)");
1691 if (Asm->isVerbose()) {
1692 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1693 if (Attr == dwarf::DW_AT_accessibility)
1694 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1695 cast<DIEInteger>(Values[i])->getValue()));
1698 // Emit an attribute using the defined form.
1699 Values[i]->EmitValue(Asm, Form);
1702 // Emit the DIE children if any.
1703 if (Abbrev.hasChildren()) {
1704 for (auto &Child : Die.getChildren())
1707 Asm->OutStreamer.AddComment("End Of Children Mark");
1712 // Emit the debug info section.
1713 void DwarfDebug::emitDebugInfo() {
1714 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1716 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1719 // Emit the abbreviation section.
1720 void DwarfDebug::emitAbbreviations() {
1721 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1723 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1726 // Emit the last address of the section and the end of the line matrix.
1727 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1728 // Define last address of section.
1729 Asm->OutStreamer.AddComment("Extended Op");
1732 Asm->OutStreamer.AddComment("Op size");
1733 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1734 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1735 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1737 Asm->OutStreamer.AddComment("Section end label");
1739 Asm->OutStreamer.EmitSymbolValue(
1740 Asm->GetTempSymbol("section_end", SectionEnd),
1741 Asm->getDataLayout().getPointerSize());
1743 // Mark end of matrix.
1744 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1750 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1751 StringRef TableName, StringRef SymName) {
1752 Accel.FinalizeTable(Asm, TableName);
1753 Asm->OutStreamer.SwitchSection(Section);
1754 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1755 Asm->OutStreamer.EmitLabel(SectionBegin);
1757 // Emit the full data.
1758 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1761 // Emit visible names into a hashed accelerator table section.
1762 void DwarfDebug::emitAccelNames() {
1763 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1764 "Names", "names_begin");
1767 // Emit objective C classes and categories into a hashed accelerator table
1769 void DwarfDebug::emitAccelObjC() {
1770 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1771 "ObjC", "objc_begin");
1774 // Emit namespace dies into a hashed accelerator table.
1775 void DwarfDebug::emitAccelNamespaces() {
1776 emitAccel(AccelNamespace,
1777 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1778 "namespac", "namespac_begin");
1781 // Emit type dies into a hashed accelerator table.
1782 void DwarfDebug::emitAccelTypes() {
1783 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1784 "types", "types_begin");
1787 // Public name handling.
1788 // The format for the various pubnames:
1790 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1791 // for the DIE that is named.
1793 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1794 // into the CU and the index value is computed according to the type of value
1795 // for the DIE that is named.
1797 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1798 // it's the offset within the debug_info/debug_types dwo section, however, the
1799 // reference in the pubname header doesn't change.
1801 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1802 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1804 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1806 // We could have a specification DIE that has our most of our knowledge,
1807 // look for that now.
1808 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1810 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1811 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1812 Linkage = dwarf::GIEL_EXTERNAL;
1813 } else if (Die->findAttribute(dwarf::DW_AT_external))
1814 Linkage = dwarf::GIEL_EXTERNAL;
1816 switch (Die->getTag()) {
1817 case dwarf::DW_TAG_class_type:
1818 case dwarf::DW_TAG_structure_type:
1819 case dwarf::DW_TAG_union_type:
1820 case dwarf::DW_TAG_enumeration_type:
1821 return dwarf::PubIndexEntryDescriptor(
1822 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1823 ? dwarf::GIEL_STATIC
1824 : dwarf::GIEL_EXTERNAL);
1825 case dwarf::DW_TAG_typedef:
1826 case dwarf::DW_TAG_base_type:
1827 case dwarf::DW_TAG_subrange_type:
1828 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1829 case dwarf::DW_TAG_namespace:
1830 return dwarf::GIEK_TYPE;
1831 case dwarf::DW_TAG_subprogram:
1832 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1833 case dwarf::DW_TAG_constant:
1834 case dwarf::DW_TAG_variable:
1835 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1836 case dwarf::DW_TAG_enumerator:
1837 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1838 dwarf::GIEL_STATIC);
1840 return dwarf::GIEK_NONE;
1844 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1846 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1847 const MCSection *PSec =
1848 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1849 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1851 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1854 void DwarfDebug::emitDebugPubSection(
1855 bool GnuStyle, const MCSection *PSec, StringRef Name,
1856 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1857 for (const auto &NU : CUMap) {
1858 DwarfCompileUnit *TheU = NU.second;
1860 const auto &Globals = (TheU->*Accessor)();
1862 if (Globals.empty())
1865 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1867 unsigned ID = TheU->getUniqueID();
1869 // Start the dwarf pubnames section.
1870 Asm->OutStreamer.SwitchSection(PSec);
1873 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1874 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1875 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1876 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1878 Asm->OutStreamer.EmitLabel(BeginLabel);
1880 Asm->OutStreamer.AddComment("DWARF Version");
1881 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1883 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1884 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1886 Asm->OutStreamer.AddComment("Compilation Unit Length");
1887 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1889 // Emit the pubnames for this compilation unit.
1890 for (const auto &GI : Globals) {
1891 const char *Name = GI.getKeyData();
1892 const DIE *Entity = GI.second;
1894 Asm->OutStreamer.AddComment("DIE offset");
1895 Asm->EmitInt32(Entity->getOffset());
1898 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1899 Asm->OutStreamer.AddComment(
1900 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1901 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1902 Asm->EmitInt8(Desc.toBits());
1905 Asm->OutStreamer.AddComment("External Name");
1906 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1909 Asm->OutStreamer.AddComment("End Mark");
1911 Asm->OutStreamer.EmitLabel(EndLabel);
1915 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1916 const MCSection *PSec =
1917 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1918 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1920 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1923 // Emit visible names into a debug str section.
1924 void DwarfDebug::emitDebugStr() {
1925 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1926 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1929 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1930 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1931 const DITypeIdentifierMap &Map,
1932 ArrayRef<DebugLocEntry::Value> Values) {
1933 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1934 return P.isVariablePiece();
1935 }) && "all values are expected to be pieces");
1936 assert(std::is_sorted(Values.begin(), Values.end()) &&
1937 "pieces are expected to be sorted");
1939 unsigned Offset = 0;
1940 for (auto Piece : Values) {
1941 DIExpression Expr = Piece.getExpression();
1942 unsigned PieceOffset = Expr.getPieceOffset();
1943 unsigned PieceSize = Expr.getPieceSize();
1944 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1945 if (Offset < PieceOffset) {
1946 // The DWARF spec seriously mandates pieces with no locations for gaps.
1947 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1948 Offset += PieceOffset-Offset;
1951 Offset += PieceSize;
1953 const unsigned SizeOfByte = 8;
1955 DIVariable Var = Piece.getVariable();
1956 assert(!Var.isIndirect() && "indirect address for piece");
1957 unsigned VarSize = Var.getSizeInBits(Map);
1958 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1959 && "piece is larger than or outside of variable");
1960 assert(PieceSize*SizeOfByte != VarSize
1961 && "piece covers entire variable");
1963 if (Piece.isLocation() && Piece.getLoc().isReg())
1964 Asm->EmitDwarfRegOpPiece(Streamer,
1966 PieceSize*SizeOfByte);
1968 emitDebugLocValue(Streamer, Piece);
1969 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1975 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1976 const DebugLocEntry &Entry) {
1977 const DebugLocEntry::Value Value = Entry.getValues()[0];
1978 if (Value.isVariablePiece())
1979 // Emit all pieces that belong to the same variable and range.
1980 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1982 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1983 emitDebugLocValue(Streamer, Value);
1986 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1987 const DebugLocEntry::Value &Value) {
1988 DIVariable DV = Value.getVariable();
1990 if (Value.isInt()) {
1991 DIBasicType BTy(resolve(DV.getType()));
1992 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1993 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1994 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1995 Streamer.EmitSLEB128(Value.getInt());
1997 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1998 Streamer.EmitULEB128(Value.getInt());
2000 } else if (Value.isLocation()) {
2001 MachineLocation Loc = Value.getLoc();
2002 DIExpression Expr = Value.getExpression();
2005 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2007 // Complex address entry.
2008 unsigned N = Expr.getNumElements();
2010 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2011 if (Loc.getOffset()) {
2013 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2014 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2015 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2016 Streamer.EmitSLEB128(Expr.getElement(1));
2018 // If first address element is OpPlus then emit
2019 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2020 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2021 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2025 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2028 // Emit remaining complex address elements.
2029 for (; i < N; ++i) {
2030 uint64_t Element = Expr.getElement(i);
2031 if (Element == dwarf::DW_OP_plus) {
2032 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2033 Streamer.EmitULEB128(Expr.getElement(++i));
2034 } else if (Element == dwarf::DW_OP_deref) {
2036 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2037 } else if (Element == dwarf::DW_OP_piece) {
2039 // handled in emitDebugLocEntry.
2041 llvm_unreachable("unknown Opcode found in complex address");
2045 // else ... ignore constant fp. There is not any good way to
2046 // to represent them here in dwarf.
2050 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2051 Asm->OutStreamer.AddComment("Loc expr size");
2052 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2053 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2054 Asm->EmitLabelDifference(end, begin, 2);
2055 Asm->OutStreamer.EmitLabel(begin);
2057 APByteStreamer Streamer(*Asm);
2058 emitDebugLocEntry(Streamer, Entry);
2060 Asm->OutStreamer.EmitLabel(end);
2063 // Emit locations into the debug loc section.
2064 void DwarfDebug::emitDebugLoc() {
2065 // Start the dwarf loc section.
2066 Asm->OutStreamer.SwitchSection(
2067 Asm->getObjFileLowering().getDwarfLocSection());
2068 unsigned char Size = Asm->getDataLayout().getPointerSize();
2069 for (const auto &DebugLoc : DotDebugLocEntries) {
2070 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2071 const DwarfCompileUnit *CU = DebugLoc.CU;
2072 assert(!CU->getRanges().empty());
2073 for (const auto &Entry : DebugLoc.List) {
2074 // Set up the range. This range is relative to the entry point of the
2075 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2076 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2077 if (CU->getRanges().size() == 1) {
2078 // Grab the begin symbol from the first range as our base.
2079 const MCSymbol *Base = CU->getRanges()[0].getStart();
2080 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2081 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2083 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2084 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2087 emitDebugLocEntryLocation(Entry);
2089 Asm->OutStreamer.EmitIntValue(0, Size);
2090 Asm->OutStreamer.EmitIntValue(0, Size);
2094 void DwarfDebug::emitDebugLocDWO() {
2095 Asm->OutStreamer.SwitchSection(
2096 Asm->getObjFileLowering().getDwarfLocDWOSection());
2097 for (const auto &DebugLoc : DotDebugLocEntries) {
2098 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2099 for (const auto &Entry : DebugLoc.List) {
2100 // Just always use start_length for now - at least that's one address
2101 // rather than two. We could get fancier and try to, say, reuse an
2102 // address we know we've emitted elsewhere (the start of the function?
2103 // The start of the CU or CU subrange that encloses this range?)
2104 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2105 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2106 Asm->EmitULEB128(idx);
2107 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2109 emitDebugLocEntryLocation(Entry);
2111 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2116 const MCSymbol *Start, *End;
2119 // Emit a debug aranges section, containing a CU lookup for any
2120 // address we can tie back to a CU.
2121 void DwarfDebug::emitDebugARanges() {
2122 // Start the dwarf aranges section.
2123 Asm->OutStreamer.SwitchSection(
2124 Asm->getObjFileLowering().getDwarfARangesSection());
2126 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2130 // Build a list of sections used.
2131 std::vector<const MCSection *> Sections;
2132 for (const auto &it : SectionMap) {
2133 const MCSection *Section = it.first;
2134 Sections.push_back(Section);
2137 // Sort the sections into order.
2138 // This is only done to ensure consistent output order across different runs.
2139 std::sort(Sections.begin(), Sections.end(), SectionSort);
2141 // Build a set of address spans, sorted by CU.
2142 for (const MCSection *Section : Sections) {
2143 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2144 if (List.size() < 2)
2147 // Sort the symbols by offset within the section.
2148 std::sort(List.begin(), List.end(),
2149 [&](const SymbolCU &A, const SymbolCU &B) {
2150 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2151 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2153 // Symbols with no order assigned should be placed at the end.
2154 // (e.g. section end labels)
2162 // If we have no section (e.g. common), just write out
2163 // individual spans for each symbol.
2165 for (const SymbolCU &Cur : List) {
2167 Span.Start = Cur.Sym;
2170 Spans[Cur.CU].push_back(Span);
2173 // Build spans between each label.
2174 const MCSymbol *StartSym = List[0].Sym;
2175 for (size_t n = 1, e = List.size(); n < e; n++) {
2176 const SymbolCU &Prev = List[n - 1];
2177 const SymbolCU &Cur = List[n];
2179 // Try and build the longest span we can within the same CU.
2180 if (Cur.CU != Prev.CU) {
2182 Span.Start = StartSym;
2184 Spans[Prev.CU].push_back(Span);
2191 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2193 // Build a list of CUs used.
2194 std::vector<DwarfCompileUnit *> CUs;
2195 for (const auto &it : Spans) {
2196 DwarfCompileUnit *CU = it.first;
2200 // Sort the CU list (again, to ensure consistent output order).
2201 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2202 return A->getUniqueID() < B->getUniqueID();
2205 // Emit an arange table for each CU we used.
2206 for (DwarfCompileUnit *CU : CUs) {
2207 std::vector<ArangeSpan> &List = Spans[CU];
2209 // Emit size of content not including length itself.
2210 unsigned ContentSize =
2211 sizeof(int16_t) + // DWARF ARange version number
2212 sizeof(int32_t) + // Offset of CU in the .debug_info section
2213 sizeof(int8_t) + // Pointer Size (in bytes)
2214 sizeof(int8_t); // Segment Size (in bytes)
2216 unsigned TupleSize = PtrSize * 2;
2218 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2220 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2222 ContentSize += Padding;
2223 ContentSize += (List.size() + 1) * TupleSize;
2225 // For each compile unit, write the list of spans it covers.
2226 Asm->OutStreamer.AddComment("Length of ARange Set");
2227 Asm->EmitInt32(ContentSize);
2228 Asm->OutStreamer.AddComment("DWARF Arange version number");
2229 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2230 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2231 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2232 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2233 Asm->EmitInt8(PtrSize);
2234 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2237 Asm->OutStreamer.EmitFill(Padding, 0xff);
2239 for (const ArangeSpan &Span : List) {
2240 Asm->EmitLabelReference(Span.Start, PtrSize);
2242 // Calculate the size as being from the span start to it's end.
2244 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2246 // For symbols without an end marker (e.g. common), we
2247 // write a single arange entry containing just that one symbol.
2248 uint64_t Size = SymSize[Span.Start];
2252 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2256 Asm->OutStreamer.AddComment("ARange terminator");
2257 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2258 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2262 // Emit visible names into a debug ranges section.
2263 void DwarfDebug::emitDebugRanges() {
2264 // Start the dwarf ranges section.
2265 Asm->OutStreamer.SwitchSection(
2266 Asm->getObjFileLowering().getDwarfRangesSection());
2268 // Size for our labels.
2269 unsigned char Size = Asm->getDataLayout().getPointerSize();
2271 // Grab the specific ranges for the compile units in the module.
2272 for (const auto &I : CUMap) {
2273 DwarfCompileUnit *TheCU = I.second;
2275 // Iterate over the misc ranges for the compile units in the module.
2276 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2277 // Emit our symbol so we can find the beginning of the range.
2278 Asm->OutStreamer.EmitLabel(List.getSym());
2280 for (const RangeSpan &Range : List.getRanges()) {
2281 const MCSymbol *Begin = Range.getStart();
2282 const MCSymbol *End = Range.getEnd();
2283 assert(Begin && "Range without a begin symbol?");
2284 assert(End && "Range without an end symbol?");
2285 if (TheCU->getRanges().size() == 1) {
2286 // Grab the begin symbol from the first range as our base.
2287 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2288 Asm->EmitLabelDifference(Begin, Base, Size);
2289 Asm->EmitLabelDifference(End, Base, Size);
2291 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2292 Asm->OutStreamer.EmitSymbolValue(End, Size);
2296 // And terminate the list with two 0 values.
2297 Asm->OutStreamer.EmitIntValue(0, Size);
2298 Asm->OutStreamer.EmitIntValue(0, Size);
2301 // Now emit a range for the CU itself.
2302 if (TheCU->getRanges().size() > 1) {
2303 Asm->OutStreamer.EmitLabel(
2304 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2305 for (const RangeSpan &Range : TheCU->getRanges()) {
2306 const MCSymbol *Begin = Range.getStart();
2307 const MCSymbol *End = Range.getEnd();
2308 assert(Begin && "Range without a begin symbol?");
2309 assert(End && "Range without an end symbol?");
2310 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2311 Asm->OutStreamer.EmitSymbolValue(End, Size);
2313 // And terminate the list with two 0 values.
2314 Asm->OutStreamer.EmitIntValue(0, Size);
2315 Asm->OutStreamer.EmitIntValue(0, Size);
2320 // DWARF5 Experimental Separate Dwarf emitters.
2322 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2323 std::unique_ptr<DwarfUnit> NewU) {
2324 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2325 U.getCUNode().getSplitDebugFilename());
2327 if (!CompilationDir.empty())
2328 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2330 addGnuPubAttributes(*NewU, Die);
2332 SkeletonHolder.addUnit(std::move(NewU));
2335 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2336 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2337 // DW_AT_addr_base, DW_AT_ranges_base.
2338 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2340 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2341 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2342 DwarfCompileUnit &NewCU = *OwnedUnit;
2343 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2344 DwarfInfoSectionSym);
2346 NewCU.initStmtList(DwarfLineSectionSym);
2348 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2353 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2354 // compile units that would normally be in debug_info.
2355 void DwarfDebug::emitDebugInfoDWO() {
2356 assert(useSplitDwarf() && "No split dwarf debug info?");
2357 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2358 // emit relocations into the dwo file.
2359 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2362 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2363 // abbreviations for the .debug_info.dwo section.
2364 void DwarfDebug::emitDebugAbbrevDWO() {
2365 assert(useSplitDwarf() && "No split dwarf?");
2366 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2369 void DwarfDebug::emitDebugLineDWO() {
2370 assert(useSplitDwarf() && "No split dwarf?");
2371 Asm->OutStreamer.SwitchSection(
2372 Asm->getObjFileLowering().getDwarfLineDWOSection());
2373 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2376 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2377 // string section and is identical in format to traditional .debug_str
2379 void DwarfDebug::emitDebugStrDWO() {
2380 assert(useSplitDwarf() && "No split dwarf?");
2381 const MCSection *OffSec =
2382 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2383 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2387 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2388 if (!useSplitDwarf())
2391 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2392 return &SplitTypeUnitFileTable;
2395 static uint64_t makeTypeSignature(StringRef Identifier) {
2397 Hash.update(Identifier);
2398 // ... take the least significant 8 bytes and return those. Our MD5
2399 // implementation always returns its results in little endian, swap bytes
2401 MD5::MD5Result Result;
2403 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2406 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2407 StringRef Identifier, DIE &RefDie,
2408 DICompositeType CTy) {
2409 // Fast path if we're building some type units and one has already used the
2410 // address pool we know we're going to throw away all this work anyway, so
2411 // don't bother building dependent types.
2412 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2415 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2417 CU.addDIETypeSignature(RefDie, *TU);
2421 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2422 AddrPool.resetUsedFlag();
2424 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2425 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2426 this, &InfoHolder, getDwoLineTable(CU));
2427 DwarfTypeUnit &NewTU = *OwnedUnit;
2428 DIE &UnitDie = NewTU.getUnitDie();
2430 TypeUnitsUnderConstruction.push_back(
2431 std::make_pair(std::move(OwnedUnit), CTy));
2433 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2436 uint64_t Signature = makeTypeSignature(Identifier);
2437 NewTU.setTypeSignature(Signature);
2439 if (useSplitDwarf())
2440 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2441 DwarfTypesDWOSectionSym);
2443 CU.applyStmtList(UnitDie);
2445 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2448 NewTU.setType(NewTU.createTypeDIE(CTy));
2451 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2452 TypeUnitsUnderConstruction.clear();
2454 // Types referencing entries in the address table cannot be placed in type
2456 if (AddrPool.hasBeenUsed()) {
2458 // Remove all the types built while building this type.
2459 // This is pessimistic as some of these types might not be dependent on
2460 // the type that used an address.
2461 for (const auto &TU : TypeUnitsToAdd)
2462 DwarfTypeUnits.erase(TU.second);
2464 // Construct this type in the CU directly.
2465 // This is inefficient because all the dependent types will be rebuilt
2466 // from scratch, including building them in type units, discovering that
2467 // they depend on addresses, throwing them out and rebuilding them.
2468 CU.constructTypeDIE(RefDie, CTy);
2472 // If the type wasn't dependent on fission addresses, finish adding the type
2473 // and all its dependent types.
2474 for (auto &TU : TypeUnitsToAdd)
2475 InfoHolder.addUnit(std::move(TU.first));
2477 CU.addDIETypeSignature(RefDie, NewTU);
2480 // Accelerator table mutators - add each name along with its companion
2481 // DIE to the proper table while ensuring that the name that we're going
2482 // to reference is in the string table. We do this since the names we
2483 // add may not only be identical to the names in the DIE.
2484 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2485 if (!useDwarfAccelTables())
2487 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2491 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2492 if (!useDwarfAccelTables())
2494 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2498 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2499 if (!useDwarfAccelTables())
2501 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2505 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2506 if (!useDwarfAccelTables())
2508 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),