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