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