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