DebugInfo: Gut DIObjCProperty and DIImportedEntity
[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.size(); i < N; ++i) {
178       DIDerivedType DT = cast<MDDerivedTypeBase>(Elements[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->getScope()))
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     for (auto *IE : CUNode->getImportedEntities())
449       ScopesWithImportedEntities.push_back(std::make_pair(IE->getScope(), IE));
450     // Stable sort to preserve the order of appearance of imported entities.
451     // This is to avoid out-of-order processing of interdependent declarations
452     // within the same scope, e.g. { namespace A = base; namespace B = A; }
453     std::stable_sort(ScopesWithImportedEntities.begin(),
454                      ScopesWithImportedEntities.end(), less_first());
455     for (auto *GV : CUNode->getGlobalVariables())
456       CU.getOrCreateGlobalVariableDIE(GV);
457     for (auto *SP : CUNode->getSubprograms())
458       SPMap.insert(std::make_pair(SP, &CU));
459     for (DIType Ty : CUNode->getEnumTypes()) {
460       // The enum types array by design contains pointers to
461       // MDNodes rather than DIRefs. Unique them here.
462       DIType UniqueTy = cast<MDType>(resolve(Ty.getRef()));
463       CU.getOrCreateTypeDIE(UniqueTy);
464     }
465     for (DIType Ty : CUNode->getRetainedTypes()) {
466       // The retained types array by design contains pointers to
467       // MDNodes rather than DIRefs. Unique them here.
468       DIType UniqueTy = cast<MDType>(resolve(Ty.getRef()));
469       CU.getOrCreateTypeDIE(UniqueTy);
470     }
471     // Emit imported_modules last so that the relevant context is already
472     // available.
473     for (auto *IE : CUNode->getImportedEntities())
474       constructAndAddImportedEntityDIE(CU, IE);
475   }
476
477   // Tell MMI that we have debug info.
478   MMI->setDebugInfoAvailability(true);
479 }
480
481 void DwarfDebug::finishVariableDefinitions() {
482   for (const auto &Var : ConcreteVariables) {
483     DIE *VariableDie = Var->getDIE();
484     assert(VariableDie);
485     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
486     // in the ConcreteVariables list, rather than looking it up again here.
487     // DIE::getUnit isn't simple - it walks parent pointers, etc.
488     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
489     assert(Unit);
490     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
491     if (AbsVar && AbsVar->getDIE()) {
492       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
493                         *AbsVar->getDIE());
494     } else
495       Unit->applyVariableAttributes(*Var, *VariableDie);
496   }
497 }
498
499 void DwarfDebug::finishSubprogramDefinitions() {
500   for (const auto &P : SPMap)
501     forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
502       CU.finishSubprogramDefinition(cast<MDSubprogram>(P.first));
503     });
504 }
505
506
507 // Collect info for variables that were optimized out.
508 void DwarfDebug::collectDeadVariables() {
509   const Module *M = MMI->getModule();
510
511   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
512     for (MDNode *N : CU_Nodes->operands()) {
513       DICompileUnit TheCU = cast<MDCompileUnit>(N);
514       // Construct subprogram DIE and add variables DIEs.
515       DwarfCompileUnit *SPCU =
516           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
517       assert(SPCU && "Unable to find Compile Unit!");
518       for (auto *SP : TheCU->getSubprograms()) {
519         if (ProcessedSPNodes.count(SP) != 0)
520           continue;
521         SPCU->collectDeadVariables(SP);
522       }
523     }
524   }
525 }
526
527 void DwarfDebug::finalizeModuleInfo() {
528   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
529
530   finishSubprogramDefinitions();
531
532   finishVariableDefinitions();
533
534   // Collect info for variables that were optimized out.
535   collectDeadVariables();
536
537   // Handle anything that needs to be done on a per-unit basis after
538   // all other generation.
539   for (const auto &P : CUMap) {
540     auto &TheCU = *P.second;
541     // Emit DW_AT_containing_type attribute to connect types with their
542     // vtable holding type.
543     TheCU.constructContainingTypeDIEs();
544
545     // Add CU specific attributes if we need to add any.
546     // If we're splitting the dwarf out now that we've got the entire
547     // CU then add the dwo id to it.
548     auto *SkCU = TheCU.getSkeleton();
549     if (useSplitDwarf()) {
550       // Emit a unique identifier for this CU.
551       uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
552       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
553                     dwarf::DW_FORM_data8, ID);
554       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
555                     dwarf::DW_FORM_data8, ID);
556
557       // We don't keep track of which addresses are used in which CU so this
558       // is a bit pessimistic under LTO.
559       if (!AddrPool.isEmpty()) {
560         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
561         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
562                               Sym, Sym);
563       }
564       if (!SkCU->getRangeLists().empty()) {
565         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
566         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
567                               Sym, Sym);
568       }
569     }
570
571     // If we have code split among multiple sections or non-contiguous
572     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
573     // remain in the .o file, otherwise add a DW_AT_low_pc.
574     // FIXME: We should use ranges allow reordering of code ala
575     // .subsections_via_symbols in mach-o. This would mean turning on
576     // ranges for all subprogram DIEs for mach-o.
577     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
578     if (unsigned NumRanges = TheCU.getRanges().size()) {
579       if (NumRanges > 1)
580         // A DW_AT_low_pc attribute may also be specified in combination with
581         // DW_AT_ranges to specify the default base address for use in
582         // location lists (see Section 2.6.2) and range lists (see Section
583         // 2.17.3).
584         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
585       else
586         TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
587       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
588     }
589   }
590
591   // Compute DIE offsets and sizes.
592   InfoHolder.computeSizeAndOffsets();
593   if (useSplitDwarf())
594     SkeletonHolder.computeSizeAndOffsets();
595 }
596
597 // Emit all Dwarf sections that should come after the content.
598 void DwarfDebug::endModule() {
599   assert(CurFn == nullptr);
600   assert(CurMI == nullptr);
601
602   // If we aren't actually generating debug info (check beginModule -
603   // conditionalized on !DisableDebugInfoPrinting and the presence of the
604   // llvm.dbg.cu metadata node)
605   if (!MMI->hasDebugInfo())
606     return;
607
608   // Finalize the debug info for the module.
609   finalizeModuleInfo();
610
611   emitDebugStr();
612
613   if (useSplitDwarf())
614     emitDebugLocDWO();
615   else
616     // Emit info into a debug loc section.
617     emitDebugLoc();
618
619   // Corresponding abbreviations into a abbrev section.
620   emitAbbreviations();
621
622   // Emit all the DIEs into a debug info section.
623   emitDebugInfo();
624
625   // Emit info into a debug aranges section.
626   if (GenerateARangeSection)
627     emitDebugARanges();
628
629   // Emit info into a debug ranges section.
630   emitDebugRanges();
631
632   if (useSplitDwarf()) {
633     emitDebugStrDWO();
634     emitDebugInfoDWO();
635     emitDebugAbbrevDWO();
636     emitDebugLineDWO();
637     // Emit DWO addresses.
638     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
639   }
640
641   // Emit info into the dwarf accelerator table sections.
642   if (useDwarfAccelTables()) {
643     emitAccelNames();
644     emitAccelObjC();
645     emitAccelNamespaces();
646     emitAccelTypes();
647   }
648
649   // Emit the pubnames and pubtypes sections if requested.
650   if (HasDwarfPubSections) {
651     emitDebugPubNames(GenerateGnuPubSections);
652     emitDebugPubTypes(GenerateGnuPubSections);
653   }
654
655   // clean up.
656   SPMap.clear();
657   AbstractVariables.clear();
658 }
659
660 // Find abstract variable, if any, associated with Var.
661 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
662                                                      DIVariable &Cleansed) {
663   LLVMContext &Ctx = DV->getContext();
664   // More then one inlined variable corresponds to one abstract variable.
665   // FIXME: This duplication of variables when inlining should probably be
666   // removed. It's done to allow each DIVariable to describe its location
667   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
668   // make it accurate then remove this duplication/cleansing stuff.
669   Cleansed = cleanseInlinedVariable(DV, Ctx);
670   auto I = AbstractVariables.find(Cleansed);
671   if (I != AbstractVariables.end())
672     return I->second.get();
673   return nullptr;
674 }
675
676 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
677   DIVariable Cleansed;
678   return getExistingAbstractVariable(DV, Cleansed);
679 }
680
681 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
682                                         LexicalScope *Scope) {
683   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
684   InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
685   AbstractVariables[Var] = std::move(AbsDbgVariable);
686 }
687
688 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
689                                                  const MDNode *ScopeNode) {
690   DIVariable Cleansed = DV;
691   if (getExistingAbstractVariable(DV, Cleansed))
692     return;
693
694   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
695                                        cast<MDLocalScope>(ScopeNode)));
696 }
697
698 void
699 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
700                                                     const MDNode *ScopeNode) {
701   DIVariable Cleansed = DV;
702   if (getExistingAbstractVariable(DV, Cleansed))
703     return;
704
705   if (LexicalScope *Scope =
706           LScopes.findAbstractScope(cast_or_null<MDLocalScope>(ScopeNode)))
707     createAbstractVariable(Cleansed, Scope);
708 }
709
710 // Collect variable information from side table maintained by MMI.
711 void DwarfDebug::collectVariableInfoFromMMITable(
712     SmallPtrSetImpl<const MDNode *> &Processed) {
713   for (const auto &VI : MMI->getVariableDbgInfo()) {
714     if (!VI.Var)
715       continue;
716     Processed.insert(VI.Var);
717     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
718
719     // If variable scope is not found then skip this variable.
720     if (!Scope)
721       continue;
722
723     DIVariable DV = cast<MDLocalVariable>(VI.Var);
724     assert(DV->isValidLocationForIntrinsic(VI.Loc) &&
725            "Expected inlined-at fields to agree");
726     DIExpression Expr = cast_or_null<MDExpression>(VI.Expr);
727     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
728     auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
729     if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
730       ConcreteVariables.push_back(std::move(RegVar));
731   }
732 }
733
734 // Get .debug_loc entry for the instruction range starting at MI.
735 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
736   const MDNode *Expr = MI->getDebugExpression();
737   const MDNode *Var = MI->getDebugVariable();
738
739   assert(MI->getNumOperands() == 4);
740   if (MI->getOperand(0).isReg()) {
741     MachineLocation MLoc;
742     // If the second operand is an immediate, this is a
743     // register-indirect address.
744     if (!MI->getOperand(1).isImm())
745       MLoc.set(MI->getOperand(0).getReg());
746     else
747       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
748     return DebugLocEntry::Value(Var, Expr, MLoc);
749   }
750   if (MI->getOperand(0).isImm())
751     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
752   if (MI->getOperand(0).isFPImm())
753     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
754   if (MI->getOperand(0).isCImm())
755     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
756
757   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
758 }
759
760 /// Determine whether two variable pieces overlap.
761 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
762   if (!P1->isBitPiece() || !P2->isBitPiece())
763     return true;
764   unsigned l1 = P1->getBitPieceOffset();
765   unsigned l2 = P2->getBitPieceOffset();
766   unsigned r1 = l1 + P1->getBitPieceSize();
767   unsigned r2 = l2 + P2->getBitPieceSize();
768   // True where [l1,r1[ and [r1,r2[ overlap.
769   return (l1 < r2) && (l2 < r1);
770 }
771
772 /// Build the location list for all DBG_VALUEs in the function that
773 /// describe the same variable.  If the ranges of several independent
774 /// pieces of the same variable overlap partially, split them up and
775 /// combine the ranges. The resulting DebugLocEntries are will have
776 /// strict monotonically increasing begin addresses and will never
777 /// overlap.
778 //
779 // Input:
780 //
781 //   Ranges History [var, loc, piece ofs size]
782 // 0 |      [x, (reg0, piece 0, 32)]
783 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
784 // 2 | |    ...
785 // 3   |    [clobber reg0]
786 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
787 //                                     x.
788 //
789 // Output:
790 //
791 // [0-1]    [x, (reg0, piece  0, 32)]
792 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
793 // [3-4]    [x, (reg1, piece 32, 32)]
794 // [4- ]    [x, (mem,  piece  0, 64)]
795 void
796 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
797                               const DbgValueHistoryMap::InstrRanges &Ranges) {
798   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
799
800   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
801     const MachineInstr *Begin = I->first;
802     const MachineInstr *End = I->second;
803     assert(Begin->isDebugValue() && "Invalid History entry");
804
805     // Check if a variable is inaccessible in this range.
806     if (Begin->getNumOperands() > 1 &&
807         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
808       OpenRanges.clear();
809       continue;
810     }
811
812     // If this piece overlaps with any open ranges, truncate them.
813     DIExpression DIExpr = Begin->getDebugExpression();
814     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
815                                [&](DebugLocEntry::Value R) {
816       return piecesOverlap(DIExpr, R.getExpression());
817     });
818     OpenRanges.erase(Last, OpenRanges.end());
819
820     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
821     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
822
823     const MCSymbol *EndLabel;
824     if (End != nullptr)
825       EndLabel = getLabelAfterInsn(End);
826     else if (std::next(I) == Ranges.end())
827       EndLabel = Asm->getFunctionEnd();
828     else
829       EndLabel = getLabelBeforeInsn(std::next(I)->first);
830     assert(EndLabel && "Forgot label after instruction ending a range!");
831
832     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
833
834     auto Value = getDebugLocValue(Begin);
835     DebugLocEntry Loc(StartLabel, EndLabel, Value);
836     bool couldMerge = false;
837
838     // If this is a piece, it may belong to the current DebugLocEntry.
839     if (DIExpr->isBitPiece()) {
840       // Add this value to the list of open ranges.
841       OpenRanges.push_back(Value);
842
843       // Attempt to add the piece to the last entry.
844       if (!DebugLoc.empty())
845         if (DebugLoc.back().MergeValues(Loc))
846           couldMerge = true;
847     }
848
849     if (!couldMerge) {
850       // Need to add a new DebugLocEntry. Add all values from still
851       // valid non-overlapping pieces.
852       if (OpenRanges.size())
853         Loc.addValues(OpenRanges);
854
855       DebugLoc.push_back(std::move(Loc));
856     }
857
858     // Attempt to coalesce the ranges of two otherwise identical
859     // DebugLocEntries.
860     auto CurEntry = DebugLoc.rbegin();
861     auto PrevEntry = std::next(CurEntry);
862     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
863       DebugLoc.pop_back();
864
865     DEBUG({
866       dbgs() << CurEntry->getValues().size() << " Values:\n";
867       for (auto Value : CurEntry->getValues()) {
868         Value.getVariable()->dump();
869         Value.getExpression()->dump();
870       }
871       dbgs() << "-----\n";
872     });
873   }
874 }
875
876
877 // Find variables for each lexical scope.
878 void
879 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
880                                 SmallPtrSetImpl<const MDNode *> &Processed) {
881   // Grab the variable info that was squirreled away in the MMI side-table.
882   collectVariableInfoFromMMITable(Processed);
883
884   for (const auto &I : DbgValues) {
885     DIVariable DV = cast<MDLocalVariable>(I.first);
886     if (Processed.count(DV))
887       continue;
888
889     // Instruction ranges, specifying where DV is accessible.
890     const auto &Ranges = I.second;
891     if (Ranges.empty())
892       continue;
893
894     LexicalScope *Scope = nullptr;
895     if (MDLocation *IA = DV.get()->getInlinedAt())
896       Scope = LScopes.findInlinedScope(DV.get()->getScope(), IA);
897     else
898       Scope = LScopes.findLexicalScope(DV.get()->getScope());
899     // If variable scope is not found then skip this variable.
900     if (!Scope)
901       continue;
902
903     Processed.insert(DV);
904     const MachineInstr *MInsn = Ranges.front().first;
905     assert(MInsn->isDebugValue() && "History must begin with debug value");
906     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
907     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
908     DbgVariable *RegVar = ConcreteVariables.back().get();
909     InfoHolder.addScopeVariable(Scope, RegVar);
910
911     // Check if the first DBG_VALUE is valid for the rest of the function.
912     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
913       continue;
914
915     // Handle multiple DBG_VALUE instructions describing one variable.
916     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
917
918     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
919     DebugLocList &LocList = DotDebugLocEntries.back();
920     LocList.CU = &TheCU;
921     LocList.Label = Asm->createTempSymbol("debug_loc");
922
923     // Build the location list for this variable.
924     buildLocationList(LocList.List, Ranges);
925     // Finalize the entry by lowering it into a DWARF bytestream.
926     for (auto &Entry : LocList.List)
927       Entry.finalize(*Asm, TypeIdentifierMap);
928   }
929
930   // Collect info for variables that were optimized out.
931   for (DIVariable DV : SP->getVariables()) {
932     if (!Processed.insert(DV).second)
933       continue;
934     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.get()->getScope())) {
935       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
936       DIExpression NoExpr;
937       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
938       InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
939     }
940   }
941 }
942
943 // Return Label preceding the instruction.
944 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
945   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
946   assert(Label && "Didn't insert label before instruction");
947   return Label;
948 }
949
950 // Return Label immediately following the instruction.
951 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
952   return LabelsAfterInsn.lookup(MI);
953 }
954
955 // Process beginning of an instruction.
956 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
957   assert(CurMI == nullptr);
958   CurMI = MI;
959   // Check if source location changes, but ignore DBG_VALUE locations.
960   if (!MI->isDebugValue()) {
961     DebugLoc DL = MI->getDebugLoc();
962     if (DL != PrevInstLoc) {
963       if (DL) {
964         unsigned Flags = 0;
965         PrevInstLoc = DL;
966         if (DL == PrologEndLoc) {
967           Flags |= DWARF2_FLAG_PROLOGUE_END;
968           PrologEndLoc = DebugLoc();
969           Flags |= DWARF2_FLAG_IS_STMT;
970         }
971         if (DL.getLine() !=
972             Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
973           Flags |= DWARF2_FLAG_IS_STMT;
974
975         const MDNode *Scope = DL.getScope();
976         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
977       } else if (UnknownLocations) {
978         PrevInstLoc = DL;
979         recordSourceLine(0, 0, nullptr, 0);
980       }
981     }
982   }
983
984   // Insert labels where requested.
985   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
986       LabelsBeforeInsn.find(MI);
987
988   // No label needed.
989   if (I == LabelsBeforeInsn.end())
990     return;
991
992   // Label already assigned.
993   if (I->second)
994     return;
995
996   if (!PrevLabel) {
997     PrevLabel = MMI->getContext().CreateTempSymbol();
998     Asm->OutStreamer.EmitLabel(PrevLabel);
999   }
1000   I->second = PrevLabel;
1001 }
1002
1003 // Process end of an instruction.
1004 void DwarfDebug::endInstruction() {
1005   assert(CurMI != nullptr);
1006   // Don't create a new label after DBG_VALUE instructions.
1007   // They don't generate code.
1008   if (!CurMI->isDebugValue())
1009     PrevLabel = nullptr;
1010
1011   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1012       LabelsAfterInsn.find(CurMI);
1013   CurMI = nullptr;
1014
1015   // No label needed.
1016   if (I == LabelsAfterInsn.end())
1017     return;
1018
1019   // Label already assigned.
1020   if (I->second)
1021     return;
1022
1023   // We need a label after this instruction.
1024   if (!PrevLabel) {
1025     PrevLabel = MMI->getContext().CreateTempSymbol();
1026     Asm->OutStreamer.EmitLabel(PrevLabel);
1027   }
1028   I->second = PrevLabel;
1029 }
1030
1031 // Each LexicalScope has first instruction and last instruction to mark
1032 // beginning and end of a scope respectively. Create an inverse map that list
1033 // scopes starts (and ends) with an instruction. One instruction may start (or
1034 // end) multiple scopes. Ignore scopes that are not reachable.
1035 void DwarfDebug::identifyScopeMarkers() {
1036   SmallVector<LexicalScope *, 4> WorkList;
1037   WorkList.push_back(LScopes.getCurrentFunctionScope());
1038   while (!WorkList.empty()) {
1039     LexicalScope *S = WorkList.pop_back_val();
1040
1041     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1042     if (!Children.empty())
1043       WorkList.append(Children.begin(), Children.end());
1044
1045     if (S->isAbstractScope())
1046       continue;
1047
1048     for (const InsnRange &R : S->getRanges()) {
1049       assert(R.first && "InsnRange does not have first instruction!");
1050       assert(R.second && "InsnRange does not have second instruction!");
1051       requestLabelBeforeInsn(R.first);
1052       requestLabelAfterInsn(R.second);
1053     }
1054   }
1055 }
1056
1057 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1058   // First known non-DBG_VALUE and non-frame setup location marks
1059   // the beginning of the function body.
1060   for (const auto &MBB : *MF)
1061     for (const auto &MI : MBB)
1062       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1063           MI.getDebugLoc()) {
1064         // Did the target forget to set the FrameSetup flag for CFI insns?
1065         assert(!MI.isCFIInstruction() &&
1066                "First non-frame-setup instruction is a CFI instruction.");
1067         return MI.getDebugLoc();
1068       }
1069   return DebugLoc();
1070 }
1071
1072 // Gather pre-function debug information.  Assumes being called immediately
1073 // after the function entry point has been emitted.
1074 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1075   CurFn = MF;
1076
1077   // If there's no debug info for the function we're not going to do anything.
1078   if (!MMI->hasDebugInfo())
1079     return;
1080
1081   auto DI = FunctionDIs.find(MF->getFunction());
1082   if (DI == FunctionDIs.end())
1083     return;
1084
1085   // Grab the lexical scopes for the function, if we don't have any of those
1086   // then we're not going to be able to do anything.
1087   LScopes.initialize(*MF);
1088   if (LScopes.empty())
1089     return;
1090
1091   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1092
1093   // Make sure that each lexical scope will have a begin/end label.
1094   identifyScopeMarkers();
1095
1096   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1097   // belongs to so that we add to the correct per-cu line table in the
1098   // non-asm case.
1099   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1100   // FnScope->getScopeNode() and DI->second should represent the same function,
1101   // though they may not be the same MDNode due to inline functions merged in
1102   // LTO where the debug info metadata still differs (either due to distinct
1103   // written differences - two versions of a linkonce_odr function
1104   // written/copied into two separate files, or some sub-optimal metadata that
1105   // isn't structurally identical (see: file path/name info from clang, which
1106   // includes the directory of the cpp file being built, even when the file name
1107   // is absolute (such as an <> lookup header)))
1108   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1109   assert(TheCU && "Unable to find compile unit!");
1110   if (Asm->OutStreamer.hasRawTextSupport())
1111     // Use a single line table if we are generating assembly.
1112     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1113   else
1114     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1115
1116   // Calculate history for local variables.
1117   calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1118                            DbgValues);
1119
1120   // Request labels for the full history.
1121   for (const auto &I : DbgValues) {
1122     const auto &Ranges = I.second;
1123     if (Ranges.empty())
1124       continue;
1125
1126     // The first mention of a function argument gets the CurrentFnBegin
1127     // label, so arguments are visible when breaking at function entry.
1128     DIVariable DIVar = Ranges.front().first->getDebugVariable();
1129     if (DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1130         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1131       LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1132       if (Ranges.front().first->getDebugExpression()->isBitPiece()) {
1133         // Mark all non-overlapping initial pieces.
1134         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1135           DIExpression Piece = I->first->getDebugExpression();
1136           if (std::all_of(Ranges.begin(), I,
1137                           [&](DbgValueHistoryMap::InstrRange Pred) {
1138                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1139               }))
1140             LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1141           else
1142             break;
1143         }
1144       }
1145     }
1146
1147     for (const auto &Range : Ranges) {
1148       requestLabelBeforeInsn(Range.first);
1149       if (Range.second)
1150         requestLabelAfterInsn(Range.second);
1151     }
1152   }
1153
1154   PrevInstLoc = DebugLoc();
1155   PrevLabel = Asm->getFunctionBegin();
1156
1157   // Record beginning of function.
1158   PrologEndLoc = findPrologueEndLoc(MF);
1159   if (MDLocation *L = PrologEndLoc) {
1160     // We'd like to list the prologue as "not statements" but GDB behaves
1161     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1162     auto *SP = L->getInlinedAtScope()->getSubprogram();
1163     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1164   }
1165 }
1166
1167 // Gather and emit post-function debug information.
1168 void DwarfDebug::endFunction(const MachineFunction *MF) {
1169   assert(CurFn == MF &&
1170       "endFunction should be called with the same function as beginFunction");
1171
1172   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1173       !FunctionDIs.count(MF->getFunction())) {
1174     // If we don't have a lexical scope for this function then there will
1175     // be a hole in the range information. Keep note of this by setting the
1176     // previously used section to nullptr.
1177     PrevCU = nullptr;
1178     CurFn = nullptr;
1179     return;
1180   }
1181
1182   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1183   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1184
1185   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1186   DISubprogram SP = cast<MDSubprogram>(FnScope->getScopeNode());
1187   DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1188
1189   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1190   collectVariableInfo(TheCU, SP, ProcessedVars);
1191
1192   // Add the range of this function to the list of ranges for the CU.
1193   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1194
1195   // Under -gmlt, skip building the subprogram if there are no inlined
1196   // subroutines inside it.
1197   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1198       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1199     assert(InfoHolder.getScopeVariables().empty());
1200     assert(DbgValues.empty());
1201     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1202     // by a -gmlt CU. Add a test and remove this assertion.
1203     assert(AbstractVariables.empty());
1204     LabelsBeforeInsn.clear();
1205     LabelsAfterInsn.clear();
1206     PrevLabel = nullptr;
1207     CurFn = nullptr;
1208     return;
1209   }
1210
1211 #ifndef NDEBUG
1212   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1213 #endif
1214   // Construct abstract scopes.
1215   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1216     DISubprogram SP = cast<MDSubprogram>(AScope->getScopeNode());
1217     // Collect info for variables that were optimized out.
1218     for (DIVariable DV : SP->getVariables()) {
1219       if (!ProcessedVars.insert(DV).second)
1220         continue;
1221       ensureAbstractVariableIsCreated(DV, DV.getContext());
1222       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1223              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1224     }
1225     constructAbstractSubprogramScopeDIE(AScope);
1226   }
1227
1228   TheCU.constructSubprogramScopeDIE(FnScope);
1229   if (auto *SkelCU = TheCU.getSkeleton())
1230     if (!LScopes.getAbstractScopesList().empty())
1231       SkelCU->constructSubprogramScopeDIE(FnScope);
1232
1233   // Clear debug info
1234   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1235   // DbgVariables except those that are also in AbstractVariables (since they
1236   // can be used cross-function)
1237   InfoHolder.getScopeVariables().clear();
1238   DbgValues.clear();
1239   LabelsBeforeInsn.clear();
1240   LabelsAfterInsn.clear();
1241   PrevLabel = nullptr;
1242   CurFn = nullptr;
1243 }
1244
1245 // Register a source line with debug info. Returns the  unique label that was
1246 // emitted and which provides correspondence to the source line list.
1247 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1248                                   unsigned Flags) {
1249   StringRef Fn;
1250   StringRef Dir;
1251   unsigned Src = 1;
1252   unsigned Discriminator = 0;
1253   if (DIScope Scope = cast_or_null<MDScope>(S)) {
1254     Fn = Scope.getFilename();
1255     Dir = Scope.getDirectory();
1256     if (DILexicalBlockFile LBF = dyn_cast<MDLexicalBlockFile>(Scope))
1257       Discriminator = LBF.getDiscriminator();
1258
1259     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1260     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1261               .getOrCreateSourceID(Fn, Dir);
1262   }
1263   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1264                                          Discriminator, Fn);
1265 }
1266
1267 //===----------------------------------------------------------------------===//
1268 // Emit Methods
1269 //===----------------------------------------------------------------------===//
1270
1271 // Emit the debug info section.
1272 void DwarfDebug::emitDebugInfo() {
1273   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1274   Holder.emitUnits(/* UseOffsets */ false);
1275 }
1276
1277 // Emit the abbreviation section.
1278 void DwarfDebug::emitAbbreviations() {
1279   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1280
1281   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1282 }
1283
1284 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1285                            StringRef TableName) {
1286   Accel.FinalizeTable(Asm, TableName);
1287   Asm->OutStreamer.SwitchSection(Section);
1288
1289   // Emit the full data.
1290   Accel.emit(Asm, Section->getBeginSymbol(), this);
1291 }
1292
1293 // Emit visible names into a hashed accelerator table section.
1294 void DwarfDebug::emitAccelNames() {
1295   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1296             "Names");
1297 }
1298
1299 // Emit objective C classes and categories into a hashed accelerator table
1300 // section.
1301 void DwarfDebug::emitAccelObjC() {
1302   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1303             "ObjC");
1304 }
1305
1306 // Emit namespace dies into a hashed accelerator table.
1307 void DwarfDebug::emitAccelNamespaces() {
1308   emitAccel(AccelNamespace,
1309             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1310             "namespac");
1311 }
1312
1313 // Emit type dies into a hashed accelerator table.
1314 void DwarfDebug::emitAccelTypes() {
1315   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1316             "types");
1317 }
1318
1319 // Public name handling.
1320 // The format for the various pubnames:
1321 //
1322 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1323 // for the DIE that is named.
1324 //
1325 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1326 // into the CU and the index value is computed according to the type of value
1327 // for the DIE that is named.
1328 //
1329 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1330 // it's the offset within the debug_info/debug_types dwo section, however, the
1331 // reference in the pubname header doesn't change.
1332
1333 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1334 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1335                                                         const DIE *Die) {
1336   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1337
1338   // We could have a specification DIE that has our most of our knowledge,
1339   // look for that now.
1340   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1341   if (SpecVal) {
1342     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1343     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1344       Linkage = dwarf::GIEL_EXTERNAL;
1345   } else if (Die->findAttribute(dwarf::DW_AT_external))
1346     Linkage = dwarf::GIEL_EXTERNAL;
1347
1348   switch (Die->getTag()) {
1349   case dwarf::DW_TAG_class_type:
1350   case dwarf::DW_TAG_structure_type:
1351   case dwarf::DW_TAG_union_type:
1352   case dwarf::DW_TAG_enumeration_type:
1353     return dwarf::PubIndexEntryDescriptor(
1354         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1355                               ? dwarf::GIEL_STATIC
1356                               : dwarf::GIEL_EXTERNAL);
1357   case dwarf::DW_TAG_typedef:
1358   case dwarf::DW_TAG_base_type:
1359   case dwarf::DW_TAG_subrange_type:
1360     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1361   case dwarf::DW_TAG_namespace:
1362     return dwarf::GIEK_TYPE;
1363   case dwarf::DW_TAG_subprogram:
1364     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1365   case dwarf::DW_TAG_variable:
1366     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1367   case dwarf::DW_TAG_enumerator:
1368     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1369                                           dwarf::GIEL_STATIC);
1370   default:
1371     return dwarf::GIEK_NONE;
1372   }
1373 }
1374
1375 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1376 ///
1377 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1378   const MCSection *PSec =
1379       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1380                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1381
1382   emitDebugPubSection(GnuStyle, PSec, "Names",
1383                       &DwarfCompileUnit::getGlobalNames);
1384 }
1385
1386 void DwarfDebug::emitDebugPubSection(
1387     bool GnuStyle, const MCSection *PSec, StringRef Name,
1388     const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1389   for (const auto &NU : CUMap) {
1390     DwarfCompileUnit *TheU = NU.second;
1391
1392     const auto &Globals = (TheU->*Accessor)();
1393
1394     if (Globals.empty())
1395       continue;
1396
1397     if (auto *Skeleton = TheU->getSkeleton())
1398       TheU = Skeleton;
1399
1400     // Start the dwarf pubnames section.
1401     Asm->OutStreamer.SwitchSection(PSec);
1402
1403     // Emit the header.
1404     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1405     MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1406     MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1407     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1408
1409     Asm->OutStreamer.EmitLabel(BeginLabel);
1410
1411     Asm->OutStreamer.AddComment("DWARF Version");
1412     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1413
1414     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1415     Asm->emitSectionOffset(TheU->getLabelBegin());
1416
1417     Asm->OutStreamer.AddComment("Compilation Unit Length");
1418     Asm->EmitInt32(TheU->getLength());
1419
1420     // Emit the pubnames for this compilation unit.
1421     for (const auto &GI : Globals) {
1422       const char *Name = GI.getKeyData();
1423       const DIE *Entity = GI.second;
1424
1425       Asm->OutStreamer.AddComment("DIE offset");
1426       Asm->EmitInt32(Entity->getOffset());
1427
1428       if (GnuStyle) {
1429         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1430         Asm->OutStreamer.AddComment(
1431             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1432             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1433         Asm->EmitInt8(Desc.toBits());
1434       }
1435
1436       Asm->OutStreamer.AddComment("External Name");
1437       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1438     }
1439
1440     Asm->OutStreamer.AddComment("End Mark");
1441     Asm->EmitInt32(0);
1442     Asm->OutStreamer.EmitLabel(EndLabel);
1443   }
1444 }
1445
1446 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1447   const MCSection *PSec =
1448       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1449                : Asm->getObjFileLowering().getDwarfPubTypesSection();
1450
1451   emitDebugPubSection(GnuStyle, PSec, "Types",
1452                       &DwarfCompileUnit::getGlobalTypes);
1453 }
1454
1455 // Emit visible names into a debug str section.
1456 void DwarfDebug::emitDebugStr() {
1457   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1458   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1459 }
1460
1461
1462 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1463                                    const DebugLocEntry &Entry) {
1464   auto Comment = Entry.getComments().begin();
1465   auto End = Entry.getComments().end();
1466   for (uint8_t Byte : Entry.getDWARFBytes())
1467     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1468 }
1469
1470 static void emitDebugLocValue(const AsmPrinter &AP,
1471                               const DITypeIdentifierMap &TypeIdentifierMap,
1472                               ByteStreamer &Streamer,
1473                               const DebugLocEntry::Value &Value,
1474                               unsigned PieceOffsetInBits) {
1475   DIVariable DV = Value.getVariable();
1476   DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1477                                     AP.getDwarfDebug()->getDwarfVersion(),
1478                                     Streamer);
1479   // Regular entry.
1480   if (Value.isInt()) {
1481     MDType *T = DV.getType().resolve(TypeIdentifierMap);
1482     auto *B = dyn_cast<MDBasicType>(T);
1483     if (B && (B->getEncoding() == dwarf::DW_ATE_signed ||
1484               B->getEncoding() == dwarf::DW_ATE_signed_char))
1485       DwarfExpr.AddSignedConstant(Value.getInt());
1486     else
1487       DwarfExpr.AddUnsignedConstant(Value.getInt());
1488   } else if (Value.isLocation()) {
1489     MachineLocation Loc = Value.getLoc();
1490     DIExpression Expr = Value.getExpression();
1491     if (!Expr || !Expr->getNumElements())
1492       // Regular entry.
1493       AP.EmitDwarfRegOp(Streamer, Loc);
1494     else {
1495       // Complex address entry.
1496       if (Loc.getOffset()) {
1497         DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1498         DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(),
1499                                 PieceOffsetInBits);
1500       } else
1501         DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1502                                           PieceOffsetInBits);
1503     }
1504   }
1505   // else ... ignore constant fp. There is not any good way to
1506   // to represent them here in dwarf.
1507   // FIXME: ^
1508 }
1509
1510
1511 void DebugLocEntry::finalize(const AsmPrinter &AP,
1512                              const DITypeIdentifierMap &TypeIdentifierMap) {
1513   BufferByteStreamer Streamer(DWARFBytes, Comments);
1514   const DebugLocEntry::Value Value = Values[0];
1515   if (Value.isBitPiece()) {
1516     // Emit all pieces that belong to the same variable and range.
1517     assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1518           return P.isBitPiece();
1519         }) && "all values are expected to be pieces");
1520     assert(std::is_sorted(Values.begin(), Values.end()) &&
1521            "pieces are expected to be sorted");
1522    
1523     unsigned Offset = 0;
1524     for (auto Piece : Values) {
1525       DIExpression Expr = Piece.getExpression();
1526       unsigned PieceOffset = Expr->getBitPieceOffset();
1527       unsigned PieceSize = Expr->getBitPieceSize();
1528       assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1529       if (Offset < PieceOffset) {
1530         // The DWARF spec seriously mandates pieces with no locations for gaps.
1531         DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1532                                      AP.getDwarfDebug()->getDwarfVersion(),
1533                                      Streamer);
1534         Expr.AddOpPiece(PieceOffset-Offset, 0);
1535         Offset += PieceOffset-Offset;
1536       }
1537       Offset += PieceSize;
1538
1539       emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1540     }
1541   } else {
1542     assert(Values.size() == 1 && "only pieces may have >1 value");
1543     emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1544   }
1545 }
1546
1547
1548 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1549   Asm->OutStreamer.AddComment("Loc expr size");
1550   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1551   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1552   Asm->EmitLabelDifference(end, begin, 2);
1553   Asm->OutStreamer.EmitLabel(begin);
1554   // Emit the entry.
1555   APByteStreamer Streamer(*Asm);
1556   emitDebugLocEntry(Streamer, Entry);
1557   // Close the range.
1558   Asm->OutStreamer.EmitLabel(end);
1559 }
1560
1561 // Emit locations into the debug loc section.
1562 void DwarfDebug::emitDebugLoc() {
1563   // Start the dwarf loc section.
1564   Asm->OutStreamer.SwitchSection(
1565       Asm->getObjFileLowering().getDwarfLocSection());
1566   unsigned char Size = Asm->getDataLayout().getPointerSize();
1567   for (const auto &DebugLoc : DotDebugLocEntries) {
1568     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1569     const DwarfCompileUnit *CU = DebugLoc.CU;
1570     for (const auto &Entry : DebugLoc.List) {
1571       // Set up the range. This range is relative to the entry point of the
1572       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1573       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1574       if (auto *Base = CU->getBaseAddress()) {
1575         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1576         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1577       } else {
1578         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1579         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1580       }
1581
1582       emitDebugLocEntryLocation(Entry);
1583     }
1584     Asm->OutStreamer.EmitIntValue(0, Size);
1585     Asm->OutStreamer.EmitIntValue(0, Size);
1586   }
1587 }
1588
1589 void DwarfDebug::emitDebugLocDWO() {
1590   Asm->OutStreamer.SwitchSection(
1591       Asm->getObjFileLowering().getDwarfLocDWOSection());
1592   for (const auto &DebugLoc : DotDebugLocEntries) {
1593     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1594     for (const auto &Entry : DebugLoc.List) {
1595       // Just always use start_length for now - at least that's one address
1596       // rather than two. We could get fancier and try to, say, reuse an
1597       // address we know we've emitted elsewhere (the start of the function?
1598       // The start of the CU or CU subrange that encloses this range?)
1599       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1600       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1601       Asm->EmitULEB128(idx);
1602       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1603
1604       emitDebugLocEntryLocation(Entry);
1605     }
1606     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1607   }
1608 }
1609
1610 struct ArangeSpan {
1611   const MCSymbol *Start, *End;
1612 };
1613
1614 // Emit a debug aranges section, containing a CU lookup for any
1615 // address we can tie back to a CU.
1616 void DwarfDebug::emitDebugARanges() {
1617   // Provides a unique id per text section.
1618   MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1619
1620   // Filter labels by section.
1621   for (const SymbolCU &SCU : ArangeLabels) {
1622     if (SCU.Sym->isInSection()) {
1623       // Make a note of this symbol and it's section.
1624       const MCSection *Section = &SCU.Sym->getSection();
1625       if (!Section->getKind().isMetadata())
1626         SectionMap[Section].push_back(SCU);
1627     } else {
1628       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1629       // appear in the output. This sucks as we rely on sections to build
1630       // arange spans. We can do it without, but it's icky.
1631       SectionMap[nullptr].push_back(SCU);
1632     }
1633   }
1634
1635   // Add terminating symbols for each section.
1636   for (const auto &I : SectionMap) {
1637     const MCSection *Section = I.first;
1638     MCSymbol *Sym = nullptr;
1639
1640     if (Section)
1641       Sym = Asm->OutStreamer.endSection(Section);
1642
1643     // Insert a final terminator.
1644     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1645   }
1646
1647   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1648
1649   for (auto &I : SectionMap) {
1650     const MCSection *Section = I.first;
1651     SmallVector<SymbolCU, 8> &List = I.second;
1652     if (List.size() < 2)
1653       continue;
1654
1655     // If we have no section (e.g. common), just write out
1656     // individual spans for each symbol.
1657     if (!Section) {
1658       for (const SymbolCU &Cur : List) {
1659         ArangeSpan Span;
1660         Span.Start = Cur.Sym;
1661         Span.End = nullptr;
1662         if (Cur.CU)
1663           Spans[Cur.CU].push_back(Span);
1664       }
1665       continue;
1666     }
1667
1668     // Sort the symbols by offset within the section.
1669     std::sort(List.begin(), List.end(),
1670               [&](const SymbolCU &A, const SymbolCU &B) {
1671       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1672       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1673
1674       // Symbols with no order assigned should be placed at the end.
1675       // (e.g. section end labels)
1676       if (IA == 0)
1677         return false;
1678       if (IB == 0)
1679         return true;
1680       return IA < IB;
1681     });
1682
1683     // Build spans between each label.
1684     const MCSymbol *StartSym = List[0].Sym;
1685     for (size_t n = 1, e = List.size(); n < e; n++) {
1686       const SymbolCU &Prev = List[n - 1];
1687       const SymbolCU &Cur = List[n];
1688
1689       // Try and build the longest span we can within the same CU.
1690       if (Cur.CU != Prev.CU) {
1691         ArangeSpan Span;
1692         Span.Start = StartSym;
1693         Span.End = Cur.Sym;
1694         Spans[Prev.CU].push_back(Span);
1695         StartSym = Cur.Sym;
1696       }
1697     }
1698   }
1699
1700   // Start the dwarf aranges section.
1701   Asm->OutStreamer.SwitchSection(
1702       Asm->getObjFileLowering().getDwarfARangesSection());
1703
1704   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1705
1706   // Build a list of CUs used.
1707   std::vector<DwarfCompileUnit *> CUs;
1708   for (const auto &it : Spans) {
1709     DwarfCompileUnit *CU = it.first;
1710     CUs.push_back(CU);
1711   }
1712
1713   // Sort the CU list (again, to ensure consistent output order).
1714   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1715     return A->getUniqueID() < B->getUniqueID();
1716   });
1717
1718   // Emit an arange table for each CU we used.
1719   for (DwarfCompileUnit *CU : CUs) {
1720     std::vector<ArangeSpan> &List = Spans[CU];
1721
1722     // Describe the skeleton CU's offset and length, not the dwo file's.
1723     if (auto *Skel = CU->getSkeleton())
1724       CU = Skel;
1725
1726     // Emit size of content not including length itself.
1727     unsigned ContentSize =
1728         sizeof(int16_t) + // DWARF ARange version number
1729         sizeof(int32_t) + // Offset of CU in the .debug_info section
1730         sizeof(int8_t) +  // Pointer Size (in bytes)
1731         sizeof(int8_t);   // Segment Size (in bytes)
1732
1733     unsigned TupleSize = PtrSize * 2;
1734
1735     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1736     unsigned Padding =
1737         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1738
1739     ContentSize += Padding;
1740     ContentSize += (List.size() + 1) * TupleSize;
1741
1742     // For each compile unit, write the list of spans it covers.
1743     Asm->OutStreamer.AddComment("Length of ARange Set");
1744     Asm->EmitInt32(ContentSize);
1745     Asm->OutStreamer.AddComment("DWARF Arange version number");
1746     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1747     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1748     Asm->emitSectionOffset(CU->getLabelBegin());
1749     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1750     Asm->EmitInt8(PtrSize);
1751     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1752     Asm->EmitInt8(0);
1753
1754     Asm->OutStreamer.EmitFill(Padding, 0xff);
1755
1756     for (const ArangeSpan &Span : List) {
1757       Asm->EmitLabelReference(Span.Start, PtrSize);
1758
1759       // Calculate the size as being from the span start to it's end.
1760       if (Span.End) {
1761         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1762       } else {
1763         // For symbols without an end marker (e.g. common), we
1764         // write a single arange entry containing just that one symbol.
1765         uint64_t Size = SymSize[Span.Start];
1766         if (Size == 0)
1767           Size = 1;
1768
1769         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1770       }
1771     }
1772
1773     Asm->OutStreamer.AddComment("ARange terminator");
1774     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1775     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1776   }
1777 }
1778
1779 // Emit visible names into a debug ranges section.
1780 void DwarfDebug::emitDebugRanges() {
1781   // Start the dwarf ranges section.
1782   Asm->OutStreamer.SwitchSection(
1783       Asm->getObjFileLowering().getDwarfRangesSection());
1784
1785   // Size for our labels.
1786   unsigned char Size = Asm->getDataLayout().getPointerSize();
1787
1788   // Grab the specific ranges for the compile units in the module.
1789   for (const auto &I : CUMap) {
1790     DwarfCompileUnit *TheCU = I.second;
1791
1792     if (auto *Skel = TheCU->getSkeleton())
1793       TheCU = Skel;
1794
1795     // Iterate over the misc ranges for the compile units in the module.
1796     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1797       // Emit our symbol so we can find the beginning of the range.
1798       Asm->OutStreamer.EmitLabel(List.getSym());
1799
1800       for (const RangeSpan &Range : List.getRanges()) {
1801         const MCSymbol *Begin = Range.getStart();
1802         const MCSymbol *End = Range.getEnd();
1803         assert(Begin && "Range without a begin symbol?");
1804         assert(End && "Range without an end symbol?");
1805         if (auto *Base = TheCU->getBaseAddress()) {
1806           Asm->EmitLabelDifference(Begin, Base, Size);
1807           Asm->EmitLabelDifference(End, Base, Size);
1808         } else {
1809           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1810           Asm->OutStreamer.EmitSymbolValue(End, Size);
1811         }
1812       }
1813
1814       // And terminate the list with two 0 values.
1815       Asm->OutStreamer.EmitIntValue(0, Size);
1816       Asm->OutStreamer.EmitIntValue(0, Size);
1817     }
1818   }
1819 }
1820
1821 // DWARF5 Experimental Separate Dwarf emitters.
1822
1823 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1824                                   std::unique_ptr<DwarfUnit> NewU) {
1825   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1826                   U.getCUNode().getSplitDebugFilename());
1827
1828   if (!CompilationDir.empty())
1829     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1830
1831   addGnuPubAttributes(*NewU, Die);
1832
1833   SkeletonHolder.addUnit(std::move(NewU));
1834 }
1835
1836 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1837 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1838 // DW_AT_addr_base, DW_AT_ranges_base.
1839 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1840
1841   auto OwnedUnit = make_unique<DwarfCompileUnit>(
1842       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1843   DwarfCompileUnit &NewCU = *OwnedUnit;
1844   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1845
1846   NewCU.initStmtList();
1847
1848   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1849
1850   return NewCU;
1851 }
1852
1853 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1854 // compile units that would normally be in debug_info.
1855 void DwarfDebug::emitDebugInfoDWO() {
1856   assert(useSplitDwarf() && "No split dwarf debug info?");
1857   // Don't emit relocations into the dwo file.
1858   InfoHolder.emitUnits(/* UseOffsets */ true);
1859 }
1860
1861 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1862 // abbreviations for the .debug_info.dwo section.
1863 void DwarfDebug::emitDebugAbbrevDWO() {
1864   assert(useSplitDwarf() && "No split dwarf?");
1865   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1866 }
1867
1868 void DwarfDebug::emitDebugLineDWO() {
1869   assert(useSplitDwarf() && "No split dwarf?");
1870   Asm->OutStreamer.SwitchSection(
1871       Asm->getObjFileLowering().getDwarfLineDWOSection());
1872   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1873 }
1874
1875 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1876 // string section and is identical in format to traditional .debug_str
1877 // sections.
1878 void DwarfDebug::emitDebugStrDWO() {
1879   assert(useSplitDwarf() && "No split dwarf?");
1880   const MCSection *OffSec =
1881       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1882   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1883                          OffSec);
1884 }
1885
1886 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1887   if (!useSplitDwarf())
1888     return nullptr;
1889   if (SingleCU)
1890     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1891   return &SplitTypeUnitFileTable;
1892 }
1893
1894 static uint64_t makeTypeSignature(StringRef Identifier) {
1895   MD5 Hash;
1896   Hash.update(Identifier);
1897   // ... take the least significant 8 bytes and return those. Our MD5
1898   // implementation always returns its results in little endian, swap bytes
1899   // appropriately.
1900   MD5::MD5Result Result;
1901   Hash.final(Result);
1902   return support::endian::read64le(Result + 8);
1903 }
1904
1905 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1906                                       StringRef Identifier, DIE &RefDie,
1907                                       DICompositeType CTy) {
1908   // Fast path if we're building some type units and one has already used the
1909   // address pool we know we're going to throw away all this work anyway, so
1910   // don't bother building dependent types.
1911   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1912     return;
1913
1914   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
1915   if (TU) {
1916     CU.addDIETypeSignature(RefDie, *TU);
1917     return;
1918   }
1919
1920   bool TopLevelType = TypeUnitsUnderConstruction.empty();
1921   AddrPool.resetUsedFlag();
1922
1923   auto OwnedUnit = make_unique<DwarfTypeUnit>(
1924       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
1925       this, &InfoHolder, getDwoLineTable(CU));
1926   DwarfTypeUnit &NewTU = *OwnedUnit;
1927   DIE &UnitDie = NewTU.getUnitDie();
1928   TU = &NewTU;
1929   TypeUnitsUnderConstruction.push_back(
1930       std::make_pair(std::move(OwnedUnit), CTy));
1931
1932   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1933                 CU.getLanguage());
1934
1935   uint64_t Signature = makeTypeSignature(Identifier);
1936   NewTU.setTypeSignature(Signature);
1937
1938   if (useSplitDwarf())
1939     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1940   else {
1941     CU.applyStmtList(UnitDie);
1942     NewTU.initSection(
1943         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1944   }
1945
1946   NewTU.setType(NewTU.createTypeDIE(CTy));
1947
1948   if (TopLevelType) {
1949     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1950     TypeUnitsUnderConstruction.clear();
1951
1952     // Types referencing entries in the address table cannot be placed in type
1953     // units.
1954     if (AddrPool.hasBeenUsed()) {
1955
1956       // Remove all the types built while building this type.
1957       // This is pessimistic as some of these types might not be dependent on
1958       // the type that used an address.
1959       for (const auto &TU : TypeUnitsToAdd)
1960         DwarfTypeUnits.erase(TU.second);
1961
1962       // Construct this type in the CU directly.
1963       // This is inefficient because all the dependent types will be rebuilt
1964       // from scratch, including building them in type units, discovering that
1965       // they depend on addresses, throwing them out and rebuilding them.
1966       CU.constructTypeDIE(RefDie, CTy);
1967       return;
1968     }
1969
1970     // If the type wasn't dependent on fission addresses, finish adding the type
1971     // and all its dependent types.
1972     for (auto &TU : TypeUnitsToAdd)
1973       InfoHolder.addUnit(std::move(TU.first));
1974   }
1975   CU.addDIETypeSignature(RefDie, NewTU);
1976 }
1977
1978 // Accelerator table mutators - add each name along with its companion
1979 // DIE to the proper table while ensuring that the name that we're going
1980 // to reference is in the string table. We do this since the names we
1981 // add may not only be identical to the names in the DIE.
1982 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
1983   if (!useDwarfAccelTables())
1984     return;
1985   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
1986                      &Die);
1987 }
1988
1989 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
1990   if (!useDwarfAccelTables())
1991     return;
1992   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
1993                     &Die);
1994 }
1995
1996 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
1997   if (!useDwarfAccelTables())
1998     return;
1999   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2000                          &Die);
2001 }
2002
2003 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2004   if (!useDwarfAccelTables())
2005     return;
2006   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2007                      &Die);
2008 }