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