Two part patch:
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "ByteStreamer.h"
16 #include "DwarfDebug.h"
17 #include "DIE.h"
18 #include "DIEHash.h"
19 #include "DwarfAccelTable.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 using namespace llvm;
53
54 static cl::opt<bool>
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56                          cl::desc("Disable debug info printing"));
57
58 static cl::opt<bool> UnknownLocations(
59     "use-unknown-locations", cl::Hidden,
60     cl::desc("Make an absence of debug location information explicit."),
61     cl::init(false));
62
63 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
64                                     cl::desc("Add the CU hash as the dwo_id."),
65                                     cl::init(false));
66
67 static cl::opt<bool>
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69                        cl::desc("Generate GNU-style pubnames and pubtypes"),
70                        cl::init(false));
71
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
73                                            cl::Hidden,
74                                            cl::desc("Generate dwarf aranges"),
75                                            cl::init(false));
76
77 namespace {
78 enum DefaultOnOff { Default, Enable, Disable };
79 }
80
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83                  cl::desc("Output prototype dwarf accelerator tables."),
84                  cl::values(clEnumVal(Default, "Default for platform"),
85                             clEnumVal(Enable, "Enabled"),
86                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
87                  cl::init(Default));
88
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91            cl::desc("Output DWARF5 split debug info."),
92            cl::values(clEnumVal(Default, "Default for platform"),
93                       clEnumVal(Enable, "Enabled"),
94                       clEnumVal(Disable, "Disabled"), clEnumValEnd),
95            cl::init(Default));
96
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99                  cl::desc("Generate DWARF pubnames and pubtypes sections"),
100                  cl::values(clEnumVal(Default, "Default for platform"),
101                             clEnumVal(Enable, "Enabled"),
102                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
103                  cl::init(Default));
104
105 static cl::opt<unsigned>
106 DwarfVersionNumber("dwarf-version", cl::Hidden,
107                    cl::desc("Generate DWARF for dwarf version."), cl::init(0));
108
109 static cl::opt<bool>
110 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
111               cl::desc("Generate DW_AT_ranges for compile units"),
112               cl::init(false));
113
114 static const char *const DWARFGroupName = "DWARF Emission";
115 static const char *const DbgTimerName = "DWARF Debug Writer";
116
117 //===----------------------------------------------------------------------===//
118
119 namespace llvm {
120
121 /// resolve - Look in the DwarfDebug map for the MDNode that
122 /// corresponds to the reference.
123 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
124   return DD->resolve(Ref);
125 }
126
127 DIType DbgVariable::getType() const {
128   DIType Ty = Var.getType();
129   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
130   // addresses instead.
131   if (Var.isBlockByrefVariable()) {
132     /* Byref variables, in Blocks, are declared by the programmer as
133        "SomeType VarName;", but the compiler creates a
134        __Block_byref_x_VarName struct, and gives the variable VarName
135        either the struct, or a pointer to the struct, as its type.  This
136        is necessary for various behind-the-scenes things the compiler
137        needs to do with by-reference variables in blocks.
138
139        However, as far as the original *programmer* is concerned, the
140        variable should still have type 'SomeType', as originally declared.
141
142        The following function dives into the __Block_byref_x_VarName
143        struct to find the original type of the variable.  This will be
144        passed back to the code generating the type for the Debug
145        Information Entry for the variable 'VarName'.  'VarName' will then
146        have the original type 'SomeType' in its debug information.
147
148        The original type 'SomeType' will be the type of the field named
149        'VarName' inside the __Block_byref_x_VarName struct.
150
151        NOTE: In order for this to not completely fail on the debugger
152        side, the Debug Information Entry for the variable VarName needs to
153        have a DW_AT_location that tells the debugger how to unwind through
154        the pointers and __Block_byref_x_VarName struct to find the actual
155        value of the variable.  The function addBlockByrefType does this.  */
156     DIType subType = Ty;
157     uint16_t tag = Ty.getTag();
158
159     if (tag == dwarf::DW_TAG_pointer_type)
160       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
161
162     DIArray Elements = DICompositeType(subType).getTypeArray();
163     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
164       DIDerivedType DT(Elements.getElement(i));
165       if (getName() == DT.getName())
166         return (resolve(DT.getTypeDerivedFrom()));
167     }
168   }
169   return Ty;
170 }
171
172 } // end llvm namespace
173
174 /// Return Dwarf Version by checking module flags.
175 static unsigned getDwarfVersionFromModule(const Module *M) {
176   Value *Val = M->getModuleFlag("Dwarf Version");
177   if (!Val)
178     return dwarf::DWARF_VERSION;
179   return cast<ConstantInt>(Val)->getZExtValue();
180 }
181
182 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
183     : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
184       PrevLabel(NULL), GlobalRangeCount(0),
185       InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
186       UsedNonDefaultText(false),
187       SkeletonHolder(A, "skel_string", DIEValueAllocator) {
188
189   DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
190   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
191   DwarfAddrSectionSym = 0;
192   DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
193   FunctionBeginSym = FunctionEndSym = 0;
194   CurFn = 0;
195   CurMI = 0;
196
197   // Turn on accelerator tables for Darwin by default, pubnames by
198   // default for non-Darwin, and handle split dwarf.
199   bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
200
201   if (DwarfAccelTables == Default)
202     HasDwarfAccelTables = IsDarwin;
203   else
204     HasDwarfAccelTables = DwarfAccelTables == Enable;
205
206   if (SplitDwarf == Default)
207     HasSplitDwarf = false;
208   else
209     HasSplitDwarf = SplitDwarf == Enable;
210
211   if (DwarfPubSections == Default)
212     HasDwarfPubSections = !IsDarwin;
213   else
214     HasDwarfPubSections = DwarfPubSections == Enable;
215
216   DwarfVersion = DwarfVersionNumber
217                      ? DwarfVersionNumber
218                      : getDwarfVersionFromModule(MMI->getModule());
219
220   {
221     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
222     beginModule();
223   }
224 }
225
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229                                 const char *SymbolStem = 0) {
230   Asm->OutStreamer.SwitchSection(Section);
231   if (!SymbolStem)
232     return 0;
233
234   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235   Asm->OutStreamer.EmitLabel(TmpSym);
236   return TmpSym;
237 }
238
239 DwarfFile::~DwarfFile() {
240   for (DwarfUnit *DU : CUs)
241     delete DU;
242 }
243
244 MCSymbol *DwarfFile::getStringPoolSym() {
245   return Asm->GetTempSymbol(StringPref);
246 }
247
248 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
249   std::pair<MCSymbol *, unsigned> &Entry =
250       StringPool.GetOrCreateValue(Str).getValue();
251   if (Entry.first)
252     return Entry.first;
253
254   Entry.second = NextStringPoolNumber++;
255   return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
256 }
257
258 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
259   std::pair<MCSymbol *, unsigned> &Entry =
260       StringPool.GetOrCreateValue(Str).getValue();
261   if (Entry.first)
262     return Entry.second;
263
264   Entry.second = NextStringPoolNumber++;
265   Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
266   return Entry.second;
267 }
268
269 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
270   std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
271       std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
272   if (P.second)
273     ++NextAddrPoolNumber;
274   return P.first->second.Number;
275 }
276
277 // Define a unique number for the abbreviation.
278 //
279 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
280   // Check the set for priors.
281   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
282
283   // If it's newly added.
284   if (InSet == &Abbrev) {
285     // Add to abbreviation list.
286     Abbreviations.push_back(&Abbrev);
287
288     // Assign the vector position + 1 as its number.
289     Abbrev.setNumber(Abbreviations.size());
290   } else {
291     // Assign existing abbreviation number.
292     Abbrev.setNumber(InSet->getNumber());
293   }
294 }
295
296 static bool isObjCClass(StringRef Name) {
297   return Name.startswith("+") || Name.startswith("-");
298 }
299
300 static bool hasObjCCategory(StringRef Name) {
301   if (!isObjCClass(Name))
302     return false;
303
304   return Name.find(") ") != StringRef::npos;
305 }
306
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308                                  StringRef &Category) {
309   if (!hasObjCCategory(In)) {
310     Class = In.slice(In.find('[') + 1, In.find(' '));
311     Category = "";
312     return;
313   }
314
315   Class = In.slice(In.find('[') + 1, In.find('('));
316   Category = In.slice(In.find('[') + 1, In.find(' '));
317   return;
318 }
319
320 static StringRef getObjCMethodName(StringRef In) {
321   return In.slice(In.find(' ') + 1, In.find(']'));
322 }
323
324 // Helper for sorting sections into a stable output order.
325 static bool SectionSort(const MCSection *A, const MCSection *B) {
326   std::string LA = (A ? A->getLabelBeginName() : "");
327   std::string LB = (B ? B->getLabelBeginName() : "");
328   return LA < LB;
329 }
330
331 // Add the various names to the Dwarf accelerator table names.
332 // TODO: Determine whether or not we should add names for programs
333 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
334 // is only slightly different than the lookup of non-standard ObjC names.
335 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
336   if (!SP.isDefinition())
337     return;
338   TheU->addAccelName(SP.getName(), Die);
339
340   // If the linkage name is different than the name, go ahead and output
341   // that as well into the name table.
342   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
343     TheU->addAccelName(SP.getLinkageName(), Die);
344
345   // If this is an Objective-C selector name add it to the ObjC accelerator
346   // too.
347   if (isObjCClass(SP.getName())) {
348     StringRef Class, Category;
349     getObjCClassCategory(SP.getName(), Class, Category);
350     TheU->addAccelObjC(Class, Die);
351     if (Category != "")
352       TheU->addAccelObjC(Category, Die);
353     // Also add the base method name to the name table.
354     TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
355   }
356 }
357
358 /// isSubprogramContext - Return true if Context is either a subprogram
359 /// or another context nested inside a subprogram.
360 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
361   if (!Context)
362     return false;
363   DIDescriptor D(Context);
364   if (D.isSubprogram())
365     return true;
366   if (D.isType())
367     return isSubprogramContext(resolve(DIType(Context).getContext()));
368   return false;
369 }
370
371 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
372 // and DW_AT_high_pc attributes. If there are global variables in this
373 // scope then create and insert DIEs for these variables.
374 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
375                                           DISubprogram SP) {
376   DIE *SPDie = SPCU->getDIE(SP);
377
378   assert(SPDie && "Unable to find subprogram DIE!");
379
380   // If we're updating an abstract DIE, then we will be adding the children and
381   // object pointer later on. But what we don't want to do is process the
382   // concrete DIE twice.
383   if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
384     // Pick up abstract subprogram DIE.
385     SPDie =
386         SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
387     SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
388   } else {
389     DISubprogram SPDecl = SP.getFunctionDeclaration();
390     if (!SPDecl.isSubprogram()) {
391       // There is not any need to generate specification DIE for a function
392       // defined at compile unit level. If a function is defined inside another
393       // function then gdb prefers the definition at top level and but does not
394       // expect specification DIE in parent function. So avoid creating
395       // specification DIE for a function defined inside a function.
396       DIScope SPContext = resolve(SP.getContext());
397       if (SP.isDefinition() && !SPContext.isCompileUnit() &&
398           !SPContext.isFile() && !isSubprogramContext(SPContext)) {
399         SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
400
401         // Add arguments.
402         DICompositeType SPTy = SP.getType();
403         DIArray Args = SPTy.getTypeArray();
404         uint16_t SPTag = SPTy.getTag();
405         if (SPTag == dwarf::DW_TAG_subroutine_type)
406           SPCU->constructSubprogramArguments(*SPDie, Args);
407         DIE *SPDeclDie = SPDie;
408         SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
409                                       *SPCU->getUnitDie());
410         SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
411       }
412     }
413   }
414
415   attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
416
417   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
418   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
419   SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
420
421   // Add name to the name table, we do this here because we're guaranteed
422   // to have concrete versions of our DW_TAG_subprogram nodes.
423   addSubprogramNames(SPCU, SP, SPDie);
424
425   return SPDie;
426 }
427
428 /// Check whether we should create a DIE for the given Scope, return true
429 /// if we don't create a DIE (the corresponding DIE is null).
430 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
431   if (Scope->isAbstractScope())
432     return false;
433
434   // We don't create a DIE if there is no Range.
435   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
436   if (Ranges.empty())
437     return true;
438
439   if (Ranges.size() > 1)
440     return false;
441
442   // We don't create a DIE if we have a single Range and the end label
443   // is null.
444   SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
445   MCSymbol *End = getLabelAfterInsn(RI->second);
446   return !End;
447 }
448
449 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
450                             dwarf::Attribute A, const MCSymbol *L,
451                             const MCSymbol *Sec) {
452   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
453     U->addSectionLabel(D, A, L);
454   else
455     U->addSectionDelta(D, A, L, Sec);
456 }
457
458 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
459                                    const SmallVectorImpl<InsnRange> &Range) {
460   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
461   // emitting it appropriately.
462   MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
463   addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
464                   DwarfDebugRangeSectionSym);
465
466   RangeSpanList List(RangeSym);
467   for (const InsnRange &R : Range) {
468     RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
469     List.addRange(std::move(Span));
470   }
471
472   // Add the range list to the set of ranges to be emitted.
473   TheCU->addRangeList(std::move(List));
474 }
475
476 // Construct new DW_TAG_lexical_block for this scope and attach
477 // DW_AT_low_pc/DW_AT_high_pc labels.
478 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
479                                           LexicalScope *Scope) {
480   if (isLexicalScopeDIENull(Scope))
481     return 0;
482
483   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
484   if (Scope->isAbstractScope())
485     return ScopeDIE;
486
487   const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
488
489   // If we have multiple ranges, emit them into the range section.
490   if (ScopeRanges.size() > 1) {
491     addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
492     return ScopeDIE;
493   }
494
495   // Construct the address range for this DIE.
496   SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
497   MCSymbol *Start = getLabelBeforeInsn(RI->first);
498   MCSymbol *End = getLabelAfterInsn(RI->second);
499   assert(End && "End label should not be null!");
500
501   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
502   assert(End->isDefined() && "Invalid end label for an inlined scope!");
503
504   TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
505   TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
506
507   return ScopeDIE;
508 }
509
510 // This scope represents inlined body of a function. Construct DIE to
511 // represent this concrete inlined copy of the function.
512 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
513                                           LexicalScope *Scope) {
514   const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
515   assert(!ScopeRanges.empty() &&
516          "LexicalScope does not have instruction markers!");
517
518   if (!Scope->getScopeNode())
519     return NULL;
520   DIScope DS(Scope->getScopeNode());
521   DISubprogram InlinedSP = getDISubprogram(DS);
522   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
523   if (!OriginDIE) {
524     DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
525     return NULL;
526   }
527
528   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
529   TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
530
531   // If we have multiple ranges, emit them into the range section.
532   if (ScopeRanges.size() > 1)
533     addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
534   else {
535     SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
536     MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
537     MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
538
539     if (StartLabel == 0 || EndLabel == 0)
540       llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
541
542     assert(StartLabel->isDefined() &&
543            "Invalid starting label for an inlined scope!");
544     assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
545
546     attachLowHighPC(TheCU, ScopeDIE, StartLabel, 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 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2400                                    const DotDebugLocEntry &Entry) {
2401   DIVariable DV(Entry.getVariable());
2402   if (Entry.isInt()) {
2403     DIBasicType BTy(DV.getType());
2404     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2405                          BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2406       Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2407       Streamer.EmitSLEB128(Entry.getInt());
2408     } else {
2409       Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2410       Streamer.EmitULEB128(Entry.getInt());
2411     }
2412   } else if (Entry.isLocation()) {
2413     MachineLocation Loc = Entry.getLoc();
2414     if (!DV.hasComplexAddress())
2415       // Regular entry.
2416       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2417     else {
2418       // Complex address entry.
2419       unsigned N = DV.getNumAddrElements();
2420       unsigned i = 0;
2421       if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2422         if (Loc.getOffset()) {
2423           i = 2;
2424           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2425           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2426           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2427           Streamer.EmitSLEB128(DV.getAddrElement(1));
2428         } else {
2429           // If first address element is OpPlus then emit
2430           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2431           MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2432           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2433           i = 2;
2434         }
2435       } else {
2436         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2437       }
2438
2439       // Emit remaining complex address elements.
2440       for (; i < N; ++i) {
2441         uint64_t Element = DV.getAddrElement(i);
2442         if (Element == DIBuilder::OpPlus) {
2443           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2444           Streamer.EmitULEB128(DV.getAddrElement(++i));
2445         } else if (Element == DIBuilder::OpDeref) {
2446           if (!Loc.isReg())
2447             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2448         } else
2449           llvm_unreachable("unknown Opcode found in complex address");
2450       }
2451     }
2452   }
2453   // else ... ignore constant fp. There is not any good way to
2454   // to represent them here in dwarf.
2455   // FIXME: ^
2456 }
2457
2458 // Emit locations into the debug loc section.
2459 void DwarfDebug::emitDebugLoc() {
2460   if (DotDebugLocEntries.empty())
2461     return;
2462
2463   for (SmallVectorImpl<DotDebugLocEntry>::iterator
2464            I = DotDebugLocEntries.begin(),
2465            E = DotDebugLocEntries.end();
2466        I != E; ++I) {
2467     DotDebugLocEntry &Entry = *I;
2468     if (I + 1 != DotDebugLocEntries.end())
2469       Entry.Merge(I + 1);
2470   }
2471
2472   // Start the dwarf loc section.
2473   Asm->OutStreamer.SwitchSection(
2474       Asm->getObjFileLowering().getDwarfLocSection());
2475   unsigned char Size = Asm->getDataLayout().getPointerSize();
2476   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2477   unsigned index = 1;
2478   for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2479            I = DotDebugLocEntries.begin(),
2480            E = DotDebugLocEntries.end();
2481        I != E; ++I, ++index) {
2482     const DotDebugLocEntry &Entry = *I;
2483     if (Entry.isMerged())
2484       continue;
2485
2486     if (Entry.isEmpty()) {
2487       Asm->OutStreamer.EmitIntValue(0, Size);
2488       Asm->OutStreamer.EmitIntValue(0, Size);
2489       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2490     } else {
2491       // Set up the range.
2492       Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2493       Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2494       Asm->OutStreamer.AddComment("Loc expr size");
2495       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2496       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2497       Asm->EmitLabelDifference(end, begin, 2);
2498       Asm->OutStreamer.EmitLabel(begin);
2499       // Emit the entry.
2500       APByteStreamer Streamer(*Asm);
2501       emitDebugLocEntry(Streamer, Entry);
2502       // Close the range.
2503       Asm->OutStreamer.EmitLabel(end);
2504     }
2505   }
2506 }
2507
2508 struct ArangeSpan {
2509   const MCSymbol *Start, *End;
2510 };
2511
2512 // Emit a debug aranges section, containing a CU lookup for any
2513 // address we can tie back to a CU.
2514 void DwarfDebug::emitDebugARanges() {
2515   // Start the dwarf aranges section.
2516   Asm->OutStreamer.SwitchSection(
2517       Asm->getObjFileLowering().getDwarfARangesSection());
2518
2519   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2520
2521   SpansType Spans;
2522
2523   // Build a list of sections used.
2524   std::vector<const MCSection *> Sections;
2525   for (const auto &it : SectionMap) {
2526     const MCSection *Section = it.first;
2527     Sections.push_back(Section);
2528   }
2529
2530   // Sort the sections into order.
2531   // This is only done to ensure consistent output order across different runs.
2532   std::sort(Sections.begin(), Sections.end(), SectionSort);
2533
2534   // Build a set of address spans, sorted by CU.
2535   for (const MCSection *Section : Sections) {
2536     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2537     if (List.size() < 2)
2538       continue;
2539
2540     // Sort the symbols by offset within the section.
2541     std::sort(List.begin(), List.end(),
2542               [&](const SymbolCU &A, const SymbolCU &B) {
2543       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2544       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2545
2546       // Symbols with no order assigned should be placed at the end.
2547       // (e.g. section end labels)
2548       if (IA == 0)
2549         return false;
2550       if (IB == 0)
2551         return true;
2552       return IA < IB;
2553     });
2554
2555     // If we have no section (e.g. common), just write out
2556     // individual spans for each symbol.
2557     if (Section == NULL) {
2558       for (const SymbolCU &Cur : List) {
2559         ArangeSpan Span;
2560         Span.Start = Cur.Sym;
2561         Span.End = NULL;
2562         if (Cur.CU)
2563           Spans[Cur.CU].push_back(Span);
2564       }
2565     } else {
2566       // Build spans between each label.
2567       const MCSymbol *StartSym = List[0].Sym;
2568       for (size_t n = 1, e = List.size(); n < e; n++) {
2569         const SymbolCU &Prev = List[n - 1];
2570         const SymbolCU &Cur = List[n];
2571
2572         // Try and build the longest span we can within the same CU.
2573         if (Cur.CU != Prev.CU) {
2574           ArangeSpan Span;
2575           Span.Start = StartSym;
2576           Span.End = Cur.Sym;
2577           Spans[Prev.CU].push_back(Span);
2578           StartSym = Cur.Sym;
2579         }
2580       }
2581     }
2582   }
2583
2584   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2585
2586   // Build a list of CUs used.
2587   std::vector<DwarfCompileUnit *> CUs;
2588   for (const auto &it : Spans) {
2589     DwarfCompileUnit *CU = it.first;
2590     CUs.push_back(CU);
2591   }
2592
2593   // Sort the CU list (again, to ensure consistent output order).
2594   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2595     return A->getUniqueID() < B->getUniqueID();
2596   });
2597
2598   // Emit an arange table for each CU we used.
2599   for (DwarfCompileUnit *CU : CUs) {
2600     std::vector<ArangeSpan> &List = Spans[CU];
2601
2602     // Emit size of content not including length itself.
2603     unsigned ContentSize =
2604         sizeof(int16_t) + // DWARF ARange version number
2605         sizeof(int32_t) + // Offset of CU in the .debug_info section
2606         sizeof(int8_t) +  // Pointer Size (in bytes)
2607         sizeof(int8_t);   // Segment Size (in bytes)
2608
2609     unsigned TupleSize = PtrSize * 2;
2610
2611     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2612     unsigned Padding =
2613         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2614
2615     ContentSize += Padding;
2616     ContentSize += (List.size() + 1) * TupleSize;
2617
2618     // For each compile unit, write the list of spans it covers.
2619     Asm->OutStreamer.AddComment("Length of ARange Set");
2620     Asm->EmitInt32(ContentSize);
2621     Asm->OutStreamer.AddComment("DWARF Arange version number");
2622     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2623     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2624     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2625     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2626     Asm->EmitInt8(PtrSize);
2627     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2628     Asm->EmitInt8(0);
2629
2630     Asm->OutStreamer.EmitFill(Padding, 0xff);
2631
2632     for (const ArangeSpan &Span : List) {
2633       Asm->EmitLabelReference(Span.Start, PtrSize);
2634
2635       // Calculate the size as being from the span start to it's end.
2636       if (Span.End) {
2637         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2638       } else {
2639         // For symbols without an end marker (e.g. common), we
2640         // write a single arange entry containing just that one symbol.
2641         uint64_t Size = SymSize[Span.Start];
2642         if (Size == 0)
2643           Size = 1;
2644
2645         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2646       }
2647     }
2648
2649     Asm->OutStreamer.AddComment("ARange terminator");
2650     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2651     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2652   }
2653 }
2654
2655 // Emit visible names into a debug ranges section.
2656 void DwarfDebug::emitDebugRanges() {
2657   // Start the dwarf ranges section.
2658   Asm->OutStreamer.SwitchSection(
2659       Asm->getObjFileLowering().getDwarfRangesSection());
2660
2661   // Size for our labels.
2662   unsigned char Size = Asm->getDataLayout().getPointerSize();
2663
2664   // Grab the specific ranges for the compile units in the module.
2665   for (const auto &I : CUMap) {
2666     DwarfCompileUnit *TheCU = I.second;
2667
2668     // Emit a symbol so we can find the beginning of our ranges.
2669     Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2670
2671     // Iterate over the misc ranges for the compile units in the module.
2672     for (const RangeSpanList &List : TheCU->getRangeLists()) {
2673       // Emit our symbol so we can find the beginning of the range.
2674       Asm->OutStreamer.EmitLabel(List.getSym());
2675
2676       for (const RangeSpan &Range : List.getRanges()) {
2677         const MCSymbol *Begin = Range.getStart();
2678         const MCSymbol *End = Range.getEnd();
2679         assert(Begin && "Range without a begin symbol?");
2680         assert(End && "Range without an end symbol?");
2681         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2682         Asm->OutStreamer.EmitSymbolValue(End, Size);
2683       }
2684
2685       // And terminate the list with two 0 values.
2686       Asm->OutStreamer.EmitIntValue(0, Size);
2687       Asm->OutStreamer.EmitIntValue(0, Size);
2688     }
2689
2690     // Now emit a range for the CU itself.
2691     if (useCURanges() && TheCU->getRanges().size()) {
2692       Asm->OutStreamer.EmitLabel(
2693           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2694       for (const RangeSpan &Range : TheCU->getRanges()) {
2695         const MCSymbol *Begin = Range.getStart();
2696         const MCSymbol *End = Range.getEnd();
2697         assert(Begin && "Range without a begin symbol?");
2698         assert(End && "Range without an end symbol?");
2699         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2700         Asm->OutStreamer.EmitSymbolValue(End, Size);
2701       }
2702       // And terminate the list with two 0 values.
2703       Asm->OutStreamer.EmitIntValue(0, Size);
2704       Asm->OutStreamer.EmitIntValue(0, Size);
2705     }
2706   }
2707 }
2708
2709 // DWARF5 Experimental Separate Dwarf emitters.
2710
2711 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2712                                   DwarfUnit *NewU) {
2713   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2714                        U->getCUNode().getSplitDebugFilename());
2715
2716   // Relocate to the beginning of the addr_base section, else 0 for the
2717   // beginning of the one for this compile unit.
2718   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2719     NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2720   else
2721     NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2722
2723   if (!CompilationDir.empty())
2724     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2725
2726   addGnuPubAttributes(NewU, Die);
2727
2728   SkeletonHolder.addUnit(NewU);
2729 }
2730
2731 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2732 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2733 // DW_AT_ranges_base, DW_AT_addr_base.
2734 // TODO: Implement DW_AT_ranges_base.
2735 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2736
2737   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2738   DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2739       CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2740   NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2741                      DwarfInfoSectionSym);
2742
2743   NewCU->initStmtList(DwarfLineSectionSym);
2744
2745   initSkeletonUnit(CU, Die, NewCU);
2746
2747   return NewCU;
2748 }
2749
2750 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2751 // DW_AT_addr_base.
2752 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2753   DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2754       *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2755
2756   DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2757   DwarfTypeUnit *NewTU =
2758       new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2759   NewTU->setTypeSignature(TU->getTypeSignature());
2760   NewTU->setType(NULL);
2761   NewTU->initSection(
2762       Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2763   CU.applyStmtList(*Die);
2764
2765   initSkeletonUnit(TU, Die, NewTU);
2766   return NewTU;
2767 }
2768
2769 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2770 // compile units that would normally be in debug_info.
2771 void DwarfDebug::emitDebugInfoDWO() {
2772   assert(useSplitDwarf() && "No split dwarf debug info?");
2773   InfoHolder.emitUnits(this,
2774                        Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2775                        DwarfAbbrevDWOSectionSym);
2776 }
2777
2778 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2779 // abbreviations for the .debug_info.dwo section.
2780 void DwarfDebug::emitDebugAbbrevDWO() {
2781   assert(useSplitDwarf() && "No split dwarf?");
2782   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2783 }
2784
2785 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2786 // string section and is identical in format to traditional .debug_str
2787 // sections.
2788 void DwarfDebug::emitDebugStrDWO() {
2789   assert(useSplitDwarf() && "No split dwarf?");
2790   const MCSection *OffSec =
2791       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2792   const MCSymbol *StrSym = DwarfStrSectionSym;
2793   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2794                          OffSec, StrSym);
2795 }
2796
2797 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2798                                       StringRef Identifier, DIE *RefDie,
2799                                       DICompositeType CTy) {
2800   // Flag the type unit reference as a declaration so that if it contains
2801   // members (implicit special members, static data member definitions, member
2802   // declarations for definitions in this CU, etc) consumers don't get confused
2803   // and think this is a full definition.
2804   CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2805
2806   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2807   if (TU) {
2808     CU.addDIETypeSignature(RefDie, *TU);
2809     return;
2810   }
2811
2812   DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2813   DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2814                                            UnitDie, CU, Asm, this, &InfoHolder);
2815   TU = NewTU;
2816   InfoHolder.addUnit(NewTU);
2817
2818   NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2819                  CU.getLanguage());
2820
2821   MD5 Hash;
2822   Hash.update(Identifier);
2823   // ... take the least significant 8 bytes and return those. Our MD5
2824   // implementation always returns its results in little endian, swap bytes
2825   // appropriately.
2826   MD5::MD5Result Result;
2827   Hash.final(Result);
2828   uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2829   NewTU->setTypeSignature(Signature);
2830   if (useSplitDwarf())
2831     NewTU->setSkeleton(constructSkeletonTU(NewTU));
2832   else
2833     CU.applyStmtList(*UnitDie);
2834
2835   NewTU->setType(NewTU->createTypeDIE(CTy));
2836
2837   NewTU->initSection(
2838       useSplitDwarf()
2839           ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2840           : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2841
2842   CU.addDIETypeSignature(RefDie, *NewTU);
2843 }
2844
2845 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2846                                  MCSymbol *Begin, MCSymbol *End) {
2847   Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2848   if (DwarfVersion < 4 || Triple(Asm->getTargetTriple()).isOSDarwin())
2849     Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2850   else
2851     Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2852 }