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