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