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