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