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