a88f6ecff1f6863a76ba6825922b6fb7233b2fe5
[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 #include "ByteStreamer.h"
16 #include "DIEHash.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfExpression.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/DIE.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 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
109   BS.EmitInt8(
110       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
111                   : dwarf::OperationEncodingString(Op));
112 }
113
114 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
115   BS.EmitSLEB128(Value, Twine(Value));
116 }
117
118 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
119   BS.EmitULEB128(Value, Twine(Value));
120 }
121
122 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
123   // This information is not available while emitting .debug_loc entries.
124   return false;
125 }
126
127 //===----------------------------------------------------------------------===//
128
129 /// resolve - Look in the DwarfDebug map for the MDNode that
130 /// corresponds to the reference.
131 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
132   return DD->resolve(Ref);
133 }
134
135 bool DbgVariable::isBlockByrefVariable() const {
136   assert(Var.isVariable() && "Invalid complex DbgVariable!");
137   return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
138 }
139
140 DIType DbgVariable::getType() const {
141   DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
142   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
143   // addresses instead.
144   if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
145     /* Byref variables, in Blocks, are declared by the programmer as
146        "SomeType VarName;", but the compiler creates a
147        __Block_byref_x_VarName struct, and gives the variable VarName
148        either the struct, or a pointer to the struct, as its type.  This
149        is necessary for various behind-the-scenes things the compiler
150        needs to do with by-reference variables in blocks.
151
152        However, as far as the original *programmer* is concerned, the
153        variable should still have type 'SomeType', as originally declared.
154
155        The following function dives into the __Block_byref_x_VarName
156        struct to find the original type of the variable.  This will be
157        passed back to the code generating the type for the Debug
158        Information Entry for the variable 'VarName'.  'VarName' will then
159        have the original type 'SomeType' in its debug information.
160
161        The original type 'SomeType' will be the type of the field named
162        'VarName' inside the __Block_byref_x_VarName struct.
163
164        NOTE: In order for this to not completely fail on the debugger
165        side, the Debug Information Entry for the variable VarName needs to
166        have a DW_AT_location that tells the debugger how to unwind through
167        the pointers and __Block_byref_x_VarName struct to find the actual
168        value of the variable.  The function addBlockByrefType does this.  */
169     DIType subType = Ty;
170     uint16_t tag = Ty.getTag();
171
172     if (tag == dwarf::DW_TAG_pointer_type)
173       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
174
175     DIArray Elements = DICompositeType(subType).getElements();
176     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
177       DIDerivedType DT(Elements.getElement(i));
178       if (getName() == DT.getName())
179         return (resolve(DT.getTypeDerivedFrom()));
180     }
181   }
182   return Ty;
183 }
184
185 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
186     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
187     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
188     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
189
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191     : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
192       InfoHolder(A, "info_string", DIEValueAllocator),
193       UsedNonDefaultText(false),
194       SkeletonHolder(A, "skel_string", DIEValueAllocator),
195       IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196       IsPS4(Triple(A->getTargetTriple()).isPS4()),
197       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
198                                        dwarf::DW_FORM_data4)),
199       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
200                                       dwarf::DW_FORM_data4)),
201       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
202                                            dwarf::DW_FORM_data4)),
203       AccelTypes(TypeAtoms) {
204
205   CurFn = nullptr;
206   CurMI = nullptr;
207
208   // Turn on accelerator tables for Darwin by default, pubnames by
209   // default for non-Darwin/PS4, and handle split dwarf.
210   if (DwarfAccelTables == Default)
211     HasDwarfAccelTables = IsDarwin;
212   else
213     HasDwarfAccelTables = DwarfAccelTables == Enable;
214
215   if (SplitDwarf == Default)
216     HasSplitDwarf = false;
217   else
218     HasSplitDwarf = SplitDwarf == Enable;
219
220   if (DwarfPubSections == Default)
221     HasDwarfPubSections = !IsDarwin && !IsPS4;
222   else
223     HasDwarfPubSections = DwarfPubSections == Enable;
224
225   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
226   DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
227                                     : MMI->getModule()->getDwarfVersion();
228
229   // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
230   // Everybody else uses GNU's.
231   UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
232
233   Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
234
235   {
236     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
237     beginModule();
238   }
239 }
240
241 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
242 DwarfDebug::~DwarfDebug() { }
243
244 static bool isObjCClass(StringRef Name) {
245   return Name.startswith("+") || Name.startswith("-");
246 }
247
248 static bool hasObjCCategory(StringRef Name) {
249   if (!isObjCClass(Name))
250     return false;
251
252   return Name.find(") ") != StringRef::npos;
253 }
254
255 static void getObjCClassCategory(StringRef In, StringRef &Class,
256                                  StringRef &Category) {
257   if (!hasObjCCategory(In)) {
258     Class = In.slice(In.find('[') + 1, In.find(' '));
259     Category = "";
260     return;
261   }
262
263   Class = In.slice(In.find('[') + 1, In.find('('));
264   Category = In.slice(In.find('[') + 1, In.find(' '));
265   return;
266 }
267
268 static StringRef getObjCMethodName(StringRef In) {
269   return In.slice(In.find(' ') + 1, In.find(']'));
270 }
271
272 // Add the various names to the Dwarf accelerator table names.
273 // TODO: Determine whether or not we should add names for programs
274 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
275 // is only slightly different than the lookup of non-standard ObjC names.
276 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
277   if (!SP.isDefinition())
278     return;
279   addAccelName(SP.getName(), Die);
280
281   // If the linkage name is different than the name, go ahead and output
282   // that as well into the name table.
283   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284     addAccelName(SP.getLinkageName(), Die);
285
286   // If this is an Objective-C selector name add it to the ObjC accelerator
287   // too.
288   if (isObjCClass(SP.getName())) {
289     StringRef Class, Category;
290     getObjCClassCategory(SP.getName(), Class, Category);
291     addAccelObjC(Class, Die);
292     if (Category != "")
293       addAccelObjC(Category, Die);
294     // Also add the base method name to the name table.
295     addAccelName(getObjCMethodName(SP.getName()), Die);
296   }
297 }
298
299 /// isSubprogramContext - Return true if Context is either a subprogram
300 /// or another context nested inside a subprogram.
301 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
302   if (!Context)
303     return false;
304   DIDescriptor D(Context);
305   if (D.isSubprogram())
306     return true;
307   if (D.isType())
308     return isSubprogramContext(resolve(DIType(Context).getContext()));
309   return false;
310 }
311
312 /// Check whether we should create a DIE for the given Scope, return true
313 /// if we don't create a DIE (the corresponding DIE is null).
314 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
315   if (Scope->isAbstractScope())
316     return false;
317
318   // We don't create a DIE if there is no Range.
319   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
320   if (Ranges.empty())
321     return true;
322
323   if (Ranges.size() > 1)
324     return false;
325
326   // We don't create a DIE if we have a single Range and the end label
327   // is null.
328   return !getLabelAfterInsn(Ranges.front().second);
329 }
330
331 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
332   F(CU);
333   if (auto *SkelCU = CU.getSkeleton())
334     F(*SkelCU);
335 }
336
337 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
338   assert(Scope && Scope->getScopeNode());
339   assert(Scope->isAbstractScope());
340   assert(!Scope->getInlinedAt());
341
342   const MDNode *SP = Scope->getScopeNode();
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   auto &CU = SPMap[SP];
349   forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
350     CU.constructAbstractSubprogramScopeDIE(Scope);
351   });
352 }
353
354 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
355   if (!GenerateGnuPubSections)
356     return;
357
358   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
359 }
360
361 // Create new DwarfCompileUnit for the given metadata node with tag
362 // DW_TAG_compile_unit.
363 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
364   StringRef FN = DIUnit.getFilename();
365   CompilationDir = DIUnit.getDirectory();
366
367   auto OwnedUnit = make_unique<DwarfCompileUnit>(
368       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
369   DwarfCompileUnit &NewCU = *OwnedUnit;
370   DIE &Die = NewCU.getUnitDie();
371   InfoHolder.addUnit(std::move(OwnedUnit));
372   if (useSplitDwarf())
373     NewCU.setSkeleton(constructSkeletonCU(NewCU));
374
375   // LTO with assembly output shares a single line table amongst multiple CUs.
376   // To avoid the compilation directory being ambiguous, let the line table
377   // explicitly describe the directory of all files, never relying on the
378   // compilation directory.
379   if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
380     Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
381         NewCU.getUniqueID(), CompilationDir);
382
383   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
384   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
385                 DIUnit.getLanguage());
386   NewCU.addString(Die, dwarf::DW_AT_name, FN);
387
388   if (!useSplitDwarf()) {
389     NewCU.initStmtList();
390
391     // If we're using split dwarf the compilation dir is going to be in the
392     // skeleton CU and so we don't need to duplicate it here.
393     if (!CompilationDir.empty())
394       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
395
396     addGnuPubAttributes(NewCU, Die);
397   }
398
399   if (DIUnit.isOptimized())
400     NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
401
402   StringRef Flags = DIUnit.getFlags();
403   if (!Flags.empty())
404     NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
405
406   if (unsigned RVer = DIUnit.getRunTimeVersion())
407     NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
408                   dwarf::DW_FORM_data1, RVer);
409
410   if (useSplitDwarf())
411     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
412   else
413     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
414
415   CUMap.insert(std::make_pair(DIUnit, &NewCU));
416   CUDieMap.insert(std::make_pair(&Die, &NewCU));
417   return NewCU;
418 }
419
420 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
421                                                   const MDNode *N) {
422   DIImportedEntity Module(N);
423   assert(Module.Verify());
424   if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
425     D->addChild(TheCU.constructImportedEntityDIE(Module));
426 }
427
428 // Emit all Dwarf sections that should come prior to the content. Create
429 // global DIEs and emit initial debug info sections. This is invoked by
430 // the target AsmPrinter.
431 void DwarfDebug::beginModule() {
432   if (DisableDebugInfoPrinting)
433     return;
434
435   const Module *M = MMI->getModule();
436
437   FunctionDIs = makeSubprogramMap(*M);
438
439   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
440   if (!CU_Nodes)
441     return;
442   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
443
444   SingleCU = CU_Nodes->getNumOperands() == 1;
445
446   for (MDNode *N : CU_Nodes->operands()) {
447     DICompileUnit CUNode(N);
448     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
449     DIArray ImportedEntities = CUNode.getImportedEntities();
450     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
451       ScopesWithImportedEntities.push_back(std::make_pair(
452           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
453           ImportedEntities.getElement(i)));
454     // Stable sort to preserve the order of appearance of imported entities.
455     // This is to avoid out-of-order processing of interdependent declarations
456     // within the same scope, e.g. { namespace A = base; namespace B = A; }
457     std::stable_sort(ScopesWithImportedEntities.begin(),
458                      ScopesWithImportedEntities.end(), less_first());
459     DIArray GVs = CUNode.getGlobalVariables();
460     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
461       CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
462     DIArray SPs = CUNode.getSubprograms();
463     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
464       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
465     DIArray EnumTypes = CUNode.getEnumTypes();
466     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
467       DIType Ty(EnumTypes.getElement(i));
468       // The enum types array by design contains pointers to
469       // MDNodes rather than DIRefs. Unique them here.
470       DIType UniqueTy(resolve(Ty.getRef()));
471       CU.getOrCreateTypeDIE(UniqueTy);
472     }
473     DIArray RetainedTypes = CUNode.getRetainedTypes();
474     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
475       DIType Ty(RetainedTypes.getElement(i));
476       // The retained types array by design contains pointers to
477       // MDNodes rather than DIRefs. Unique them here.
478       DIType UniqueTy(resolve(Ty.getRef()));
479       CU.getOrCreateTypeDIE(UniqueTy);
480     }
481     // Emit imported_modules last so that the relevant context is already
482     // available.
483     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
484       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
485   }
486
487   // Tell MMI that we have debug info.
488   MMI->setDebugInfoAvailability(true);
489 }
490
491 void DwarfDebug::finishVariableDefinitions() {
492   for (const auto &Var : ConcreteVariables) {
493     DIE *VariableDie = Var->getDIE();
494     assert(VariableDie);
495     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
496     // in the ConcreteVariables list, rather than looking it up again here.
497     // DIE::getUnit isn't simple - it walks parent pointers, etc.
498     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
499     assert(Unit);
500     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
501     if (AbsVar && AbsVar->getDIE()) {
502       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
503                         *AbsVar->getDIE());
504     } else
505       Unit->applyVariableAttributes(*Var, *VariableDie);
506   }
507 }
508
509 void DwarfDebug::finishSubprogramDefinitions() {
510   for (const auto &P : SPMap)
511     forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
512       CU.finishSubprogramDefinition(DISubprogram(P.first));
513     });
514 }
515
516
517 // Collect info for variables that were optimized out.
518 void DwarfDebug::collectDeadVariables() {
519   const Module *M = MMI->getModule();
520
521   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
522     for (MDNode *N : CU_Nodes->operands()) {
523       DICompileUnit TheCU(N);
524       // Construct subprogram DIE and add variables DIEs.
525       DwarfCompileUnit *SPCU =
526           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
527       assert(SPCU && "Unable to find Compile Unit!");
528       DIArray Subprograms = TheCU.getSubprograms();
529       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
530         DISubprogram SP(Subprograms.getElement(i));
531         if (ProcessedSPNodes.count(SP) != 0)
532           continue;
533         SPCU->collectDeadVariables(SP);
534       }
535     }
536   }
537 }
538
539 void DwarfDebug::finalizeModuleInfo() {
540   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
541
542   finishSubprogramDefinitions();
543
544   finishVariableDefinitions();
545
546   // Collect info for variables that were optimized out.
547   collectDeadVariables();
548
549   // Handle anything that needs to be done on a per-unit basis after
550   // all other generation.
551   for (const auto &P : CUMap) {
552     auto &TheCU = *P.second;
553     // Emit DW_AT_containing_type attribute to connect types with their
554     // vtable holding type.
555     TheCU.constructContainingTypeDIEs();
556
557     // Add CU specific attributes if we need to add any.
558     // If we're splitting the dwarf out now that we've got the entire
559     // CU then add the dwo id to it.
560     auto *SkCU = TheCU.getSkeleton();
561     if (useSplitDwarf()) {
562       // Emit a unique identifier for this CU.
563       uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
564       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
565                     dwarf::DW_FORM_data8, ID);
566       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
567                     dwarf::DW_FORM_data8, ID);
568
569       // We don't keep track of which addresses are used in which CU so this
570       // is a bit pessimistic under LTO.
571       if (!AddrPool.isEmpty()) {
572         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
573         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
574                               Sym, Sym);
575       }
576       if (!SkCU->getRangeLists().empty()) {
577         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
578         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
579                               Sym, Sym);
580       }
581     }
582
583     // If we have code split among multiple sections or non-contiguous
584     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
585     // remain in the .o file, otherwise add a DW_AT_low_pc.
586     // FIXME: We should use ranges allow reordering of code ala
587     // .subsections_via_symbols in mach-o. This would mean turning on
588     // ranges for all subprogram DIEs for mach-o.
589     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
590     if (unsigned NumRanges = TheCU.getRanges().size()) {
591       if (NumRanges > 1)
592         // A DW_AT_low_pc attribute may also be specified in combination with
593         // DW_AT_ranges to specify the default base address for use in
594         // location lists (see Section 2.6.2) and range lists (see Section
595         // 2.17.3).
596         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
597       else
598         TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
599       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
600     }
601   }
602
603   // Compute DIE offsets and sizes.
604   InfoHolder.computeSizeAndOffsets();
605   if (useSplitDwarf())
606     SkeletonHolder.computeSizeAndOffsets();
607 }
608
609 // Emit all Dwarf sections that should come after the content.
610 void DwarfDebug::endModule() {
611   assert(CurFn == nullptr);
612   assert(CurMI == nullptr);
613
614   // If we aren't actually generating debug info (check beginModule -
615   // conditionalized on !DisableDebugInfoPrinting and the presence of the
616   // llvm.dbg.cu metadata node)
617   if (!MMI->hasDebugInfo())
618     return;
619
620   // Finalize the debug info for the module.
621   finalizeModuleInfo();
622
623   emitDebugStr();
624
625   if (useSplitDwarf())
626     emitDebugLocDWO();
627   else
628     // Emit info into a debug loc section.
629     emitDebugLoc();
630
631   // Corresponding abbreviations into a abbrev section.
632   emitAbbreviations();
633
634   // Emit all the DIEs into a debug info section.
635   emitDebugInfo();
636
637   // Emit info into a debug aranges section.
638   if (GenerateARangeSection)
639     emitDebugARanges();
640
641   // Emit info into a debug ranges section.
642   emitDebugRanges();
643
644   if (useSplitDwarf()) {
645     emitDebugStrDWO();
646     emitDebugInfoDWO();
647     emitDebugAbbrevDWO();
648     emitDebugLineDWO();
649     // Emit DWO addresses.
650     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
651   }
652
653   // Emit info into the dwarf accelerator table sections.
654   if (useDwarfAccelTables()) {
655     emitAccelNames();
656     emitAccelObjC();
657     emitAccelNamespaces();
658     emitAccelTypes();
659   }
660
661   // Emit the pubnames and pubtypes sections if requested.
662   if (HasDwarfPubSections) {
663     emitDebugPubNames(GenerateGnuPubSections);
664     emitDebugPubTypes(GenerateGnuPubSections);
665   }
666
667   // clean up.
668   SPMap.clear();
669   AbstractVariables.clear();
670 }
671
672 // Find abstract variable, if any, associated with Var.
673 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
674                                                      DIVariable &Cleansed) {
675   LLVMContext &Ctx = DV->getContext();
676   // More then one inlined variable corresponds to one abstract variable.
677   // FIXME: This duplication of variables when inlining should probably be
678   // removed. It's done to allow each DIVariable to describe its location
679   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
680   // make it accurate then remove this duplication/cleansing stuff.
681   Cleansed = cleanseInlinedVariable(DV, Ctx);
682   auto I = AbstractVariables.find(Cleansed);
683   if (I != AbstractVariables.end())
684     return I->second.get();
685   return nullptr;
686 }
687
688 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
689   DIVariable Cleansed;
690   return getExistingAbstractVariable(DV, Cleansed);
691 }
692
693 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
694                                         LexicalScope *Scope) {
695   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
696   InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
697   AbstractVariables[Var] = std::move(AbsDbgVariable);
698 }
699
700 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
701                                                  const MDNode *ScopeNode) {
702   DIVariable Cleansed = DV;
703   if (getExistingAbstractVariable(DV, Cleansed))
704     return;
705
706   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
707 }
708
709 void
710 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
711                                                     const MDNode *ScopeNode) {
712   DIVariable Cleansed = DV;
713   if (getExistingAbstractVariable(DV, Cleansed))
714     return;
715
716   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
717     createAbstractVariable(Cleansed, Scope);
718 }
719
720 // Collect variable information from side table maintained by MMI.
721 void DwarfDebug::collectVariableInfoFromMMITable(
722     SmallPtrSetImpl<const MDNode *> &Processed) {
723   for (const auto &VI : MMI->getVariableDbgInfo()) {
724     if (!VI.Var)
725       continue;
726     Processed.insert(VI.Var);
727     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
728
729     // If variable scope is not found then skip this variable.
730     if (!Scope)
731       continue;
732
733     DIVariable DV(VI.Var);
734     DIExpression Expr(VI.Expr);
735     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
736     auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
737     if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
738       ConcreteVariables.push_back(std::move(RegVar));
739   }
740 }
741
742 // Get .debug_loc entry for the instruction range starting at MI.
743 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
744   const MDNode *Expr = MI->getDebugExpression();
745   const MDNode *Var = MI->getDebugVariable();
746
747   assert(MI->getNumOperands() == 4);
748   if (MI->getOperand(0).isReg()) {
749     MachineLocation MLoc;
750     // If the second operand is an immediate, this is a
751     // register-indirect address.
752     if (!MI->getOperand(1).isImm())
753       MLoc.set(MI->getOperand(0).getReg());
754     else
755       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
756     return DebugLocEntry::Value(Var, Expr, MLoc);
757   }
758   if (MI->getOperand(0).isImm())
759     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
760   if (MI->getOperand(0).isFPImm())
761     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
762   if (MI->getOperand(0).isCImm())
763     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
764
765   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
766 }
767
768 /// Determine whether two variable pieces overlap.
769 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
770   if (!P1.isBitPiece() || !P2.isBitPiece())
771     return true;
772   unsigned l1 = P1.getBitPieceOffset();
773   unsigned l2 = P2.getBitPieceOffset();
774   unsigned r1 = l1 + P1.getBitPieceSize();
775   unsigned r2 = l2 + P2.getBitPieceSize();
776   // True where [l1,r1[ and [r1,r2[ overlap.
777   return (l1 < r2) && (l2 < r1);
778 }
779
780 /// Build the location list for all DBG_VALUEs in the function that
781 /// describe the same variable.  If the ranges of several independent
782 /// pieces of the same variable overlap partially, split them up and
783 /// combine the ranges. The resulting DebugLocEntries are will have
784 /// strict monotonically increasing begin addresses and will never
785 /// overlap.
786 //
787 // Input:
788 //
789 //   Ranges History [var, loc, piece ofs size]
790 // 0 |      [x, (reg0, piece 0, 32)]
791 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
792 // 2 | |    ...
793 // 3   |    [clobber reg0]
794 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
795 //                                     x.
796 //
797 // Output:
798 //
799 // [0-1]    [x, (reg0, piece  0, 32)]
800 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
801 // [3-4]    [x, (reg1, piece 32, 32)]
802 // [4- ]    [x, (mem,  piece  0, 64)]
803 void
804 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
805                               const DbgValueHistoryMap::InstrRanges &Ranges) {
806   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
807
808   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
809     const MachineInstr *Begin = I->first;
810     const MachineInstr *End = I->second;
811     assert(Begin->isDebugValue() && "Invalid History entry");
812
813     // Check if a variable is inaccessible in this range.
814     if (Begin->getNumOperands() > 1 &&
815         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
816       OpenRanges.clear();
817       continue;
818     }
819
820     // If this piece overlaps with any open ranges, truncate them.
821     DIExpression DIExpr = Begin->getDebugExpression();
822     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
823                                [&](DebugLocEntry::Value R) {
824       return piecesOverlap(DIExpr, R.getExpression());
825     });
826     OpenRanges.erase(Last, OpenRanges.end());
827
828     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
829     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
830
831     const MCSymbol *EndLabel;
832     if (End != nullptr)
833       EndLabel = getLabelAfterInsn(End);
834     else if (std::next(I) == Ranges.end())
835       EndLabel = Asm->getFunctionEnd();
836     else
837       EndLabel = getLabelBeforeInsn(std::next(I)->first);
838     assert(EndLabel && "Forgot label after instruction ending a range!");
839
840     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
841
842     auto Value = getDebugLocValue(Begin);
843     DebugLocEntry Loc(StartLabel, EndLabel, Value);
844     bool couldMerge = false;
845
846     // If this is a piece, it may belong to the current DebugLocEntry.
847     if (DIExpr.isBitPiece()) {
848       // Add this value to the list of open ranges.
849       OpenRanges.push_back(Value);
850
851       // Attempt to add the piece to the last entry.
852       if (!DebugLoc.empty())
853         if (DebugLoc.back().MergeValues(Loc))
854           couldMerge = true;
855     }
856
857     if (!couldMerge) {
858       // Need to add a new DebugLocEntry. Add all values from still
859       // valid non-overlapping pieces.
860       if (OpenRanges.size())
861         Loc.addValues(OpenRanges);
862
863       DebugLoc.push_back(std::move(Loc));
864     }
865
866     // Attempt to coalesce the ranges of two otherwise identical
867     // DebugLocEntries.
868     auto CurEntry = DebugLoc.rbegin();
869     auto PrevEntry = std::next(CurEntry);
870     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
871       DebugLoc.pop_back();
872
873     DEBUG({
874       dbgs() << CurEntry->getValues().size() << " Values:\n";
875       for (auto Value : CurEntry->getValues()) {
876         Value.getVariable()->dump();
877         Value.getExpression()->dump();
878       }
879       dbgs() << "-----\n";
880     });
881   }
882 }
883
884
885 // Find variables for each lexical scope.
886 void
887 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
888                                 SmallPtrSetImpl<const MDNode *> &Processed) {
889   // Grab the variable info that was squirreled away in the MMI side-table.
890   collectVariableInfoFromMMITable(Processed);
891
892   for (const auto &I : DbgValues) {
893     DIVariable DV(I.first);
894     if (Processed.count(DV))
895       continue;
896
897     // Instruction ranges, specifying where DV is accessible.
898     const auto &Ranges = I.second;
899     if (Ranges.empty())
900       continue;
901
902     LexicalScope *Scope = nullptr;
903     if (MDNode *IA = DV.getInlinedAt())
904       Scope = LScopes.findInlinedScope(DV.getContext(), IA);
905     else
906       Scope = LScopes.findLexicalScope(DV.getContext());
907     // If variable scope is not found then skip this variable.
908     if (!Scope)
909       continue;
910
911     Processed.insert(DV);
912     const MachineInstr *MInsn = Ranges.front().first;
913     assert(MInsn->isDebugValue() && "History must begin with debug value");
914     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
915     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
916     DbgVariable *RegVar = ConcreteVariables.back().get();
917     InfoHolder.addScopeVariable(Scope, RegVar);
918
919     // Check if the first DBG_VALUE is valid for the rest of the function.
920     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
921       continue;
922
923     // Handle multiple DBG_VALUE instructions describing one variable.
924     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
925
926     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
927     DebugLocList &LocList = DotDebugLocEntries.back();
928     LocList.CU = &TheCU;
929     LocList.Label =
930         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
931
932     // Build the location list for this variable.
933     buildLocationList(LocList.List, Ranges);
934     // Finalize the entry by lowering it into a DWARF bytestream.
935     for (auto &Entry : LocList.List)
936       Entry.finalize(*Asm, TypeIdentifierMap);
937   }
938
939   // Collect info for variables that were optimized out.
940   DIArray Variables = SP.getVariables();
941   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
942     DIVariable DV(Variables.getElement(i));
943     assert(DV.isVariable());
944     if (!Processed.insert(DV).second)
945       continue;
946     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
947       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
948       DIExpression NoExpr;
949       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
950       InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
951     }
952   }
953 }
954
955 // Return Label preceding the instruction.
956 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
957   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
958   assert(Label && "Didn't insert label before instruction");
959   return Label;
960 }
961
962 // Return Label immediately following the instruction.
963 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
964   return LabelsAfterInsn.lookup(MI);
965 }
966
967 // Process beginning of an instruction.
968 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
969   assert(CurMI == nullptr);
970   CurMI = MI;
971   // Check if source location changes, but ignore DBG_VALUE locations.
972   if (!MI->isDebugValue()) {
973     DebugLoc DL = MI->getDebugLoc();
974     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
975       unsigned Flags = 0;
976       PrevInstLoc = DL;
977       if (DL == PrologEndLoc) {
978         Flags |= DWARF2_FLAG_PROLOGUE_END;
979         PrologEndLoc = DebugLoc();
980         Flags |= DWARF2_FLAG_IS_STMT;
981       }
982       if (DL.getLine() !=
983           Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
984         Flags |= DWARF2_FLAG_IS_STMT;
985
986       if (!DL.isUnknown()) {
987         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
988         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
989       } else
990         recordSourceLine(0, 0, nullptr, 0);
991     }
992   }
993
994   // Insert labels where requested.
995   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
996       LabelsBeforeInsn.find(MI);
997
998   // No label needed.
999   if (I == LabelsBeforeInsn.end())
1000     return;
1001
1002   // Label already assigned.
1003   if (I->second)
1004     return;
1005
1006   if (!PrevLabel) {
1007     PrevLabel = MMI->getContext().CreateTempSymbol();
1008     Asm->OutStreamer.EmitLabel(PrevLabel);
1009   }
1010   I->second = PrevLabel;
1011 }
1012
1013 // Process end of an instruction.
1014 void DwarfDebug::endInstruction() {
1015   assert(CurMI != nullptr);
1016   // Don't create a new label after DBG_VALUE instructions.
1017   // They don't generate code.
1018   if (!CurMI->isDebugValue())
1019     PrevLabel = nullptr;
1020
1021   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1022       LabelsAfterInsn.find(CurMI);
1023   CurMI = nullptr;
1024
1025   // No label needed.
1026   if (I == LabelsAfterInsn.end())
1027     return;
1028
1029   // Label already assigned.
1030   if (I->second)
1031     return;
1032
1033   // We need a label after this instruction.
1034   if (!PrevLabel) {
1035     PrevLabel = MMI->getContext().CreateTempSymbol();
1036     Asm->OutStreamer.EmitLabel(PrevLabel);
1037   }
1038   I->second = PrevLabel;
1039 }
1040
1041 // Each LexicalScope has first instruction and last instruction to mark
1042 // beginning and end of a scope respectively. Create an inverse map that list
1043 // scopes starts (and ends) with an instruction. One instruction may start (or
1044 // end) multiple scopes. Ignore scopes that are not reachable.
1045 void DwarfDebug::identifyScopeMarkers() {
1046   SmallVector<LexicalScope *, 4> WorkList;
1047   WorkList.push_back(LScopes.getCurrentFunctionScope());
1048   while (!WorkList.empty()) {
1049     LexicalScope *S = WorkList.pop_back_val();
1050
1051     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1052     if (!Children.empty())
1053       WorkList.append(Children.begin(), Children.end());
1054
1055     if (S->isAbstractScope())
1056       continue;
1057
1058     for (const InsnRange &R : S->getRanges()) {
1059       assert(R.first && "InsnRange does not have first instruction!");
1060       assert(R.second && "InsnRange does not have second instruction!");
1061       requestLabelBeforeInsn(R.first);
1062       requestLabelAfterInsn(R.second);
1063     }
1064   }
1065 }
1066
1067 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1068   // First known non-DBG_VALUE and non-frame setup location marks
1069   // the beginning of the function body.
1070   for (const auto &MBB : *MF)
1071     for (const auto &MI : MBB)
1072       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1073           !MI.getDebugLoc().isUnknown()) {
1074         // Did the target forget to set the FrameSetup flag for CFI insns?
1075         assert(!MI.isCFIInstruction() &&
1076                "First non-frame-setup instruction is a CFI instruction.");
1077         return MI.getDebugLoc();
1078       }
1079   return DebugLoc();
1080 }
1081
1082 // Gather pre-function debug information.  Assumes being called immediately
1083 // after the function entry point has been emitted.
1084 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1085   CurFn = MF;
1086
1087   // If there's no debug info for the function we're not going to do anything.
1088   if (!MMI->hasDebugInfo())
1089     return;
1090
1091   auto DI = FunctionDIs.find(MF->getFunction());
1092   if (DI == FunctionDIs.end())
1093     return;
1094
1095   // Grab the lexical scopes for the function, if we don't have any of those
1096   // then we're not going to be able to do anything.
1097   LScopes.initialize(*MF);
1098   if (LScopes.empty())
1099     return;
1100
1101   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1102
1103   // Make sure that each lexical scope will have a begin/end label.
1104   identifyScopeMarkers();
1105
1106   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1107   // belongs to so that we add to the correct per-cu line table in the
1108   // non-asm case.
1109   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1110   // FnScope->getScopeNode() and DI->second should represent the same function,
1111   // though they may not be the same MDNode due to inline functions merged in
1112   // LTO where the debug info metadata still differs (either due to distinct
1113   // written differences - two versions of a linkonce_odr function
1114   // written/copied into two separate files, or some sub-optimal metadata that
1115   // isn't structurally identical (see: file path/name info from clang, which
1116   // includes the directory of the cpp file being built, even when the file name
1117   // is absolute (such as an <> lookup header)))
1118   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1119   assert(TheCU && "Unable to find compile unit!");
1120   if (Asm->OutStreamer.hasRawTextSupport())
1121     // Use a single line table if we are generating assembly.
1122     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1123   else
1124     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1125
1126   // Calculate history for local variables.
1127   calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1128                            DbgValues);
1129
1130   // Request labels for the full history.
1131   for (const auto &I : DbgValues) {
1132     const auto &Ranges = I.second;
1133     if (Ranges.empty())
1134       continue;
1135
1136     // The first mention of a function argument gets the CurrentFnBegin
1137     // label, so arguments are visible when breaking at function entry.
1138     DIVariable DIVar(Ranges.front().first->getDebugVariable());
1139     if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1140         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1141       LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1142       if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1143         // Mark all non-overlapping initial pieces.
1144         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1145           DIExpression Piece = I->first->getDebugExpression();
1146           if (std::all_of(Ranges.begin(), I,
1147                           [&](DbgValueHistoryMap::InstrRange Pred) {
1148                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1149               }))
1150             LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1151           else
1152             break;
1153         }
1154       }
1155     }
1156
1157     for (const auto &Range : Ranges) {
1158       requestLabelBeforeInsn(Range.first);
1159       if (Range.second)
1160         requestLabelAfterInsn(Range.second);
1161     }
1162   }
1163
1164   PrevInstLoc = DebugLoc();
1165   PrevLabel = Asm->getFunctionBegin();
1166
1167   // Record beginning of function.
1168   PrologEndLoc = findPrologueEndLoc(MF);
1169   if (!PrologEndLoc.isUnknown()) {
1170     DebugLoc FnStartDL =
1171         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1172
1173     // We'd like to list the prologue as "not statements" but GDB behaves
1174     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1175     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1176                      FnStartDL.getScope(MF->getFunction()->getContext()),
1177                      DWARF2_FLAG_IS_STMT);
1178   }
1179 }
1180
1181 // Gather and emit post-function debug information.
1182 void DwarfDebug::endFunction(const MachineFunction *MF) {
1183   assert(CurFn == MF &&
1184       "endFunction should be called with the same function as beginFunction");
1185
1186   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1187       !FunctionDIs.count(MF->getFunction())) {
1188     // If we don't have a lexical scope for this function then there will
1189     // be a hole in the range information. Keep note of this by setting the
1190     // previously used section to nullptr.
1191     PrevCU = nullptr;
1192     CurFn = nullptr;
1193     return;
1194   }
1195
1196   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1197   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1198
1199   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1200   DISubprogram SP(FnScope->getScopeNode());
1201   DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1202
1203   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1204   collectVariableInfo(TheCU, SP, ProcessedVars);
1205
1206   // Add the range of this function to the list of ranges for the CU.
1207   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1208
1209   // Under -gmlt, skip building the subprogram if there are no inlined
1210   // subroutines inside it.
1211   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1212       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1213     assert(InfoHolder.getScopeVariables().empty());
1214     assert(DbgValues.empty());
1215     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1216     // by a -gmlt CU. Add a test and remove this assertion.
1217     assert(AbstractVariables.empty());
1218     LabelsBeforeInsn.clear();
1219     LabelsAfterInsn.clear();
1220     PrevLabel = nullptr;
1221     CurFn = nullptr;
1222     return;
1223   }
1224
1225 #ifndef NDEBUG
1226   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1227 #endif
1228   // Construct abstract scopes.
1229   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1230     DISubprogram SP(AScope->getScopeNode());
1231     assert(SP.isSubprogram());
1232     // Collect info for variables that were optimized out.
1233     DIArray Variables = SP.getVariables();
1234     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1235       DIVariable DV(Variables.getElement(i));
1236       assert(DV && DV.isVariable());
1237       if (!ProcessedVars.insert(DV).second)
1238         continue;
1239       ensureAbstractVariableIsCreated(DV, DV.getContext());
1240       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1241              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1242     }
1243     constructAbstractSubprogramScopeDIE(AScope);
1244   }
1245
1246   TheCU.constructSubprogramScopeDIE(FnScope);
1247   if (auto *SkelCU = TheCU.getSkeleton())
1248     if (!LScopes.getAbstractScopesList().empty())
1249       SkelCU->constructSubprogramScopeDIE(FnScope);
1250
1251   // Clear debug info
1252   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1253   // DbgVariables except those that are also in AbstractVariables (since they
1254   // can be used cross-function)
1255   InfoHolder.getScopeVariables().clear();
1256   DbgValues.clear();
1257   LabelsBeforeInsn.clear();
1258   LabelsAfterInsn.clear();
1259   PrevLabel = nullptr;
1260   CurFn = nullptr;
1261 }
1262
1263 // Register a source line with debug info. Returns the  unique label that was
1264 // emitted and which provides correspondence to the source line list.
1265 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1266                                   unsigned Flags) {
1267   StringRef Fn;
1268   StringRef Dir;
1269   unsigned Src = 1;
1270   unsigned Discriminator = 0;
1271   if (DIScope Scope = DIScope(S)) {
1272     assert(Scope.isScope());
1273     Fn = Scope.getFilename();
1274     Dir = Scope.getDirectory();
1275     if (Scope.isLexicalBlockFile())
1276       Discriminator = DILexicalBlockFile(S).getDiscriminator();
1277
1278     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1279     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1280               .getOrCreateSourceID(Fn, Dir);
1281   }
1282   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1283                                          Discriminator, Fn);
1284 }
1285
1286 //===----------------------------------------------------------------------===//
1287 // Emit Methods
1288 //===----------------------------------------------------------------------===//
1289
1290 // Emit the debug info section.
1291 void DwarfDebug::emitDebugInfo() {
1292   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1293   Holder.emitUnits(/* UseOffsets */ false);
1294 }
1295
1296 // Emit the abbreviation section.
1297 void DwarfDebug::emitAbbreviations() {
1298   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1299
1300   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1301 }
1302
1303 // Emit the last address of the section and the end of the line matrix.
1304 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1305   // Define last address of section.
1306   Asm->OutStreamer.AddComment("Extended Op");
1307   Asm->EmitInt8(0);
1308
1309   Asm->OutStreamer.AddComment("Op size");
1310   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1311   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1312   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1313
1314   Asm->OutStreamer.AddComment("Section end label");
1315
1316   Asm->OutStreamer.EmitSymbolValue(
1317       Asm->GetTempSymbol("section_end", SectionEnd),
1318       Asm->getDataLayout().getPointerSize());
1319
1320   // Mark end of matrix.
1321   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1322   Asm->EmitInt8(0);
1323   Asm->EmitInt8(1);
1324   Asm->EmitInt8(1);
1325 }
1326
1327 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1328                            StringRef TableName) {
1329   Accel.FinalizeTable(Asm, TableName);
1330   Asm->OutStreamer.SwitchSection(Section);
1331
1332   // Emit the full data.
1333   Accel.emit(Asm, Section->getBeginSymbol(), this);
1334 }
1335
1336 // Emit visible names into a hashed accelerator table section.
1337 void DwarfDebug::emitAccelNames() {
1338   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1339             "Names");
1340 }
1341
1342 // Emit objective C classes and categories into a hashed accelerator table
1343 // section.
1344 void DwarfDebug::emitAccelObjC() {
1345   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1346             "ObjC");
1347 }
1348
1349 // Emit namespace dies into a hashed accelerator table.
1350 void DwarfDebug::emitAccelNamespaces() {
1351   emitAccel(AccelNamespace,
1352             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1353             "namespac");
1354 }
1355
1356 // Emit type dies into a hashed accelerator table.
1357 void DwarfDebug::emitAccelTypes() {
1358   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1359             "types");
1360 }
1361
1362 // Public name handling.
1363 // The format for the various pubnames:
1364 //
1365 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1366 // for the DIE that is named.
1367 //
1368 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1369 // into the CU and the index value is computed according to the type of value
1370 // for the DIE that is named.
1371 //
1372 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1373 // it's the offset within the debug_info/debug_types dwo section, however, the
1374 // reference in the pubname header doesn't change.
1375
1376 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1377 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1378                                                         const DIE *Die) {
1379   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1380
1381   // We could have a specification DIE that has our most of our knowledge,
1382   // look for that now.
1383   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1384   if (SpecVal) {
1385     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1386     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1387       Linkage = dwarf::GIEL_EXTERNAL;
1388   } else if (Die->findAttribute(dwarf::DW_AT_external))
1389     Linkage = dwarf::GIEL_EXTERNAL;
1390
1391   switch (Die->getTag()) {
1392   case dwarf::DW_TAG_class_type:
1393   case dwarf::DW_TAG_structure_type:
1394   case dwarf::DW_TAG_union_type:
1395   case dwarf::DW_TAG_enumeration_type:
1396     return dwarf::PubIndexEntryDescriptor(
1397         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1398                               ? dwarf::GIEL_STATIC
1399                               : dwarf::GIEL_EXTERNAL);
1400   case dwarf::DW_TAG_typedef:
1401   case dwarf::DW_TAG_base_type:
1402   case dwarf::DW_TAG_subrange_type:
1403     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1404   case dwarf::DW_TAG_namespace:
1405     return dwarf::GIEK_TYPE;
1406   case dwarf::DW_TAG_subprogram:
1407     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1408   case dwarf::DW_TAG_variable:
1409     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1410   case dwarf::DW_TAG_enumerator:
1411     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1412                                           dwarf::GIEL_STATIC);
1413   default:
1414     return dwarf::GIEK_NONE;
1415   }
1416 }
1417
1418 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1419 ///
1420 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1421   const MCSection *PSec =
1422       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1423                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1424
1425   emitDebugPubSection(GnuStyle, PSec, "Names",
1426                       &DwarfCompileUnit::getGlobalNames);
1427 }
1428
1429 void DwarfDebug::emitDebugPubSection(
1430     bool GnuStyle, const MCSection *PSec, StringRef Name,
1431     const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1432   for (const auto &NU : CUMap) {
1433     DwarfCompileUnit *TheU = NU.second;
1434
1435     const auto &Globals = (TheU->*Accessor)();
1436
1437     if (Globals.empty())
1438       continue;
1439
1440     if (auto *Skeleton = TheU->getSkeleton())
1441       TheU = Skeleton;
1442     unsigned ID = TheU->getUniqueID();
1443
1444     // Start the dwarf pubnames section.
1445     Asm->OutStreamer.SwitchSection(PSec);
1446
1447     // Emit the header.
1448     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1449     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1450     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1451     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1452
1453     Asm->OutStreamer.EmitLabel(BeginLabel);
1454
1455     Asm->OutStreamer.AddComment("DWARF Version");
1456     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1457
1458     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1459     Asm->emitSectionOffset(TheU->getLabelBegin());
1460
1461     Asm->OutStreamer.AddComment("Compilation Unit Length");
1462     Asm->EmitInt32(TheU->getLength());
1463
1464     // Emit the pubnames for this compilation unit.
1465     for (const auto &GI : Globals) {
1466       const char *Name = GI.getKeyData();
1467       const DIE *Entity = GI.second;
1468
1469       Asm->OutStreamer.AddComment("DIE offset");
1470       Asm->EmitInt32(Entity->getOffset());
1471
1472       if (GnuStyle) {
1473         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1474         Asm->OutStreamer.AddComment(
1475             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1476             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1477         Asm->EmitInt8(Desc.toBits());
1478       }
1479
1480       Asm->OutStreamer.AddComment("External Name");
1481       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1482     }
1483
1484     Asm->OutStreamer.AddComment("End Mark");
1485     Asm->EmitInt32(0);
1486     Asm->OutStreamer.EmitLabel(EndLabel);
1487   }
1488 }
1489
1490 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1491   const MCSection *PSec =
1492       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1493                : Asm->getObjFileLowering().getDwarfPubTypesSection();
1494
1495   emitDebugPubSection(GnuStyle, PSec, "Types",
1496                       &DwarfCompileUnit::getGlobalTypes);
1497 }
1498
1499 // Emit visible names into a debug str section.
1500 void DwarfDebug::emitDebugStr() {
1501   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1502   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1503 }
1504
1505
1506 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1507                                    const DebugLocEntry &Entry) {
1508   auto Comment = Entry.getComments().begin();
1509   auto End = Entry.getComments().end();
1510   for (uint8_t Byte : Entry.getDWARFBytes())
1511     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1512 }
1513
1514 static void emitDebugLocValue(const AsmPrinter &AP,
1515                               const DITypeIdentifierMap &TypeIdentifierMap,
1516                               ByteStreamer &Streamer,
1517                               const DebugLocEntry::Value &Value,
1518                               unsigned PieceOffsetInBits) {
1519   DIVariable DV = Value.getVariable();
1520   DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1521                                     AP.getDwarfDebug()->getDwarfVersion(),
1522                                     Streamer);
1523   // Regular entry.
1524   if (Value.isInt()) {
1525     DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1526     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1527                          BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1528       DwarfExpr.AddSignedConstant(Value.getInt());
1529     else
1530       DwarfExpr.AddUnsignedConstant(Value.getInt());
1531   } else if (Value.isLocation()) {
1532     MachineLocation Loc = Value.getLoc();
1533     DIExpression Expr = Value.getExpression();
1534     if (!Expr || (Expr.getNumElements() == 0))
1535       // Regular entry.
1536       AP.EmitDwarfRegOp(Streamer, Loc);
1537     else {
1538       // Complex address entry.
1539       if (Loc.getOffset()) {
1540         DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1541         DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1542       } else
1543         DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1544                                           PieceOffsetInBits);
1545     }
1546   }
1547   // else ... ignore constant fp. There is not any good way to
1548   // to represent them here in dwarf.
1549   // FIXME: ^
1550 }
1551
1552
1553 void DebugLocEntry::finalize(const AsmPrinter &AP,
1554                              const DITypeIdentifierMap &TypeIdentifierMap) {
1555   BufferByteStreamer Streamer(DWARFBytes, Comments);
1556   const DebugLocEntry::Value Value = Values[0];
1557   if (Value.isBitPiece()) {
1558     // Emit all pieces that belong to the same variable and range.
1559     assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1560           return P.isBitPiece();
1561         }) && "all values are expected to be pieces");
1562     assert(std::is_sorted(Values.begin(), Values.end()) &&
1563            "pieces are expected to be sorted");
1564    
1565     unsigned Offset = 0;
1566     for (auto Piece : Values) {
1567       DIExpression Expr = Piece.getExpression();
1568       unsigned PieceOffset = Expr.getBitPieceOffset();
1569       unsigned PieceSize = Expr.getBitPieceSize();
1570       assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1571       if (Offset < PieceOffset) {
1572         // The DWARF spec seriously mandates pieces with no locations for gaps.
1573         DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1574                                      AP.getDwarfDebug()->getDwarfVersion(),
1575                                      Streamer);
1576         Expr.AddOpPiece(PieceOffset-Offset, 0);
1577         Offset += PieceOffset-Offset;
1578       }
1579       Offset += PieceSize;
1580    
1581 #ifndef NDEBUG
1582       DIVariable Var = Piece.getVariable();
1583       unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1584       assert(PieceSize+PieceOffset <= VarSize
1585              && "piece is larger than or outside of variable");
1586       assert(PieceSize != VarSize
1587              && "piece covers entire variable");
1588 #endif
1589       emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1590     }
1591   } else {
1592     assert(Values.size() == 1 && "only pieces may have >1 value");
1593     emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1594   }
1595 }
1596
1597
1598 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1599   Asm->OutStreamer.AddComment("Loc expr size");
1600   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1601   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1602   Asm->EmitLabelDifference(end, begin, 2);
1603   Asm->OutStreamer.EmitLabel(begin);
1604   // Emit the entry.
1605   APByteStreamer Streamer(*Asm);
1606   emitDebugLocEntry(Streamer, Entry);
1607   // Close the range.
1608   Asm->OutStreamer.EmitLabel(end);
1609 }
1610
1611 // Emit locations into the debug loc section.
1612 void DwarfDebug::emitDebugLoc() {
1613   // Start the dwarf loc section.
1614   Asm->OutStreamer.SwitchSection(
1615       Asm->getObjFileLowering().getDwarfLocSection());
1616   unsigned char Size = Asm->getDataLayout().getPointerSize();
1617   for (const auto &DebugLoc : DotDebugLocEntries) {
1618     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1619     const DwarfCompileUnit *CU = DebugLoc.CU;
1620     for (const auto &Entry : DebugLoc.List) {
1621       // Set up the range. This range is relative to the entry point of the
1622       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1623       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1624       if (auto *Base = CU->getBaseAddress()) {
1625         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1626         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1627       } else {
1628         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1629         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1630       }
1631
1632       emitDebugLocEntryLocation(Entry);
1633     }
1634     Asm->OutStreamer.EmitIntValue(0, Size);
1635     Asm->OutStreamer.EmitIntValue(0, Size);
1636   }
1637 }
1638
1639 void DwarfDebug::emitDebugLocDWO() {
1640   Asm->OutStreamer.SwitchSection(
1641       Asm->getObjFileLowering().getDwarfLocDWOSection());
1642   for (const auto &DebugLoc : DotDebugLocEntries) {
1643     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1644     for (const auto &Entry : DebugLoc.List) {
1645       // Just always use start_length for now - at least that's one address
1646       // rather than two. We could get fancier and try to, say, reuse an
1647       // address we know we've emitted elsewhere (the start of the function?
1648       // The start of the CU or CU subrange that encloses this range?)
1649       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1650       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1651       Asm->EmitULEB128(idx);
1652       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1653
1654       emitDebugLocEntryLocation(Entry);
1655     }
1656     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1657   }
1658 }
1659
1660 struct ArangeSpan {
1661   const MCSymbol *Start, *End;
1662 };
1663
1664 // Emit a debug aranges section, containing a CU lookup for any
1665 // address we can tie back to a CU.
1666 void DwarfDebug::emitDebugARanges() {
1667   // Provides a unique id per text section.
1668   MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1669
1670   // Filter labels by section.
1671   for (const SymbolCU &SCU : ArangeLabels) {
1672     if (SCU.Sym->isInSection()) {
1673       // Make a note of this symbol and it's section.
1674       const MCSection *Section = &SCU.Sym->getSection();
1675       if (!Section->getKind().isMetadata())
1676         SectionMap[Section].push_back(SCU);
1677     } else {
1678       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1679       // appear in the output. This sucks as we rely on sections to build
1680       // arange spans. We can do it without, but it's icky.
1681       SectionMap[nullptr].push_back(SCU);
1682     }
1683   }
1684
1685   // Add terminating symbols for each section.
1686   unsigned ID = 0;
1687   for (const auto &I : SectionMap) {
1688     const MCSection *Section = I.first;
1689     MCSymbol *Sym = nullptr;
1690
1691     if (Section) {
1692       // We can't call MCSection::getLabelEndName, as it's only safe to do so
1693       // if we know the section name up-front. For user-created sections, the
1694       // resulting label may not be valid to use as a label. (section names can
1695       // use a greater set of characters on some systems)
1696       Sym = Asm->GetTempSymbol("debug_end", ID);
1697       Asm->OutStreamer.SwitchSection(Section);
1698       Asm->OutStreamer.EmitLabel(Sym);
1699     }
1700
1701     // Insert a final terminator.
1702     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1703     ++ID;
1704   }
1705
1706   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1707
1708   for (auto &I : SectionMap) {
1709     const MCSection *Section = I.first;
1710     SmallVector<SymbolCU, 8> &List = I.second;
1711     if (List.size() < 2)
1712       continue;
1713
1714     // If we have no section (e.g. common), just write out
1715     // individual spans for each symbol.
1716     if (!Section) {
1717       for (const SymbolCU &Cur : List) {
1718         ArangeSpan Span;
1719         Span.Start = Cur.Sym;
1720         Span.End = nullptr;
1721         if (Cur.CU)
1722           Spans[Cur.CU].push_back(Span);
1723       }
1724       continue;
1725     }
1726
1727     // Sort the symbols by offset within the section.
1728     std::sort(List.begin(), List.end(),
1729               [&](const SymbolCU &A, const SymbolCU &B) {
1730       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1731       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1732
1733       // Symbols with no order assigned should be placed at the end.
1734       // (e.g. section end labels)
1735       if (IA == 0)
1736         return false;
1737       if (IB == 0)
1738         return true;
1739       return IA < IB;
1740     });
1741
1742     // Build spans between each label.
1743     const MCSymbol *StartSym = List[0].Sym;
1744     for (size_t n = 1, e = List.size(); n < e; n++) {
1745       const SymbolCU &Prev = List[n - 1];
1746       const SymbolCU &Cur = List[n];
1747
1748       // Try and build the longest span we can within the same CU.
1749       if (Cur.CU != Prev.CU) {
1750         ArangeSpan Span;
1751         Span.Start = StartSym;
1752         Span.End = Cur.Sym;
1753         Spans[Prev.CU].push_back(Span);
1754         StartSym = Cur.Sym;
1755       }
1756     }
1757   }
1758
1759   // Start the dwarf aranges section.
1760   Asm->OutStreamer.SwitchSection(
1761       Asm->getObjFileLowering().getDwarfARangesSection());
1762
1763   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1764
1765   // Build a list of CUs used.
1766   std::vector<DwarfCompileUnit *> CUs;
1767   for (const auto &it : Spans) {
1768     DwarfCompileUnit *CU = it.first;
1769     CUs.push_back(CU);
1770   }
1771
1772   // Sort the CU list (again, to ensure consistent output order).
1773   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1774     return A->getUniqueID() < B->getUniqueID();
1775   });
1776
1777   // Emit an arange table for each CU we used.
1778   for (DwarfCompileUnit *CU : CUs) {
1779     std::vector<ArangeSpan> &List = Spans[CU];
1780
1781     // Describe the skeleton CU's offset and length, not the dwo file's.
1782     if (auto *Skel = CU->getSkeleton())
1783       CU = Skel;
1784
1785     // Emit size of content not including length itself.
1786     unsigned ContentSize =
1787         sizeof(int16_t) + // DWARF ARange version number
1788         sizeof(int32_t) + // Offset of CU in the .debug_info section
1789         sizeof(int8_t) +  // Pointer Size (in bytes)
1790         sizeof(int8_t);   // Segment Size (in bytes)
1791
1792     unsigned TupleSize = PtrSize * 2;
1793
1794     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1795     unsigned Padding =
1796         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1797
1798     ContentSize += Padding;
1799     ContentSize += (List.size() + 1) * TupleSize;
1800
1801     // For each compile unit, write the list of spans it covers.
1802     Asm->OutStreamer.AddComment("Length of ARange Set");
1803     Asm->EmitInt32(ContentSize);
1804     Asm->OutStreamer.AddComment("DWARF Arange version number");
1805     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1806     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1807     Asm->emitSectionOffset(CU->getLabelBegin());
1808     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1809     Asm->EmitInt8(PtrSize);
1810     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1811     Asm->EmitInt8(0);
1812
1813     Asm->OutStreamer.EmitFill(Padding, 0xff);
1814
1815     for (const ArangeSpan &Span : List) {
1816       Asm->EmitLabelReference(Span.Start, PtrSize);
1817
1818       // Calculate the size as being from the span start to it's end.
1819       if (Span.End) {
1820         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1821       } else {
1822         // For symbols without an end marker (e.g. common), we
1823         // write a single arange entry containing just that one symbol.
1824         uint64_t Size = SymSize[Span.Start];
1825         if (Size == 0)
1826           Size = 1;
1827
1828         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1829       }
1830     }
1831
1832     Asm->OutStreamer.AddComment("ARange terminator");
1833     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1834     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1835   }
1836 }
1837
1838 // Emit visible names into a debug ranges section.
1839 void DwarfDebug::emitDebugRanges() {
1840   // Start the dwarf ranges section.
1841   Asm->OutStreamer.SwitchSection(
1842       Asm->getObjFileLowering().getDwarfRangesSection());
1843
1844   // Size for our labels.
1845   unsigned char Size = Asm->getDataLayout().getPointerSize();
1846
1847   // Grab the specific ranges for the compile units in the module.
1848   for (const auto &I : CUMap) {
1849     DwarfCompileUnit *TheCU = I.second;
1850
1851     if (auto *Skel = TheCU->getSkeleton())
1852       TheCU = Skel;
1853
1854     // Iterate over the misc ranges for the compile units in the module.
1855     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1856       // Emit our symbol so we can find the beginning of the range.
1857       Asm->OutStreamer.EmitLabel(List.getSym());
1858
1859       for (const RangeSpan &Range : List.getRanges()) {
1860         const MCSymbol *Begin = Range.getStart();
1861         const MCSymbol *End = Range.getEnd();
1862         assert(Begin && "Range without a begin symbol?");
1863         assert(End && "Range without an end symbol?");
1864         if (auto *Base = TheCU->getBaseAddress()) {
1865           Asm->EmitLabelDifference(Begin, Base, Size);
1866           Asm->EmitLabelDifference(End, Base, Size);
1867         } else {
1868           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1869           Asm->OutStreamer.EmitSymbolValue(End, Size);
1870         }
1871       }
1872
1873       // And terminate the list with two 0 values.
1874       Asm->OutStreamer.EmitIntValue(0, Size);
1875       Asm->OutStreamer.EmitIntValue(0, Size);
1876     }
1877   }
1878 }
1879
1880 // DWARF5 Experimental Separate Dwarf emitters.
1881
1882 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1883                                   std::unique_ptr<DwarfUnit> NewU) {
1884   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1885                   U.getCUNode().getSplitDebugFilename());
1886
1887   if (!CompilationDir.empty())
1888     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1889
1890   addGnuPubAttributes(*NewU, Die);
1891
1892   SkeletonHolder.addUnit(std::move(NewU));
1893 }
1894
1895 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1896 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1897 // DW_AT_addr_base, DW_AT_ranges_base.
1898 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1899
1900   auto OwnedUnit = make_unique<DwarfCompileUnit>(
1901       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1902   DwarfCompileUnit &NewCU = *OwnedUnit;
1903   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1904
1905   NewCU.initStmtList();
1906
1907   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1908
1909   return NewCU;
1910 }
1911
1912 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1913 // compile units that would normally be in debug_info.
1914 void DwarfDebug::emitDebugInfoDWO() {
1915   assert(useSplitDwarf() && "No split dwarf debug info?");
1916   // Don't emit relocations into the dwo file.
1917   InfoHolder.emitUnits(/* UseOffsets */ true);
1918 }
1919
1920 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1921 // abbreviations for the .debug_info.dwo section.
1922 void DwarfDebug::emitDebugAbbrevDWO() {
1923   assert(useSplitDwarf() && "No split dwarf?");
1924   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1925 }
1926
1927 void DwarfDebug::emitDebugLineDWO() {
1928   assert(useSplitDwarf() && "No split dwarf?");
1929   Asm->OutStreamer.SwitchSection(
1930       Asm->getObjFileLowering().getDwarfLineDWOSection());
1931   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1932 }
1933
1934 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1935 // string section and is identical in format to traditional .debug_str
1936 // sections.
1937 void DwarfDebug::emitDebugStrDWO() {
1938   assert(useSplitDwarf() && "No split dwarf?");
1939   const MCSection *OffSec =
1940       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1941   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1942                          OffSec);
1943 }
1944
1945 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1946   if (!useSplitDwarf())
1947     return nullptr;
1948   if (SingleCU)
1949     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1950   return &SplitTypeUnitFileTable;
1951 }
1952
1953 static uint64_t makeTypeSignature(StringRef Identifier) {
1954   MD5 Hash;
1955   Hash.update(Identifier);
1956   // ... take the least significant 8 bytes and return those. Our MD5
1957   // implementation always returns its results in little endian, swap bytes
1958   // appropriately.
1959   MD5::MD5Result Result;
1960   Hash.final(Result);
1961   return support::endian::read64le(Result + 8);
1962 }
1963
1964 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1965                                       StringRef Identifier, DIE &RefDie,
1966                                       DICompositeType CTy) {
1967   // Fast path if we're building some type units and one has already used the
1968   // address pool we know we're going to throw away all this work anyway, so
1969   // don't bother building dependent types.
1970   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1971     return;
1972
1973   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
1974   if (TU) {
1975     CU.addDIETypeSignature(RefDie, *TU);
1976     return;
1977   }
1978
1979   bool TopLevelType = TypeUnitsUnderConstruction.empty();
1980   AddrPool.resetUsedFlag();
1981
1982   auto OwnedUnit = make_unique<DwarfTypeUnit>(
1983       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
1984       this, &InfoHolder, getDwoLineTable(CU));
1985   DwarfTypeUnit &NewTU = *OwnedUnit;
1986   DIE &UnitDie = NewTU.getUnitDie();
1987   TU = &NewTU;
1988   TypeUnitsUnderConstruction.push_back(
1989       std::make_pair(std::move(OwnedUnit), CTy));
1990
1991   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1992                 CU.getLanguage());
1993
1994   uint64_t Signature = makeTypeSignature(Identifier);
1995   NewTU.setTypeSignature(Signature);
1996
1997   if (useSplitDwarf())
1998     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1999   else {
2000     CU.applyStmtList(UnitDie);
2001     NewTU.initSection(
2002         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2003   }
2004
2005   NewTU.setType(NewTU.createTypeDIE(CTy));
2006
2007   if (TopLevelType) {
2008     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2009     TypeUnitsUnderConstruction.clear();
2010
2011     // Types referencing entries in the address table cannot be placed in type
2012     // units.
2013     if (AddrPool.hasBeenUsed()) {
2014
2015       // Remove all the types built while building this type.
2016       // This is pessimistic as some of these types might not be dependent on
2017       // the type that used an address.
2018       for (const auto &TU : TypeUnitsToAdd)
2019         DwarfTypeUnits.erase(TU.second);
2020
2021       // Construct this type in the CU directly.
2022       // This is inefficient because all the dependent types will be rebuilt
2023       // from scratch, including building them in type units, discovering that
2024       // they depend on addresses, throwing them out and rebuilding them.
2025       CU.constructTypeDIE(RefDie, CTy);
2026       return;
2027     }
2028
2029     // If the type wasn't dependent on fission addresses, finish adding the type
2030     // and all its dependent types.
2031     for (auto &TU : TypeUnitsToAdd)
2032       InfoHolder.addUnit(std::move(TU.first));
2033   }
2034   CU.addDIETypeSignature(RefDie, NewTU);
2035 }
2036
2037 // Accelerator table mutators - add each name along with its companion
2038 // DIE to the proper table while ensuring that the name that we're going
2039 // to reference is in the string table. We do this since the names we
2040 // add may not only be identical to the names in the DIE.
2041 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2042   if (!useDwarfAccelTables())
2043     return;
2044   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2045                      &Die);
2046 }
2047
2048 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2049   if (!useDwarfAccelTables())
2050     return;
2051   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2052                     &Die);
2053 }
2054
2055 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2056   if (!useDwarfAccelTables())
2057     return;
2058   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2059                          &Die);
2060 }
2061
2062 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2063   if (!useDwarfAccelTables())
2064     return;
2065   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2066                      &Die);
2067 }