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