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