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