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