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