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