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