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