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