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