]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/AsmPrinter/DwarfDebug.cpp
Remove unused parameter
[opencl/llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
18 #include "DIE.h"
19 #include "DIEHash.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"
54 using namespace llvm;
56 #define DEBUG_TYPE "dwarfdebug"
58 static cl::opt<bool>
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."),
65     cl::init(false));
67 static cl::opt<bool>
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69                        cl::desc("Generate GNU-style pubnames and pubtypes"),
70                        cl::init(false));
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73                                            cl::Hidden,
74                                            cl::desc("Generate dwarf aranges"),
75                                            cl::init(false));
77 namespace {
78 enum DefaultOnOff { Default, Enable, Disable };
79 }
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),
87                  cl::init(Default));
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),
95            cl::init(Default));
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),
103                  cl::init(Default));
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.  */
150     DIType subType = Ty;
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()));
161     }
162   }
163   return Ty;
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;
191   CurFn = nullptr;
192   CurMI = 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;
198   else
199     HasDwarfAccelTables = DwarfAccelTables == Enable;
201   if (SplitDwarf == Default)
202     HasSplitDwarf = false;
203   else
204     HasSplitDwarf = SplitDwarf == Enable;
206   if (DwarfPubSections == Default)
207     HasDwarfPubSections = !IsDarwin;
208   else
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);
217   {
218     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
219     beginModule();
220   }
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);
231   if (!SymbolStem)
232     return nullptr;
234   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235   Asm->OutStreamer.EmitLabel(TmpSym);
236   return TmpSym;
239 static bool isObjCClass(StringRef Name) {
240   return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244   if (!isObjCClass(Name))
245     return false;
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(' '));
254     Category = "";
255     return;
256   }
258   Class = In.slice(In.find('[') + 1, In.find('('));
259   Category = In.slice(In.find('[') + 1, In.find(' '));
260   return;
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() : "");
271   return LA < LB;
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())
280     return;
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
289   // too.
290   if (isObjCClass(SP.getName())) {
291     StringRef Class, Category;
292     getObjCClassCategory(SP.getName(), Class, Category);
293     addAccelObjC(Class, Die);
294     if (Category != "")
295       addAccelObjC(Category, Die);
296     // Also add the base method name to the name table.
297     addAccelName(getObjCMethodName(SP.getName()), Die);
298   }
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) {
304   if (!Context)
305     return false;
306   DIDescriptor D(Context);
307   if (D.isSubprogram())
308     return true;
309   if (D.isType())
310     return isSubprogramContext(resolve(DIType(Context).getContext()));
311   return false;
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())
318     return false;
320   // We don't create a DIE if there is no Range.
321   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
322   if (Ranges.empty())
323     return true;
325   if (Ranges.size() > 1)
326     return false;
328   // We don't create a DIE if we have a single Range and the end label
329   // is null.
330   return !getLabelAfterInsn(Ranges.front().second);
333 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
334   assert(Scope && Scope->getScopeNode());
335   assert(Scope->isAbstractScope());
336   assert(!Scope->getInlinedAt());
338   DISubprogram SP(Scope->getScopeNode());
340   ProcessedSPNodes.insert(SP);
342   DIE *&AbsDef = AbstractSPDies[SP];
343   if (AbsDef)
344     return;
346   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
347   // was inlined from another compile unit.
348   DwarfCompileUnit &SPCU = *SPMap[SP];
349   DIE *ContextDIE;
351   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
352   // the important distinction that the DIDescriptor is not associated with the
353   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
354   // any). It could be refactored to some common utility function.
355   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
356     ContextDIE = &SPCU.getUnitDie();
357     SPCU.getOrCreateSubprogramDIE(SPDecl);
358   } else
359     ContextDIE = SPCU.getOrCreateContextDIE(resolve(SP.getContext()));
361   // Passing null as the associated DIDescriptor because the abstract definition
362   // shouldn't be found by lookup.
363   AbsDef = &SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE,
364                                  DIDescriptor());
365   SPCU.applySubprogramAttributesToDefinition(SP, *AbsDef);
367   if (SPCU.getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
368     SPCU.addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
369   if (DIE *ObjectPointer = SPCU.createAndAddScopeChildren(Scope, *AbsDef))
370     SPCU.addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
373 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
374   if (!GenerateGnuPubSections)
375     return;
377   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
380 // Create new DwarfCompileUnit for the given metadata node with tag
381 // DW_TAG_compile_unit.
382 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
383   StringRef FN = DIUnit.getFilename();
384   CompilationDir = DIUnit.getDirectory();
386   auto OwnedUnit = make_unique<DwarfCompileUnit>(
387       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
388   DwarfCompileUnit &NewCU = *OwnedUnit;
389   DIE &Die = NewCU.getUnitDie();
390   InfoHolder.addUnit(std::move(OwnedUnit));
392   // LTO with assembly output shares a single line table amongst multiple CUs.
393   // To avoid the compilation directory being ambiguous, let the line table
394   // explicitly describe the directory of all files, never relying on the
395   // compilation directory.
396   if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
397     Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
398         NewCU.getUniqueID(), CompilationDir);
400   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
401   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
402                 DIUnit.getLanguage());
403   NewCU.addString(Die, dwarf::DW_AT_name, FN);
405   if (!useSplitDwarf()) {
406     NewCU.initStmtList(DwarfLineSectionSym);
408     // If we're using split dwarf the compilation dir is going to be in the
409     // skeleton CU and so we don't need to duplicate it here.
410     if (!CompilationDir.empty())
411       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
413     addGnuPubAttributes(NewCU, Die);
414   }
416   if (DIUnit.isOptimized())
417     NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
419   StringRef Flags = DIUnit.getFlags();
420   if (!Flags.empty())
421     NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
423   if (unsigned RVer = DIUnit.getRunTimeVersion())
424     NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
425                   dwarf::DW_FORM_data1, RVer);
427   if (!FirstCU)
428     FirstCU = &NewCU;
430   if (useSplitDwarf()) {
431     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
432                       DwarfInfoDWOSectionSym);
433     NewCU.setSkeleton(constructSkeletonCU(NewCU));
434   } else
435     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
436                       DwarfInfoSectionSym);
438   CUMap.insert(std::make_pair(DIUnit, &NewCU));
439   CUDieMap.insert(std::make_pair(&Die, &NewCU));
440   return NewCU;
443 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
444                                                   const MDNode *N) {
445   DIImportedEntity Module(N);
446   assert(Module.Verify());
447   if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
448     D->addChild(TheCU.constructImportedEntityDIE(Module));
451 // Emit all Dwarf sections that should come prior to the content. Create
452 // global DIEs and emit initial debug info sections. This is invoked by
453 // the target AsmPrinter.
454 void DwarfDebug::beginModule() {
455   if (DisableDebugInfoPrinting)
456     return;
458   const Module *M = MMI->getModule();
460   FunctionDIs = makeSubprogramMap(*M);
462   // If module has named metadata anchors then use them, otherwise scan the
463   // module using debug info finder to collect debug info.
464   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
465   if (!CU_Nodes)
466     return;
467   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
469   // Emit initial sections so we can reference labels later.
470   emitSectionLabels();
472   SingleCU = CU_Nodes->getNumOperands() == 1;
474   for (MDNode *N : CU_Nodes->operands()) {
475     DICompileUnit CUNode(N);
476     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
477     DIArray ImportedEntities = CUNode.getImportedEntities();
478     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
479       ScopesWithImportedEntities.push_back(std::make_pair(
480           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
481           ImportedEntities.getElement(i)));
482     std::sort(ScopesWithImportedEntities.begin(),
483               ScopesWithImportedEntities.end(), less_first());
484     DIArray GVs = CUNode.getGlobalVariables();
485     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
486       CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
487     DIArray SPs = CUNode.getSubprograms();
488     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
489       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
490     DIArray EnumTypes = CUNode.getEnumTypes();
491     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
492       DIType Ty(EnumTypes.getElement(i));
493       // The enum types array by design contains pointers to
494       // MDNodes rather than DIRefs. Unique them here.
495       DIType UniqueTy(resolve(Ty.getRef()));
496       CU.getOrCreateTypeDIE(UniqueTy);
497     }
498     DIArray RetainedTypes = CUNode.getRetainedTypes();
499     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
500       DIType Ty(RetainedTypes.getElement(i));
501       // The retained types array by design contains pointers to
502       // MDNodes rather than DIRefs. Unique them here.
503       DIType UniqueTy(resolve(Ty.getRef()));
504       CU.getOrCreateTypeDIE(UniqueTy);
505     }
506     // Emit imported_modules last so that the relevant context is already
507     // available.
508     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
509       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
510   }
512   // Tell MMI that we have debug info.
513   MMI->setDebugInfoAvailability(true);
515   // Prime section data.
516   SectionMap[Asm->getObjFileLowering().getTextSection()];
519 void DwarfDebug::finishVariableDefinitions() {
520   for (const auto &Var : ConcreteVariables) {
521     DIE *VariableDie = Var->getDIE();
522     assert(VariableDie);
523     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
524     // in the ConcreteVariables list, rather than looking it up again here.
525     // DIE::getUnit isn't simple - it walks parent pointers, etc.
526     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
527     assert(Unit);
528     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
529     if (AbsVar && AbsVar->getDIE()) {
530       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
531                         *AbsVar->getDIE());
532     } else
533       Unit->applyVariableAttributes(*Var, *VariableDie);
534   }
537 void DwarfDebug::finishSubprogramDefinitions() {
538   const Module *M = MMI->getModule();
540   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
541   for (MDNode *N : CU_Nodes->operands()) {
542     DICompileUnit TheCU(N);
543     // Construct subprogram DIE and add variables DIEs.
544     DwarfCompileUnit *SPCU =
545         static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
546     DIArray Subprograms = TheCU.getSubprograms();
547     for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
548       DISubprogram SP(Subprograms.getElement(i));
549       // Perhaps the subprogram is in another CU (such as due to comdat
550       // folding, etc), in which case ignore it here.
551       if (SPMap[SP] != SPCU)
552         continue;
553       DIE *D = SPCU->getDIE(SP);
554       if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
555         if (D)
556           // If this subprogram has an abstract definition, reference that
557           SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
558       } else {
559         if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
560           // Lazily construct the subprogram if we didn't see either concrete or
561           // inlined versions during codegen. (except in -gmlt ^ where we want
562           // to omit these entirely)
563           D = SPCU->getOrCreateSubprogramDIE(SP);
564         if (D)
565           // And attach the attributes
566           SPCU->applySubprogramAttributesToDefinition(SP, *D);
567       }
568     }
569   }
573 // Collect info for variables that were optimized out.
574 void DwarfDebug::collectDeadVariables() {
575   const Module *M = MMI->getModule();
577   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
578     for (MDNode *N : CU_Nodes->operands()) {
579       DICompileUnit TheCU(N);
580       // Construct subprogram DIE and add variables DIEs.
581       DwarfCompileUnit *SPCU =
582           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
583       assert(SPCU && "Unable to find Compile Unit!");
584       DIArray Subprograms = TheCU.getSubprograms();
585       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
586         DISubprogram SP(Subprograms.getElement(i));
587         if (ProcessedSPNodes.count(SP) != 0)
588           continue;
589         assert(SP.isSubprogram() &&
590                "CU's subprogram list contains a non-subprogram");
591         assert(SP.isDefinition() &&
592                "CU's subprogram list contains a subprogram declaration");
593         DIArray Variables = SP.getVariables();
594         if (Variables.getNumElements() == 0)
595           continue;
597         DIE *SPDIE = AbstractSPDies.lookup(SP);
598         if (!SPDIE)
599           SPDIE = SPCU->getDIE(SP);
600         assert(SPDIE);
601         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
602           DIVariable DV(Variables.getElement(vi));
603           assert(DV.isVariable());
604           DbgVariable NewVar(DV, DIExpression(nullptr), this);
605           auto VariableDie = SPCU->constructVariableDIE(NewVar);
606           SPCU->applyVariableAttributes(NewVar, *VariableDie);
607           SPDIE->addChild(std::move(VariableDie));
608         }
609       }
610     }
611   }
614 void DwarfDebug::finalizeModuleInfo() {
615   finishSubprogramDefinitions();
617   finishVariableDefinitions();
619   // Collect info for variables that were optimized out.
620   collectDeadVariables();
622   // Handle anything that needs to be done on a per-unit basis after
623   // all other generation.
624   for (const auto &TheU : getUnits()) {
625     // Emit DW_AT_containing_type attribute to connect types with their
626     // vtable holding type.
627     TheU->constructContainingTypeDIEs();
629     // Add CU specific attributes if we need to add any.
630     if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
631       // If we're splitting the dwarf out now that we've got the entire
632       // CU then add the dwo id to it.
633       DwarfCompileUnit *SkCU =
634           static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
635       if (useSplitDwarf()) {
636         // Emit a unique identifier for this CU.
637         uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
638         TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
639                       dwarf::DW_FORM_data8, ID);
640         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
641                       dwarf::DW_FORM_data8, ID);
643         // We don't keep track of which addresses are used in which CU so this
644         // is a bit pessimistic under LTO.
645         if (!AddrPool.isEmpty())
646           SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
647                                 DwarfAddrSectionSym, DwarfAddrSectionSym);
648         if (!TheU->getRangeLists().empty())
649           SkCU->addSectionLabel(
650               SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
651               DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
652       }
654       // If we have code split among multiple sections or non-contiguous
655       // ranges of code then emit a DW_AT_ranges attribute on the unit that will
656       // remain in the .o file, otherwise add a DW_AT_low_pc.
657       // FIXME: We should use ranges allow reordering of code ala
658       // .subsections_via_symbols in mach-o. This would mean turning on
659       // ranges for all subprogram DIEs for mach-o.
660       DwarfCompileUnit &U =
661           SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
662       unsigned NumRanges = TheU->getRanges().size();
663       if (NumRanges) {
664         if (NumRanges > 1) {
665           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
666                             Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
667                             DwarfDebugRangeSectionSym);
669           // A DW_AT_low_pc attribute may also be specified in combination with
670           // DW_AT_ranges to specify the default base address for use in
671           // location lists (see Section 2.6.2) and range lists (see Section
672           // 2.17.3).
673           U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
674                     0);
675         } else {
676           RangeSpan &Range = TheU->getRanges().back();
677           U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
678         }
679       }
680     }
681   }
683   // Compute DIE offsets and sizes.
684   InfoHolder.computeSizeAndOffsets();
685   if (useSplitDwarf())
686     SkeletonHolder.computeSizeAndOffsets();
689 void DwarfDebug::endSections() {
690   // Filter labels by section.
691   for (const SymbolCU &SCU : ArangeLabels) {
692     if (SCU.Sym->isInSection()) {
693       // Make a note of this symbol and it's section.
694       const MCSection *Section = &SCU.Sym->getSection();
695       if (!Section->getKind().isMetadata())
696         SectionMap[Section].push_back(SCU);
697     } else {
698       // Some symbols (e.g. common/bss on mach-o) can have no section but still
699       // appear in the output. This sucks as we rely on sections to build
700       // arange spans. We can do it without, but it's icky.
701       SectionMap[nullptr].push_back(SCU);
702     }
703   }
705   // Build a list of sections used.
706   std::vector<const MCSection *> Sections;
707   for (const auto &it : SectionMap) {
708     const MCSection *Section = it.first;
709     Sections.push_back(Section);
710   }
712   // Sort the sections into order.
713   // This is only done to ensure consistent output order across different runs.
714   std::sort(Sections.begin(), Sections.end(), SectionSort);
716   // Add terminating symbols for each section.
717   for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
718     const MCSection *Section = Sections[ID];
719     MCSymbol *Sym = nullptr;
721     if (Section) {
722       // We can't call MCSection::getLabelEndName, as it's only safe to do so
723       // if we know the section name up-front. For user-created sections, the
724       // resulting label may not be valid to use as a label. (section names can
725       // use a greater set of characters on some systems)
726       Sym = Asm->GetTempSymbol("debug_end", ID);
727       Asm->OutStreamer.SwitchSection(Section);
728       Asm->OutStreamer.EmitLabel(Sym);
729     }
731     // Insert a final terminator.
732     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
733   }
736 // Emit all Dwarf sections that should come after the content.
737 void DwarfDebug::endModule() {
738   assert(CurFn == nullptr);
739   assert(CurMI == nullptr);
741   if (!FirstCU)
742     return;
744   // End any existing sections.
745   // TODO: Does this need to happen?
746   endSections();
748   // Finalize the debug info for the module.
749   finalizeModuleInfo();
751   emitDebugStr();
753   // Emit all the DIEs into a debug info section.
754   emitDebugInfo();
756   // Corresponding abbreviations into a abbrev section.
757   emitAbbreviations();
759   // Emit info into a debug aranges section.
760   if (GenerateARangeSection)
761     emitDebugARanges();
763   // Emit info into a debug ranges section.
764   emitDebugRanges();
766   if (useSplitDwarf()) {
767     emitDebugStrDWO();
768     emitDebugInfoDWO();
769     emitDebugAbbrevDWO();
770     emitDebugLineDWO();
771     emitDebugLocDWO();
772     // Emit DWO addresses.
773     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
774   } else
775     // Emit info into a debug loc section.
776     emitDebugLoc();
778   // Emit info into the dwarf accelerator table sections.
779   if (useDwarfAccelTables()) {
780     emitAccelNames();
781     emitAccelObjC();
782     emitAccelNamespaces();
783     emitAccelTypes();
784   }
786   // Emit the pubnames and pubtypes sections if requested.
787   if (HasDwarfPubSections) {
788     emitDebugPubNames(GenerateGnuPubSections);
789     emitDebugPubTypes(GenerateGnuPubSections);
790   }
792   // clean up.
793   SPMap.clear();
794   AbstractVariables.clear();
796   // Reset these for the next Module if we have one.
797   FirstCU = nullptr;
800 // Find abstract variable, if any, associated with Var.
801 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
802                                                      DIVariable &Cleansed) {
803   LLVMContext &Ctx = DV->getContext();
804   // More then one inlined variable corresponds to one abstract variable.
805   // FIXME: This duplication of variables when inlining should probably be
806   // removed. It's done to allow each DIVariable to describe its location
807   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
808   // make it accurate then remove this duplication/cleansing stuff.
809   Cleansed = cleanseInlinedVariable(DV, Ctx);
810   auto I = AbstractVariables.find(Cleansed);
811   if (I != AbstractVariables.end())
812     return I->second.get();
813   return nullptr;
816 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
817   DIVariable Cleansed;
818   return getExistingAbstractVariable(DV, Cleansed);
821 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
822                                         LexicalScope *Scope) {
823   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
824   addScopeVariable(Scope, AbsDbgVariable.get());
825   AbstractVariables[Var] = std::move(AbsDbgVariable);
828 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
829                                                  const MDNode *ScopeNode) {
830   DIVariable Cleansed = DV;
831   if (getExistingAbstractVariable(DV, Cleansed))
832     return;
834   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
837 void
838 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
839                                                     const MDNode *ScopeNode) {
840   DIVariable Cleansed = DV;
841   if (getExistingAbstractVariable(DV, Cleansed))
842     return;
844   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
845     createAbstractVariable(Cleansed, Scope);
848 // If Var is a current function argument then add it to CurrentFnArguments list.
849 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
850   if (!LScopes.isCurrentFunctionScope(Scope))
851     return false;
852   DIVariable DV = Var->getVariable();
853   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
854     return false;
855   unsigned ArgNo = DV.getArgNumber();
856   if (ArgNo == 0)
857     return false;
859   size_t Size = CurrentFnArguments.size();
860   if (Size == 0)
861     CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
862   // llvm::Function argument size is not good indicator of how many
863   // arguments does the function have at source level.
864   if (ArgNo > Size)
865     CurrentFnArguments.resize(ArgNo * 2);
866   assert(!CurrentFnArguments[ArgNo - 1]);
867   CurrentFnArguments[ArgNo - 1] = Var;
868   return true;
871 // Collect variable information from side table maintained by MMI.
872 void DwarfDebug::collectVariableInfoFromMMITable(
873     SmallPtrSetImpl<const MDNode *> &Processed) {
874   for (const auto &VI : MMI->getVariableDbgInfo()) {
875     if (!VI.Var)
876       continue;
877     Processed.insert(VI.Var);
878     DIVariable DV(VI.Var);
879     DIExpression Expr(VI.Expr);
880     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
882     // If variable scope is not found then skip this variable.
883     if (!Scope)
884       continue;
886     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
887     ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
888     DbgVariable *RegVar = ConcreteVariables.back().get();
889     RegVar->setFrameIndex(VI.Slot);
890     addScopeVariable(Scope, RegVar);
891   }
894 // Get .debug_loc entry for the instruction range starting at MI.
895 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
896   const MDNode *Expr = MI->getDebugExpression();
897   const MDNode *Var = MI->getDebugVariable();
899   assert(MI->getNumOperands() == 4);
900   if (MI->getOperand(0).isReg()) {
901     MachineLocation MLoc;
902     // If the second operand is an immediate, this is a
903     // register-indirect address.
904     if (!MI->getOperand(1).isImm())
905       MLoc.set(MI->getOperand(0).getReg());
906     else
907       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
908     return DebugLocEntry::Value(Var, Expr, MLoc);
909   }
910   if (MI->getOperand(0).isImm())
911     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
912   if (MI->getOperand(0).isFPImm())
913     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
914   if (MI->getOperand(0).isCImm())
915     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
917   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
920 /// Determine whether two variable pieces overlap.
921 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
922   if (!P1.isVariablePiece() || !P2.isVariablePiece())
923     return true;
924   unsigned l1 = P1.getPieceOffset();
925   unsigned l2 = P2.getPieceOffset();
926   unsigned r1 = l1 + P1.getPieceSize();
927   unsigned r2 = l2 + P2.getPieceSize();
928   // True where [l1,r1[ and [r1,r2[ overlap.
929   return (l1 < r2) && (l2 < r1);
932 /// Build the location list for all DBG_VALUEs in the function that
933 /// describe the same variable.  If the ranges of several independent
934 /// pieces of the same variable overlap partially, split them up and
935 /// combine the ranges. The resulting DebugLocEntries are will have
936 /// strict monotonically increasing begin addresses and will never
937 /// overlap.
938 //
939 // Input:
940 //
941 //   Ranges History [var, loc, piece ofs size]
942 // 0 |      [x, (reg0, piece 0, 32)]
943 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
944 // 2 | |    ...
945 // 3   |    [clobber reg0]
946 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
947 //
948 // Output:
949 //
950 // [0-1]    [x, (reg0, piece  0, 32)]
951 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
952 // [3-4]    [x, (reg1, piece 32, 32)]
953 // [4- ]    [x, (mem,  piece  0, 64)]
954 void
955 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
956                               const DbgValueHistoryMap::InstrRanges &Ranges) {
957   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
959   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
960     const MachineInstr *Begin = I->first;
961     const MachineInstr *End = I->second;
962     assert(Begin->isDebugValue() && "Invalid History entry");
964     // Check if a variable is inaccessible in this range.
965     if (Begin->getNumOperands() > 1 &&
966         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
967       OpenRanges.clear();
968       continue;
969     }
971     // If this piece overlaps with any open ranges, truncate them.
972     DIExpression DIExpr = Begin->getDebugExpression();
973     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
974                                [&](DebugLocEntry::Value R) {
975       return piecesOverlap(DIExpr, R.getExpression());
976     });
977     OpenRanges.erase(Last, OpenRanges.end());
979     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
980     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
982     const MCSymbol *EndLabel;
983     if (End != nullptr)
984       EndLabel = getLabelAfterInsn(End);
985     else if (std::next(I) == Ranges.end())
986       EndLabel = FunctionEndSym;
987     else
988       EndLabel = getLabelBeforeInsn(std::next(I)->first);
989     assert(EndLabel && "Forgot label after instruction ending a range!");
991     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
993     auto Value = getDebugLocValue(Begin);
994     DebugLocEntry Loc(StartLabel, EndLabel, Value);
995     bool couldMerge = false;
997     // If this is a piece, it may belong to the current DebugLocEntry.
998     if (DIExpr.isVariablePiece()) {
999       // Add this value to the list of open ranges.
1000       OpenRanges.push_back(Value);
1002       // Attempt to add the piece to the last entry.
1003       if (!DebugLoc.empty())
1004         if (DebugLoc.back().MergeValues(Loc))
1005           couldMerge = true;
1006     }
1008     if (!couldMerge) {
1009       // Need to add a new DebugLocEntry. Add all values from still
1010       // valid non-overlapping pieces.
1011       if (OpenRanges.size())
1012         Loc.addValues(OpenRanges);
1014       DebugLoc.push_back(std::move(Loc));
1015     }
1017     // Attempt to coalesce the ranges of two otherwise identical
1018     // DebugLocEntries.
1019     auto CurEntry = DebugLoc.rbegin();
1020     auto PrevEntry = std::next(CurEntry);
1021     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1022       DebugLoc.pop_back();
1024     DEBUG({
1025       dbgs() << CurEntry->getValues().size() << " Values:\n";
1026       for (auto Value : CurEntry->getValues()) {
1027         Value.getVariable()->dump();
1028         Value.getExpression()->dump();
1029       }
1030       dbgs() << "-----\n";
1031     });
1032   }
1036 // Find variables for each lexical scope.
1037 void
1038 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1039   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1040   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1042   // Grab the variable info that was squirreled away in the MMI side-table.
1043   collectVariableInfoFromMMITable(Processed);
1045   for (const auto &I : DbgValues) {
1046     DIVariable DV(I.first);
1047     if (Processed.count(DV))
1048       continue;
1050     // Instruction ranges, specifying where DV is accessible.
1051     const auto &Ranges = I.second;
1052     if (Ranges.empty())
1053       continue;
1055     LexicalScope *Scope = nullptr;
1056     if (MDNode *IA = DV.getInlinedAt()) {
1057       DebugLoc DL = DebugLoc::getFromDILocation(IA);
1058       Scope = LScopes.findInlinedScope(DebugLoc::get(
1059           DL.getLine(), DL.getCol(), DV.getContext(), IA));
1060     } else
1061       Scope = LScopes.findLexicalScope(DV.getContext());
1062     // If variable scope is not found then skip this variable.
1063     if (!Scope)
1064       continue;
1066     Processed.insert(DV);
1067     const MachineInstr *MInsn = Ranges.front().first;
1068     assert(MInsn->isDebugValue() && "History must begin with debug value");
1069     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1070     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1071     DbgVariable *RegVar = ConcreteVariables.back().get();
1072     addScopeVariable(Scope, RegVar);
1074     // Check if the first DBG_VALUE is valid for the rest of the function.
1075     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1076       continue;
1078     // Handle multiple DBG_VALUE instructions describing one variable.
1079     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1081     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1082     DebugLocList &LocList = DotDebugLocEntries.back();
1083     LocList.CU = TheCU;
1084     LocList.Label =
1085         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1087     // Build the location list for this variable.
1088     buildLocationList(LocList.List, Ranges);
1089   }
1091   // Collect info for variables that were optimized out.
1092   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1093   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1094     DIVariable DV(Variables.getElement(i));
1095     assert(DV.isVariable());
1096     if (!Processed.insert(DV))
1097       continue;
1098     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1099       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1100       DIExpression NoExpr;
1101       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1102       addScopeVariable(Scope, ConcreteVariables.back().get());
1103     }
1104   }
1107 // Return Label preceding the instruction.
1108 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1109   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1110   assert(Label && "Didn't insert label before instruction");
1111   return Label;
1114 // Return Label immediately following the instruction.
1115 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1116   return LabelsAfterInsn.lookup(MI);
1119 // Process beginning of an instruction.
1120 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1121   assert(CurMI == nullptr);
1122   CurMI = MI;
1123   // Check if source location changes, but ignore DBG_VALUE locations.
1124   if (!MI->isDebugValue()) {
1125     DebugLoc DL = MI->getDebugLoc();
1126     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1127       unsigned Flags = 0;
1128       PrevInstLoc = DL;
1129       if (DL == PrologEndLoc) {
1130         Flags |= DWARF2_FLAG_PROLOGUE_END;
1131         PrologEndLoc = DebugLoc();
1132       }
1133       if (PrologEndLoc.isUnknown())
1134         Flags |= DWARF2_FLAG_IS_STMT;
1136       if (!DL.isUnknown()) {
1137         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1138         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1139       } else
1140         recordSourceLine(0, 0, nullptr, 0);
1141     }
1142   }
1144   // Insert labels where requested.
1145   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1146       LabelsBeforeInsn.find(MI);
1148   // No label needed.
1149   if (I == LabelsBeforeInsn.end())
1150     return;
1152   // Label already assigned.
1153   if (I->second)
1154     return;
1156   if (!PrevLabel) {
1157     PrevLabel = MMI->getContext().CreateTempSymbol();
1158     Asm->OutStreamer.EmitLabel(PrevLabel);
1159   }
1160   I->second = PrevLabel;
1163 // Process end of an instruction.
1164 void DwarfDebug::endInstruction() {
1165   assert(CurMI != nullptr);
1166   // Don't create a new label after DBG_VALUE instructions.
1167   // They don't generate code.
1168   if (!CurMI->isDebugValue())
1169     PrevLabel = nullptr;
1171   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1172       LabelsAfterInsn.find(CurMI);
1173   CurMI = nullptr;
1175   // No label needed.
1176   if (I == LabelsAfterInsn.end())
1177     return;
1179   // Label already assigned.
1180   if (I->second)
1181     return;
1183   // We need a label after this instruction.
1184   if (!PrevLabel) {
1185     PrevLabel = MMI->getContext().CreateTempSymbol();
1186     Asm->OutStreamer.EmitLabel(PrevLabel);
1187   }
1188   I->second = PrevLabel;
1191 // Each LexicalScope has first instruction and last instruction to mark
1192 // beginning and end of a scope respectively. Create an inverse map that list
1193 // scopes starts (and ends) with an instruction. One instruction may start (or
1194 // end) multiple scopes. Ignore scopes that are not reachable.
1195 void DwarfDebug::identifyScopeMarkers() {
1196   SmallVector<LexicalScope *, 4> WorkList;
1197   WorkList.push_back(LScopes.getCurrentFunctionScope());
1198   while (!WorkList.empty()) {
1199     LexicalScope *S = WorkList.pop_back_val();
1201     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1202     if (!Children.empty())
1203       WorkList.append(Children.begin(), Children.end());
1205     if (S->isAbstractScope())
1206       continue;
1208     for (const InsnRange &R : S->getRanges()) {
1209       assert(R.first && "InsnRange does not have first instruction!");
1210       assert(R.second && "InsnRange does not have second instruction!");
1211       requestLabelBeforeInsn(R.first);
1212       requestLabelAfterInsn(R.second);
1213     }
1214   }
1217 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1218   // First known non-DBG_VALUE and non-frame setup location marks
1219   // the beginning of the function body.
1220   for (const auto &MBB : *MF)
1221     for (const auto &MI : MBB)
1222       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1223           !MI.getDebugLoc().isUnknown())
1224         return MI.getDebugLoc();
1225   return DebugLoc();
1228 // Gather pre-function debug information.  Assumes being called immediately
1229 // after the function entry point has been emitted.
1230 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1231   CurFn = MF;
1233   // If there's no debug info for the function we're not going to do anything.
1234   if (!MMI->hasDebugInfo())
1235     return;
1237   auto DI = FunctionDIs.find(MF->getFunction());
1238   if (DI == FunctionDIs.end())
1239     return;
1241   // Grab the lexical scopes for the function, if we don't have any of those
1242   // then we're not going to be able to do anything.
1243   LScopes.initialize(*MF);
1244   if (LScopes.empty())
1245     return;
1247   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1249   // Make sure that each lexical scope will have a begin/end label.
1250   identifyScopeMarkers();
1252   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1253   // belongs to so that we add to the correct per-cu line table in the
1254   // non-asm case.
1255   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1256   // FnScope->getScopeNode() and DI->second should represent the same function,
1257   // though they may not be the same MDNode due to inline functions merged in
1258   // LTO where the debug info metadata still differs (either due to distinct
1259   // written differences - two versions of a linkonce_odr function
1260   // written/copied into two separate files, or some sub-optimal metadata that
1261   // isn't structurally identical (see: file path/name info from clang, which
1262   // includes the directory of the cpp file being built, even when the file name
1263   // is absolute (such as an <> lookup header)))
1264   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1265   assert(TheCU && "Unable to find compile unit!");
1266   if (Asm->OutStreamer.hasRawTextSupport())
1267     // Use a single line table if we are generating assembly.
1268     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1269   else
1270     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1272   // Emit a label for the function so that we have a beginning address.
1273   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1274   // Assumes in correct section after the entry point.
1275   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1277   // Calculate history for local variables.
1278   calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1279                            DbgValues);
1281   // Request labels for the full history.
1282   for (const auto &I : DbgValues) {
1283     const auto &Ranges = I.second;
1284     if (Ranges.empty())
1285       continue;
1287     // The first mention of a function argument gets the FunctionBeginSym
1288     // label, so arguments are visible when breaking at function entry.
1289     DIVariable DIVar(Ranges.front().first->getDebugVariable());
1290     if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1291         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1292       LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1293       if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1294         // Mark all non-overlapping initial pieces.
1295         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1296           DIExpression Piece = I->first->getDebugExpression();
1297           if (std::all_of(Ranges.begin(), I,
1298                           [&](DbgValueHistoryMap::InstrRange Pred) {
1299                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1300               }))
1301             LabelsBeforeInsn[I->first] = FunctionBeginSym;
1302           else
1303             break;
1304         }
1305       }
1306     }
1308     for (const auto &Range : Ranges) {
1309       requestLabelBeforeInsn(Range.first);
1310       if (Range.second)
1311         requestLabelAfterInsn(Range.second);
1312     }
1313   }
1315   PrevInstLoc = DebugLoc();
1316   PrevLabel = FunctionBeginSym;
1318   // Record beginning of function.
1319   PrologEndLoc = findPrologueEndLoc(MF);
1320   if (!PrologEndLoc.isUnknown()) {
1321     DebugLoc FnStartDL =
1322         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1323     recordSourceLine(
1324         FnStartDL.getLine(), FnStartDL.getCol(),
1325         FnStartDL.getScope(MF->getFunction()->getContext()),
1326         // We'd like to list the prologue as "not statements" but GDB behaves
1327         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1328         DWARF2_FLAG_IS_STMT);
1329   }
1332 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1333   if (addCurrentFnArgument(Var, LS))
1334     return;
1335   SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1336   DIVariable DV = Var->getVariable();
1337   // Variables with positive arg numbers are parameters.
1338   if (unsigned ArgNum = DV.getArgNumber()) {
1339     // Keep all parameters in order at the start of the variable list to ensure
1340     // function types are correct (no out-of-order parameters)
1341     //
1342     // This could be improved by only doing it for optimized builds (unoptimized
1343     // builds have the right order to begin with), searching from the back (this
1344     // would catch the unoptimized case quickly), or doing a binary search
1345     // rather than linear search.
1346     SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1347     while (I != Vars.end()) {
1348       unsigned CurNum = (*I)->getVariable().getArgNumber();
1349       // A local (non-parameter) variable has been found, insert immediately
1350       // before it.
1351       if (CurNum == 0)
1352         break;
1353       // A later indexed parameter has been found, insert immediately before it.
1354       if (CurNum > ArgNum)
1355         break;
1356       ++I;
1357     }
1358     Vars.insert(I, Var);
1359     return;
1360   }
1362   Vars.push_back(Var);
1365 // Gather and emit post-function debug information.
1366 void DwarfDebug::endFunction(const MachineFunction *MF) {
1367   // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1368   // though the beginFunction may not be called at all.
1369   // We should handle both cases.
1370   if (!CurFn)
1371     CurFn = MF;
1372   else
1373     assert(CurFn == MF);
1374   assert(CurFn != nullptr);
1376   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1377       !FunctionDIs.count(MF->getFunction())) {
1378     // If we don't have a lexical scope for this function then there will
1379     // be a hole in the range information. Keep note of this by setting the
1380     // previously used section to nullptr.
1381     PrevCU = nullptr;
1382     CurFn = nullptr;
1383     return;
1384   }
1386   // Define end label for subprogram.
1387   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1388   // Assumes in correct section after the entry point.
1389   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1391   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1392   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1394   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1395   collectVariableInfo(ProcessedVars);
1397   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1398   DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1400   // Add the range of this function to the list of ranges for the CU.
1401   TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1403   // Under -gmlt, skip building the subprogram if there are no inlined
1404   // subroutines inside it.
1405   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1406       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1407     assert(ScopeVariables.empty());
1408     assert(CurrentFnArguments.empty());
1409     assert(DbgValues.empty());
1410     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1411     // by a -gmlt CU. Add a test and remove this assertion.
1412     assert(AbstractVariables.empty());
1413     LabelsBeforeInsn.clear();
1414     LabelsAfterInsn.clear();
1415     PrevLabel = nullptr;
1416     CurFn = nullptr;
1417     return;
1418   }
1420   // Construct abstract scopes.
1421   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1422     DISubprogram SP(AScope->getScopeNode());
1423     assert(SP.isSubprogram());
1424     // Collect info for variables that were optimized out.
1425     DIArray Variables = SP.getVariables();
1426     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1427       DIVariable DV(Variables.getElement(i));
1428       assert(DV && DV.isVariable());
1429       if (!ProcessedVars.insert(DV))
1430         continue;
1431       ensureAbstractVariableIsCreated(DV, DV.getContext());
1432     }
1433     constructAbstractSubprogramScopeDIE(AScope);
1434   }
1436   TheCU.constructSubprogramScopeDIE(FnScope);
1438   // Clear debug info
1439   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1440   // DbgVariables except those that are also in AbstractVariables (since they
1441   // can be used cross-function)
1442   ScopeVariables.clear();
1443   CurrentFnArguments.clear();
1444   DbgValues.clear();
1445   LabelsBeforeInsn.clear();
1446   LabelsAfterInsn.clear();
1447   PrevLabel = nullptr;
1448   CurFn = nullptr;
1451 // Register a source line with debug info. Returns the  unique label that was
1452 // emitted and which provides correspondence to the source line list.
1453 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1454                                   unsigned Flags) {
1455   StringRef Fn;
1456   StringRef Dir;
1457   unsigned Src = 1;
1458   unsigned Discriminator = 0;
1459   if (DIScope Scope = DIScope(S)) {
1460     assert(Scope.isScope());
1461     Fn = Scope.getFilename();
1462     Dir = Scope.getDirectory();
1463     if (Scope.isLexicalBlockFile())
1464       Discriminator = DILexicalBlockFile(S).getDiscriminator();
1466     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1467     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1468               .getOrCreateSourceID(Fn, Dir);
1469   }
1470   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1471                                          Discriminator, Fn);
1474 //===----------------------------------------------------------------------===//
1475 // Emit Methods
1476 //===----------------------------------------------------------------------===//
1478 // Emit initial Dwarf sections with a label at the start of each one.
1479 void DwarfDebug::emitSectionLabels() {
1480   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1482   // Dwarf sections base addresses.
1483   DwarfInfoSectionSym =
1484       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1485   if (useSplitDwarf()) {
1486     DwarfInfoDWOSectionSym =
1487         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1488     DwarfTypesDWOSectionSym =
1489         emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1490   }
1491   DwarfAbbrevSectionSym =
1492       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1493   if (useSplitDwarf())
1494     DwarfAbbrevDWOSectionSym = emitSectionSym(
1495         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1496   if (GenerateARangeSection)
1497     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1499   DwarfLineSectionSym =
1500       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1501   if (GenerateGnuPubSections) {
1502     DwarfGnuPubNamesSectionSym =
1503         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1504     DwarfGnuPubTypesSectionSym =
1505         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1506   } else if (HasDwarfPubSections) {
1507     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1508     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1509   }
1511   DwarfStrSectionSym =
1512       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1513   if (useSplitDwarf()) {
1514     DwarfStrDWOSectionSym =
1515         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1516     DwarfAddrSectionSym =
1517         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1518     DwarfDebugLocSectionSym =
1519         emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1520   } else
1521     DwarfDebugLocSectionSym =
1522         emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1523   DwarfDebugRangeSectionSym =
1524       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1527 // Recursively emits a debug information entry.
1528 void DwarfDebug::emitDIE(DIE &Die) {
1529   // Get the abbreviation for this DIE.
1530   const DIEAbbrev &Abbrev = Die.getAbbrev();
1532   // Emit the code (index) for the abbreviation.
1533   if (Asm->isVerbose())
1534     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1535                                 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1536                                 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1537                                 dwarf::TagString(Abbrev.getTag()));
1538   Asm->EmitULEB128(Abbrev.getNumber());
1540   const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1541   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1543   // Emit the DIE attribute values.
1544   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1545     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1546     dwarf::Form Form = AbbrevData[i].getForm();
1547     assert(Form && "Too many attributes for DIE (check abbreviation)");
1549     if (Asm->isVerbose()) {
1550       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1551       if (Attr == dwarf::DW_AT_accessibility)
1552         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1553             cast<DIEInteger>(Values[i])->getValue()));
1554     }
1556     // Emit an attribute using the defined form.
1557     Values[i]->EmitValue(Asm, Form);
1558   }
1560   // Emit the DIE children if any.
1561   if (Abbrev.hasChildren()) {
1562     for (auto &Child : Die.getChildren())
1563       emitDIE(*Child);
1565     Asm->OutStreamer.AddComment("End Of Children Mark");
1566     Asm->EmitInt8(0);
1567   }
1570 // Emit the debug info section.
1571 void DwarfDebug::emitDebugInfo() {
1572   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1574   Holder.emitUnits(this, DwarfAbbrevSectionSym);
1577 // Emit the abbreviation section.
1578 void DwarfDebug::emitAbbreviations() {
1579   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1581   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1584 // Emit the last address of the section and the end of the line matrix.
1585 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1586   // Define last address of section.
1587   Asm->OutStreamer.AddComment("Extended Op");
1588   Asm->EmitInt8(0);
1590   Asm->OutStreamer.AddComment("Op size");
1591   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1592   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1593   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1595   Asm->OutStreamer.AddComment("Section end label");
1597   Asm->OutStreamer.EmitSymbolValue(
1598       Asm->GetTempSymbol("section_end", SectionEnd),
1599       Asm->getDataLayout().getPointerSize());
1601   // Mark end of matrix.
1602   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1603   Asm->EmitInt8(0);
1604   Asm->EmitInt8(1);
1605   Asm->EmitInt8(1);
1608 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1609                            StringRef TableName, StringRef SymName) {
1610   Accel.FinalizeTable(Asm, TableName);
1611   Asm->OutStreamer.SwitchSection(Section);
1612   auto *SectionBegin = Asm->GetTempSymbol(SymName);
1613   Asm->OutStreamer.EmitLabel(SectionBegin);
1615   // Emit the full data.
1616   Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1619 // Emit visible names into a hashed accelerator table section.
1620 void DwarfDebug::emitAccelNames() {
1621   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1622             "Names", "names_begin");
1625 // Emit objective C classes and categories into a hashed accelerator table
1626 // section.
1627 void DwarfDebug::emitAccelObjC() {
1628   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1629             "ObjC", "objc_begin");
1632 // Emit namespace dies into a hashed accelerator table.
1633 void DwarfDebug::emitAccelNamespaces() {
1634   emitAccel(AccelNamespace,
1635             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1636             "namespac", "namespac_begin");
1639 // Emit type dies into a hashed accelerator table.
1640 void DwarfDebug::emitAccelTypes() {
1641   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1642             "types", "types_begin");
1645 // Public name handling.
1646 // The format for the various pubnames:
1647 //
1648 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1649 // for the DIE that is named.
1650 //
1651 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1652 // into the CU and the index value is computed according to the type of value
1653 // for the DIE that is named.
1654 //
1655 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1656 // it's the offset within the debug_info/debug_types dwo section, however, the
1657 // reference in the pubname header doesn't change.
1659 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1660 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1661                                                         const DIE *Die) {
1662   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1664   // We could have a specification DIE that has our most of our knowledge,
1665   // look for that now.
1666   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1667   if (SpecVal) {
1668     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1669     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1670       Linkage = dwarf::GIEL_EXTERNAL;
1671   } else if (Die->findAttribute(dwarf::DW_AT_external))
1672     Linkage = dwarf::GIEL_EXTERNAL;
1674   switch (Die->getTag()) {
1675   case dwarf::DW_TAG_class_type:
1676   case dwarf::DW_TAG_structure_type:
1677   case dwarf::DW_TAG_union_type:
1678   case dwarf::DW_TAG_enumeration_type:
1679     return dwarf::PubIndexEntryDescriptor(
1680         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1681                               ? dwarf::GIEL_STATIC
1682                               : dwarf::GIEL_EXTERNAL);
1683   case dwarf::DW_TAG_typedef:
1684   case dwarf::DW_TAG_base_type:
1685   case dwarf::DW_TAG_subrange_type:
1686     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1687   case dwarf::DW_TAG_namespace:
1688     return dwarf::GIEK_TYPE;
1689   case dwarf::DW_TAG_subprogram:
1690     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1691   case dwarf::DW_TAG_constant:
1692   case dwarf::DW_TAG_variable:
1693     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1694   case dwarf::DW_TAG_enumerator:
1695     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1696                                           dwarf::GIEL_STATIC);
1697   default:
1698     return dwarf::GIEK_NONE;
1699   }
1702 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1703 ///
1704 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1705   const MCSection *PSec =
1706       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1707                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1709   emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1712 void DwarfDebug::emitDebugPubSection(
1713     bool GnuStyle, const MCSection *PSec, StringRef Name,
1714     const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1715   for (const auto &NU : CUMap) {
1716     DwarfCompileUnit *TheU = NU.second;
1718     const auto &Globals = (TheU->*Accessor)();
1720     if (Globals.empty())
1721       continue;
1723     if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1724       TheU = Skeleton;
1725     unsigned ID = TheU->getUniqueID();
1727     // Start the dwarf pubnames section.
1728     Asm->OutStreamer.SwitchSection(PSec);
1730     // Emit the header.
1731     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1732     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1733     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1734     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1736     Asm->OutStreamer.EmitLabel(BeginLabel);
1738     Asm->OutStreamer.AddComment("DWARF Version");
1739     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1741     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1742     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1744     Asm->OutStreamer.AddComment("Compilation Unit Length");
1745     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1747     // Emit the pubnames for this compilation unit.
1748     for (const auto &GI : Globals) {
1749       const char *Name = GI.getKeyData();
1750       const DIE *Entity = GI.second;
1752       Asm->OutStreamer.AddComment("DIE offset");
1753       Asm->EmitInt32(Entity->getOffset());
1755       if (GnuStyle) {
1756         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1757         Asm->OutStreamer.AddComment(
1758             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1759             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1760         Asm->EmitInt8(Desc.toBits());
1761       }
1763       Asm->OutStreamer.AddComment("External Name");
1764       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1765     }
1767     Asm->OutStreamer.AddComment("End Mark");
1768     Asm->EmitInt32(0);
1769     Asm->OutStreamer.EmitLabel(EndLabel);
1770   }
1773 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1774   const MCSection *PSec =
1775       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1776                : Asm->getObjFileLowering().getDwarfPubTypesSection();
1778   emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1781 // Emit visible names into a debug str section.
1782 void DwarfDebug::emitDebugStr() {
1783   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1784   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1787 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1788 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1789                                const DITypeIdentifierMap &Map,
1790                                ArrayRef<DebugLocEntry::Value> Values) {
1791   assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1792         return P.isVariablePiece();
1793       }) && "all values are expected to be pieces");
1794   assert(std::is_sorted(Values.begin(), Values.end()) &&
1795          "pieces are expected to be sorted");
1797   unsigned Offset = 0;
1798   for (auto Piece : Values) {
1799     DIExpression Expr = Piece.getExpression();
1800     unsigned PieceOffset = Expr.getPieceOffset();
1801     unsigned PieceSize = Expr.getPieceSize();
1802     assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1803     if (Offset < PieceOffset) {
1804       // The DWARF spec seriously mandates pieces with no locations for gaps.
1805       Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1806       Offset += PieceOffset-Offset;
1807     }
1809     Offset += PieceSize;
1811     const unsigned SizeOfByte = 8;
1812 #ifndef NDEBUG
1813     DIVariable Var = Piece.getVariable();
1814     assert(!Var.isIndirect() && "indirect address for piece");
1815     unsigned VarSize = Var.getSizeInBits(Map);
1816     assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1817            && "piece is larger than or outside of variable");
1818     assert(PieceSize*SizeOfByte != VarSize
1819            && "piece covers entire variable");
1820 #endif
1821     if (Piece.isLocation() && Piece.getLoc().isReg())
1822       Asm->EmitDwarfRegOpPiece(Streamer,
1823                                Piece.getLoc(),
1824                                PieceSize*SizeOfByte);
1825     else {
1826       emitDebugLocValue(Streamer, Piece);
1827       Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1828     }
1829   }
1833 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1834                                    const DebugLocEntry &Entry) {
1835   const DebugLocEntry::Value Value = Entry.getValues()[0];
1836   if (Value.isVariablePiece())
1837     // Emit all pieces that belong to the same variable and range.
1838     return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1840   assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1841   emitDebugLocValue(Streamer, Value);
1844 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1845                                    const DebugLocEntry::Value &Value) {
1846   DIVariable DV = Value.getVariable();
1847   // Regular entry.
1848   if (Value.isInt()) {
1849     DIBasicType BTy(resolve(DV.getType()));
1850     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1851                          BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1852       Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1853       Streamer.EmitSLEB128(Value.getInt());
1854     } else {
1855       Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1856       Streamer.EmitULEB128(Value.getInt());
1857     }
1858   } else if (Value.isLocation()) {
1859     MachineLocation Loc = Value.getLoc();
1860     DIExpression Expr = Value.getExpression();
1861     if (!Expr)
1862       // Regular entry.
1863       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1864     else {
1865       // Complex address entry.
1866       unsigned N = Expr.getNumElements();
1867       unsigned i = 0;
1868       if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1869         if (Loc.getOffset()) {
1870           i = 2;
1871           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1872           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1873           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1874           Streamer.EmitSLEB128(Expr.getElement(1));
1875         } else {
1876           // If first address element is OpPlus then emit
1877           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1878           MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1879           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1880           i = 2;
1881         }
1882       } else {
1883         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1884       }
1886       // Emit remaining complex address elements.
1887       for (; i < N; ++i) {
1888         uint64_t Element = Expr.getElement(i);
1889         if (Element == dwarf::DW_OP_plus) {
1890           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1891           Streamer.EmitULEB128(Expr.getElement(++i));
1892         } else if (Element == dwarf::DW_OP_deref) {
1893           if (!Loc.isReg())
1894             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1895         } else if (Element == dwarf::DW_OP_piece) {
1896           i += 3;
1897           // handled in emitDebugLocEntry.
1898         } else
1899           llvm_unreachable("unknown Opcode found in complex address");
1900       }
1901     }
1902   }
1903   // else ... ignore constant fp. There is not any good way to
1904   // to represent them here in dwarf.
1905   // FIXME: ^
1908 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1909   Asm->OutStreamer.AddComment("Loc expr size");
1910   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1911   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1912   Asm->EmitLabelDifference(end, begin, 2);
1913   Asm->OutStreamer.EmitLabel(begin);
1914   // Emit the entry.
1915   APByteStreamer Streamer(*Asm);
1916   emitDebugLocEntry(Streamer, Entry);
1917   // Close the range.
1918   Asm->OutStreamer.EmitLabel(end);
1921 // Emit locations into the debug loc section.
1922 void DwarfDebug::emitDebugLoc() {
1923   // Start the dwarf loc section.
1924   Asm->OutStreamer.SwitchSection(
1925       Asm->getObjFileLowering().getDwarfLocSection());
1926   unsigned char Size = Asm->getDataLayout().getPointerSize();
1927   for (const auto &DebugLoc : DotDebugLocEntries) {
1928     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1929     const DwarfCompileUnit *CU = DebugLoc.CU;
1930     assert(!CU->getRanges().empty());
1931     for (const auto &Entry : DebugLoc.List) {
1932       // Set up the range. This range is relative to the entry point of the
1933       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1934       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1935       if (CU->getRanges().size() == 1) {
1936         // Grab the begin symbol from the first range as our base.
1937         const MCSymbol *Base = CU->getRanges()[0].getStart();
1938         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1939         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1940       } else {
1941         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1942         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1943       }
1945       emitDebugLocEntryLocation(Entry);
1946     }
1947     Asm->OutStreamer.EmitIntValue(0, Size);
1948     Asm->OutStreamer.EmitIntValue(0, Size);
1949   }
1952 void DwarfDebug::emitDebugLocDWO() {
1953   Asm->OutStreamer.SwitchSection(
1954       Asm->getObjFileLowering().getDwarfLocDWOSection());
1955   for (const auto &DebugLoc : DotDebugLocEntries) {
1956     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1957     for (const auto &Entry : DebugLoc.List) {
1958       // Just always use start_length for now - at least that's one address
1959       // rather than two. We could get fancier and try to, say, reuse an
1960       // address we know we've emitted elsewhere (the start of the function?
1961       // The start of the CU or CU subrange that encloses this range?)
1962       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1963       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1964       Asm->EmitULEB128(idx);
1965       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1967       emitDebugLocEntryLocation(Entry);
1968     }
1969     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1970   }
1973 struct ArangeSpan {
1974   const MCSymbol *Start, *End;
1975 };
1977 // Emit a debug aranges section, containing a CU lookup for any
1978 // address we can tie back to a CU.
1979 void DwarfDebug::emitDebugARanges() {
1980   // Start the dwarf aranges section.
1981   Asm->OutStreamer.SwitchSection(
1982       Asm->getObjFileLowering().getDwarfARangesSection());
1984   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1986   SpansType Spans;
1988   // Build a list of sections used.
1989   std::vector<const MCSection *> Sections;
1990   for (const auto &it : SectionMap) {
1991     const MCSection *Section = it.first;
1992     Sections.push_back(Section);
1993   }
1995   // Sort the sections into order.
1996   // This is only done to ensure consistent output order across different runs.
1997   std::sort(Sections.begin(), Sections.end(), SectionSort);
1999   // Build a set of address spans, sorted by CU.
2000   for (const MCSection *Section : Sections) {
2001     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2002     if (List.size() < 2)
2003       continue;
2005     // Sort the symbols by offset within the section.
2006     std::sort(List.begin(), List.end(),
2007               [&](const SymbolCU &A, const SymbolCU &B) {
2008       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2009       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2011       // Symbols with no order assigned should be placed at the end.
2012       // (e.g. section end labels)
2013       if (IA == 0)
2014         return false;
2015       if (IB == 0)
2016         return true;
2017       return IA < IB;
2018     });
2020     // If we have no section (e.g. common), just write out
2021     // individual spans for each symbol.
2022     if (!Section) {
2023       for (const SymbolCU &Cur : List) {
2024         ArangeSpan Span;
2025         Span.Start = Cur.Sym;
2026         Span.End = nullptr;
2027         if (Cur.CU)
2028           Spans[Cur.CU].push_back(Span);
2029       }
2030     } else {
2031       // Build spans between each label.
2032       const MCSymbol *StartSym = List[0].Sym;
2033       for (size_t n = 1, e = List.size(); n < e; n++) {
2034         const SymbolCU &Prev = List[n - 1];
2035         const SymbolCU &Cur = List[n];
2037         // Try and build the longest span we can within the same CU.
2038         if (Cur.CU != Prev.CU) {
2039           ArangeSpan Span;
2040           Span.Start = StartSym;
2041           Span.End = Cur.Sym;
2042           Spans[Prev.CU].push_back(Span);
2043           StartSym = Cur.Sym;
2044         }
2045       }
2046     }
2047   }
2049   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2051   // Build a list of CUs used.
2052   std::vector<DwarfCompileUnit *> CUs;
2053   for (const auto &it : Spans) {
2054     DwarfCompileUnit *CU = it.first;
2055     CUs.push_back(CU);
2056   }
2058   // Sort the CU list (again, to ensure consistent output order).
2059   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2060     return A->getUniqueID() < B->getUniqueID();
2061   });
2063   // Emit an arange table for each CU we used.
2064   for (DwarfCompileUnit *CU : CUs) {
2065     std::vector<ArangeSpan> &List = Spans[CU];
2067     // Emit size of content not including length itself.
2068     unsigned ContentSize =
2069         sizeof(int16_t) + // DWARF ARange version number
2070         sizeof(int32_t) + // Offset of CU in the .debug_info section
2071         sizeof(int8_t) +  // Pointer Size (in bytes)
2072         sizeof(int8_t);   // Segment Size (in bytes)
2074     unsigned TupleSize = PtrSize * 2;
2076     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2077     unsigned Padding =
2078         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2080     ContentSize += Padding;
2081     ContentSize += (List.size() + 1) * TupleSize;
2083     // For each compile unit, write the list of spans it covers.
2084     Asm->OutStreamer.AddComment("Length of ARange Set");
2085     Asm->EmitInt32(ContentSize);
2086     Asm->OutStreamer.AddComment("DWARF Arange version number");
2087     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2088     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2089     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2090     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2091     Asm->EmitInt8(PtrSize);
2092     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2093     Asm->EmitInt8(0);
2095     Asm->OutStreamer.EmitFill(Padding, 0xff);
2097     for (const ArangeSpan &Span : List) {
2098       Asm->EmitLabelReference(Span.Start, PtrSize);
2100       // Calculate the size as being from the span start to it's end.
2101       if (Span.End) {
2102         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2103       } else {
2104         // For symbols without an end marker (e.g. common), we
2105         // write a single arange entry containing just that one symbol.
2106         uint64_t Size = SymSize[Span.Start];
2107         if (Size == 0)
2108           Size = 1;
2110         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2111       }
2112     }
2114     Asm->OutStreamer.AddComment("ARange terminator");
2115     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2116     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2117   }
2120 // Emit visible names into a debug ranges section.
2121 void DwarfDebug::emitDebugRanges() {
2122   // Start the dwarf ranges section.
2123   Asm->OutStreamer.SwitchSection(
2124       Asm->getObjFileLowering().getDwarfRangesSection());
2126   // Size for our labels.
2127   unsigned char Size = Asm->getDataLayout().getPointerSize();
2129   // Grab the specific ranges for the compile units in the module.
2130   for (const auto &I : CUMap) {
2131     DwarfCompileUnit *TheCU = I.second;
2133     // Iterate over the misc ranges for the compile units in the module.
2134     for (const RangeSpanList &List : TheCU->getRangeLists()) {
2135       // Emit our symbol so we can find the beginning of the range.
2136       Asm->OutStreamer.EmitLabel(List.getSym());
2138       for (const RangeSpan &Range : List.getRanges()) {
2139         const MCSymbol *Begin = Range.getStart();
2140         const MCSymbol *End = Range.getEnd();
2141         assert(Begin && "Range without a begin symbol?");
2142         assert(End && "Range without an end symbol?");
2143         if (TheCU->getRanges().size() == 1) {
2144           // Grab the begin symbol from the first range as our base.
2145           const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2146           Asm->EmitLabelDifference(Begin, Base, Size);
2147           Asm->EmitLabelDifference(End, Base, Size);
2148         } else {
2149           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2150           Asm->OutStreamer.EmitSymbolValue(End, Size);
2151         }
2152       }
2154       // And terminate the list with two 0 values.
2155       Asm->OutStreamer.EmitIntValue(0, Size);
2156       Asm->OutStreamer.EmitIntValue(0, Size);
2157     }
2159     // Now emit a range for the CU itself.
2160     if (TheCU->getRanges().size() > 1) {
2161       Asm->OutStreamer.EmitLabel(
2162           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2163       for (const RangeSpan &Range : TheCU->getRanges()) {
2164         const MCSymbol *Begin = Range.getStart();
2165         const MCSymbol *End = Range.getEnd();
2166         assert(Begin && "Range without a begin symbol?");
2167         assert(End && "Range without an end symbol?");
2168         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2169         Asm->OutStreamer.EmitSymbolValue(End, Size);
2170       }
2171       // And terminate the list with two 0 values.
2172       Asm->OutStreamer.EmitIntValue(0, Size);
2173       Asm->OutStreamer.EmitIntValue(0, Size);
2174     }
2175   }
2178 // DWARF5 Experimental Separate Dwarf emitters.
2180 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2181                                   std::unique_ptr<DwarfUnit> NewU) {
2182   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2183                        U.getCUNode().getSplitDebugFilename());
2185   if (!CompilationDir.empty())
2186     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2188   addGnuPubAttributes(*NewU, Die);
2190   SkeletonHolder.addUnit(std::move(NewU));
2193 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2194 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2195 // DW_AT_addr_base, DW_AT_ranges_base.
2196 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2198   auto OwnedUnit = make_unique<DwarfCompileUnit>(
2199       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2200   DwarfCompileUnit &NewCU = *OwnedUnit;
2201   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2202                     DwarfInfoSectionSym);
2204   NewCU.initStmtList(DwarfLineSectionSym);
2206   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2208   return NewCU;
2211 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2212 // compile units that would normally be in debug_info.
2213 void DwarfDebug::emitDebugInfoDWO() {
2214   assert(useSplitDwarf() && "No split dwarf debug info?");
2215   // Don't pass an abbrev symbol, using a constant zero instead so as not to
2216   // emit relocations into the dwo file.
2217   InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2220 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2221 // abbreviations for the .debug_info.dwo section.
2222 void DwarfDebug::emitDebugAbbrevDWO() {
2223   assert(useSplitDwarf() && "No split dwarf?");
2224   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2227 void DwarfDebug::emitDebugLineDWO() {
2228   assert(useSplitDwarf() && "No split dwarf?");
2229   Asm->OutStreamer.SwitchSection(
2230       Asm->getObjFileLowering().getDwarfLineDWOSection());
2231   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2234 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2235 // string section and is identical in format to traditional .debug_str
2236 // sections.
2237 void DwarfDebug::emitDebugStrDWO() {
2238   assert(useSplitDwarf() && "No split dwarf?");
2239   const MCSection *OffSec =
2240       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2241   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2242                          OffSec);
2245 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2246   if (!useSplitDwarf())
2247     return nullptr;
2248   if (SingleCU)
2249     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2250   return &SplitTypeUnitFileTable;
2253 static uint64_t makeTypeSignature(StringRef Identifier) {
2254   MD5 Hash;
2255   Hash.update(Identifier);
2256   // ... take the least significant 8 bytes and return those. Our MD5
2257   // implementation always returns its results in little endian, swap bytes
2258   // appropriately.
2259   MD5::MD5Result Result;
2260   Hash.final(Result);
2261   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2264 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2265                                       StringRef Identifier, DIE &RefDie,
2266                                       DICompositeType CTy) {
2267   // Fast path if we're building some type units and one has already used the
2268   // address pool we know we're going to throw away all this work anyway, so
2269   // don't bother building dependent types.
2270   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2271     return;
2273   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2274   if (TU) {
2275     CU.addDIETypeSignature(RefDie, *TU);
2276     return;
2277   }
2279   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2280   AddrPool.resetUsedFlag();
2282   auto OwnedUnit = make_unique<DwarfTypeUnit>(
2283       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2284       this, &InfoHolder, getDwoLineTable(CU));
2285   DwarfTypeUnit &NewTU = *OwnedUnit;
2286   DIE &UnitDie = NewTU.getUnitDie();
2287   TU = &NewTU;
2288   TypeUnitsUnderConstruction.push_back(
2289       std::make_pair(std::move(OwnedUnit), CTy));
2291   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2292                 CU.getLanguage());
2294   uint64_t Signature = makeTypeSignature(Identifier);
2295   NewTU.setTypeSignature(Signature);
2297   if (useSplitDwarf())
2298     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2299                       DwarfTypesDWOSectionSym);
2300   else {
2301     CU.applyStmtList(UnitDie);
2302     NewTU.initSection(
2303         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2304   }
2306   NewTU.setType(NewTU.createTypeDIE(CTy));
2308   if (TopLevelType) {
2309     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2310     TypeUnitsUnderConstruction.clear();
2312     // Types referencing entries in the address table cannot be placed in type
2313     // units.
2314     if (AddrPool.hasBeenUsed()) {
2316       // Remove all the types built while building this type.
2317       // This is pessimistic as some of these types might not be dependent on
2318       // the type that used an address.
2319       for (const auto &TU : TypeUnitsToAdd)
2320         DwarfTypeUnits.erase(TU.second);
2322       // Construct this type in the CU directly.
2323       // This is inefficient because all the dependent types will be rebuilt
2324       // from scratch, including building them in type units, discovering that
2325       // they depend on addresses, throwing them out and rebuilding them.
2326       CU.constructTypeDIE(RefDie, CTy);
2327       return;
2328     }
2330     // If the type wasn't dependent on fission addresses, finish adding the type
2331     // and all its dependent types.
2332     for (auto &TU : TypeUnitsToAdd)
2333       InfoHolder.addUnit(std::move(TU.first));
2334   }
2335   CU.addDIETypeSignature(RefDie, NewTU);
2338 // Accelerator table mutators - add each name along with its companion
2339 // DIE to the proper table while ensuring that the name that we're going
2340 // to reference is in the string table. We do this since the names we
2341 // add may not only be identical to the names in the DIE.
2342 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2343   if (!useDwarfAccelTables())
2344     return;
2345   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2346                      &Die);
2349 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2350   if (!useDwarfAccelTables())
2351     return;
2352   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2353                     &Die);
2356 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2357   if (!useDwarfAccelTables())
2358     return;
2359   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2360                          &Die);
2363 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2364   if (!useDwarfAccelTables())
2365     return;
2366   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2367                      &Die);