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