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