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