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