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