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