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