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