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