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