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