Refactor DebugLocDWARFExpression so it doesn't require access to the
[oota-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 //===----------------------------------------------------------------------===//
13
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
16 #include "DIEHash.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfExpression.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/DIE.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;
55
56 #define DEBUG_TYPE "dwarfdebug"
57
58 static cl::opt<bool>
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60                          cl::desc("Disable debug info printing"));
61
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));
66
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));
71
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73                                            cl::Hidden,
74                                            cl::desc("Generate dwarf aranges"),
75                                            cl::init(false));
76
77 namespace {
78 enum DefaultOnOff { Default, Enable, Disable };
79 }
80
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));
88
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));
96
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));
104
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
107
108 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
109   BS.EmitInt8(
110       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
111                   : dwarf::OperationEncodingString(Op));
112 }
113
114 void DebugLocDwarfExpression::EmitSigned(int Value) {
115   BS.EmitSLEB128(Value, Twine(Value));
116 }
117
118 void DebugLocDwarfExpression::EmitUnsigned(unsigned Value) {
119   BS.EmitULEB128(Value, Twine(Value));
120 }
121
122 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
123   // This information is not available while emitting .debug_loc entries.
124   return false;
125 }
126
127 //===----------------------------------------------------------------------===//
128
129 /// resolve - Look in the DwarfDebug map for the MDNode that
130 /// corresponds to the reference.
131 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
132   return DD->resolve(Ref);
133 }
134
135 bool DbgVariable::isBlockByrefVariable() const {
136   assert(Var.isVariable() && "Invalid complex DbgVariable!");
137   return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
138 }
139
140 DIType DbgVariable::getType() const {
141   DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
142   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
143   // addresses instead.
144   if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
145     /* Byref variables, in Blocks, are declared by the programmer as
146        "SomeType VarName;", but the compiler creates a
147        __Block_byref_x_VarName struct, and gives the variable VarName
148        either the struct, or a pointer to the struct, as its type.  This
149        is necessary for various behind-the-scenes things the compiler
150        needs to do with by-reference variables in blocks.
151
152        However, as far as the original *programmer* is concerned, the
153        variable should still have type 'SomeType', as originally declared.
154
155        The following function dives into the __Block_byref_x_VarName
156        struct to find the original type of the variable.  This will be
157        passed back to the code generating the type for the Debug
158        Information Entry for the variable 'VarName'.  'VarName' will then
159        have the original type 'SomeType' in its debug information.
160
161        The original type 'SomeType' will be the type of the field named
162        'VarName' inside the __Block_byref_x_VarName struct.
163
164        NOTE: In order for this to not completely fail on the debugger
165        side, the Debug Information Entry for the variable VarName needs to
166        have a DW_AT_location that tells the debugger how to unwind through
167        the pointers and __Block_byref_x_VarName struct to find the actual
168        value of the variable.  The function addBlockByrefType does this.  */
169     DIType subType = Ty;
170     uint16_t tag = Ty.getTag();
171
172     if (tag == dwarf::DW_TAG_pointer_type)
173       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
174
175     DIArray Elements = DICompositeType(subType).getElements();
176     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
177       DIDerivedType DT(Elements.getElement(i));
178       if (getName() == DT.getName())
179         return (resolve(DT.getTypeDerivedFrom()));
180     }
181   }
182   return Ty;
183 }
184
185 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
186     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
187     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
188     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
189
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191     : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
192       InfoHolder(A, *this, "info_string", DIEValueAllocator),
193       UsedNonDefaultText(false),
194       SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
195       IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
197                                        dwarf::DW_FORM_data4)),
198       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
199                                       dwarf::DW_FORM_data4)),
200       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
201                                            dwarf::DW_FORM_data4)),
202       AccelTypes(TypeAtoms) {
203
204   DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
205   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
206   DwarfLineSectionSym = nullptr;
207   DwarfAddrSectionSym = nullptr;
208   DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
209   FunctionBeginSym = FunctionEndSym = nullptr;
210   CurFn = nullptr;
211   CurMI = nullptr;
212
213   // Turn on accelerator tables for Darwin by default, pubnames by
214   // default for non-Darwin, and handle split dwarf.
215   if (DwarfAccelTables == Default)
216     HasDwarfAccelTables = IsDarwin;
217   else
218     HasDwarfAccelTables = DwarfAccelTables == Enable;
219
220   if (SplitDwarf == Default)
221     HasSplitDwarf = false;
222   else
223     HasSplitDwarf = SplitDwarf == Enable;
224
225   if (DwarfPubSections == Default)
226     HasDwarfPubSections = !IsDarwin;
227   else
228     HasDwarfPubSections = DwarfPubSections == Enable;
229
230   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
231   DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
232                                     : MMI->getModule()->getDwarfVersion();
233
234   Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
235
236   {
237     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
238     beginModule();
239   }
240 }
241
242 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
243 DwarfDebug::~DwarfDebug() { }
244
245 // Switch to the specified MCSection and emit an assembler
246 // temporary label to it if SymbolStem is specified.
247 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
248                                 const char *SymbolStem = nullptr) {
249   Asm->OutStreamer.SwitchSection(Section);
250   if (!SymbolStem)
251     return nullptr;
252
253   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
254   Asm->OutStreamer.EmitLabel(TmpSym);
255   return TmpSym;
256 }
257
258 static bool isObjCClass(StringRef Name) {
259   return Name.startswith("+") || Name.startswith("-");
260 }
261
262 static bool hasObjCCategory(StringRef Name) {
263   if (!isObjCClass(Name))
264     return false;
265
266   return Name.find(") ") != StringRef::npos;
267 }
268
269 static void getObjCClassCategory(StringRef In, StringRef &Class,
270                                  StringRef &Category) {
271   if (!hasObjCCategory(In)) {
272     Class = In.slice(In.find('[') + 1, In.find(' '));
273     Category = "";
274     return;
275   }
276
277   Class = In.slice(In.find('[') + 1, In.find('('));
278   Category = In.slice(In.find('[') + 1, In.find(' '));
279   return;
280 }
281
282 static StringRef getObjCMethodName(StringRef In) {
283   return In.slice(In.find(' ') + 1, In.find(']'));
284 }
285
286 // Helper for sorting sections into a stable output order.
287 static bool SectionSort(const MCSection *A, const MCSection *B) {
288   std::string LA = (A ? A->getLabelBeginName() : "");
289   std::string LB = (B ? B->getLabelBeginName() : "");
290   return LA < LB;
291 }
292
293 // Add the various names to the Dwarf accelerator table names.
294 // TODO: Determine whether or not we should add names for programs
295 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
296 // is only slightly different than the lookup of non-standard ObjC names.
297 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
298   if (!SP.isDefinition())
299     return;
300   addAccelName(SP.getName(), Die);
301
302   // If the linkage name is different than the name, go ahead and output
303   // that as well into the name table.
304   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
305     addAccelName(SP.getLinkageName(), Die);
306
307   // If this is an Objective-C selector name add it to the ObjC accelerator
308   // too.
309   if (isObjCClass(SP.getName())) {
310     StringRef Class, Category;
311     getObjCClassCategory(SP.getName(), Class, Category);
312     addAccelObjC(Class, Die);
313     if (Category != "")
314       addAccelObjC(Category, Die);
315     // Also add the base method name to the name table.
316     addAccelName(getObjCMethodName(SP.getName()), Die);
317   }
318 }
319
320 /// isSubprogramContext - Return true if Context is either a subprogram
321 /// or another context nested inside a subprogram.
322 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
323   if (!Context)
324     return false;
325   DIDescriptor D(Context);
326   if (D.isSubprogram())
327     return true;
328   if (D.isType())
329     return isSubprogramContext(resolve(DIType(Context).getContext()));
330   return false;
331 }
332
333 /// Check whether we should create a DIE for the given Scope, return true
334 /// if we don't create a DIE (the corresponding DIE is null).
335 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
336   if (Scope->isAbstractScope())
337     return false;
338
339   // We don't create a DIE if there is no Range.
340   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
341   if (Ranges.empty())
342     return true;
343
344   if (Ranges.size() > 1)
345     return false;
346
347   // We don't create a DIE if we have a single Range and the end label
348   // is null.
349   return !getLabelAfterInsn(Ranges.front().second);
350 }
351
352 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
353   F(CU);
354   if (auto *SkelCU = CU.getSkeleton())
355     F(*SkelCU);
356 }
357
358 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
359   assert(Scope && Scope->getScopeNode());
360   assert(Scope->isAbstractScope());
361   assert(!Scope->getInlinedAt());
362
363   const MDNode *SP = Scope->getScopeNode();
364
365   ProcessedSPNodes.insert(SP);
366
367   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
368   // was inlined from another compile unit.
369   auto &CU = SPMap[SP];
370   forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
371     CU.constructAbstractSubprogramScopeDIE(Scope);
372   });
373 }
374
375 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
376   if (!GenerateGnuPubSections)
377     return;
378
379   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
380 }
381
382 // Create new DwarfCompileUnit for the given metadata node with tag
383 // DW_TAG_compile_unit.
384 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
385   StringRef FN = DIUnit.getFilename();
386   CompilationDir = DIUnit.getDirectory();
387
388   auto OwnedUnit = make_unique<DwarfCompileUnit>(
389       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
390   DwarfCompileUnit &NewCU = *OwnedUnit;
391   DIE &Die = NewCU.getUnitDie();
392   InfoHolder.addUnit(std::move(OwnedUnit));
393   if (useSplitDwarf())
394     NewCU.setSkeleton(constructSkeletonCU(NewCU));
395
396   // LTO with assembly output shares a single line table amongst multiple CUs.
397   // To avoid the compilation directory being ambiguous, let the line table
398   // explicitly describe the directory of all files, never relying on the
399   // compilation directory.
400   if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
401     Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
402         NewCU.getUniqueID(), CompilationDir);
403
404   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
405   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
406                 DIUnit.getLanguage());
407   NewCU.addString(Die, dwarf::DW_AT_name, FN);
408
409   if (!useSplitDwarf()) {
410     NewCU.initStmtList(DwarfLineSectionSym);
411
412     // If we're using split dwarf the compilation dir is going to be in the
413     // skeleton CU and so we don't need to duplicate it here.
414     if (!CompilationDir.empty())
415       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
416
417     addGnuPubAttributes(NewCU, Die);
418   }
419
420   if (DIUnit.isOptimized())
421     NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
422
423   StringRef Flags = DIUnit.getFlags();
424   if (!Flags.empty())
425     NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
426
427   if (unsigned RVer = DIUnit.getRunTimeVersion())
428     NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
429                   dwarf::DW_FORM_data1, RVer);
430
431   if (useSplitDwarf())
432     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
433                       DwarfInfoDWOSectionSym);
434   else
435     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
436                       DwarfInfoSectionSym);
437
438   CUMap.insert(std::make_pair(DIUnit, &NewCU));
439   CUDieMap.insert(std::make_pair(&Die, &NewCU));
440   return NewCU;
441 }
442
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));
449 }
450
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;
457
458   const Module *M = MMI->getModule();
459
460   FunctionDIs = makeSubprogramMap(*M);
461
462   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
463   if (!CU_Nodes)
464     return;
465   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
466
467   // Emit initial sections so we can reference labels later.
468   emitSectionLabels();
469
470   SingleCU = CU_Nodes->getNumOperands() == 1;
471
472   for (MDNode *N : CU_Nodes->operands()) {
473     DICompileUnit CUNode(N);
474     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
475     DIArray ImportedEntities = CUNode.getImportedEntities();
476     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
477       ScopesWithImportedEntities.push_back(std::make_pair(
478           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
479           ImportedEntities.getElement(i)));
480     std::sort(ScopesWithImportedEntities.begin(),
481               ScopesWithImportedEntities.end(), less_first());
482     DIArray GVs = CUNode.getGlobalVariables();
483     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
484       CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
485     DIArray SPs = CUNode.getSubprograms();
486     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
487       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
488     DIArray EnumTypes = CUNode.getEnumTypes();
489     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
490       DIType Ty(EnumTypes.getElement(i));
491       // The enum types array by design contains pointers to
492       // MDNodes rather than DIRefs. Unique them here.
493       DIType UniqueTy(resolve(Ty.getRef()));
494       CU.getOrCreateTypeDIE(UniqueTy);
495     }
496     DIArray RetainedTypes = CUNode.getRetainedTypes();
497     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
498       DIType Ty(RetainedTypes.getElement(i));
499       // The retained types array by design contains pointers to
500       // MDNodes rather than DIRefs. Unique them here.
501       DIType UniqueTy(resolve(Ty.getRef()));
502       CU.getOrCreateTypeDIE(UniqueTy);
503     }
504     // Emit imported_modules last so that the relevant context is already
505     // available.
506     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
507       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
508   }
509
510   // Tell MMI that we have debug info.
511   MMI->setDebugInfoAvailability(true);
512 }
513
514 void DwarfDebug::finishVariableDefinitions() {
515   for (const auto &Var : ConcreteVariables) {
516     DIE *VariableDie = Var->getDIE();
517     assert(VariableDie);
518     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
519     // in the ConcreteVariables list, rather than looking it up again here.
520     // DIE::getUnit isn't simple - it walks parent pointers, etc.
521     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
522     assert(Unit);
523     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
524     if (AbsVar && AbsVar->getDIE()) {
525       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
526                         *AbsVar->getDIE());
527     } else
528       Unit->applyVariableAttributes(*Var, *VariableDie);
529   }
530 }
531
532 void DwarfDebug::finishSubprogramDefinitions() {
533   for (const auto &P : SPMap)
534     forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
535       CU.finishSubprogramDefinition(DISubprogram(P.first));
536     });
537 }
538
539
540 // Collect info for variables that were optimized out.
541 void DwarfDebug::collectDeadVariables() {
542   const Module *M = MMI->getModule();
543
544   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
545     for (MDNode *N : CU_Nodes->operands()) {
546       DICompileUnit TheCU(N);
547       // Construct subprogram DIE and add variables DIEs.
548       DwarfCompileUnit *SPCU =
549           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
550       assert(SPCU && "Unable to find Compile Unit!");
551       DIArray Subprograms = TheCU.getSubprograms();
552       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
553         DISubprogram SP(Subprograms.getElement(i));
554         if (ProcessedSPNodes.count(SP) != 0)
555           continue;
556         SPCU->collectDeadVariables(SP);
557       }
558     }
559   }
560 }
561
562 void DwarfDebug::finalizeModuleInfo() {
563   finishSubprogramDefinitions();
564
565   finishVariableDefinitions();
566
567   // Collect info for variables that were optimized out.
568   collectDeadVariables();
569
570   // Handle anything that needs to be done on a per-unit basis after
571   // all other generation.
572   for (const auto &P : CUMap) {
573     auto &TheCU = *P.second;
574     // Emit DW_AT_containing_type attribute to connect types with their
575     // vtable holding type.
576     TheCU.constructContainingTypeDIEs();
577
578     // Add CU specific attributes if we need to add any.
579     // If we're splitting the dwarf out now that we've got the entire
580     // CU then add the dwo id to it.
581     auto *SkCU = TheCU.getSkeleton();
582     if (useSplitDwarf()) {
583       // Emit a unique identifier for this CU.
584       uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
585       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
586                     dwarf::DW_FORM_data8, ID);
587       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
588                     dwarf::DW_FORM_data8, ID);
589
590       // We don't keep track of which addresses are used in which CU so this
591       // is a bit pessimistic under LTO.
592       if (!AddrPool.isEmpty())
593         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
594                               DwarfAddrSectionSym, DwarfAddrSectionSym);
595       if (!SkCU->getRangeLists().empty())
596         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
597                               DwarfDebugRangeSectionSym,
598                               DwarfDebugRangeSectionSym);
599     }
600
601     // If we have code split among multiple sections or non-contiguous
602     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
603     // remain in the .o file, otherwise add a DW_AT_low_pc.
604     // FIXME: We should use ranges allow reordering of code ala
605     // .subsections_via_symbols in mach-o. This would mean turning on
606     // ranges for all subprogram DIEs for mach-o.
607     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
608     if (unsigned NumRanges = TheCU.getRanges().size()) {
609       if (NumRanges > 1)
610         // A DW_AT_low_pc attribute may also be specified in combination with
611         // DW_AT_ranges to specify the default base address for use in
612         // location lists (see Section 2.6.2) and range lists (see Section
613         // 2.17.3).
614         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
615       else
616         TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
617       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
618     }
619   }
620
621   // Compute DIE offsets and sizes.
622   InfoHolder.computeSizeAndOffsets();
623   if (useSplitDwarf())
624     SkeletonHolder.computeSizeAndOffsets();
625 }
626
627 // Emit all Dwarf sections that should come after the content.
628 void DwarfDebug::endModule() {
629   assert(CurFn == nullptr);
630   assert(CurMI == nullptr);
631
632   // If we aren't actually generating debug info (check beginModule -
633   // conditionalized on !DisableDebugInfoPrinting and the presence of the
634   // llvm.dbg.cu metadata node)
635   if (!DwarfInfoSectionSym)
636     return;
637
638   // Finalize the debug info for the module.
639   finalizeModuleInfo();
640
641   emitDebugStr();
642
643   // Emit all the DIEs into a debug info section.
644   emitDebugInfo();
645
646   // Corresponding abbreviations into a abbrev section.
647   emitAbbreviations();
648
649   // Emit info into a debug aranges section.
650   if (GenerateARangeSection)
651     emitDebugARanges();
652
653   // Emit info into a debug ranges section.
654   emitDebugRanges();
655
656   if (useSplitDwarf()) {
657     emitDebugStrDWO();
658     emitDebugInfoDWO();
659     emitDebugAbbrevDWO();
660     emitDebugLineDWO();
661     emitDebugLocDWO();
662     // Emit DWO addresses.
663     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
664   } else
665     // Emit info into a debug loc section.
666     emitDebugLoc();
667
668   // Emit info into the dwarf accelerator table sections.
669   if (useDwarfAccelTables()) {
670     emitAccelNames();
671     emitAccelObjC();
672     emitAccelNamespaces();
673     emitAccelTypes();
674   }
675
676   // Emit the pubnames and pubtypes sections if requested.
677   if (HasDwarfPubSections) {
678     emitDebugPubNames(GenerateGnuPubSections);
679     emitDebugPubTypes(GenerateGnuPubSections);
680   }
681
682   // clean up.
683   SPMap.clear();
684   AbstractVariables.clear();
685 }
686
687 // Find abstract variable, if any, associated with Var.
688 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
689                                                      DIVariable &Cleansed) {
690   LLVMContext &Ctx = DV->getContext();
691   // More then one inlined variable corresponds to one abstract variable.
692   // FIXME: This duplication of variables when inlining should probably be
693   // removed. It's done to allow each DIVariable to describe its location
694   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
695   // make it accurate then remove this duplication/cleansing stuff.
696   Cleansed = cleanseInlinedVariable(DV, Ctx);
697   auto I = AbstractVariables.find(Cleansed);
698   if (I != AbstractVariables.end())
699     return I->second.get();
700   return nullptr;
701 }
702
703 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
704   DIVariable Cleansed;
705   return getExistingAbstractVariable(DV, Cleansed);
706 }
707
708 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
709                                         LexicalScope *Scope) {
710   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
711   InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
712   AbstractVariables[Var] = std::move(AbsDbgVariable);
713 }
714
715 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
716                                                  const MDNode *ScopeNode) {
717   DIVariable Cleansed = DV;
718   if (getExistingAbstractVariable(DV, Cleansed))
719     return;
720
721   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
722 }
723
724 void
725 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
726                                                     const MDNode *ScopeNode) {
727   DIVariable Cleansed = DV;
728   if (getExistingAbstractVariable(DV, Cleansed))
729     return;
730
731   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
732     createAbstractVariable(Cleansed, Scope);
733 }
734
735 // Collect variable information from side table maintained by MMI.
736 void DwarfDebug::collectVariableInfoFromMMITable(
737     SmallPtrSetImpl<const MDNode *> &Processed) {
738   for (const auto &VI : MMI->getVariableDbgInfo()) {
739     if (!VI.Var)
740       continue;
741     Processed.insert(VI.Var);
742     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
743
744     // If variable scope is not found then skip this variable.
745     if (!Scope)
746       continue;
747
748     DIVariable DV(VI.Var);
749     DIExpression Expr(VI.Expr);
750     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
751     auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
752     if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
753       ConcreteVariables.push_back(std::move(RegVar));
754   }
755 }
756
757 // Get .debug_loc entry for the instruction range starting at MI.
758 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
759   const MDNode *Expr = MI->getDebugExpression();
760   const MDNode *Var = MI->getDebugVariable();
761
762   assert(MI->getNumOperands() == 4);
763   if (MI->getOperand(0).isReg()) {
764     MachineLocation MLoc;
765     // If the second operand is an immediate, this is a
766     // register-indirect address.
767     if (!MI->getOperand(1).isImm())
768       MLoc.set(MI->getOperand(0).getReg());
769     else
770       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
771     return DebugLocEntry::Value(Var, Expr, MLoc);
772   }
773   if (MI->getOperand(0).isImm())
774     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
775   if (MI->getOperand(0).isFPImm())
776     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
777   if (MI->getOperand(0).isCImm())
778     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
779
780   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
781 }
782
783 /// Determine whether two variable pieces overlap.
784 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
785   if (!P1.isBitPiece() || !P2.isBitPiece())
786     return true;
787   unsigned l1 = P1.getBitPieceOffset();
788   unsigned l2 = P2.getBitPieceOffset();
789   unsigned r1 = l1 + P1.getBitPieceSize();
790   unsigned r2 = l2 + P2.getBitPieceSize();
791   // True where [l1,r1[ and [r1,r2[ overlap.
792   return (l1 < r2) && (l2 < r1);
793 }
794
795 /// Build the location list for all DBG_VALUEs in the function that
796 /// describe the same variable.  If the ranges of several independent
797 /// pieces of the same variable overlap partially, split them up and
798 /// combine the ranges. The resulting DebugLocEntries are will have
799 /// strict monotonically increasing begin addresses and will never
800 /// overlap.
801 //
802 // Input:
803 //
804 //   Ranges History [var, loc, piece ofs size]
805 // 0 |      [x, (reg0, piece 0, 32)]
806 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
807 // 2 | |    ...
808 // 3   |    [clobber reg0]
809 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
810 //                                     x.
811 //
812 // Output:
813 //
814 // [0-1]    [x, (reg0, piece  0, 32)]
815 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
816 // [3-4]    [x, (reg1, piece 32, 32)]
817 // [4- ]    [x, (mem,  piece  0, 64)]
818 void
819 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
820                               const DbgValueHistoryMap::InstrRanges &Ranges) {
821   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
822
823   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
824     const MachineInstr *Begin = I->first;
825     const MachineInstr *End = I->second;
826     assert(Begin->isDebugValue() && "Invalid History entry");
827
828     // Check if a variable is inaccessible in this range.
829     if (Begin->getNumOperands() > 1 &&
830         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
831       OpenRanges.clear();
832       continue;
833     }
834
835     // If this piece overlaps with any open ranges, truncate them.
836     DIExpression DIExpr = Begin->getDebugExpression();
837     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
838                                [&](DebugLocEntry::Value R) {
839       return piecesOverlap(DIExpr, R.getExpression());
840     });
841     OpenRanges.erase(Last, OpenRanges.end());
842
843     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
844     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
845
846     const MCSymbol *EndLabel;
847     if (End != nullptr)
848       EndLabel = getLabelAfterInsn(End);
849     else if (std::next(I) == Ranges.end())
850       EndLabel = FunctionEndSym;
851     else
852       EndLabel = getLabelBeforeInsn(std::next(I)->first);
853     assert(EndLabel && "Forgot label after instruction ending a range!");
854
855     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
856
857     auto Value = getDebugLocValue(Begin);
858     DebugLocEntry Loc(StartLabel, EndLabel, Value);
859     bool couldMerge = false;
860
861     // If this is a piece, it may belong to the current DebugLocEntry.
862     if (DIExpr.isBitPiece()) {
863       // Add this value to the list of open ranges.
864       OpenRanges.push_back(Value);
865
866       // Attempt to add the piece to the last entry.
867       if (!DebugLoc.empty())
868         if (DebugLoc.back().MergeValues(Loc))
869           couldMerge = true;
870     }
871
872     if (!couldMerge) {
873       // Need to add a new DebugLocEntry. Add all values from still
874       // valid non-overlapping pieces.
875       if (OpenRanges.size())
876         Loc.addValues(OpenRanges);
877
878       DebugLoc.push_back(std::move(Loc));
879     }
880
881     // Attempt to coalesce the ranges of two otherwise identical
882     // DebugLocEntries.
883     auto CurEntry = DebugLoc.rbegin();
884     auto PrevEntry = std::next(CurEntry);
885     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
886       DebugLoc.pop_back();
887
888     DEBUG({
889       dbgs() << CurEntry->getValues().size() << " Values:\n";
890       for (auto Value : CurEntry->getValues()) {
891         Value.getVariable()->dump();
892         Value.getExpression()->dump();
893       }
894       dbgs() << "-----\n";
895     });
896   }
897 }
898
899
900 // Find variables for each lexical scope.
901 void
902 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
903                                 SmallPtrSetImpl<const MDNode *> &Processed) {
904   // Grab the variable info that was squirreled away in the MMI side-table.
905   collectVariableInfoFromMMITable(Processed);
906
907   for (const auto &I : DbgValues) {
908     DIVariable DV(I.first);
909     if (Processed.count(DV))
910       continue;
911
912     // Instruction ranges, specifying where DV is accessible.
913     const auto &Ranges = I.second;
914     if (Ranges.empty())
915       continue;
916
917     LexicalScope *Scope = nullptr;
918     if (MDNode *IA = DV.getInlinedAt())
919       Scope = LScopes.findInlinedScope(DV.getContext(), IA);
920     else
921       Scope = LScopes.findLexicalScope(DV.getContext());
922     // If variable scope is not found then skip this variable.
923     if (!Scope)
924       continue;
925
926     Processed.insert(DV);
927     const MachineInstr *MInsn = Ranges.front().first;
928     assert(MInsn->isDebugValue() && "History must begin with debug value");
929     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
930     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
931     DbgVariable *RegVar = ConcreteVariables.back().get();
932     InfoHolder.addScopeVariable(Scope, RegVar);
933
934     // Check if the first DBG_VALUE is valid for the rest of the function.
935     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
936       continue;
937
938     // Handle multiple DBG_VALUE instructions describing one variable.
939     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
940
941     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
942     DebugLocList &LocList = DotDebugLocEntries.back();
943     LocList.CU = &TheCU;
944     LocList.Label =
945         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
946
947     // Build the location list for this variable.
948     buildLocationList(LocList.List, Ranges);
949     // Finalize the entry by lowering it into a DWARF bytestream.
950     for (auto &Entry : LocList.List)
951       Entry.finalize(*Asm, TypeIdentifierMap);
952   }
953
954   // Collect info for variables that were optimized out.
955   DIArray Variables = SP.getVariables();
956   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
957     DIVariable DV(Variables.getElement(i));
958     assert(DV.isVariable());
959     if (!Processed.insert(DV).second)
960       continue;
961     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
962       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
963       DIExpression NoExpr;
964       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
965       InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
966     }
967   }
968 }
969
970 // Return Label preceding the instruction.
971 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
972   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
973   assert(Label && "Didn't insert label before instruction");
974   return Label;
975 }
976
977 // Return Label immediately following the instruction.
978 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
979   return LabelsAfterInsn.lookup(MI);
980 }
981
982 // Process beginning of an instruction.
983 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
984   assert(CurMI == nullptr);
985   CurMI = MI;
986   // Check if source location changes, but ignore DBG_VALUE locations.
987   if (!MI->isDebugValue()) {
988     DebugLoc DL = MI->getDebugLoc();
989     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
990       unsigned Flags = 0;
991       PrevInstLoc = DL;
992       if (DL == PrologEndLoc) {
993         Flags |= DWARF2_FLAG_PROLOGUE_END;
994         PrologEndLoc = DebugLoc();
995         Flags |= DWARF2_FLAG_IS_STMT;
996       }
997       if (DL.getLine() !=
998           Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
999         Flags |= DWARF2_FLAG_IS_STMT;
1000
1001       if (!DL.isUnknown()) {
1002         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1003         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1004       } else
1005         recordSourceLine(0, 0, nullptr, 0);
1006     }
1007   }
1008
1009   // Insert labels where requested.
1010   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1011       LabelsBeforeInsn.find(MI);
1012
1013   // No label needed.
1014   if (I == LabelsBeforeInsn.end())
1015     return;
1016
1017   // Label already assigned.
1018   if (I->second)
1019     return;
1020
1021   if (!PrevLabel) {
1022     PrevLabel = MMI->getContext().CreateTempSymbol();
1023     Asm->OutStreamer.EmitLabel(PrevLabel);
1024   }
1025   I->second = PrevLabel;
1026 }
1027
1028 // Process end of an instruction.
1029 void DwarfDebug::endInstruction() {
1030   assert(CurMI != nullptr);
1031   // Don't create a new label after DBG_VALUE instructions.
1032   // They don't generate code.
1033   if (!CurMI->isDebugValue())
1034     PrevLabel = nullptr;
1035
1036   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1037       LabelsAfterInsn.find(CurMI);
1038   CurMI = nullptr;
1039
1040   // No label needed.
1041   if (I == LabelsAfterInsn.end())
1042     return;
1043
1044   // Label already assigned.
1045   if (I->second)
1046     return;
1047
1048   // We need a label after this instruction.
1049   if (!PrevLabel) {
1050     PrevLabel = MMI->getContext().CreateTempSymbol();
1051     Asm->OutStreamer.EmitLabel(PrevLabel);
1052   }
1053   I->second = PrevLabel;
1054 }
1055
1056 // Each LexicalScope has first instruction and last instruction to mark
1057 // beginning and end of a scope respectively. Create an inverse map that list
1058 // scopes starts (and ends) with an instruction. One instruction may start (or
1059 // end) multiple scopes. Ignore scopes that are not reachable.
1060 void DwarfDebug::identifyScopeMarkers() {
1061   SmallVector<LexicalScope *, 4> WorkList;
1062   WorkList.push_back(LScopes.getCurrentFunctionScope());
1063   while (!WorkList.empty()) {
1064     LexicalScope *S = WorkList.pop_back_val();
1065
1066     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1067     if (!Children.empty())
1068       WorkList.append(Children.begin(), Children.end());
1069
1070     if (S->isAbstractScope())
1071       continue;
1072
1073     for (const InsnRange &R : S->getRanges()) {
1074       assert(R.first && "InsnRange does not have first instruction!");
1075       assert(R.second && "InsnRange does not have second instruction!");
1076       requestLabelBeforeInsn(R.first);
1077       requestLabelAfterInsn(R.second);
1078     }
1079   }
1080 }
1081
1082 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1083   // First known non-DBG_VALUE and non-frame setup location marks
1084   // the beginning of the function body.
1085   for (const auto &MBB : *MF)
1086     for (const auto &MI : MBB)
1087       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1088           !MI.getDebugLoc().isUnknown()) {
1089         // Did the target forget to set the FrameSetup flag for CFI insns?
1090         assert(!MI.isCFIInstruction() &&
1091                "First non-frame-setup instruction is a CFI instruction.");
1092         return MI.getDebugLoc();
1093       }
1094   return DebugLoc();
1095 }
1096
1097 // Gather pre-function debug information.  Assumes being called immediately
1098 // after the function entry point has been emitted.
1099 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1100   CurFn = MF;
1101
1102   // If there's no debug info for the function we're not going to do anything.
1103   if (!MMI->hasDebugInfo())
1104     return;
1105
1106   auto DI = FunctionDIs.find(MF->getFunction());
1107   if (DI == FunctionDIs.end())
1108     return;
1109
1110   // Grab the lexical scopes for the function, if we don't have any of those
1111   // then we're not going to be able to do anything.
1112   LScopes.initialize(*MF);
1113   if (LScopes.empty())
1114     return;
1115
1116   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1117
1118   // Make sure that each lexical scope will have a begin/end label.
1119   identifyScopeMarkers();
1120
1121   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1122   // belongs to so that we add to the correct per-cu line table in the
1123   // non-asm case.
1124   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1125   // FnScope->getScopeNode() and DI->second should represent the same function,
1126   // though they may not be the same MDNode due to inline functions merged in
1127   // LTO where the debug info metadata still differs (either due to distinct
1128   // written differences - two versions of a linkonce_odr function
1129   // written/copied into two separate files, or some sub-optimal metadata that
1130   // isn't structurally identical (see: file path/name info from clang, which
1131   // includes the directory of the cpp file being built, even when the file name
1132   // is absolute (such as an <> lookup header)))
1133   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1134   assert(TheCU && "Unable to find compile unit!");
1135   if (Asm->OutStreamer.hasRawTextSupport())
1136     // Use a single line table if we are generating assembly.
1137     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1138   else
1139     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1140
1141   // Emit a label for the function so that we have a beginning address.
1142   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1143   // Assumes in correct section after the entry point.
1144   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1145
1146   // Calculate history for local variables.
1147   calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1148                            DbgValues);
1149
1150   // Request labels for the full history.
1151   for (const auto &I : DbgValues) {
1152     const auto &Ranges = I.second;
1153     if (Ranges.empty())
1154       continue;
1155
1156     // The first mention of a function argument gets the FunctionBeginSym
1157     // label, so arguments are visible when breaking at function entry.
1158     DIVariable DIVar(Ranges.front().first->getDebugVariable());
1159     if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1160         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1161       LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1162       if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1163         // Mark all non-overlapping initial pieces.
1164         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1165           DIExpression Piece = I->first->getDebugExpression();
1166           if (std::all_of(Ranges.begin(), I,
1167                           [&](DbgValueHistoryMap::InstrRange Pred) {
1168                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1169               }))
1170             LabelsBeforeInsn[I->first] = FunctionBeginSym;
1171           else
1172             break;
1173         }
1174       }
1175     }
1176
1177     for (const auto &Range : Ranges) {
1178       requestLabelBeforeInsn(Range.first);
1179       if (Range.second)
1180         requestLabelAfterInsn(Range.second);
1181     }
1182   }
1183
1184   PrevInstLoc = DebugLoc();
1185   PrevLabel = FunctionBeginSym;
1186
1187   // Record beginning of function.
1188   PrologEndLoc = findPrologueEndLoc(MF);
1189   if (!PrologEndLoc.isUnknown()) {
1190     DebugLoc FnStartDL =
1191         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1192
1193     // We'd like to list the prologue as "not statements" but GDB behaves
1194     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1195     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1196                      FnStartDL.getScope(MF->getFunction()->getContext()),
1197                      DWARF2_FLAG_IS_STMT);
1198   }
1199 }
1200
1201 // Gather and emit post-function debug information.
1202 void DwarfDebug::endFunction(const MachineFunction *MF) {
1203   assert(CurFn == MF &&
1204       "endFunction should be called with the same function as beginFunction");
1205
1206   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1207       !FunctionDIs.count(MF->getFunction())) {
1208     // If we don't have a lexical scope for this function then there will
1209     // be a hole in the range information. Keep note of this by setting the
1210     // previously used section to nullptr.
1211     PrevCU = nullptr;
1212     CurFn = nullptr;
1213     return;
1214   }
1215
1216   // Define end label for subprogram.
1217   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1218   // Assumes in correct section after the entry point.
1219   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1220
1221   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1222   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1223
1224   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1225   DISubprogram SP(FnScope->getScopeNode());
1226   DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1227
1228   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1229   collectVariableInfo(TheCU, SP, ProcessedVars);
1230
1231   // Add the range of this function to the list of ranges for the CU.
1232   TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1233
1234   // Under -gmlt, skip building the subprogram if there are no inlined
1235   // subroutines inside it.
1236   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1237       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1238     assert(InfoHolder.getScopeVariables().empty());
1239     assert(DbgValues.empty());
1240     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1241     // by a -gmlt CU. Add a test and remove this assertion.
1242     assert(AbstractVariables.empty());
1243     LabelsBeforeInsn.clear();
1244     LabelsAfterInsn.clear();
1245     PrevLabel = nullptr;
1246     CurFn = nullptr;
1247     return;
1248   }
1249
1250 #ifndef NDEBUG
1251   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1252 #endif
1253   // Construct abstract scopes.
1254   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1255     DISubprogram SP(AScope->getScopeNode());
1256     assert(SP.isSubprogram());
1257     // Collect info for variables that were optimized out.
1258     DIArray Variables = SP.getVariables();
1259     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1260       DIVariable DV(Variables.getElement(i));
1261       assert(DV && DV.isVariable());
1262       if (!ProcessedVars.insert(DV).second)
1263         continue;
1264       ensureAbstractVariableIsCreated(DV, DV.getContext());
1265       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1266              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1267     }
1268     constructAbstractSubprogramScopeDIE(AScope);
1269   }
1270
1271   TheCU.constructSubprogramScopeDIE(FnScope);
1272   if (auto *SkelCU = TheCU.getSkeleton())
1273     if (!LScopes.getAbstractScopesList().empty())
1274       SkelCU->constructSubprogramScopeDIE(FnScope);
1275
1276   // Clear debug info
1277   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1278   // DbgVariables except those that are also in AbstractVariables (since they
1279   // can be used cross-function)
1280   InfoHolder.getScopeVariables().clear();
1281   DbgValues.clear();
1282   LabelsBeforeInsn.clear();
1283   LabelsAfterInsn.clear();
1284   PrevLabel = nullptr;
1285   CurFn = nullptr;
1286 }
1287
1288 // Register a source line with debug info. Returns the  unique label that was
1289 // emitted and which provides correspondence to the source line list.
1290 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1291                                   unsigned Flags) {
1292   StringRef Fn;
1293   StringRef Dir;
1294   unsigned Src = 1;
1295   unsigned Discriminator = 0;
1296   if (DIScope Scope = DIScope(S)) {
1297     assert(Scope.isScope());
1298     Fn = Scope.getFilename();
1299     Dir = Scope.getDirectory();
1300     if (Scope.isLexicalBlockFile())
1301       Discriminator = DILexicalBlockFile(S).getDiscriminator();
1302
1303     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1304     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1305               .getOrCreateSourceID(Fn, Dir);
1306   }
1307   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1308                                          Discriminator, Fn);
1309 }
1310
1311 //===----------------------------------------------------------------------===//
1312 // Emit Methods
1313 //===----------------------------------------------------------------------===//
1314
1315 // Emit initial Dwarf sections with a label at the start of each one.
1316 void DwarfDebug::emitSectionLabels() {
1317   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1318
1319   // Dwarf sections base addresses.
1320   DwarfInfoSectionSym =
1321       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1322   if (useSplitDwarf()) {
1323     DwarfInfoDWOSectionSym =
1324         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1325     DwarfTypesDWOSectionSym = emitSectionSym(
1326         Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1327   }
1328   DwarfAbbrevSectionSym =
1329       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1330   if (useSplitDwarf())
1331     DwarfAbbrevDWOSectionSym = emitSectionSym(
1332         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1333   if (GenerateARangeSection)
1334     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1335
1336   DwarfLineSectionSym =
1337       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1338   if (GenerateGnuPubSections) {
1339     DwarfGnuPubNamesSectionSym =
1340         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1341     DwarfGnuPubTypesSectionSym =
1342         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1343   } else if (HasDwarfPubSections) {
1344     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1345     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1346   }
1347
1348   DwarfStrSectionSym =
1349       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1350   if (useSplitDwarf()) {
1351     DwarfStrDWOSectionSym =
1352         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1353     DwarfAddrSectionSym =
1354         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1355     DwarfDebugLocSectionSym =
1356         emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1357   } else
1358     DwarfDebugLocSectionSym =
1359         emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1360   DwarfDebugRangeSectionSym =
1361       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1362 }
1363
1364 // Recursively emits a debug information entry.
1365 void DwarfDebug::emitDIE(DIE &Die) {
1366   // Get the abbreviation for this DIE.
1367   const DIEAbbrev &Abbrev = Die.getAbbrev();
1368
1369   // Emit the code (index) for the abbreviation.
1370   if (Asm->isVerbose())
1371     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1372                                 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1373                                 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1374                                 dwarf::TagString(Abbrev.getTag()));
1375   Asm->EmitULEB128(Abbrev.getNumber());
1376
1377   const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1378   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1379
1380   // Emit the DIE attribute values.
1381   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1382     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1383     dwarf::Form Form = AbbrevData[i].getForm();
1384     assert(Form && "Too many attributes for DIE (check abbreviation)");
1385
1386     if (Asm->isVerbose()) {
1387       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1388       if (Attr == dwarf::DW_AT_accessibility)
1389         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1390             cast<DIEInteger>(Values[i])->getValue()));
1391     }
1392
1393     // Emit an attribute using the defined form.
1394     Values[i]->EmitValue(Asm, Form);
1395   }
1396
1397   // Emit the DIE children if any.
1398   if (Abbrev.hasChildren()) {
1399     for (auto &Child : Die.getChildren())
1400       emitDIE(*Child);
1401
1402     Asm->OutStreamer.AddComment("End Of Children Mark");
1403     Asm->EmitInt8(0);
1404   }
1405 }
1406
1407 // Emit the debug info section.
1408 void DwarfDebug::emitDebugInfo() {
1409   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1410
1411   Holder.emitUnits(DwarfAbbrevSectionSym);
1412 }
1413
1414 // Emit the abbreviation section.
1415 void DwarfDebug::emitAbbreviations() {
1416   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1417
1418   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1419 }
1420
1421 // Emit the last address of the section and the end of the line matrix.
1422 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1423   // Define last address of section.
1424   Asm->OutStreamer.AddComment("Extended Op");
1425   Asm->EmitInt8(0);
1426
1427   Asm->OutStreamer.AddComment("Op size");
1428   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1429   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1430   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1431
1432   Asm->OutStreamer.AddComment("Section end label");
1433
1434   Asm->OutStreamer.EmitSymbolValue(
1435       Asm->GetTempSymbol("section_end", SectionEnd),
1436       Asm->getDataLayout().getPointerSize());
1437
1438   // Mark end of matrix.
1439   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1440   Asm->EmitInt8(0);
1441   Asm->EmitInt8(1);
1442   Asm->EmitInt8(1);
1443 }
1444
1445 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1446                            StringRef TableName, StringRef SymName) {
1447   Accel.FinalizeTable(Asm, TableName);
1448   Asm->OutStreamer.SwitchSection(Section);
1449   auto *SectionBegin = Asm->GetTempSymbol(SymName);
1450   Asm->OutStreamer.EmitLabel(SectionBegin);
1451
1452   // Emit the full data.
1453   Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1454 }
1455
1456 // Emit visible names into a hashed accelerator table section.
1457 void DwarfDebug::emitAccelNames() {
1458   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1459             "Names", "names_begin");
1460 }
1461
1462 // Emit objective C classes and categories into a hashed accelerator table
1463 // section.
1464 void DwarfDebug::emitAccelObjC() {
1465   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1466             "ObjC", "objc_begin");
1467 }
1468
1469 // Emit namespace dies into a hashed accelerator table.
1470 void DwarfDebug::emitAccelNamespaces() {
1471   emitAccel(AccelNamespace,
1472             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1473             "namespac", "namespac_begin");
1474 }
1475
1476 // Emit type dies into a hashed accelerator table.
1477 void DwarfDebug::emitAccelTypes() {
1478   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1479             "types", "types_begin");
1480 }
1481
1482 // Public name handling.
1483 // The format for the various pubnames:
1484 //
1485 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1486 // for the DIE that is named.
1487 //
1488 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1489 // into the CU and the index value is computed according to the type of value
1490 // for the DIE that is named.
1491 //
1492 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1493 // it's the offset within the debug_info/debug_types dwo section, however, the
1494 // reference in the pubname header doesn't change.
1495
1496 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1497 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1498                                                         const DIE *Die) {
1499   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1500
1501   // We could have a specification DIE that has our most of our knowledge,
1502   // look for that now.
1503   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1504   if (SpecVal) {
1505     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1506     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1507       Linkage = dwarf::GIEL_EXTERNAL;
1508   } else if (Die->findAttribute(dwarf::DW_AT_external))
1509     Linkage = dwarf::GIEL_EXTERNAL;
1510
1511   switch (Die->getTag()) {
1512   case dwarf::DW_TAG_class_type:
1513   case dwarf::DW_TAG_structure_type:
1514   case dwarf::DW_TAG_union_type:
1515   case dwarf::DW_TAG_enumeration_type:
1516     return dwarf::PubIndexEntryDescriptor(
1517         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1518                               ? dwarf::GIEL_STATIC
1519                               : dwarf::GIEL_EXTERNAL);
1520   case dwarf::DW_TAG_typedef:
1521   case dwarf::DW_TAG_base_type:
1522   case dwarf::DW_TAG_subrange_type:
1523     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1524   case dwarf::DW_TAG_namespace:
1525     return dwarf::GIEK_TYPE;
1526   case dwarf::DW_TAG_subprogram:
1527     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1528   case dwarf::DW_TAG_variable:
1529     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1530   case dwarf::DW_TAG_enumerator:
1531     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1532                                           dwarf::GIEL_STATIC);
1533   default:
1534     return dwarf::GIEK_NONE;
1535   }
1536 }
1537
1538 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1539 ///
1540 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1541   const MCSection *PSec =
1542       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1543                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1544
1545   emitDebugPubSection(GnuStyle, PSec, "Names",
1546                       &DwarfCompileUnit::getGlobalNames);
1547 }
1548
1549 void DwarfDebug::emitDebugPubSection(
1550     bool GnuStyle, const MCSection *PSec, StringRef Name,
1551     const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1552   for (const auto &NU : CUMap) {
1553     DwarfCompileUnit *TheU = NU.second;
1554
1555     const auto &Globals = (TheU->*Accessor)();
1556
1557     if (Globals.empty())
1558       continue;
1559
1560     if (auto *Skeleton = TheU->getSkeleton())
1561       TheU = Skeleton;
1562     unsigned ID = TheU->getUniqueID();
1563
1564     // Start the dwarf pubnames section.
1565     Asm->OutStreamer.SwitchSection(PSec);
1566
1567     // Emit the header.
1568     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1569     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1570     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1571     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1572
1573     Asm->OutStreamer.EmitLabel(BeginLabel);
1574
1575     Asm->OutStreamer.AddComment("DWARF Version");
1576     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1577
1578     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1579     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1580
1581     Asm->OutStreamer.AddComment("Compilation Unit Length");
1582     Asm->EmitInt32(TheU->getLength());
1583
1584     // Emit the pubnames for this compilation unit.
1585     for (const auto &GI : Globals) {
1586       const char *Name = GI.getKeyData();
1587       const DIE *Entity = GI.second;
1588
1589       Asm->OutStreamer.AddComment("DIE offset");
1590       Asm->EmitInt32(Entity->getOffset());
1591
1592       if (GnuStyle) {
1593         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1594         Asm->OutStreamer.AddComment(
1595             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1596             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1597         Asm->EmitInt8(Desc.toBits());
1598       }
1599
1600       Asm->OutStreamer.AddComment("External Name");
1601       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1602     }
1603
1604     Asm->OutStreamer.AddComment("End Mark");
1605     Asm->EmitInt32(0);
1606     Asm->OutStreamer.EmitLabel(EndLabel);
1607   }
1608 }
1609
1610 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1611   const MCSection *PSec =
1612       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1613                : Asm->getObjFileLowering().getDwarfPubTypesSection();
1614
1615   emitDebugPubSection(GnuStyle, PSec, "Types",
1616                       &DwarfCompileUnit::getGlobalTypes);
1617 }
1618
1619 // Emit visible names into a debug str section.
1620 void DwarfDebug::emitDebugStr() {
1621   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1622   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1623 }
1624
1625
1626 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1627                                    const DebugLocEntry &Entry) {
1628   auto Comment = Entry.getComments().begin();
1629   auto End = Entry.getComments().end();
1630   for (uint8_t Byte : Entry.getDWARFBytes())
1631     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1632 }
1633
1634 static void emitDebugLocValue(const AsmPrinter &AP,
1635                               const DITypeIdentifierMap &TypeIdentifierMap,
1636                               ByteStreamer &Streamer,
1637                               const DebugLocEntry::Value &Value,
1638                               unsigned PieceOffsetInBits) {
1639   DIVariable DV = Value.getVariable();
1640   DebugLocDwarfExpression DwarfExpr(
1641       *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1642       AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1643   // Regular entry.
1644   if (Value.isInt()) {
1645     DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1646     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1647                          BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1648       DwarfExpr.AddSignedConstant(Value.getInt());
1649     else
1650       DwarfExpr.AddUnsignedConstant(Value.getInt());
1651   } else if (Value.isLocation()) {
1652     MachineLocation Loc = Value.getLoc();
1653     DIExpression Expr = Value.getExpression();
1654     if (!Expr || (Expr.getNumElements() == 0))
1655       // Regular entry.
1656       AP.EmitDwarfRegOp(Streamer, Loc);
1657     else {
1658       // Complex address entry.
1659       if (Loc.getOffset()) {
1660         DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1661         DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1662       } else
1663         DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1664                                           PieceOffsetInBits);
1665     }
1666   }
1667   // else ... ignore constant fp. There is not any good way to
1668   // to represent them here in dwarf.
1669   // FIXME: ^
1670 }
1671
1672
1673 void DebugLocEntry::finalize(const AsmPrinter &AP,
1674                              const DITypeIdentifierMap &TypeIdentifierMap) {
1675   BufferByteStreamer Streamer(DWARFBytes, Comments);
1676   const DebugLocEntry::Value Value = Values[0];
1677   if (Value.isBitPiece()) {
1678     // Emit all pieces that belong to the same variable and range.
1679     assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1680           return P.isBitPiece();
1681         }) && "all values are expected to be pieces");
1682     assert(std::is_sorted(Values.begin(), Values.end()) &&
1683            "pieces are expected to be sorted");
1684    
1685     unsigned Offset = 0;
1686     for (auto Piece : Values) {
1687       DIExpression Expr = Piece.getExpression();
1688       unsigned PieceOffset = Expr.getBitPieceOffset();
1689       unsigned PieceSize = Expr.getBitPieceSize();
1690       assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1691       if (Offset < PieceOffset) {
1692         // The DWARF spec seriously mandates pieces with no locations for gaps.
1693         DebugLocDwarfExpression Expr(
1694             *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1695             AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1696         Expr.AddOpPiece(PieceOffset-Offset, 0);
1697         Offset += PieceOffset-Offset;
1698       }
1699       Offset += PieceSize;
1700    
1701 #ifndef NDEBUG
1702       DIVariable Var = Piece.getVariable();
1703       unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1704       assert(PieceSize+PieceOffset <= VarSize
1705              && "piece is larger than or outside of variable");
1706       assert(PieceSize != VarSize
1707              && "piece covers entire variable");
1708 #endif
1709       emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1710     }
1711   } else {
1712     assert(Values.size() == 1 && "only pieces may have >1 value");
1713     emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1714   }
1715 }
1716
1717
1718 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1719   Asm->OutStreamer.AddComment("Loc expr size");
1720   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1721   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1722   Asm->EmitLabelDifference(end, begin, 2);
1723   Asm->OutStreamer.EmitLabel(begin);
1724   // Emit the entry.
1725   APByteStreamer Streamer(*Asm);
1726   emitDebugLocEntry(Streamer, Entry);
1727   // Close the range.
1728   Asm->OutStreamer.EmitLabel(end);
1729 }
1730
1731 // Emit locations into the debug loc section.
1732 void DwarfDebug::emitDebugLoc() {
1733   // Start the dwarf loc section.
1734   Asm->OutStreamer.SwitchSection(
1735       Asm->getObjFileLowering().getDwarfLocSection());
1736   unsigned char Size = Asm->getDataLayout().getPointerSize();
1737   for (const auto &DebugLoc : DotDebugLocEntries) {
1738     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1739     const DwarfCompileUnit *CU = DebugLoc.CU;
1740     for (const auto &Entry : DebugLoc.List) {
1741       // Set up the range. This range is relative to the entry point of the
1742       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1743       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1744       if (auto *Base = CU->getBaseAddress()) {
1745         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1746         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1747       } else {
1748         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1749         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1750       }
1751
1752       emitDebugLocEntryLocation(Entry);
1753     }
1754     Asm->OutStreamer.EmitIntValue(0, Size);
1755     Asm->OutStreamer.EmitIntValue(0, Size);
1756   }
1757 }
1758
1759 void DwarfDebug::emitDebugLocDWO() {
1760   Asm->OutStreamer.SwitchSection(
1761       Asm->getObjFileLowering().getDwarfLocDWOSection());
1762   for (const auto &DebugLoc : DotDebugLocEntries) {
1763     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1764     for (const auto &Entry : DebugLoc.List) {
1765       // Just always use start_length for now - at least that's one address
1766       // rather than two. We could get fancier and try to, say, reuse an
1767       // address we know we've emitted elsewhere (the start of the function?
1768       // The start of the CU or CU subrange that encloses this range?)
1769       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1770       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1771       Asm->EmitULEB128(idx);
1772       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1773
1774       emitDebugLocEntryLocation(Entry);
1775     }
1776     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1777   }
1778 }
1779
1780 struct ArangeSpan {
1781   const MCSymbol *Start, *End;
1782 };
1783
1784 // Emit a debug aranges section, containing a CU lookup for any
1785 // address we can tie back to a CU.
1786 void DwarfDebug::emitDebugARanges() {
1787   // Provides a unique id per text section.
1788   DenseMap<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1789
1790   // Prime section data.
1791   SectionMap[Asm->getObjFileLowering().getTextSection()];
1792
1793   // Filter labels by section.
1794   for (const SymbolCU &SCU : ArangeLabels) {
1795     if (SCU.Sym->isInSection()) {
1796       // Make a note of this symbol and it's section.
1797       const MCSection *Section = &SCU.Sym->getSection();
1798       if (!Section->getKind().isMetadata())
1799         SectionMap[Section].push_back(SCU);
1800     } else {
1801       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1802       // appear in the output. This sucks as we rely on sections to build
1803       // arange spans. We can do it without, but it's icky.
1804       SectionMap[nullptr].push_back(SCU);
1805     }
1806   }
1807
1808   // Build a list of sections used.
1809   std::vector<const MCSection *> Sections;
1810   for (const auto &it : SectionMap) {
1811     const MCSection *Section = it.first;
1812     Sections.push_back(Section);
1813   }
1814
1815   // Sort the sections into order.
1816   // This is only done to ensure consistent output order across different runs.
1817   std::sort(Sections.begin(), Sections.end(), SectionSort);
1818
1819   // Add terminating symbols for each section.
1820   for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1821     const MCSection *Section = Sections[ID];
1822     MCSymbol *Sym = nullptr;
1823
1824     if (Section) {
1825       // We can't call MCSection::getLabelEndName, as it's only safe to do so
1826       // if we know the section name up-front. For user-created sections, the
1827       // resulting label may not be valid to use as a label. (section names can
1828       // use a greater set of characters on some systems)
1829       Sym = Asm->GetTempSymbol("debug_end", ID);
1830       Asm->OutStreamer.SwitchSection(Section);
1831       Asm->OutStreamer.EmitLabel(Sym);
1832     }
1833
1834     // Insert a final terminator.
1835     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1836   }
1837
1838   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1839
1840   for (const MCSection *Section : Sections) {
1841     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1842     if (List.size() < 2)
1843       continue;
1844
1845     // If we have no section (e.g. common), just write out
1846     // individual spans for each symbol.
1847     if (!Section) {
1848       for (const SymbolCU &Cur : List) {
1849         ArangeSpan Span;
1850         Span.Start = Cur.Sym;
1851         Span.End = nullptr;
1852         if (Cur.CU)
1853           Spans[Cur.CU].push_back(Span);
1854       }
1855       continue;
1856     }
1857
1858     // Sort the symbols by offset within the section.
1859     std::sort(List.begin(), List.end(),
1860               [&](const SymbolCU &A, const SymbolCU &B) {
1861       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1862       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1863
1864       // Symbols with no order assigned should be placed at the end.
1865       // (e.g. section end labels)
1866       if (IA == 0)
1867         return false;
1868       if (IB == 0)
1869         return true;
1870       return IA < IB;
1871     });
1872
1873     // Build spans between each label.
1874     const MCSymbol *StartSym = List[0].Sym;
1875     for (size_t n = 1, e = List.size(); n < e; n++) {
1876       const SymbolCU &Prev = List[n - 1];
1877       const SymbolCU &Cur = List[n];
1878
1879       // Try and build the longest span we can within the same CU.
1880       if (Cur.CU != Prev.CU) {
1881         ArangeSpan Span;
1882         Span.Start = StartSym;
1883         Span.End = Cur.Sym;
1884         Spans[Prev.CU].push_back(Span);
1885         StartSym = Cur.Sym;
1886       }
1887     }
1888   }
1889
1890   // Start the dwarf aranges section.
1891   Asm->OutStreamer.SwitchSection(
1892       Asm->getObjFileLowering().getDwarfARangesSection());
1893
1894   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1895
1896   // Build a list of CUs used.
1897   std::vector<DwarfCompileUnit *> CUs;
1898   for (const auto &it : Spans) {
1899     DwarfCompileUnit *CU = it.first;
1900     CUs.push_back(CU);
1901   }
1902
1903   // Sort the CU list (again, to ensure consistent output order).
1904   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1905     return A->getUniqueID() < B->getUniqueID();
1906   });
1907
1908   // Emit an arange table for each CU we used.
1909   for (DwarfCompileUnit *CU : CUs) {
1910     std::vector<ArangeSpan> &List = Spans[CU];
1911
1912     // Describe the skeleton CU's offset and length, not the dwo file's.
1913     if (auto *Skel = CU->getSkeleton())
1914       CU = Skel;
1915
1916     // Emit size of content not including length itself.
1917     unsigned ContentSize =
1918         sizeof(int16_t) + // DWARF ARange version number
1919         sizeof(int32_t) + // Offset of CU in the .debug_info section
1920         sizeof(int8_t) +  // Pointer Size (in bytes)
1921         sizeof(int8_t);   // Segment Size (in bytes)
1922
1923     unsigned TupleSize = PtrSize * 2;
1924
1925     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1926     unsigned Padding =
1927         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1928
1929     ContentSize += Padding;
1930     ContentSize += (List.size() + 1) * TupleSize;
1931
1932     // For each compile unit, write the list of spans it covers.
1933     Asm->OutStreamer.AddComment("Length of ARange Set");
1934     Asm->EmitInt32(ContentSize);
1935     Asm->OutStreamer.AddComment("DWARF Arange version number");
1936     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1937     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1938     Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1939     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1940     Asm->EmitInt8(PtrSize);
1941     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1942     Asm->EmitInt8(0);
1943
1944     Asm->OutStreamer.EmitFill(Padding, 0xff);
1945
1946     for (const ArangeSpan &Span : List) {
1947       Asm->EmitLabelReference(Span.Start, PtrSize);
1948
1949       // Calculate the size as being from the span start to it's end.
1950       if (Span.End) {
1951         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1952       } else {
1953         // For symbols without an end marker (e.g. common), we
1954         // write a single arange entry containing just that one symbol.
1955         uint64_t Size = SymSize[Span.Start];
1956         if (Size == 0)
1957           Size = 1;
1958
1959         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1960       }
1961     }
1962
1963     Asm->OutStreamer.AddComment("ARange terminator");
1964     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1965     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1966   }
1967 }
1968
1969 // Emit visible names into a debug ranges section.
1970 void DwarfDebug::emitDebugRanges() {
1971   // Start the dwarf ranges section.
1972   Asm->OutStreamer.SwitchSection(
1973       Asm->getObjFileLowering().getDwarfRangesSection());
1974
1975   // Size for our labels.
1976   unsigned char Size = Asm->getDataLayout().getPointerSize();
1977
1978   // Grab the specific ranges for the compile units in the module.
1979   for (const auto &I : CUMap) {
1980     DwarfCompileUnit *TheCU = I.second;
1981
1982     if (auto *Skel = TheCU->getSkeleton())
1983       TheCU = Skel;
1984
1985     // Iterate over the misc ranges for the compile units in the module.
1986     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1987       // Emit our symbol so we can find the beginning of the range.
1988       Asm->OutStreamer.EmitLabel(List.getSym());
1989
1990       for (const RangeSpan &Range : List.getRanges()) {
1991         const MCSymbol *Begin = Range.getStart();
1992         const MCSymbol *End = Range.getEnd();
1993         assert(Begin && "Range without a begin symbol?");
1994         assert(End && "Range without an end symbol?");
1995         if (auto *Base = TheCU->getBaseAddress()) {
1996           Asm->EmitLabelDifference(Begin, Base, Size);
1997           Asm->EmitLabelDifference(End, Base, Size);
1998         } else {
1999           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2000           Asm->OutStreamer.EmitSymbolValue(End, Size);
2001         }
2002       }
2003
2004       // And terminate the list with two 0 values.
2005       Asm->OutStreamer.EmitIntValue(0, Size);
2006       Asm->OutStreamer.EmitIntValue(0, Size);
2007     }
2008   }
2009 }
2010
2011 // DWARF5 Experimental Separate Dwarf emitters.
2012
2013 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2014                                   std::unique_ptr<DwarfUnit> NewU) {
2015   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2016                   U.getCUNode().getSplitDebugFilename());
2017
2018   if (!CompilationDir.empty())
2019     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2020
2021   addGnuPubAttributes(*NewU, Die);
2022
2023   SkeletonHolder.addUnit(std::move(NewU));
2024 }
2025
2026 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2027 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2028 // DW_AT_addr_base, DW_AT_ranges_base.
2029 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2030
2031   auto OwnedUnit = make_unique<DwarfCompileUnit>(
2032       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2033   DwarfCompileUnit &NewCU = *OwnedUnit;
2034   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2035                     DwarfInfoSectionSym);
2036
2037   NewCU.initStmtList(DwarfLineSectionSym);
2038
2039   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2040
2041   return NewCU;
2042 }
2043
2044 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2045 // compile units that would normally be in debug_info.
2046 void DwarfDebug::emitDebugInfoDWO() {
2047   assert(useSplitDwarf() && "No split dwarf debug info?");
2048   // Don't pass an abbrev symbol, using a constant zero instead so as not to
2049   // emit relocations into the dwo file.
2050   InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2051 }
2052
2053 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2054 // abbreviations for the .debug_info.dwo section.
2055 void DwarfDebug::emitDebugAbbrevDWO() {
2056   assert(useSplitDwarf() && "No split dwarf?");
2057   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2058 }
2059
2060 void DwarfDebug::emitDebugLineDWO() {
2061   assert(useSplitDwarf() && "No split dwarf?");
2062   Asm->OutStreamer.SwitchSection(
2063       Asm->getObjFileLowering().getDwarfLineDWOSection());
2064   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2065 }
2066
2067 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2068 // string section and is identical in format to traditional .debug_str
2069 // sections.
2070 void DwarfDebug::emitDebugStrDWO() {
2071   assert(useSplitDwarf() && "No split dwarf?");
2072   const MCSection *OffSec =
2073       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2074   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2075                          OffSec);
2076 }
2077
2078 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2079   if (!useSplitDwarf())
2080     return nullptr;
2081   if (SingleCU)
2082     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2083   return &SplitTypeUnitFileTable;
2084 }
2085
2086 static uint64_t makeTypeSignature(StringRef Identifier) {
2087   MD5 Hash;
2088   Hash.update(Identifier);
2089   // ... take the least significant 8 bytes and return those. Our MD5
2090   // implementation always returns its results in little endian, swap bytes
2091   // appropriately.
2092   MD5::MD5Result Result;
2093   Hash.final(Result);
2094   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2095 }
2096
2097 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2098                                       StringRef Identifier, DIE &RefDie,
2099                                       DICompositeType CTy) {
2100   // Fast path if we're building some type units and one has already used the
2101   // address pool we know we're going to throw away all this work anyway, so
2102   // don't bother building dependent types.
2103   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2104     return;
2105
2106   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2107   if (TU) {
2108     CU.addDIETypeSignature(RefDie, *TU);
2109     return;
2110   }
2111
2112   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2113   AddrPool.resetUsedFlag();
2114
2115   auto OwnedUnit = make_unique<DwarfTypeUnit>(
2116       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2117       this, &InfoHolder, getDwoLineTable(CU));
2118   DwarfTypeUnit &NewTU = *OwnedUnit;
2119   DIE &UnitDie = NewTU.getUnitDie();
2120   TU = &NewTU;
2121   TypeUnitsUnderConstruction.push_back(
2122       std::make_pair(std::move(OwnedUnit), CTy));
2123
2124   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2125                 CU.getLanguage());
2126
2127   uint64_t Signature = makeTypeSignature(Identifier);
2128   NewTU.setTypeSignature(Signature);
2129
2130   if (useSplitDwarf())
2131     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2132   else {
2133     CU.applyStmtList(UnitDie);
2134     NewTU.initSection(
2135         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2136   }
2137
2138   NewTU.setType(NewTU.createTypeDIE(CTy));
2139
2140   if (TopLevelType) {
2141     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2142     TypeUnitsUnderConstruction.clear();
2143
2144     // Types referencing entries in the address table cannot be placed in type
2145     // units.
2146     if (AddrPool.hasBeenUsed()) {
2147
2148       // Remove all the types built while building this type.
2149       // This is pessimistic as some of these types might not be dependent on
2150       // the type that used an address.
2151       for (const auto &TU : TypeUnitsToAdd)
2152         DwarfTypeUnits.erase(TU.second);
2153
2154       // Construct this type in the CU directly.
2155       // This is inefficient because all the dependent types will be rebuilt
2156       // from scratch, including building them in type units, discovering that
2157       // they depend on addresses, throwing them out and rebuilding them.
2158       CU.constructTypeDIE(RefDie, CTy);
2159       return;
2160     }
2161
2162     // If the type wasn't dependent on fission addresses, finish adding the type
2163     // and all its dependent types.
2164     for (auto &TU : TypeUnitsToAdd)
2165       InfoHolder.addUnit(std::move(TU.first));
2166   }
2167   CU.addDIETypeSignature(RefDie, NewTU);
2168 }
2169
2170 // Accelerator table mutators - add each name along with its companion
2171 // DIE to the proper table while ensuring that the name that we're going
2172 // to reference is in the string table. We do this since the names we
2173 // add may not only be identical to the names in the DIE.
2174 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2175   if (!useDwarfAccelTables())
2176     return;
2177   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2178                      &Die);
2179 }
2180
2181 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2182   if (!useDwarfAccelTables())
2183     return;
2184   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2185                     &Die);
2186 }
2187
2188 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2189   if (!useDwarfAccelTables())
2190     return;
2191   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2192                          &Die);
2193 }
2194
2195 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2196   if (!useDwarfAccelTables())
2197     return;
2198   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2199                      &Die);
2200 }