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