OSDN Git Service

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