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