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