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