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