1327952Sdim//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed// This file contains support for writing dwarf debug info into asm files.
10193323Sed//
11193323Sed//===----------------------------------------------------------------------===//
12204961Srdivacky
13280031Sdim#include "DwarfDebug.h"
14276479Sdim#include "ByteStreamer.h"
15261991Sdim#include "DIEHash.h"
16288943Sdim#include "DebugLocEntry.h"
17327952Sdim#include "DebugLocStream.h"
18280031Sdim#include "DwarfCompileUnit.h"
19280031Sdim#include "DwarfExpression.h"
20327952Sdim#include "DwarfFile.h"
21276479Sdim#include "DwarfUnit.h"
22327952Sdim#include "llvm/ADT/APInt.h"
23327952Sdim#include "llvm/ADT/DenseMap.h"
24327952Sdim#include "llvm/ADT/DenseSet.h"
25327952Sdim#include "llvm/ADT/MapVector.h"
26249423Sdim#include "llvm/ADT/STLExtras.h"
27327952Sdim#include "llvm/ADT/SmallVector.h"
28327952Sdim#include "llvm/ADT/StringRef.h"
29360784Sdim#include "llvm/ADT/Statistic.h"
30249423Sdim#include "llvm/ADT/Triple.h"
31327952Sdim#include "llvm/ADT/Twine.h"
32321369Sdim#include "llvm/BinaryFormat/Dwarf.h"
33341825Sdim#include "llvm/CodeGen/AccelTable.h"
34327952Sdim#include "llvm/CodeGen/AsmPrinter.h"
35280031Sdim#include "llvm/CodeGen/DIE.h"
36327952Sdim#include "llvm/CodeGen/LexicalScopes.h"
37327952Sdim#include "llvm/CodeGen/MachineBasicBlock.h"
38198090Srdivacky#include "llvm/CodeGen/MachineFunction.h"
39327952Sdim#include "llvm/CodeGen/MachineInstr.h"
40193323Sed#include "llvm/CodeGen/MachineModuleInfo.h"
41327952Sdim#include "llvm/CodeGen/MachineOperand.h"
42344779Sdim#include "llvm/CodeGen/TargetInstrInfo.h"
43360784Sdim#include "llvm/CodeGen/TargetLowering.h"
44327952Sdim#include "llvm/CodeGen/TargetRegisterInfo.h"
45327952Sdim#include "llvm/CodeGen/TargetSubtargetInfo.h"
46353358Sdim#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
47353358Sdim#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
48249423Sdim#include "llvm/IR/Constants.h"
49327952Sdim#include "llvm/IR/DebugInfoMetadata.h"
50327952Sdim#include "llvm/IR/DebugLoc.h"
51327952Sdim#include "llvm/IR/Function.h"
52327952Sdim#include "llvm/IR/GlobalVariable.h"
53249423Sdim#include "llvm/IR/Module.h"
54204961Srdivacky#include "llvm/MC/MCAsmInfo.h"
55327952Sdim#include "llvm/MC/MCContext.h"
56296417Sdim#include "llvm/MC/MCDwarf.h"
57198090Srdivacky#include "llvm/MC/MCSection.h"
58198090Srdivacky#include "llvm/MC/MCStreamer.h"
59204961Srdivacky#include "llvm/MC/MCSymbol.h"
60327952Sdim#include "llvm/MC/MCTargetOptions.h"
61327952Sdim#include "llvm/MC/MachineLocation.h"
62327952Sdim#include "llvm/MC/SectionKind.h"
63327952Sdim#include "llvm/Pass.h"
64327952Sdim#include "llvm/Support/Casting.h"
65207618Srdivacky#include "llvm/Support/CommandLine.h"
66198090Srdivacky#include "llvm/Support/Debug.h"
67198090Srdivacky#include "llvm/Support/ErrorHandling.h"
68261991Sdim#include "llvm/Support/MD5.h"
69327952Sdim#include "llvm/Support/MathExtras.h"
70193323Sed#include "llvm/Support/Timer.h"
71288943Sdim#include "llvm/Support/raw_ostream.h"
72341825Sdim#include "llvm/Target/TargetLoweringObjectFile.h"
73249423Sdim#include "llvm/Target/TargetMachine.h"
74249423Sdim#include "llvm/Target/TargetOptions.h"
75327952Sdim#include <algorithm>
76327952Sdim#include <cassert>
77327952Sdim#include <cstddef>
78327952Sdim#include <cstdint>
79327952Sdim#include <iterator>
80327952Sdim#include <string>
81327952Sdim#include <utility>
82327952Sdim#include <vector>
83309124Sdim
84193323Sedusing namespace llvm;
85193323Sed
86276479Sdim#define DEBUG_TYPE "dwarfdebug"
87276479Sdim
88360784SdimSTATISTIC(NumCSParams, "Number of dbg call site params created");
89360784Sdim
90261991Sdimstatic cl::opt<bool>
91261991SdimDisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
92261991Sdim                         cl::desc("Disable debug info printing"));
93207618Srdivacky
94327952Sdimstatic cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
95327952Sdim    "use-dwarf-ranges-base-address-specifier", cl::Hidden,
96327952Sdim    cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
97261991Sdim
98276479Sdimstatic cl::opt<bool> GenerateARangeSection("generate-arange-section",
99276479Sdim                                           cl::Hidden,
100276479Sdim                                           cl::desc("Generate dwarf aranges"),
101276479Sdim                                           cl::init(false));
102276479Sdim
103341825Sdimstatic cl::opt<bool>
104341825Sdim    GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
105341825Sdim                           cl::desc("Generate DWARF4 type units."),
106341825Sdim                           cl::init(false));
107341825Sdim
108321369Sdimstatic cl::opt<bool> SplitDwarfCrossCuReferences(
109321369Sdim    "split-dwarf-cross-cu-references", cl::Hidden,
110321369Sdim    cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
111321369Sdim
112276479Sdimenum DefaultOnOff { Default, Enable, Disable };
113243830Sdim
114314564Sdimstatic cl::opt<DefaultOnOff> UnknownLocations(
115314564Sdim    "use-unknown-locations", cl::Hidden,
116314564Sdim    cl::desc("Make an absence of debug location information explicit."),
117314564Sdim    cl::values(clEnumVal(Default, "At top of block or after label"),
118314564Sdim               clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
119314564Sdim    cl::init(Default));
120314564Sdim
121341825Sdimstatic cl::opt<AccelTableKind> AccelTables(
122341825Sdim    "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
123341825Sdim    cl::values(clEnumValN(AccelTableKind::Default, "Default",
124341825Sdim                          "Default for platform"),
125341825Sdim               clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
126341825Sdim               clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
127341825Sdim               clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
128341825Sdim    cl::init(AccelTableKind::Default));
129341825Sdim
130261991Sdimstatic cl::opt<DefaultOnOff>
131341825SdimDwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
132341825Sdim                 cl::desc("Use inlined strings rather than string section."),
133261991Sdim                 cl::values(clEnumVal(Default, "Default for platform"),
134261991Sdim                            clEnumVal(Enable, "Enabled"),
135314564Sdim                            clEnumVal(Disable, "Disabled")),
136261991Sdim                 cl::init(Default));
137234353Sdim
138341825Sdimstatic cl::opt<bool>
139341825Sdim    NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
140341825Sdim                         cl::desc("Disable emission .debug_ranges section."),
141341825Sdim                         cl::init(false));
142341825Sdim
143341825Sdimstatic cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
144341825Sdim    "dwarf-sections-as-references", cl::Hidden,
145341825Sdim    cl::desc("Use sections+offset as references rather than labels."),
146341825Sdim    cl::values(clEnumVal(Default, "Default for platform"),
147341825Sdim               clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
148341825Sdim    cl::init(Default));
149341825Sdim
150309124Sdimenum LinkageNameOption {
151309124Sdim  DefaultLinkageNames,
152309124Sdim  AllLinkageNames,
153309124Sdim  AbstractLinkageNames
154309124Sdim};
155327952Sdim
156309124Sdimstatic cl::opt<LinkageNameOption>
157309124Sdim    DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
158309124Sdim                      cl::desc("Which DWARF linkage-name attributes to emit."),
159309124Sdim                      cl::values(clEnumValN(DefaultLinkageNames, "Default",
160309124Sdim                                            "Default for platform"),
161309124Sdim                                 clEnumValN(AllLinkageNames, "All", "All"),
162309124Sdim                                 clEnumValN(AbstractLinkageNames, "Abstract",
163314564Sdim                                            "Abstract subprograms")),
164309124Sdim                      cl::init(DefaultLinkageNames));
165296417Sdim
166314564Sdimstatic const char *const DWARFGroupName = "dwarf";
167314564Sdimstatic const char *const DWARFGroupDescription = "DWARF Emission";
168314564Sdimstatic const char *const DbgTimerName = "writer";
169314564Sdimstatic const char *const DbgTimerDescription = "DWARF Debug Writer";
170353358Sdimstatic constexpr unsigned ULEB128PadSize = 4;
171207618Srdivacky
172321369Sdimvoid DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
173360784Sdim  getActiveStreamer().EmitInt8(
174288943Sdim      Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
175288943Sdim                  : dwarf::OperationEncodingString(Op));
176288943Sdim}
177288943Sdim
178321369Sdimvoid DebugLocDwarfExpression::emitSigned(int64_t Value) {
179360784Sdim  getActiveStreamer().EmitSLEB128(Value, Twine(Value));
180288943Sdim}
181288943Sdim
182321369Sdimvoid DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
183360784Sdim  getActiveStreamer().EmitULEB128(Value, Twine(Value));
184288943Sdim}
185288943Sdim
186353358Sdimvoid DebugLocDwarfExpression::emitData1(uint8_t Value) {
187360784Sdim  getActiveStreamer().EmitInt8(Value, Twine(Value));
188353358Sdim}
189353358Sdim
190353358Sdimvoid DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
191353358Sdim  assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
192360784Sdim  getActiveStreamer().EmitULEB128(Idx, Twine(Idx), ULEB128PadSize);
193353358Sdim}
194353358Sdim
195309124Sdimbool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
196309124Sdim                                              unsigned MachineReg) {
197288943Sdim  // This information is not available while emitting .debug_loc entries.
198288943Sdim  return false;
199288943Sdim}
200288943Sdim
201360784Sdimvoid DebugLocDwarfExpression::enableTemporaryBuffer() {
202360784Sdim  assert(!IsBuffering && "Already buffering?");
203360784Sdim  if (!TmpBuf)
204360784Sdim    TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
205360784Sdim  IsBuffering = true;
206276479Sdim}
207276479Sdim
208360784Sdimvoid DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
209249423Sdim
210360784Sdimunsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
211360784Sdim  return TmpBuf ? TmpBuf->Bytes.size() : 0;
212360784Sdim}
213249423Sdim
214360784Sdimvoid DebugLocDwarfExpression::commitTemporaryBuffer() {
215360784Sdim  if (!TmpBuf)
216360784Sdim    return;
217360784Sdim  for (auto Byte : enumerate(TmpBuf->Bytes)) {
218360784Sdim    const char *Comment = (Byte.index() < TmpBuf->Comments.size())
219360784Sdim                              ? TmpBuf->Comments[Byte.index()].c_str()
220360784Sdim                              : "";
221360784Sdim    OutBS.EmitInt8(Byte.value(), Comment);
222212904Sdim  }
223360784Sdim  TmpBuf->Bytes.clear();
224360784Sdim  TmpBuf->Comments.clear();
225221345Sdim}
226193323Sed
227360784Sdimconst DIType *DbgVariable::getType() const {
228360784Sdim  return getVariable()->getType();
229360784Sdim}
230360784Sdim
231353358Sdim/// Get .debug_loc entry for the instruction range starting at MI.
232353358Sdimstatic DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
233353358Sdim  const DIExpression *Expr = MI->getDebugExpression();
234353358Sdim  assert(MI->getNumOperands() == 4);
235353358Sdim  if (MI->getOperand(0).isReg()) {
236353358Sdim    auto RegOp = MI->getOperand(0);
237353358Sdim    auto Op1 = MI->getOperand(1);
238353358Sdim    // If the second operand is an immediate, this is a
239353358Sdim    // register-indirect address.
240353358Sdim    assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
241353358Sdim    MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
242353358Sdim    return DbgValueLoc(Expr, MLoc);
243353358Sdim  }
244360784Sdim  if (MI->getOperand(0).isTargetIndex()) {
245360784Sdim    auto Op = MI->getOperand(0);
246360784Sdim    return DbgValueLoc(Expr,
247360784Sdim                       TargetIndexLocation(Op.getIndex(), Op.getOffset()));
248360784Sdim  }
249353358Sdim  if (MI->getOperand(0).isImm())
250353358Sdim    return DbgValueLoc(Expr, MI->getOperand(0).getImm());
251353358Sdim  if (MI->getOperand(0).isFPImm())
252353358Sdim    return DbgValueLoc(Expr, MI->getOperand(0).getFPImm());
253353358Sdim  if (MI->getOperand(0).isCImm())
254353358Sdim    return DbgValueLoc(Expr, MI->getOperand(0).getCImm());
255353358Sdim
256353358Sdim  llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
257353358Sdim}
258353358Sdim
259353358Sdimvoid DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
260353358Sdim  assert(FrameIndexExprs.empty() && "Already initialized?");
261353358Sdim  assert(!ValueLoc.get() && "Already initialized?");
262353358Sdim
263353358Sdim  assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
264353358Sdim  assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
265353358Sdim         "Wrong inlined-at");
266353358Sdim
267360784Sdim  ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
268353358Sdim  if (auto *E = DbgValue->getDebugExpression())
269353358Sdim    if (E->getNumElements())
270353358Sdim      FrameIndexExprs.push_back({0, E});
271353358Sdim}
272353358Sdim
273314564SdimArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
274321369Sdim  if (FrameIndexExprs.size() == 1)
275321369Sdim    return FrameIndexExprs;
276321369Sdim
277327952Sdim  assert(llvm::all_of(FrameIndexExprs,
278327952Sdim                      [](const FrameIndexExpr &A) {
279327952Sdim                        return A.Expr->isFragment();
280327952Sdim                      }) &&
281321369Sdim         "multiple FI expressions without DW_OP_LLVM_fragment");
282344779Sdim  llvm::sort(FrameIndexExprs,
283341825Sdim             [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
284341825Sdim               return A.Expr->getFragmentInfo()->OffsetInBits <
285341825Sdim                      B.Expr->getFragmentInfo()->OffsetInBits;
286341825Sdim             });
287327952Sdim
288314564Sdim  return FrameIndexExprs;
289314564Sdim}
290314564Sdim
291327952Sdimvoid DbgVariable::addMMIEntry(const DbgVariable &V) {
292353358Sdim  assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
293353358Sdim  assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
294344779Sdim  assert(V.getVariable() == getVariable() && "conflicting variable");
295344779Sdim  assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
296327952Sdim
297327952Sdim  assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
298327952Sdim  assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
299327952Sdim
300327952Sdim  // FIXME: This logic should not be necessary anymore, as we now have proper
301327952Sdim  // deduplication. However, without it, we currently run into the assertion
302327952Sdim  // below, which means that we are likely dealing with broken input, i.e. two
303327952Sdim  // non-fragment entries for the same variable at different frame indices.
304327952Sdim  if (FrameIndexExprs.size()) {
305327952Sdim    auto *Expr = FrameIndexExprs.back().Expr;
306327952Sdim    if (!Expr || !Expr->isFragment())
307327952Sdim      return;
308327952Sdim  }
309327952Sdim
310327952Sdim  for (const auto &FIE : V.FrameIndexExprs)
311327952Sdim    // Ignore duplicate entries.
312327952Sdim    if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
313327952Sdim          return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
314327952Sdim        }))
315327952Sdim      FrameIndexExprs.push_back(FIE);
316327952Sdim
317327952Sdim  assert((FrameIndexExprs.size() == 1 ||
318327952Sdim          llvm::all_of(FrameIndexExprs,
319327952Sdim                       [](FrameIndexExpr &FIE) {
320327952Sdim                         return FIE.Expr && FIE.Expr->isFragment();
321327952Sdim                       })) &&
322327952Sdim         "conflicting locations for variable");
323327952Sdim}
324327952Sdim
325341825Sdimstatic AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
326341825Sdim                                            bool GenerateTypeUnits,
327341825Sdim                                            DebuggerKind Tuning,
328341825Sdim                                            const Triple &TT) {
329341825Sdim  // Honor an explicit request.
330341825Sdim  if (AccelTables != AccelTableKind::Default)
331341825Sdim    return AccelTables;
332193323Sed
333341825Sdim  // Accelerator tables with type units are currently not supported.
334341825Sdim  if (GenerateTypeUnits)
335341825Sdim    return AccelTableKind::None;
336341825Sdim
337341825Sdim  // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
338341825Sdim  // always implies debug_names. For lower standard versions we use apple
339341825Sdim  // accelerator tables on apple platforms and debug_names elsewhere.
340341825Sdim  if (DwarfVersion >= 5)
341341825Sdim    return AccelTableKind::Dwarf;
342341825Sdim  if (Tuning == DebuggerKind::LLDB)
343341825Sdim    return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
344341825Sdim                                   : AccelTableKind::Dwarf;
345341825Sdim  return AccelTableKind::None;
346341825Sdim}
347341825Sdim
348206274SrdivackyDwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
349309124Sdim    : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
350309124Sdim      InfoHolder(A, "info_string", DIEValueAllocator),
351288943Sdim      SkeletonHolder(A, "skel_string", DIEValueAllocator),
352341825Sdim      IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
353314564Sdim  const Triple &TT = Asm->TM.getTargetTriple();
354234353Sdim
355353358Sdim  // Make sure we know our "debugger tuning".  The target option takes
356296417Sdim  // precedence; fall back to triple-based defaults.
357296417Sdim  if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
358296417Sdim    DebuggerTuning = Asm->TM.Options.DebuggerTuning;
359296417Sdim  else if (IsDarwin)
360296417Sdim    DebuggerTuning = DebuggerKind::LLDB;
361296417Sdim  else if (TT.isPS4CPU())
362296417Sdim    DebuggerTuning = DebuggerKind::SCE;
363296417Sdim  else
364296417Sdim    DebuggerTuning = DebuggerKind::GDB;
365296417Sdim
366341825Sdim  if (DwarfInlinedStrings == Default)
367341825Sdim    UseInlineStrings = TT.isNVPTX();
368261991Sdim  else
369341825Sdim    UseInlineStrings = DwarfInlinedStrings == Enable;
370243830Sdim
371341825Sdim  UseLocSection = !TT.isNVPTX();
372341825Sdim
373309124Sdim  HasAppleExtensionAttributes = tuneForLLDB();
374309124Sdim
375321369Sdim  // Handle split DWARF.
376321369Sdim  HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
377249423Sdim
378309124Sdim  // SCE defaults to linkage names only for abstract subprograms.
379309124Sdim  if (DwarfLinkageNames == DefaultLinkageNames)
380309124Sdim    UseAllLinkageNames = !tuneForSCE();
381296417Sdim  else
382309124Sdim    UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
383296417Sdim
384276479Sdim  unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
385314564Sdim  unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
386276479Sdim                                    : MMI->getModule()->getDwarfVersion();
387341825Sdim  // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
388341825Sdim  DwarfVersion =
389341825Sdim      TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
390261991Sdim
391341825Sdim  UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
392341825Sdim
393341825Sdim  // Use sections as references. Force for NVPTX.
394341825Sdim  if (DwarfSectionsAsReferences == Default)
395341825Sdim    UseSectionsAsReferences = TT.isNVPTX();
396341825Sdim  else
397341825Sdim    UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
398341825Sdim
399341825Sdim  // Don't generate type units for unsupported object file formats.
400341825Sdim  GenerateTypeUnits =
401341825Sdim      A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
402341825Sdim
403341825Sdim  TheAccelTableKind = computeAccelTableKind(
404341825Sdim      DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
405341825Sdim
406296417Sdim  // Work around a GDB bug. GDB doesn't support the standard opcode;
407296417Sdim  // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
408296417Sdim  // is defined as of DWARF 3.
409296417Sdim  // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
410296417Sdim  // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
411296417Sdim  UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
412276479Sdim
413309124Sdim  // GDB does not fully support the DWARF 4 representation for bitfields.
414309124Sdim  UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
415309124Sdim
416341825Sdim  // The DWARF v5 string offsets table has - possibly shared - contributions
417341825Sdim  // from each compile and type unit each preceded by a header. The string
418341825Sdim  // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
419341825Sdim  // a monolithic string offsets table without any header.
420341825Sdim  UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
421341825Sdim
422288943Sdim  Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
423193323Sed}
424193323Sed
425276479Sdim// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
426327952SdimDwarfDebug::~DwarfDebug() = default;
427276479Sdim
428234353Sdimstatic bool isObjCClass(StringRef Name) {
429234353Sdim  return Name.startswith("+") || Name.startswith("-");
430234353Sdim}
431234353Sdim
432234353Sdimstatic bool hasObjCCategory(StringRef Name) {
433276479Sdim  if (!isObjCClass(Name))
434276479Sdim    return false;
435234353Sdim
436261991Sdim  return Name.find(") ") != StringRef::npos;
437234353Sdim}
438234353Sdim
439234353Sdimstatic void getObjCClassCategory(StringRef In, StringRef &Class,
440234353Sdim                                 StringRef &Category) {
441234353Sdim  if (!hasObjCCategory(In)) {
442234353Sdim    Class = In.slice(In.find('[') + 1, In.find(' '));
443234353Sdim    Category = "";
444234353Sdim    return;
445234353Sdim  }
446234353Sdim
447234353Sdim  Class = In.slice(In.find('[') + 1, In.find('('));
448234353Sdim  Category = In.slice(In.find('[') + 1, In.find(' '));
449234353Sdim}
450234353Sdim
451234353Sdimstatic StringRef getObjCMethodName(StringRef In) {
452234353Sdim  return In.slice(In.find(' ') + 1, In.find(']'));
453234353Sdim}
454234353Sdim
455234353Sdim// Add the various names to the Dwarf accelerator table names.
456344779Sdimvoid DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
457344779Sdim                                    const DISubprogram *SP, DIE &Die) {
458344779Sdim  if (getAccelTableKind() != AccelTableKind::Apple &&
459344779Sdim      CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
460344779Sdim    return;
461344779Sdim
462288943Sdim  if (!SP->isDefinition())
463276479Sdim    return;
464234353Sdim
465341825Sdim  if (SP->getName() != "")
466344779Sdim    addAccelName(CU, SP->getName(), Die);
467341825Sdim
468341825Sdim  // If the linkage name is different than the name, go ahead and output that as
469341825Sdim  // well into the name table. Only do that if we are going to actually emit
470341825Sdim  // that name.
471341825Sdim  if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
472341825Sdim      (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
473344779Sdim    addAccelName(CU, SP->getLinkageName(), Die);
474234353Sdim
475234353Sdim  // If this is an Objective-C selector name add it to the ObjC accelerator
476234353Sdim  // too.
477288943Sdim  if (isObjCClass(SP->getName())) {
478234353Sdim    StringRef Class, Category;
479288943Sdim    getObjCClassCategory(SP->getName(), Class, Category);
480344779Sdim    addAccelObjC(CU, Class, Die);
481234353Sdim    if (Category != "")
482344779Sdim      addAccelObjC(CU, Category, Die);
483234353Sdim    // Also add the base method name to the name table.
484344779Sdim    addAccelName(CU, getObjCMethodName(SP->getName()), Die);
485234353Sdim  }
486234353Sdim}
487234353Sdim
488261991Sdim/// Check whether we should create a DIE for the given Scope, return true
489261991Sdim/// if we don't create a DIE (the corresponding DIE is null).
490261991Sdimbool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
491261991Sdim  if (Scope->isAbstractScope())
492261991Sdim    return false;
493261991Sdim
494261991Sdim  // We don't create a DIE if there is no Range.
495261991Sdim  const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
496261991Sdim  if (Ranges.empty())
497261991Sdim    return true;
498261991Sdim
499261991Sdim  if (Ranges.size() > 1)
500261991Sdim    return false;
501261991Sdim
502261991Sdim  // We don't create a DIE if we have a single Range and the end label
503261991Sdim  // is null.
504280031Sdim  return !getLabelAfterInsn(Ranges.front().second);
505261991Sdim}
506261991Sdim
507314564Sdimtemplate <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
508280031Sdim  F(CU);
509280031Sdim  if (auto *SkelCU = CU.getSkeleton())
510314564Sdim    if (CU.getCUNode()->getSplitDebugInlining())
511314564Sdim      F(*SkelCU);
512276479Sdim}
513276479Sdim
514321369Sdimbool DwarfDebug::shareAcrossDWOCUs() const {
515321369Sdim  return SplitDwarfCrossCuReferences;
516321369Sdim}
517321369Sdim
518321369Sdimvoid DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
519321369Sdim                                                     LexicalScope *Scope) {
520276479Sdim  assert(Scope && Scope->getScopeNode());
521276479Sdim  assert(Scope->isAbstractScope());
522276479Sdim  assert(!Scope->getInlinedAt());
523276479Sdim
524314564Sdim  auto *SP = cast<DISubprogram>(Scope->getScopeNode());
525276479Sdim
526276479Sdim  // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
527276479Sdim  // was inlined from another compile unit.
528321369Sdim  if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
529321369Sdim    // Avoid building the original CU if it won't be used
530321369Sdim    SrcCU.constructAbstractSubprogramScopeDIE(Scope);
531321369Sdim  else {
532321369Sdim    auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
533321369Sdim    if (auto *SkelCU = CU.getSkeleton()) {
534321369Sdim      (shareAcrossDWOCUs() ? CU : SrcCU)
535321369Sdim          .constructAbstractSubprogramScopeDIE(Scope);
536321369Sdim      if (CU.getCUNode()->getSplitDebugInlining())
537321369Sdim        SkelCU->constructAbstractSubprogramScopeDIE(Scope);
538321369Sdim    } else
539321369Sdim      CU.constructAbstractSubprogramScopeDIE(Scope);
540321369Sdim  }
541276479Sdim}
542276479Sdim
543360784Sdim/// Try to interpret values loaded into registers that forward parameters
544360784Sdim/// for \p CallMI. Store parameters with interpreted value into \p Params.
545360784Sdimstatic void collectCallSiteParameters(const MachineInstr *CallMI,
546360784Sdim                                      ParamSet &Params) {
547360784Sdim  auto *MF = CallMI->getMF();
548360784Sdim  auto CalleesMap = MF->getCallSitesInfo();
549360784Sdim  auto CallFwdRegsInfo = CalleesMap.find(CallMI);
550360784Sdim
551360784Sdim  // There is no information for the call instruction.
552360784Sdim  if (CallFwdRegsInfo == CalleesMap.end())
553360784Sdim    return;
554360784Sdim
555360784Sdim  auto *MBB = CallMI->getParent();
556360784Sdim  const auto &TRI = MF->getSubtarget().getRegisterInfo();
557360784Sdim  const auto &TII = MF->getSubtarget().getInstrInfo();
558360784Sdim  const auto &TLI = MF->getSubtarget().getTargetLowering();
559360784Sdim
560360784Sdim  // Skip the call instruction.
561360784Sdim  auto I = std::next(CallMI->getReverseIterator());
562360784Sdim
563360784Sdim  DenseSet<unsigned> ForwardedRegWorklist;
564360784Sdim  // Add all the forwarding registers into the ForwardedRegWorklist.
565360784Sdim  for (auto ArgReg : CallFwdRegsInfo->second) {
566360784Sdim    bool InsertedReg = ForwardedRegWorklist.insert(ArgReg.Reg).second;
567360784Sdim    assert(InsertedReg && "Single register used to forward two arguments?");
568360784Sdim    (void)InsertedReg;
569360784Sdim  }
570360784Sdim
571360784Sdim  // We erase, from the ForwardedRegWorklist, those forwarding registers for
572360784Sdim  // which we successfully describe a loaded value (by using
573360784Sdim  // the describeLoadedValue()). For those remaining arguments in the working
574360784Sdim  // list, for which we do not describe a loaded value by
575360784Sdim  // the describeLoadedValue(), we try to generate an entry value expression
576360784Sdim  // for their call site value desctipion, if the call is within the entry MBB.
577360784Sdim  // The RegsForEntryValues maps a forwarding register into the register holding
578360784Sdim  // the entry value.
579360784Sdim  // TODO: Handle situations when call site parameter value can be described
580360784Sdim  // as the entry value within basic blocks other then the first one.
581360784Sdim  bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
582360784Sdim  DenseMap<unsigned, unsigned> RegsForEntryValues;
583360784Sdim
584360784Sdim  // If the MI is an instruction defining one or more parameters' forwarding
585360784Sdim  // registers, add those defines. We can currently only describe forwarded
586360784Sdim  // registers that are explicitly defined, but keep track of implicit defines
587360784Sdim  // also to remove those registers from the work list.
588360784Sdim  auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
589360784Sdim                                          SmallVectorImpl<unsigned> &Explicit,
590360784Sdim                                          SmallVectorImpl<unsigned> &Implicit) {
591360784Sdim    if (MI.isDebugInstr())
592360784Sdim      return;
593360784Sdim
594360784Sdim    for (const MachineOperand &MO : MI.operands()) {
595360784Sdim      if (MO.isReg() && MO.isDef() &&
596360784Sdim          Register::isPhysicalRegister(MO.getReg())) {
597360784Sdim        for (auto FwdReg : ForwardedRegWorklist) {
598360784Sdim          if (TRI->regsOverlap(FwdReg, MO.getReg())) {
599360784Sdim            if (MO.isImplicit())
600360784Sdim              Implicit.push_back(FwdReg);
601360784Sdim            else
602360784Sdim              Explicit.push_back(FwdReg);
603360784Sdim          }
604360784Sdim        }
605360784Sdim      }
606360784Sdim    }
607360784Sdim  };
608360784Sdim
609360784Sdim  auto finishCallSiteParam = [&](DbgValueLoc DbgLocVal, unsigned Reg) {
610360784Sdim    unsigned FwdReg = Reg;
611360784Sdim    if (ShouldTryEmitEntryVals) {
612360784Sdim      auto EntryValReg = RegsForEntryValues.find(Reg);
613360784Sdim      if (EntryValReg != RegsForEntryValues.end())
614360784Sdim        FwdReg = EntryValReg->second;
615360784Sdim    }
616360784Sdim
617360784Sdim    DbgCallSiteParam CSParm(FwdReg, DbgLocVal);
618360784Sdim    Params.push_back(CSParm);
619360784Sdim    ++NumCSParams;
620360784Sdim  };
621360784Sdim
622360784Sdim  // Search for a loading value in forwarding registers.
623360784Sdim  for (; I != MBB->rend(); ++I) {
624360784Sdim    // Skip bundle headers.
625360784Sdim    if (I->isBundle())
626360784Sdim      continue;
627360784Sdim
628360784Sdim    // If the next instruction is a call we can not interpret parameter's
629360784Sdim    // forwarding registers or we finished the interpretation of all parameters.
630360784Sdim    if (I->isCall())
631360784Sdim      return;
632360784Sdim
633360784Sdim    if (ForwardedRegWorklist.empty())
634360784Sdim      return;
635360784Sdim
636360784Sdim    SmallVector<unsigned, 4> ExplicitFwdRegDefs;
637360784Sdim    SmallVector<unsigned, 4> ImplicitFwdRegDefs;
638360784Sdim    getForwardingRegsDefinedByMI(*I, ExplicitFwdRegDefs, ImplicitFwdRegDefs);
639360784Sdim    if (ExplicitFwdRegDefs.empty() && ImplicitFwdRegDefs.empty())
640360784Sdim      continue;
641360784Sdim
642360784Sdim    // If the MI clobbers more then one forwarding register we must remove
643360784Sdim    // all of them from the working list.
644360784Sdim    for (auto Reg : concat<unsigned>(ExplicitFwdRegDefs, ImplicitFwdRegDefs))
645360784Sdim      ForwardedRegWorklist.erase(Reg);
646360784Sdim
647360784Sdim    for (auto ParamFwdReg : ExplicitFwdRegDefs) {
648360784Sdim      if (auto ParamValue = TII->describeLoadedValue(*I, ParamFwdReg)) {
649360784Sdim        if (ParamValue->first.isImm()) {
650360784Sdim          int64_t Val = ParamValue->first.getImm();
651360784Sdim          DbgValueLoc DbgLocVal(ParamValue->second, Val);
652360784Sdim          finishCallSiteParam(DbgLocVal, ParamFwdReg);
653360784Sdim        } else if (ParamValue->first.isReg()) {
654360784Sdim          Register RegLoc = ParamValue->first.getReg();
655360784Sdim          // TODO: For now, there is no use of describing the value loaded into the
656360784Sdim          //       register that is also the source registers (e.g. $r0 = add $r0, x).
657360784Sdim          if (ParamFwdReg == RegLoc)
658360784Sdim            continue;
659360784Sdim
660360784Sdim          unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
661360784Sdim          Register FP = TRI->getFrameRegister(*MF);
662360784Sdim          bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
663360784Sdim          if (TRI->isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
664360784Sdim            DbgValueLoc DbgLocVal(ParamValue->second,
665360784Sdim                                  MachineLocation(RegLoc,
666360784Sdim                                                  /*IsIndirect=*/IsSPorFP));
667360784Sdim            finishCallSiteParam(DbgLocVal, ParamFwdReg);
668360784Sdim          // TODO: Add support for entry value plus an expression.
669360784Sdim          } else if (ShouldTryEmitEntryVals &&
670360784Sdim                     ParamValue->second->getNumElements() == 0) {
671360784Sdim            ForwardedRegWorklist.insert(RegLoc);
672360784Sdim            RegsForEntryValues[RegLoc] = ParamFwdReg;
673360784Sdim          }
674360784Sdim        }
675360784Sdim      }
676360784Sdim    }
677360784Sdim  }
678360784Sdim
679360784Sdim  // Emit the call site parameter's value as an entry value.
680360784Sdim  if (ShouldTryEmitEntryVals) {
681360784Sdim    // Create an expression where the register's entry value is used.
682360784Sdim    DIExpression *EntryExpr = DIExpression::get(
683360784Sdim        MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
684360784Sdim    for (auto RegEntry : ForwardedRegWorklist) {
685360784Sdim      unsigned FwdReg = RegEntry;
686360784Sdim      auto EntryValReg = RegsForEntryValues.find(RegEntry);
687360784Sdim        if (EntryValReg != RegsForEntryValues.end())
688360784Sdim          FwdReg = EntryValReg->second;
689360784Sdim
690360784Sdim      DbgValueLoc DbgLocVal(EntryExpr, MachineLocation(RegEntry));
691360784Sdim      DbgCallSiteParam CSParm(FwdReg, DbgLocVal);
692360784Sdim      Params.push_back(CSParm);
693360784Sdim      ++NumCSParams;
694360784Sdim    }
695360784Sdim  }
696360784Sdim}
697360784Sdim
698344779Sdimvoid DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
699344779Sdim                                            DwarfCompileUnit &CU, DIE &ScopeDIE,
700344779Sdim                                            const MachineFunction &MF) {
701344779Sdim  // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
702344779Sdim  // the subprogram is required to have one.
703344779Sdim  if (!SP.areAllCallsDescribed() || !SP.isDefinition())
704344779Sdim    return;
705344779Sdim
706344779Sdim  // Use DW_AT_call_all_calls to express that call site entries are present
707344779Sdim  // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
708344779Sdim  // because one of its requirements is not met: call site entries for
709344779Sdim  // optimized-out calls are elided.
710360784Sdim  CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
711344779Sdim
712344779Sdim  const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
713344779Sdim  assert(TII && "TargetInstrInfo not found: cannot label tail calls");
714360784Sdim  bool ApplyGNUExtensions = getDwarfVersion() == 4 && tuneForGDB();
715344779Sdim
716344779Sdim  // Emit call site entries for each call or tail call in the function.
717344779Sdim  for (const MachineBasicBlock &MBB : MF) {
718344779Sdim    for (const MachineInstr &MI : MBB.instrs()) {
719360784Sdim      // Bundles with call in them will pass the isCall() test below but do not
720360784Sdim      // have callee operand information so skip them here. Iterator will
721360784Sdim      // eventually reach the call MI.
722360784Sdim      if (MI.isBundle())
723360784Sdim        continue;
724360784Sdim
725344779Sdim      // Skip instructions which aren't calls. Both calls and tail-calling jump
726344779Sdim      // instructions (e.g TAILJMPd64) are classified correctly here.
727344779Sdim      if (!MI.isCall())
728344779Sdim        continue;
729344779Sdim
730344779Sdim      // TODO: Add support for targets with delay slots (see: beginInstruction).
731344779Sdim      if (MI.hasDelaySlot())
732344779Sdim        return;
733344779Sdim
734344779Sdim      // If this is a direct call, find the callee's subprogram.
735360784Sdim      // In the case of an indirect call find the register that holds
736360784Sdim      // the callee.
737344779Sdim      const MachineOperand &CalleeOp = MI.getOperand(0);
738360784Sdim      if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
739344779Sdim        continue;
740344779Sdim
741360784Sdim      unsigned CallReg = 0;
742360784Sdim      const DISubprogram *CalleeSP = nullptr;
743360784Sdim      const Function *CalleeDecl = nullptr;
744360784Sdim      if (CalleeOp.isReg()) {
745360784Sdim        CallReg = CalleeOp.getReg();
746360784Sdim        if (!CallReg)
747360784Sdim          continue;
748360784Sdim      } else {
749360784Sdim        CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
750360784Sdim        if (!CalleeDecl || !CalleeDecl->getSubprogram())
751360784Sdim          continue;
752360784Sdim        CalleeSP = CalleeDecl->getSubprogram();
753360784Sdim      }
754360784Sdim
755344779Sdim      // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
756344779Sdim
757344779Sdim      bool IsTail = TII->isTailCall(MI);
758344779Sdim
759360784Sdim      // If MI is in a bundle, the label was created after the bundle since
760360784Sdim      // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
761360784Sdim      // to search for that label below.
762360784Sdim      const MachineInstr *TopLevelCallMI =
763360784Sdim          MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
764360784Sdim
765360784Sdim      // For tail calls, for non-gdb tuning, no return PC information is needed.
766360784Sdim      // For regular calls (and tail calls in GDB tuning), the return PC
767360784Sdim      // is needed to disambiguate paths in the call graph which could lead to
768360784Sdim      // some target function.
769344779Sdim      const MCExpr *PCOffset =
770360784Sdim          (IsTail && !tuneForGDB())
771360784Sdim              ? nullptr
772360784Sdim              : getFunctionLocalOffsetAfterInsn(TopLevelCallMI);
773344779Sdim
774360784Sdim      // Return address of a call-like instruction for a normal call or a
775360784Sdim      // jump-like instruction for a tail call. This is needed for
776360784Sdim      // GDB + DWARF 4 tuning.
777360784Sdim      const MCSymbol *PCAddr =
778360784Sdim          ApplyGNUExtensions
779360784Sdim              ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
780360784Sdim              : nullptr;
781360784Sdim
782360784Sdim      assert((IsTail || PCOffset || PCAddr) &&
783360784Sdim             "Call without return PC information");
784360784Sdim
785344779Sdim      LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
786360784Sdim                        << (CalleeDecl ? CalleeDecl->getName()
787360784Sdim                                       : StringRef(MF.getSubtarget()
788360784Sdim                                                       .getRegisterInfo()
789360784Sdim                                                       ->getName(CallReg)))
790360784Sdim                        << (IsTail ? " [IsTail]" : "") << "\n");
791360784Sdim
792360784Sdim      DIE &CallSiteDIE =
793360784Sdim            CU.constructCallSiteEntryDIE(ScopeDIE, CalleeSP, IsTail, PCAddr,
794360784Sdim                                         PCOffset, CallReg);
795360784Sdim
796360784Sdim      // GDB and LLDB support call site parameter debug info.
797360784Sdim      if (Asm->TM.Options.EnableDebugEntryValues &&
798360784Sdim          (tuneForGDB() || tuneForLLDB())) {
799360784Sdim        ParamSet Params;
800360784Sdim        // Try to interpret values of call site parameters.
801360784Sdim        collectCallSiteParameters(&MI, Params);
802360784Sdim        CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
803360784Sdim      }
804344779Sdim    }
805344779Sdim  }
806344779Sdim}
807344779Sdim
808321369Sdimvoid DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
809327952Sdim  if (!U.hasDwarfPubSections())
810276479Sdim    return;
811261991Sdim
812276479Sdim  U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
813193323Sed}
814193323Sed
815344779Sdimvoid DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
816344779Sdim                                      DwarfCompileUnit &NewCU) {
817344779Sdim  DIE &Die = NewCU.getUnitDie();
818288943Sdim  StringRef FN = DIUnit->getFilename();
819193323Sed
820321369Sdim  StringRef Producer = DIUnit->getProducer();
821321369Sdim  StringRef Flags = DIUnit->getFlags();
822344779Sdim  if (!Flags.empty() && !useAppleExtensionAttributes()) {
823321369Sdim    std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
824321369Sdim    NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
825321369Sdim  } else
826321369Sdim    NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
827321369Sdim
828276479Sdim  NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
829288943Sdim                DIUnit->getSourceLanguage());
830276479Sdim  NewCU.addString(Die, dwarf::DW_AT_name, FN);
831251662Sdim
832341825Sdim  // Add DW_str_offsets_base to the unit DIE, except for split units.
833341825Sdim  if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
834341825Sdim    NewCU.addStringOffsetsStart();
835341825Sdim
836251662Sdim  if (!useSplitDwarf()) {
837288943Sdim    NewCU.initStmtList();
838261991Sdim
839261991Sdim    // If we're using split dwarf the compilation dir is going to be in the
840261991Sdim    // skeleton CU and so we don't need to duplicate it here.
841261991Sdim    if (!CompilationDir.empty())
842276479Sdim      NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
843261991Sdim
844276479Sdim    addGnuPubAttributes(NewCU, Die);
845251662Sdim  }
846193323Sed
847309124Sdim  if (useAppleExtensionAttributes()) {
848309124Sdim    if (DIUnit->isOptimized())
849309124Sdim      NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
850193323Sed
851309124Sdim    StringRef Flags = DIUnit->getFlags();
852309124Sdim    if (!Flags.empty())
853309124Sdim      NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
854249423Sdim
855309124Sdim    if (unsigned RVer = DIUnit->getRuntimeVersion())
856309124Sdim      NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
857309124Sdim                    dwarf::DW_FORM_data1, RVer);
858309124Sdim  }
859193323Sed
860296417Sdim  if (DIUnit->getDWOId()) {
861296417Sdim    // This CU is either a clang module DWO or a skeleton CU.
862296417Sdim    NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
863296417Sdim                  DIUnit->getDWOId());
864360784Sdim    if (!DIUnit->getSplitDebugFilename().empty()) {
865296417Sdim      // This is a prefabricated skeleton CU.
866360784Sdim      dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
867360784Sdim                                         ? dwarf::DW_AT_dwo_name
868360784Sdim                                         : dwarf::DW_AT_GNU_dwo_name;
869360784Sdim      NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
870360784Sdim    }
871296417Sdim  }
872344779Sdim}
873344779Sdim// Create new DwarfCompileUnit for the given metadata node with tag
874344779Sdim// DW_TAG_compile_unit.
875344779SdimDwarfCompileUnit &
876344779SdimDwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
877344779Sdim  if (auto *CU = CUMap.lookup(DIUnit))
878344779Sdim    return *CU;
879296417Sdim
880344779Sdim  CompilationDir = DIUnit->getDirectory();
881344779Sdim
882360784Sdim  auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
883344779Sdim      InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
884344779Sdim  DwarfCompileUnit &NewCU = *OwnedUnit;
885344779Sdim  InfoHolder.addUnit(std::move(OwnedUnit));
886344779Sdim
887344779Sdim  for (auto *IE : DIUnit->getImportedEntities())
888344779Sdim    NewCU.addImportedEntity(IE);
889344779Sdim
890344779Sdim  // LTO with assembly output shares a single line table amongst multiple CUs.
891344779Sdim  // To avoid the compilation directory being ambiguous, let the line table
892344779Sdim  // explicitly describe the directory of all files, never relying on the
893344779Sdim  // compilation directory.
894344779Sdim  if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
895344779Sdim    Asm->OutStreamer->emitDwarfFile0Directive(
896344779Sdim        CompilationDir, DIUnit->getFilename(),
897344779Sdim        NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
898344779Sdim        NewCU.getUniqueID());
899344779Sdim
900344779Sdim  if (useSplitDwarf()) {
901344779Sdim    NewCU.setSkeleton(constructSkeletonCU(NewCU));
902344779Sdim    NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
903344779Sdim  } else {
904344779Sdim    finishUnitAttributes(DIUnit, NewCU);
905344779Sdim    NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
906344779Sdim  }
907344779Sdim
908353358Sdim  // Create DIEs for function declarations used for call site debug info.
909353358Sdim  for (auto Scope : DIUnit->getRetainedTypes())
910353358Sdim    if (auto *SP = dyn_cast_or_null<DISubprogram>(Scope))
911353358Sdim      NewCU.getOrCreateSubprogramDIE(SP);
912353358Sdim
913314564Sdim  CUMap.insert({DIUnit, &NewCU});
914344779Sdim  CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
915226633Sdim  return NewCU;
916193323Sed}
917193323Sed
918280031Sdimvoid DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
919288943Sdim                                                  const DIImportedEntity *N) {
920327952Sdim  if (isa<DILocalScope>(N->getScope()))
921327952Sdim    return;
922288943Sdim  if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
923288943Sdim    D->addChild(TheCU.constructImportedEntityDIE(N));
924251662Sdim}
925251662Sdim
926314564Sdim/// Sort and unique GVEs by comparing their fragment offset.
927314564Sdimstatic SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
928314564SdimsortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
929344779Sdim  llvm::sort(
930344779Sdim      GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
931344779Sdim        // Sort order: first null exprs, then exprs without fragment
932344779Sdim        // info, then sort by fragment offset in bits.
933344779Sdim        // FIXME: Come up with a more comprehensive comparator so
934344779Sdim        // the sorting isn't non-deterministic, and so the following
935344779Sdim        // std::unique call works correctly.
936344779Sdim        if (!A.Expr || !B.Expr)
937344779Sdim          return !!B.Expr;
938344779Sdim        auto FragmentA = A.Expr->getFragmentInfo();
939344779Sdim        auto FragmentB = B.Expr->getFragmentInfo();
940344779Sdim        if (!FragmentA || !FragmentB)
941344779Sdim          return !!FragmentB;
942344779Sdim        return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
943344779Sdim      });
944314564Sdim  GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
945314564Sdim                         [](DwarfCompileUnit::GlobalExpr A,
946314564Sdim                            DwarfCompileUnit::GlobalExpr B) {
947314564Sdim                           return A.Expr == B.Expr;
948314564Sdim                         }),
949314564Sdim             GVEs.end());
950314564Sdim  return GVEs;
951314564Sdim}
952314564Sdim
953249423Sdim// Emit all Dwarf sections that should come prior to the content. Create
954249423Sdim// global DIEs and emit initial debug info sections. This is invoked by
955249423Sdim// the target AsmPrinter.
956249423Sdimvoid DwarfDebug::beginModule() {
957314564Sdim  NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
958314564Sdim                     DWARFGroupDescription, TimePassesIsEnabled);
959344779Sdim  if (DisableDebugInfoPrinting) {
960344779Sdim    MMI->setDebugInfoAvailability(false);
961207618Srdivacky    return;
962344779Sdim  }
963193323Sed
964249423Sdim  const Module *M = MMI->getModule();
965249423Sdim
966309124Sdim  unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
967309124Sdim                                       M->debug_compile_units_end());
968309124Sdim  // Tell MMI whether we have debug info.
969344779Sdim  assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
970344779Sdim         "DebugInfoAvailabilty initialized unexpectedly");
971309124Sdim  SingleCU = NumDebugCUs == 1;
972314564Sdim  DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
973314564Sdim      GVMap;
974314564Sdim  for (const GlobalVariable &Global : M->globals()) {
975314564Sdim    SmallVector<DIGlobalVariableExpression *, 1> GVs;
976314564Sdim    Global.getDebugInfo(GVs);
977314564Sdim    for (auto *GVE : GVs)
978314564Sdim      GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
979314564Sdim  }
980195098Sed
981341825Sdim  // Create the symbol that designates the start of the unit's contribution
982341825Sdim  // to the string offsets table. In a split DWARF scenario, only the skeleton
983341825Sdim  // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
984341825Sdim  if (useSegmentedStringOffsetsTable())
985341825Sdim    (useSplitDwarf() ? SkeletonHolder : InfoHolder)
986341825Sdim        .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
987341825Sdim
988341825Sdim
989344779Sdim  // Create the symbols that designates the start of the DWARF v5 range list
990344779Sdim  // and locations list tables. They are located past the table headers.
991344779Sdim  if (getDwarfVersion() >= 5) {
992344779Sdim    DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
993344779Sdim    Holder.setRnglistsTableBaseSym(
994344779Sdim        Asm->createTempSymbol("rnglists_table_base"));
995344779Sdim
996344779Sdim    if (useSplitDwarf())
997344779Sdim      InfoHolder.setRnglistsTableBaseSym(
998344779Sdim          Asm->createTempSymbol("rnglists_dwo_table_base"));
999344779Sdim  }
1000344779Sdim
1001344779Sdim  // Create the symbol that points to the first entry following the debug
1002344779Sdim  // address table (.debug_addr) header.
1003344779Sdim  AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1004360784Sdim  DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1005344779Sdim
1006309124Sdim  for (DICompileUnit *CUNode : M->debug_compile_units()) {
1007327952Sdim    // FIXME: Move local imported entities into a list attached to the
1008327952Sdim    // subprogram, then this search won't be needed and a
1009327952Sdim    // getImportedEntities().empty() test should go below with the rest.
1010327952Sdim    bool HasNonLocalImportedEntities = llvm::any_of(
1011327952Sdim        CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1012327952Sdim          return !isa<DILocalScope>(IE->getScope());
1013327952Sdim        });
1014327952Sdim
1015327952Sdim    if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1016327952Sdim        CUNode->getRetainedTypes().empty() &&
1017327952Sdim        CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1018321369Sdim      continue;
1019321369Sdim
1020321369Sdim    DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1021314564Sdim
1022314564Sdim    // Global Variables.
1023327952Sdim    for (auto *GVE : CUNode->getGlobalVariables()) {
1024327952Sdim      // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1025327952Sdim      // already know about the variable and it isn't adding a constant
1026327952Sdim      // expression.
1027327952Sdim      auto &GVMapEntry = GVMap[GVE->getVariable()];
1028327952Sdim      auto *Expr = GVE->getExpression();
1029327952Sdim      if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1030327952Sdim        GVMapEntry.push_back({nullptr, Expr});
1031327952Sdim    }
1032314564Sdim    DenseSet<DIGlobalVariable *> Processed;
1033314564Sdim    for (auto *GVE : CUNode->getGlobalVariables()) {
1034314564Sdim      DIGlobalVariable *GV = GVE->getVariable();
1035314564Sdim      if (Processed.insert(GV).second)
1036314564Sdim        CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1037314564Sdim    }
1038314564Sdim
1039288943Sdim    for (auto *Ty : CUNode->getEnumTypes()) {
1040280031Sdim      // The enum types array by design contains pointers to
1041280031Sdim      // MDNodes rather than DIRefs. Unique them here.
1042309124Sdim      CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1043280031Sdim    }
1044288943Sdim    for (auto *Ty : CUNode->getRetainedTypes()) {
1045276479Sdim      // The retained types array by design contains pointers to
1046276479Sdim      // MDNodes rather than DIRefs. Unique them here.
1047309124Sdim      if (DIType *RT = dyn_cast<DIType>(Ty))
1048309124Sdim          // There is no point in force-emitting a forward declaration.
1049309124Sdim          CU.getOrCreateTypeDIE(RT);
1050276479Sdim    }
1051251662Sdim    // Emit imported_modules last so that the relevant context is already
1052251662Sdim    // available.
1053288943Sdim    for (auto *IE : CUNode->getImportedEntities())
1054288943Sdim      constructAndAddImportedEntityDIE(CU, IE);
1055249423Sdim  }
1056193323Sed}
1057193323Sed
1058344779Sdimvoid DwarfDebug::finishEntityDefinitions() {
1059344779Sdim  for (const auto &Entity : ConcreteEntities) {
1060344779Sdim    DIE *Die = Entity->getDIE();
1061344779Sdim    assert(Die);
1062276479Sdim    // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1063344779Sdim    // in the ConcreteEntities list, rather than looking it up again here.
1064276479Sdim    // DIE::getUnit isn't simple - it walks parent pointers, etc.
1065344779Sdim    DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1066276479Sdim    assert(Unit);
1067344779Sdim    Unit->finishEntityDefinition(Entity.get());
1068249423Sdim  }
1069249423Sdim}
1070249423Sdim
1071276479Sdimvoid DwarfDebug::finishSubprogramDefinitions() {
1072321369Sdim  for (const DISubprogram *SP : ProcessedSPNodes) {
1073321369Sdim    assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1074321369Sdim    forBothCUs(
1075321369Sdim        getOrCreateDwarfCompileUnit(SP->getUnit()),
1076321369Sdim        [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1077321369Sdim  }
1078276479Sdim}
1079276479Sdim
1080276479Sdimvoid DwarfDebug::finalizeModuleInfo() {
1081288943Sdim  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1082288943Sdim
1083276479Sdim  finishSubprogramDefinitions();
1084261991Sdim
1085344779Sdim  finishEntityDefinitions();
1086261991Sdim
1087321369Sdim  // Include the DWO file name in the hash if there's more than one CU.
1088321369Sdim  // This handles ThinLTO's situation where imported CUs may very easily be
1089321369Sdim  // duplicate with the same CU partially imported into another ThinLTO unit.
1090321369Sdim  StringRef DWOName;
1091321369Sdim  if (CUMap.size() > 1)
1092321369Sdim    DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1093321369Sdim
1094276479Sdim  // Handle anything that needs to be done on a per-unit basis after
1095276479Sdim  // all other generation.
1096280031Sdim  for (const auto &P : CUMap) {
1097280031Sdim    auto &TheCU = *P.second;
1098344779Sdim    if (TheCU.getCUNode()->isDebugDirectivesOnly())
1099344779Sdim      continue;
1100261991Sdim    // Emit DW_AT_containing_type attribute to connect types with their
1101261991Sdim    // vtable holding type.
1102280031Sdim    TheCU.constructContainingTypeDIEs();
1103261991Sdim
1104276479Sdim    // Add CU specific attributes if we need to add any.
1105280031Sdim    // If we're splitting the dwarf out now that we've got the entire
1106280031Sdim    // CU then add the dwo id to it.
1107280031Sdim    auto *SkCU = TheCU.getSkeleton();
1108360784Sdim
1109360784Sdim    bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1110360784Sdim
1111360784Sdim    if (HasSplitUnit) {
1112360784Sdim      dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1113360784Sdim                                         ? dwarf::DW_AT_dwo_name
1114360784Sdim                                         : dwarf::DW_AT_GNU_dwo_name;
1115344779Sdim      finishUnitAttributes(TheCU.getCUNode(), TheCU);
1116360784Sdim      TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1117344779Sdim                      Asm->TM.Options.MCOptions.SplitDwarfFile);
1118360784Sdim      SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1119344779Sdim                      Asm->TM.Options.MCOptions.SplitDwarfFile);
1120280031Sdim      // Emit a unique identifier for this CU.
1121321369Sdim      uint64_t ID =
1122321369Sdim          DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
1123341825Sdim      if (getDwarfVersion() >= 5) {
1124341825Sdim        TheCU.setDWOId(ID);
1125341825Sdim        SkCU->setDWOId(ID);
1126341825Sdim      } else {
1127341825Sdim        TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1128341825Sdim                      dwarf::DW_FORM_data8, ID);
1129341825Sdim        SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1130341825Sdim                      dwarf::DW_FORM_data8, ID);
1131341825Sdim      }
1132344779Sdim
1133344779Sdim      if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1134288943Sdim        const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1135280031Sdim        SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1136288943Sdim                              Sym, Sym);
1137288943Sdim      }
1138344779Sdim    } else if (SkCU) {
1139344779Sdim      finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1140280031Sdim    }
1141276479Sdim
1142280031Sdim    // If we have code split among multiple sections or non-contiguous
1143280031Sdim    // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1144280031Sdim    // remain in the .o file, otherwise add a DW_AT_low_pc.
1145280031Sdim    // FIXME: We should use ranges allow reordering of code ala
1146280031Sdim    // .subsections_via_symbols in mach-o. This would mean turning on
1147280031Sdim    // ranges for all subprogram DIEs for mach-o.
1148280031Sdim    DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1149344779Sdim
1150280031Sdim    if (unsigned NumRanges = TheCU.getRanges().size()) {
1151341825Sdim      if (NumRanges > 1 && useRangesSection())
1152280031Sdim        // A DW_AT_low_pc attribute may also be specified in combination with
1153280031Sdim        // DW_AT_ranges to specify the default base address for use in
1154280031Sdim        // location lists (see Section 2.6.2) and range lists (see Section
1155280031Sdim        // 2.17.3).
1156280031Sdim        U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1157280031Sdim      else
1158360784Sdim        U.setBaseAddress(TheCU.getRanges().front().Begin);
1159280031Sdim      U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1160261991Sdim    }
1161296417Sdim
1162353358Sdim    // We don't keep track of which addresses are used in which CU so this
1163353358Sdim    // is a bit pessimistic under LTO.
1164360784Sdim    if ((!AddrPool.isEmpty() || TheCU.hasRangeLists()) &&
1165360784Sdim        (getDwarfVersion() >= 5 || HasSplitUnit))
1166353358Sdim      U.addAddrTableBase();
1167353358Sdim
1168344779Sdim    if (getDwarfVersion() >= 5) {
1169344779Sdim      if (U.hasRangeLists())
1170344779Sdim        U.addRnglistsBase();
1171341825Sdim
1172360784Sdim      if (!DebugLocs.getLists().empty()) {
1173360784Sdim        if (!useSplitDwarf())
1174360784Sdim          U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1175360784Sdim                            DebugLocs.getSym(),
1176360784Sdim                            TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1177360784Sdim      }
1178344779Sdim    }
1179344779Sdim
1180296417Sdim    auto *CUNode = cast<DICompileUnit>(P.first);
1181309124Sdim    // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
1182360784Sdim    if (CUNode->getMacros()) {
1183360784Sdim      if (useSplitDwarf())
1184360784Sdim        TheCU.addSectionDelta(TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1185360784Sdim                            U.getMacroLabelBegin(),
1186360784Sdim                            TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1187360784Sdim      else
1188360784Sdim        U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1189360784Sdim                          U.getMacroLabelBegin(),
1190360784Sdim                          TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1191360784Sdim    }
1192200581Srdivacky  }
1193200581Srdivacky
1194327952Sdim  // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1195327952Sdim  for (auto *CUNode : MMI->getModule()->debug_compile_units())
1196327952Sdim    if (CUNode->getDWOId())
1197327952Sdim      getOrCreateDwarfCompileUnit(CUNode);
1198327952Sdim
1199261991Sdim  // Compute DIE offsets and sizes.
1200249423Sdim  InfoHolder.computeSizeAndOffsets();
1201249423Sdim  if (useSplitDwarf())
1202249423Sdim    SkeletonHolder.computeSizeAndOffsets();
1203249423Sdim}
1204249423Sdim
1205249423Sdim// Emit all Dwarf sections that should come after the content.
1206249423Sdimvoid DwarfDebug::endModule() {
1207276479Sdim  assert(CurFn == nullptr);
1208276479Sdim  assert(CurMI == nullptr);
1209193323Sed
1210353358Sdim  for (const auto &P : CUMap) {
1211353358Sdim    auto &CU = *P.second;
1212353358Sdim    CU.createBaseTypeDIEs();
1213353358Sdim  }
1214353358Sdim
1215280031Sdim  // If we aren't actually generating debug info (check beginModule -
1216280031Sdim  // conditionalized on !DisableDebugInfoPrinting and the presence of the
1217280031Sdim  // llvm.dbg.cu metadata node)
1218288943Sdim  if (!MMI->hasDebugInfo())
1219276479Sdim    return;
1220193323Sed
1221249423Sdim  // Finalize the debug info for the module.
1222249423Sdim  finalizeModuleInfo();
1223249423Sdim
1224276479Sdim  emitDebugStr();
1225261991Sdim
1226288943Sdim  if (useSplitDwarf())
1227360784Sdim    // Emit debug_loc.dwo/debug_loclists.dwo section.
1228288943Sdim    emitDebugLocDWO();
1229288943Sdim  else
1230360784Sdim    // Emit debug_loc/debug_loclists section.
1231288943Sdim    emitDebugLoc();
1232249423Sdim
1233276479Sdim  // Corresponding abbreviations into a abbrev section.
1234276479Sdim  emitAbbreviations();
1235249423Sdim
1236288943Sdim  // Emit all the DIEs into a debug info section.
1237288943Sdim  emitDebugInfo();
1238288943Sdim
1239276479Sdim  // Emit info into a debug aranges section.
1240276479Sdim  if (GenerateARangeSection)
1241249423Sdim    emitDebugARanges();
1242249423Sdim
1243276479Sdim  // Emit info into a debug ranges section.
1244276479Sdim  emitDebugRanges();
1245249423Sdim
1246360784Sdim  if (useSplitDwarf())
1247360784Sdim  // Emit info into a debug macinfo.dwo section.
1248360784Sdim    emitDebugMacinfoDWO();
1249360784Sdim  else
1250296417Sdim  // Emit info into a debug macinfo section.
1251360784Sdim    emitDebugMacinfo();
1252296417Sdim
1253276479Sdim  if (useSplitDwarf()) {
1254276479Sdim    emitDebugStrDWO();
1255249423Sdim    emitDebugInfoDWO();
1256249423Sdim    emitDebugAbbrevDWO();
1257276479Sdim    emitDebugLineDWO();
1258344779Sdim    emitDebugRangesDWO();
1259288943Sdim  }
1260249423Sdim
1261344779Sdim  emitDebugAddr();
1262344779Sdim
1263243830Sdim  // Emit info into the dwarf accelerator table sections.
1264341825Sdim  switch (getAccelTableKind()) {
1265341825Sdim  case AccelTableKind::Apple:
1266234353Sdim    emitAccelNames();
1267234353Sdim    emitAccelObjC();
1268234353Sdim    emitAccelNamespaces();
1269234353Sdim    emitAccelTypes();
1270341825Sdim    break;
1271341825Sdim  case AccelTableKind::Dwarf:
1272341825Sdim    emitAccelDebugNames();
1273341825Sdim    break;
1274341825Sdim  case AccelTableKind::None:
1275341825Sdim    break;
1276341825Sdim  case AccelTableKind::Default:
1277341825Sdim    llvm_unreachable("Default should have already been resolved.");
1278234353Sdim  }
1279249423Sdim
1280261991Sdim  // Emit the pubnames and pubtypes sections if requested.
1281327952Sdim  emitDebugPubSections();
1282249423Sdim
1283212904Sdim  // clean up.
1284321369Sdim  // FIXME: AbstractVariables.clear();
1285193323Sed}
1286193323Sed
1287344779Sdimvoid DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1288344779Sdim                                               const DINode *Node,
1289344779Sdim                                               const MDNode *ScopeNode) {
1290344779Sdim  if (CU.getExistingAbstractEntity(Node))
1291276479Sdim    return;
1292276479Sdim
1293344779Sdim  CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1294288943Sdim                                       cast<DILocalScope>(ScopeNode)));
1295276479Sdim}
1296276479Sdim
1297344779Sdimvoid DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1298344779Sdim    const DINode *Node, const MDNode *ScopeNode) {
1299344779Sdim  if (CU.getExistingAbstractEntity(Node))
1300276479Sdim    return;
1301276479Sdim
1302288943Sdim  if (LexicalScope *Scope =
1303288943Sdim          LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1304344779Sdim    CU.createAbstractEntity(Node, Scope);
1305276479Sdim}
1306327952Sdim
1307314564Sdim// Collect variable information from side table maintained by MF.
1308314564Sdimvoid DwarfDebug::collectVariableInfoFromMFTable(
1309344779Sdim    DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1310344779Sdim  SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1311314564Sdim  for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1312276479Sdim    if (!VI.Var)
1313276479Sdim      continue;
1314288943Sdim    assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1315288943Sdim           "Expected inlined-at fields to agree");
1316288943Sdim
1317344779Sdim    InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1318288943Sdim    Processed.insert(Var);
1319276479Sdim    LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1320199481Srdivacky
1321199481Srdivacky    // If variable scope is not found then skip this variable.
1322276479Sdim    if (!Scope)
1323199481Srdivacky      continue;
1324199481Srdivacky
1325344779Sdim    ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1326360784Sdim    auto RegVar = std::make_unique<DbgVariable>(
1327344779Sdim                    cast<DILocalVariable>(Var.first), Var.second);
1328288943Sdim    RegVar->initializeMMI(VI.Expr, VI.Slot);
1329327952Sdim    if (DbgVariable *DbgVar = MFVars.lookup(Var))
1330327952Sdim      DbgVar->addMMIEntry(*RegVar);
1331327952Sdim    else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1332327952Sdim      MFVars.insert({Var, RegVar.get()});
1333344779Sdim      ConcreteEntities.push_back(std::move(RegVar));
1334327952Sdim    }
1335198090Srdivacky  }
1336208599Srdivacky}
1337205218Srdivacky
1338353358Sdim/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1339353358Sdim/// enclosing lexical scope. The check ensures there are no other instructions
1340353358Sdim/// in the same lexical scope preceding the DBG_VALUE and that its range is
1341353358Sdim/// either open or otherwise rolls off the end of the scope.
1342353358Sdimstatic bool validThroughout(LexicalScopes &LScopes,
1343353358Sdim                            const MachineInstr *DbgValue,
1344353358Sdim                            const MachineInstr *RangeEnd) {
1345353358Sdim  assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1346353358Sdim  auto MBB = DbgValue->getParent();
1347353358Sdim  auto DL = DbgValue->getDebugLoc();
1348353358Sdim  auto *LScope = LScopes.findLexicalScope(DL);
1349353358Sdim  // Scope doesn't exist; this is a dead DBG_VALUE.
1350353358Sdim  if (!LScope)
1351353358Sdim    return false;
1352353358Sdim  auto &LSRange = LScope->getRanges();
1353353358Sdim  if (LSRange.size() == 0)
1354353358Sdim    return false;
1355353358Sdim
1356353358Sdim  // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1357353358Sdim  const MachineInstr *LScopeBegin = LSRange.front().first;
1358353358Sdim  // Early exit if the lexical scope begins outside of the current block.
1359353358Sdim  if (LScopeBegin->getParent() != MBB)
1360353358Sdim    return false;
1361353358Sdim  MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1362353358Sdim  for (++Pred; Pred != MBB->rend(); ++Pred) {
1363353358Sdim    if (Pred->getFlag(MachineInstr::FrameSetup))
1364353358Sdim      break;
1365353358Sdim    auto PredDL = Pred->getDebugLoc();
1366353358Sdim    if (!PredDL || Pred->isMetaInstruction())
1367353358Sdim      continue;
1368353358Sdim    // Check whether the instruction preceding the DBG_VALUE is in the same
1369353358Sdim    // (sub)scope as the DBG_VALUE.
1370353358Sdim    if (DL->getScope() == PredDL->getScope())
1371353358Sdim      return false;
1372353358Sdim    auto *PredScope = LScopes.findLexicalScope(PredDL);
1373353358Sdim    if (!PredScope || LScope->dominates(PredScope))
1374353358Sdim      return false;
1375224145Sdim  }
1376224145Sdim
1377353358Sdim  // If the range of the DBG_VALUE is open-ended, report success.
1378353358Sdim  if (!RangeEnd)
1379353358Sdim    return true;
1380224145Sdim
1381353358Sdim  // Fail if there are instructions belonging to our scope in another block.
1382353358Sdim  const MachineInstr *LScopeEnd = LSRange.back().second;
1383353358Sdim  if (LScopeEnd->getParent() != MBB)
1384353358Sdim    return false;
1385296417Sdim
1386353358Sdim  // Single, constant DBG_VALUEs in the prologue are promoted to be live
1387353358Sdim  // throughout the function. This is a hack, presumably for DWARF v2 and not
1388353358Sdim  // necessarily correct. It would be much better to use a dbg.declare instead
1389353358Sdim  // if we know the constant is live throughout the scope.
1390353358Sdim  if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1391353358Sdim    return true;
1392296417Sdim
1393296417Sdim  return false;
1394296417Sdim}
1395296417Sdim
1396280031Sdim/// Build the location list for all DBG_VALUEs in the function that
1397353358Sdim/// describe the same variable. The resulting DebugLocEntries will have
1398280031Sdim/// strict monotonically increasing begin addresses and will never
1399353358Sdim/// overlap. If the resulting list has only one entry that is valid
1400353358Sdim/// throughout variable's scope return true.
1401280031Sdim//
1402353358Sdim// See the definition of DbgValueHistoryMap::Entry for an explanation of the
1403353358Sdim// different kinds of history map entries. One thing to be aware of is that if
1404353358Sdim// a debug value is ended by another entry (rather than being valid until the
1405353358Sdim// end of the function), that entry's instruction may or may not be included in
1406353358Sdim// the range, depending on if the entry is a clobbering entry (it has an
1407353358Sdim// instruction that clobbers one or more preceding locations), or if it is an
1408353358Sdim// (overlapping) debug value entry. This distinction can be seen in the example
1409353358Sdim// below. The first debug value is ended by the clobbering entry 2, and the
1410353358Sdim// second and third debug values are ended by the overlapping debug value entry
1411353358Sdim// 4.
1412353358Sdim//
1413280031Sdim// Input:
1414280031Sdim//
1415353358Sdim//   History map entries [type, end index, mi]
1416280031Sdim//
1417353358Sdim// 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1418353358Sdim// 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1419353358Sdim// 2 | |    [Clobber, $reg0 = [...], -, -]
1420353358Sdim// 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1421353358Sdim// 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1422280031Sdim//
1423353358Sdim// Output [start, end) [Value...]:
1424353358Sdim//
1425353358Sdim// [0-1)    [(reg0, fragment 0, 32)]
1426353358Sdim// [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1427353358Sdim// [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1428353358Sdim// [4-)     [(@g, fragment 0, 96)]
1429353358Sdimbool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1430353358Sdim                                   const DbgValueHistoryMap::Entries &Entries) {
1431353358Sdim  using OpenRange =
1432353358Sdim      std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1433353358Sdim  SmallVector<OpenRange, 4> OpenRanges;
1434353358Sdim  bool isSafeForSingleLocation = true;
1435353358Sdim  const MachineInstr *StartDebugMI = nullptr;
1436353358Sdim  const MachineInstr *EndMI = nullptr;
1437280031Sdim
1438353358Sdim  for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1439353358Sdim    const MachineInstr *Instr = EI->getInstr();
1440280031Sdim
1441353358Sdim    // Remove all values that are no longer live.
1442353358Sdim    size_t Index = std::distance(EB, EI);
1443353358Sdim    auto Last =
1444353358Sdim        remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1445280031Sdim    OpenRanges.erase(Last, OpenRanges.end());
1446280031Sdim
1447353358Sdim    // If we are dealing with a clobbering entry, this iteration will result in
1448353358Sdim    // a location list entry starting after the clobbering instruction.
1449353358Sdim    const MCSymbol *StartLabel =
1450353358Sdim        EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1451353358Sdim    assert(StartLabel &&
1452353358Sdim           "Forgot label before/after instruction starting a range!");
1453280031Sdim
1454280031Sdim    const MCSymbol *EndLabel;
1455353358Sdim    if (std::next(EI) == Entries.end()) {
1456288943Sdim      EndLabel = Asm->getFunctionEnd();
1457353358Sdim      if (EI->isClobber())
1458353358Sdim        EndMI = EI->getInstr();
1459353358Sdim    }
1460353358Sdim    else if (std::next(EI)->isClobber())
1461353358Sdim      EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1462280031Sdim    else
1463353358Sdim      EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1464280031Sdim    assert(EndLabel && "Forgot label after instruction ending a range!");
1465280031Sdim
1466353358Sdim    if (EI->isDbgValue())
1467353358Sdim      LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1468280031Sdim
1469353358Sdim    // If this history map entry has a debug value, add that to the list of
1470353358Sdim    // open ranges and check if its location is valid for a single value
1471353358Sdim    // location.
1472353358Sdim    if (EI->isDbgValue()) {
1473353358Sdim      // Do not add undef debug values, as they are redundant information in
1474353358Sdim      // the location list entries. An undef debug results in an empty location
1475353358Sdim      // description. If there are any non-undef fragments then padding pieces
1476353358Sdim      // with empty location descriptions will automatically be inserted, and if
1477353358Sdim      // all fragments are undef then the whole location list entry is
1478353358Sdim      // redundant.
1479353358Sdim      if (!Instr->isUndefDebugValue()) {
1480353358Sdim        auto Value = getDebugLocValue(Instr);
1481353358Sdim        OpenRanges.emplace_back(EI->getEndIndex(), Value);
1482344779Sdim
1483353358Sdim        // TODO: Add support for single value fragment locations.
1484353358Sdim        if (Instr->getDebugExpression()->isFragment())
1485353358Sdim          isSafeForSingleLocation = false;
1486353358Sdim
1487353358Sdim        if (!StartDebugMI)
1488353358Sdim          StartDebugMI = Instr;
1489353358Sdim      } else {
1490353358Sdim        isSafeForSingleLocation = false;
1491353358Sdim      }
1492353358Sdim    }
1493353358Sdim
1494353358Sdim    // Location list entries with empty location descriptions are redundant
1495353358Sdim    // information in DWARF, so do not emit those.
1496353358Sdim    if (OpenRanges.empty())
1497353358Sdim      continue;
1498353358Sdim
1499344779Sdim    // Omit entries with empty ranges as they do not have any effect in DWARF.
1500344779Sdim    if (StartLabel == EndLabel) {
1501344779Sdim      LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1502344779Sdim      continue;
1503344779Sdim    }
1504344779Sdim
1505353358Sdim    SmallVector<DbgValueLoc, 4> Values;
1506353358Sdim    for (auto &R : OpenRanges)
1507353358Sdim      Values.push_back(R.second);
1508353358Sdim    DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1509280031Sdim
1510280031Sdim    // Attempt to coalesce the ranges of two otherwise identical
1511280031Sdim    // DebugLocEntries.
1512280031Sdim    auto CurEntry = DebugLoc.rbegin();
1513341825Sdim    LLVM_DEBUG({
1514280031Sdim      dbgs() << CurEntry->getValues().size() << " Values:\n";
1515288943Sdim      for (auto &Value : CurEntry->getValues())
1516309124Sdim        Value.dump();
1517280031Sdim      dbgs() << "-----\n";
1518280031Sdim    });
1519288943Sdim
1520288943Sdim    auto PrevEntry = std::next(CurEntry);
1521288943Sdim    if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1522288943Sdim      DebugLoc.pop_back();
1523280031Sdim  }
1524353358Sdim
1525353358Sdim  return DebugLoc.size() == 1 && isSafeForSingleLocation &&
1526353358Sdim         validThroughout(LScopes, StartDebugMI, EndMI);
1527280031Sdim}
1528280031Sdim
1529344779SdimDbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1530344779Sdim                                            LexicalScope &Scope,
1531344779Sdim                                            const DINode *Node,
1532344779Sdim                                            const DILocation *Location,
1533344779Sdim                                            const MCSymbol *Sym) {
1534344779Sdim  ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1535344779Sdim  if (isa<const DILocalVariable>(Node)) {
1536344779Sdim    ConcreteEntities.push_back(
1537360784Sdim        std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1538344779Sdim                                       Location));
1539344779Sdim    InfoHolder.addScopeVariable(&Scope,
1540344779Sdim        cast<DbgVariable>(ConcreteEntities.back().get()));
1541344779Sdim  } else if (isa<const DILabel>(Node)) {
1542344779Sdim    ConcreteEntities.push_back(
1543360784Sdim        std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1544344779Sdim                                    Location, Sym));
1545344779Sdim    InfoHolder.addScopeLabel(&Scope,
1546344779Sdim        cast<DbgLabel>(ConcreteEntities.back().get()));
1547344779Sdim  }
1548344779Sdim  return ConcreteEntities.back().get();
1549288943Sdim}
1550280031Sdim
1551249423Sdim// Find variables for each lexical scope.
1552344779Sdimvoid DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1553344779Sdim                                   const DISubprogram *SP,
1554344779Sdim                                   DenseSet<InlinedEntity> &Processed) {
1555261991Sdim  // Grab the variable info that was squirreled away in the MMI side-table.
1556321369Sdim  collectVariableInfoFromMFTable(TheCU, Processed);
1557208599Srdivacky
1558276479Sdim  for (const auto &I : DbgValues) {
1559344779Sdim    InlinedEntity IV = I.first;
1560288943Sdim    if (Processed.count(IV))
1561221345Sdim      continue;
1562206083Srdivacky
1563288943Sdim    // Instruction ranges, specifying where IV is accessible.
1564353358Sdim    const auto &HistoryMapEntries = I.second;
1565353358Sdim    if (HistoryMapEntries.empty())
1566208599Srdivacky      continue;
1567207618Srdivacky
1568276479Sdim    LexicalScope *Scope = nullptr;
1569344779Sdim    const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1570288943Sdim    if (const DILocation *IA = IV.second)
1571344779Sdim      Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1572288943Sdim    else
1573344779Sdim      Scope = LScopes.findLexicalScope(LocalVar->getScope());
1574208599Srdivacky    // If variable scope is not found then skip this variable.
1575208599Srdivacky    if (!Scope)
1576208599Srdivacky      continue;
1577208599Srdivacky
1578288943Sdim    Processed.insert(IV);
1579344779Sdim    DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1580344779Sdim                                            *Scope, LocalVar, IV.second));
1581288943Sdim
1582353358Sdim    const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1583221345Sdim    assert(MInsn->isDebugValue() && "History must begin with debug value");
1584221345Sdim
1585321369Sdim    // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1586353358Sdim    // If the history map contains a single debug value, there may be an
1587353358Sdim    // additional entry which clobbers the debug value.
1588353358Sdim    size_t HistSize = HistoryMapEntries.size();
1589353358Sdim    bool SingleValueWithClobber =
1590353358Sdim        HistSize == 2 && HistoryMapEntries[1].isClobber();
1591353358Sdim    if (HistSize == 1 || SingleValueWithClobber) {
1592353358Sdim      const auto *End =
1593353358Sdim          SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1594353358Sdim      if (validThroughout(LScopes, MInsn, End)) {
1595353358Sdim        RegVar->initializeDbgValue(MInsn);
1596353358Sdim        continue;
1597353358Sdim      }
1598288943Sdim    }
1599353358Sdim
1600341825Sdim    // Do not emit location lists if .debug_loc secton is disabled.
1601341825Sdim    if (!useLocSection())
1602341825Sdim      continue;
1603208599Srdivacky
1604249423Sdim    // Handle multiple DBG_VALUE instructions describing one variable.
1605288943Sdim    DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1606221345Sdim
1607288943Sdim    // Build the location list for this variable.
1608288943Sdim    SmallVector<DebugLocEntry, 8> Entries;
1609353358Sdim    bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1610212904Sdim
1611353358Sdim    // Check whether buildLocationList managed to merge all locations to one
1612353358Sdim    // that is valid throughout the variable's scope. If so, produce single
1613353358Sdim    // value location.
1614353358Sdim    if (isValidSingleLocation) {
1615353358Sdim      RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1616353358Sdim      continue;
1617353358Sdim    }
1618353358Sdim
1619309124Sdim    // If the variable has a DIBasicType, extract it.  Basic types cannot have
1620288943Sdim    // unique identifiers, so don't bother resolving the type with the
1621288943Sdim    // identifier map.
1622288943Sdim    const DIBasicType *BT = dyn_cast<DIBasicType>(
1623344779Sdim        static_cast<const Metadata *>(LocalVar->getType()));
1624288943Sdim
1625288943Sdim    // Finalize the entry by lowering it into a DWARF bytestream.
1626288943Sdim    for (auto &Entry : Entries)
1627353358Sdim      Entry.finalize(*Asm, List, BT, TheCU);
1628208599Srdivacky  }
1629205218Srdivacky
1630344779Sdim  // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1631344779Sdim  // DWARF-related DbgLabel.
1632344779Sdim  for (const auto &I : DbgLabels) {
1633344779Sdim    InlinedEntity IL = I.first;
1634344779Sdim    const MachineInstr *MI = I.second;
1635344779Sdim    if (MI == nullptr)
1636344779Sdim      continue;
1637344779Sdim
1638344779Sdim    LexicalScope *Scope = nullptr;
1639344779Sdim    const DILabel *Label = cast<DILabel>(IL.first);
1640360784Sdim    // The scope could have an extra lexical block file.
1641360784Sdim    const DILocalScope *LocalScope =
1642360784Sdim        Label->getScope()->getNonLexicalBlockFileScope();
1643344779Sdim    // Get inlined DILocation if it is inlined label.
1644344779Sdim    if (const DILocation *IA = IL.second)
1645360784Sdim      Scope = LScopes.findInlinedScope(LocalScope, IA);
1646344779Sdim    else
1647360784Sdim      Scope = LScopes.findLexicalScope(LocalScope);
1648344779Sdim    // If label scope is not found then skip this label.
1649344779Sdim    if (!Scope)
1650344779Sdim      continue;
1651344779Sdim
1652344779Sdim    Processed.insert(IL);
1653344779Sdim    /// At this point, the temporary label is created.
1654344779Sdim    /// Save the temporary label to DbgLabel entity to get the
1655344779Sdim    /// actually address when generating Dwarf DIE.
1656344779Sdim    MCSymbol *Sym = getLabelBeforeInsn(MI);
1657344779Sdim    createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1658344779Sdim  }
1659344779Sdim
1660344779Sdim  // Collect info for variables/labels that were optimized out.
1661341825Sdim  for (const DINode *DN : SP->getRetainedNodes()) {
1662344779Sdim    if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1663344779Sdim      continue;
1664344779Sdim    LexicalScope *Scope = nullptr;
1665341825Sdim    if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1666344779Sdim      Scope = LScopes.findLexicalScope(DV->getScope());
1667344779Sdim    } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1668344779Sdim      Scope = LScopes.findLexicalScope(DL->getScope());
1669341825Sdim    }
1670344779Sdim
1671344779Sdim    if (Scope)
1672344779Sdim      createConcreteEntity(TheCU, *Scope, DN, nullptr);
1673205218Srdivacky  }
1674198090Srdivacky}
1675198090Srdivacky
1676249423Sdim// Process beginning of an instruction.
1677218893Sdimvoid DwarfDebug::beginInstruction(const MachineInstr *MI) {
1678309124Sdim  DebugHandlerBase::beginInstruction(MI);
1679309124Sdim  assert(CurMI);
1680309124Sdim
1681327952Sdim  const auto *SP = MI->getMF()->getFunction().getSubprogram();
1682321369Sdim  if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1683321369Sdim    return;
1684321369Sdim
1685314564Sdim  // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1686341825Sdim  // If the instruction is part of the function frame setup code, do not emit
1687341825Sdim  // any line record, as there is no correspondence with any user code.
1688341825Sdim  if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1689314564Sdim    return;
1690314564Sdim  const DebugLoc &DL = MI->getDebugLoc();
1691314564Sdim  // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1692314564Sdim  // the last line number actually emitted, to see if it was line 0.
1693314564Sdim  unsigned LastAsmLine =
1694314564Sdim      Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1695234353Sdim
1696344779Sdim  // Request a label after the call in order to emit AT_return_pc information
1697344779Sdim  // in call site entries. TODO: Add support for targets with delay slots.
1698344779Sdim  if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1699344779Sdim    requestLabelAfterInsn(MI);
1700344779Sdim
1701314564Sdim  if (DL == PrevInstLoc) {
1702314564Sdim    // If we have an ongoing unspecified location, nothing to do here.
1703314564Sdim    if (!DL)
1704314564Sdim      return;
1705314564Sdim    // We have an explicit location, same as the previous location.
1706314564Sdim    // But we might be coming back to it after a line 0 record.
1707314564Sdim    if (LastAsmLine == 0 && DL.getLine() != 0) {
1708314564Sdim      // Reinstate the source location but not marked as a statement.
1709314564Sdim      const MDNode *Scope = DL.getScope();
1710314564Sdim      recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1711314564Sdim    }
1712314564Sdim    return;
1713314564Sdim  }
1714314564Sdim
1715314564Sdim  if (!DL) {
1716314564Sdim    // We have an unspecified location, which might want to be line 0.
1717314564Sdim    // If we have already emitted a line-0 record, don't repeat it.
1718314564Sdim    if (LastAsmLine == 0)
1719314564Sdim      return;
1720314564Sdim    // If user said Don't Do That, don't do that.
1721314564Sdim    if (UnknownLocations == Disable)
1722314564Sdim      return;
1723314564Sdim    // See if we have a reason to emit a line-0 record now.
1724314564Sdim    // Reasons to emit a line-0 record include:
1725314564Sdim    // - User asked for it (UnknownLocations).
1726314564Sdim    // - Instruction has a label, so it's referenced from somewhere else,
1727314564Sdim    //   possibly debug information; we want it to have a source location.
1728314564Sdim    // - Instruction is at the top of a block; we don't want to inherit the
1729314564Sdim    //   location from the physically previous (maybe unrelated) block.
1730314564Sdim    if (UnknownLocations == Enable || PrevLabel ||
1731314564Sdim        (PrevInstBB && PrevInstBB != MI->getParent())) {
1732314564Sdim      // Preserve the file and column numbers, if we can, to save space in
1733314564Sdim      // the encoded line table.
1734314564Sdim      // Do not update PrevInstLoc, it remembers the last non-0 line.
1735314564Sdim      const MDNode *Scope = nullptr;
1736314564Sdim      unsigned Column = 0;
1737314564Sdim      if (PrevInstLoc) {
1738314564Sdim        Scope = PrevInstLoc.getScope();
1739314564Sdim        Column = PrevInstLoc.getCol();
1740288943Sdim      }
1741314564Sdim      recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1742221345Sdim    }
1743314564Sdim    return;
1744208599Srdivacky  }
1745314564Sdim
1746314564Sdim  // We have an explicit location, different from the previous location.
1747314564Sdim  // Don't repeat a line-0 record, but otherwise emit the new location.
1748314564Sdim  // (The new location might be an explicit line 0, which we do emit.)
1749353358Sdim  if (DL.getLine() == 0 && LastAsmLine == 0)
1750314564Sdim    return;
1751314564Sdim  unsigned Flags = 0;
1752314564Sdim  if (DL == PrologEndLoc) {
1753314564Sdim    Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1754314564Sdim    PrologEndLoc = DebugLoc();
1755314564Sdim  }
1756314564Sdim  // If the line changed, we call that a new statement; unless we went to
1757314564Sdim  // line 0 and came back, in which case it is not a new statement.
1758314564Sdim  unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1759314564Sdim  if (DL.getLine() && DL.getLine() != OldLine)
1760314564Sdim    Flags |= DWARF2_FLAG_IS_STMT;
1761314564Sdim
1762314564Sdim  const MDNode *Scope = DL.getScope();
1763314564Sdim  recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1764314564Sdim
1765314564Sdim  // If we're not at line 0, remember this location.
1766314564Sdim  if (DL.getLine())
1767314564Sdim    PrevInstLoc = DL;
1768221345Sdim}
1769206083Srdivacky
1770276479Sdimstatic DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1771276479Sdim  // First known non-DBG_VALUE and non-frame setup location marks
1772276479Sdim  // the beginning of the function body.
1773276479Sdim  for (const auto &MBB : *MF)
1774276479Sdim    for (const auto &MI : MBB)
1775321369Sdim      if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1776296417Sdim          MI.getDebugLoc())
1777276479Sdim        return MI.getDebugLoc();
1778223017Sdim  return DebugLoc();
1779218893Sdim}
1780218893Sdim
1781353358Sdim/// Register a source line with debug info. Returns the  unique label that was
1782353358Sdim/// emitted and which provides correspondence to the source line list.
1783353358Sdimstatic void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1784353358Sdim                             const MDNode *S, unsigned Flags, unsigned CUID,
1785353358Sdim                             uint16_t DwarfVersion,
1786353358Sdim                             ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1787353358Sdim  StringRef Fn;
1788353358Sdim  unsigned FileNo = 1;
1789353358Sdim  unsigned Discriminator = 0;
1790353358Sdim  if (auto *Scope = cast_or_null<DIScope>(S)) {
1791353358Sdim    Fn = Scope->getFilename();
1792353358Sdim    if (Line != 0 && DwarfVersion >= 4)
1793353358Sdim      if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1794353358Sdim        Discriminator = LBF->getDiscriminator();
1795353358Sdim
1796353358Sdim    FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1797353358Sdim                 .getOrCreateSourceID(Scope->getFile());
1798353358Sdim  }
1799353358Sdim  Asm.OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1800353358Sdim                                         Discriminator, Fn);
1801353358Sdim}
1802353358Sdim
1803353358SdimDebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
1804353358Sdim                                             unsigned CUID) {
1805353358Sdim  // Get beginning of function.
1806353358Sdim  if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1807353358Sdim    // Ensure the compile unit is created if the function is called before
1808353358Sdim    // beginFunction().
1809353358Sdim    (void)getOrCreateDwarfCompileUnit(
1810353358Sdim        MF.getFunction().getSubprogram()->getUnit());
1811353358Sdim    // We'd like to list the prologue as "not statements" but GDB behaves
1812353358Sdim    // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1813353358Sdim    const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1814353358Sdim    ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1815353358Sdim                       CUID, getDwarfVersion(), getUnits());
1816353358Sdim    return PrologEndLoc;
1817353358Sdim  }
1818353358Sdim  return DebugLoc();
1819353358Sdim}
1820353358Sdim
1821249423Sdim// Gather pre-function debug information.  Assumes being called immediately
1822249423Sdim// after the function entry point has been emitted.
1823321369Sdimvoid DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1824276479Sdim  CurFn = MF;
1825261991Sdim
1826327952Sdim  auto *SP = MF->getFunction().getSubprogram();
1827321369Sdim  assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1828321369Sdim  if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1829261991Sdim    return;
1830261991Sdim
1831360784Sdim  SectionLabels.insert(std::make_pair(&Asm->getFunctionBegin()->getSection(),
1832360784Sdim                                      Asm->getFunctionBegin()));
1833360784Sdim
1834321369Sdim  DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1835280031Sdim
1836276479Sdim  // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1837261991Sdim  // belongs to so that we add to the correct per-cu line table in the
1838261991Sdim  // non-asm case.
1839288943Sdim  if (Asm->OutStreamer->hasRawTextSupport())
1840276479Sdim    // Use a single line table if we are generating assembly.
1841288943Sdim    Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1842251662Sdim  else
1843321369Sdim    Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1844249423Sdim
1845223017Sdim  // Record beginning of function.
1846353358Sdim  PrologEndLoc = emitInitialLocDirective(
1847353358Sdim      *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1848193323Sed}
1849193323Sed
1850321369Sdimvoid DwarfDebug::skippedNonDebugFunction() {
1851321369Sdim  // If we don't have a subprogram for this function then there will be a hole
1852321369Sdim  // in the range information. Keep note of this by setting the previously used
1853321369Sdim  // section to nullptr.
1854321369Sdim  PrevCU = nullptr;
1855321369Sdim  CurFn = nullptr;
1856321369Sdim}
1857321369Sdim
1858249423Sdim// Gather and emit post-function debug information.
1859321369Sdimvoid DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1860327952Sdim  const DISubprogram *SP = MF->getFunction().getSubprogram();
1861321369Sdim
1862280031Sdim  assert(CurFn == MF &&
1863280031Sdim      "endFunction should be called with the same function as beginFunction");
1864193323Sed
1865276479Sdim  // Set DwarfDwarfCompileUnitID in MCContext to default value.
1866288943Sdim  Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1867249423Sdim
1868280031Sdim  LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1869314564Sdim  assert(!FnScope || SP == FnScope->getScopeNode());
1870309124Sdim  DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1871344779Sdim  if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1872344779Sdim    PrevLabel = nullptr;
1873344779Sdim    CurFn = nullptr;
1874344779Sdim    return;
1875344779Sdim  }
1876280031Sdim
1877344779Sdim  DenseSet<InlinedEntity> Processed;
1878344779Sdim  collectEntityInfo(TheCU, SP, Processed);
1879249423Sdim
1880280031Sdim  // Add the range of this function to the list of ranges for the CU.
1881360784Sdim  TheCU.addRange({Asm->getFunctionBegin(), Asm->getFunctionEnd()});
1882208599Srdivacky
1883280031Sdim  // Under -gmlt, skip building the subprogram if there are no inlined
1884321369Sdim  // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1885321369Sdim  // is still needed as we need its source location.
1886321369Sdim  if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1887321369Sdim      TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1888280031Sdim      LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1889280031Sdim    assert(InfoHolder.getScopeVariables().empty());
1890280031Sdim    PrevLabel = nullptr;
1891280031Sdim    CurFn = nullptr;
1892280031Sdim    return;
1893280031Sdim  }
1894280031Sdim
1895280031Sdim#ifndef NDEBUG
1896280031Sdim  size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1897280031Sdim#endif
1898226633Sdim  // Construct abstract scopes.
1899276479Sdim  for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1900288943Sdim    auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1901341825Sdim    for (const DINode *DN : SP->getRetainedNodes()) {
1902344779Sdim      if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1903344779Sdim        continue;
1904344779Sdim
1905344779Sdim      const MDNode *Scope = nullptr;
1906344779Sdim      if (auto *DV = dyn_cast<DILocalVariable>(DN))
1907344779Sdim        Scope = DV->getScope();
1908344779Sdim      else if (auto *DL = dyn_cast<DILabel>(DN))
1909344779Sdim        Scope = DL->getScope();
1910344779Sdim      else
1911344779Sdim        llvm_unreachable("Unexpected DI type!");
1912344779Sdim
1913344779Sdim      // Collect info for variables/labels that were optimized out.
1914344779Sdim      ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1915344779Sdim      assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1916344779Sdim             && "ensureAbstractEntityIsCreated inserted abstract scopes");
1917210299Sed    }
1918321369Sdim    constructAbstractSubprogramScopeDIE(TheCU, AScope);
1919226633Sdim  }
1920249423Sdim
1921314564Sdim  ProcessedSPNodes.insert(SP);
1922344779Sdim  DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1923280031Sdim  if (auto *SkelCU = TheCU.getSkeleton())
1924314564Sdim    if (!LScopes.getAbstractScopesList().empty() &&
1925314564Sdim        TheCU.getCUNode()->getSplitDebugInlining())
1926314564Sdim      SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1927249423Sdim
1928344779Sdim  // Construct call site entries.
1929344779Sdim  constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1930344779Sdim
1931193323Sed  // Clear debug info
1932276479Sdim  // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1933276479Sdim  // DbgVariables except those that are also in AbstractVariables (since they
1934276479Sdim  // can be used cross-function)
1935280031Sdim  InfoHolder.getScopeVariables().clear();
1936344779Sdim  InfoHolder.getScopeLabels().clear();
1937276479Sdim  PrevLabel = nullptr;
1938276479Sdim  CurFn = nullptr;
1939193323Sed}
1940193323Sed
1941249423Sdim// Register a source line with debug info. Returns the  unique label that was
1942249423Sdim// emitted and which provides correspondence to the source line list.
1943223017Sdimvoid DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1944223017Sdim                                  unsigned Flags) {
1945353358Sdim  ::recordSourceLine(*Asm, Line, Col, S, Flags,
1946353358Sdim                     Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
1947353358Sdim                     getDwarfVersion(), getUnits());
1948193323Sed}
1949193323Sed
1950193323Sed//===----------------------------------------------------------------------===//
1951193323Sed// Emit Methods
1952193323Sed//===----------------------------------------------------------------------===//
1953193323Sed
1954249423Sdim// Emit the debug info section.
1955249423Sdimvoid DwarfDebug::emitDebugInfo() {
1956276479Sdim  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1957288943Sdim  Holder.emitUnits(/* UseOffsets */ false);
1958249423Sdim}
1959249423Sdim
1960249423Sdim// Emit the abbreviation section.
1961249423Sdimvoid DwarfDebug::emitAbbreviations() {
1962276479Sdim  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1963249423Sdim
1964276479Sdim  Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1965193323Sed}
1966193323Sed
1967341825Sdimvoid DwarfDebug::emitStringOffsetsTableHeader() {
1968341825Sdim  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1969341825Sdim  Holder.getStringPool().emitStringOffsetsTableHeader(
1970341825Sdim      *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1971341825Sdim      Holder.getStringOffsetsStartSym());
1972341825Sdim}
1973341825Sdim
1974341825Sdimtemplate <typename AccelTableT>
1975341825Sdimvoid DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1976288943Sdim                           StringRef TableName) {
1977288943Sdim  Asm->OutStreamer->SwitchSection(Section);
1978212904Sdim
1979234353Sdim  // Emit the full data.
1980341825Sdim  emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1981234353Sdim}
1982212904Sdim
1983341825Sdimvoid DwarfDebug::emitAccelDebugNames() {
1984341825Sdim  // Don't emit anything if we have no compilation units to index.
1985341825Sdim  if (getUnits().empty())
1986341825Sdim    return;
1987341825Sdim
1988341825Sdim  emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1989341825Sdim}
1990341825Sdim
1991280031Sdim// Emit visible names into a hashed accelerator table section.
1992280031Sdimvoid DwarfDebug::emitAccelNames() {
1993280031Sdim  emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1994288943Sdim            "Names");
1995280031Sdim}
1996280031Sdim
1997249423Sdim// Emit objective C classes and categories into a hashed accelerator table
1998249423Sdim// section.
1999234353Sdimvoid DwarfDebug::emitAccelObjC() {
2000280031Sdim  emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2001288943Sdim            "ObjC");
2002234353Sdim}
2003212904Sdim
2004249423Sdim// Emit namespace dies into a hashed accelerator table.
2005234353Sdimvoid DwarfDebug::emitAccelNamespaces() {
2006280031Sdim  emitAccel(AccelNamespace,
2007280031Sdim            Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2008288943Sdim            "namespac");
2009234353Sdim}
2010234353Sdim
2011249423Sdim// Emit type dies into a hashed accelerator table.
2012234353Sdimvoid DwarfDebug::emitAccelTypes() {
2013280031Sdim  emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2014288943Sdim            "types");
2015193323Sed}
2016193323Sed
2017261991Sdim// Public name handling.
2018261991Sdim// The format for the various pubnames:
2019261991Sdim//
2020261991Sdim// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2021261991Sdim// for the DIE that is named.
2022261991Sdim//
2023261991Sdim// gnu pubnames - offset/index value/name tuples where the offset is the offset
2024261991Sdim// into the CU and the index value is computed according to the type of value
2025261991Sdim// for the DIE that is named.
2026261991Sdim//
2027261991Sdim// For type units the offset is the offset of the skeleton DIE. For split dwarf
2028261991Sdim// it's the offset within the debug_info/debug_types dwo section, however, the
2029261991Sdim// reference in the pubname header doesn't change.
2030261991Sdim
2031261991Sdim/// computeIndexValue - Compute the gdb index value for the DIE and CU.
2032276479Sdimstatic dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2033276479Sdim                                                        const DIE *Die) {
2034321369Sdim  // Entities that ended up only in a Type Unit reference the CU instead (since
2035321369Sdim  // the pub entry has offsets within the CU there's no real offset that can be
2036321369Sdim  // provided anyway). As it happens all such entities (namespaces and types,
2037321369Sdim  // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2038321369Sdim  // not to be true it would be necessary to persist this information from the
2039321369Sdim  // point at which the entry is added to the index data structure - since by
2040321369Sdim  // the time the index is built from that, the original type/namespace DIE in a
2041321369Sdim  // type unit has already been destroyed so it can't be queried for properties
2042321369Sdim  // like tag, etc.
2043321369Sdim  if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2044321369Sdim    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2045321369Sdim                                          dwarf::GIEL_EXTERNAL);
2046261991Sdim  dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2047261991Sdim
2048261991Sdim  // We could have a specification DIE that has our most of our knowledge,
2049261991Sdim  // look for that now.
2050288943Sdim  if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2051288943Sdim    DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2052276479Sdim    if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2053261991Sdim      Linkage = dwarf::GIEL_EXTERNAL;
2054261991Sdim  } else if (Die->findAttribute(dwarf::DW_AT_external))
2055261991Sdim    Linkage = dwarf::GIEL_EXTERNAL;
2056261991Sdim
2057261991Sdim  switch (Die->getTag()) {
2058261991Sdim  case dwarf::DW_TAG_class_type:
2059261991Sdim  case dwarf::DW_TAG_structure_type:
2060261991Sdim  case dwarf::DW_TAG_union_type:
2061261991Sdim  case dwarf::DW_TAG_enumeration_type:
2062261991Sdim    return dwarf::PubIndexEntryDescriptor(
2063360784Sdim        dwarf::GIEK_TYPE,
2064360784Sdim        dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2065360784Sdim            ? dwarf::GIEL_EXTERNAL
2066360784Sdim            : dwarf::GIEL_STATIC);
2067261991Sdim  case dwarf::DW_TAG_typedef:
2068261991Sdim  case dwarf::DW_TAG_base_type:
2069261991Sdim  case dwarf::DW_TAG_subrange_type:
2070261991Sdim    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2071261991Sdim  case dwarf::DW_TAG_namespace:
2072261991Sdim    return dwarf::GIEK_TYPE;
2073261991Sdim  case dwarf::DW_TAG_subprogram:
2074261991Sdim    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2075261991Sdim  case dwarf::DW_TAG_variable:
2076261991Sdim    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2077261991Sdim  case dwarf::DW_TAG_enumerator:
2078261991Sdim    return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2079261991Sdim                                          dwarf::GIEL_STATIC);
2080261991Sdim  default:
2081261991Sdim    return dwarf::GIEK_NONE;
2082261991Sdim  }
2083261991Sdim}
2084261991Sdim
2085327952Sdim/// emitDebugPubSections - Emit visible names and types into debug pubnames and
2086327952Sdim/// pubtypes sections.
2087327952Sdimvoid DwarfDebug::emitDebugPubSections() {
2088276479Sdim  for (const auto &NU : CUMap) {
2089276479Sdim    DwarfCompileUnit *TheU = NU.second;
2090327952Sdim    if (!TheU->hasDwarfPubSections())
2091327952Sdim      continue;
2092276479Sdim
2093344779Sdim    bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2094344779Sdim                    DICompileUnit::DebugNameTableKind::GNU;
2095276479Sdim
2096327952Sdim    Asm->OutStreamer->SwitchSection(
2097327952Sdim        GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2098327952Sdim                 : Asm->getObjFileLowering().getDwarfPubNamesSection());
2099327952Sdim    emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2100276479Sdim
2101327952Sdim    Asm->OutStreamer->SwitchSection(
2102327952Sdim        GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2103327952Sdim                 : Asm->getObjFileLowering().getDwarfPubTypesSection());
2104327952Sdim    emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2105327952Sdim  }
2106327952Sdim}
2107276479Sdim
2108341825Sdimvoid DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2109341825Sdim  if (useSectionsAsReferences())
2110341825Sdim    Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
2111341825Sdim                         CU.getDebugSectionOffset());
2112341825Sdim  else
2113341825Sdim    Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2114341825Sdim}
2115341825Sdim
2116327952Sdimvoid DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2117327952Sdim                                     DwarfCompileUnit *TheU,
2118327952Sdim                                     const StringMap<const DIE *> &Globals) {
2119327952Sdim  if (auto *Skeleton = TheU->getSkeleton())
2120327952Sdim    TheU = Skeleton;
2121249423Sdim
2122327952Sdim  // Emit the header.
2123327952Sdim  Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
2124327952Sdim  MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2125327952Sdim  MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2126327952Sdim  Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2127249423Sdim
2128327952Sdim  Asm->OutStreamer->EmitLabel(BeginLabel);
2129249423Sdim
2130327952Sdim  Asm->OutStreamer->AddComment("DWARF Version");
2131341825Sdim  Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2132249423Sdim
2133327952Sdim  Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2134341825Sdim  emitSectionReference(*TheU);
2135249423Sdim
2136327952Sdim  Asm->OutStreamer->AddComment("Compilation Unit Length");
2137341825Sdim  Asm->emitInt32(TheU->getLength());
2138249423Sdim
2139327952Sdim  // Emit the pubnames for this compilation unit.
2140327952Sdim  for (const auto &GI : Globals) {
2141327952Sdim    const char *Name = GI.getKeyData();
2142327952Sdim    const DIE *Entity = GI.second;
2143249423Sdim
2144327952Sdim    Asm->OutStreamer->AddComment("DIE offset");
2145341825Sdim    Asm->emitInt32(Entity->getOffset());
2146249423Sdim
2147327952Sdim    if (GnuStyle) {
2148327952Sdim      dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2149327952Sdim      Asm->OutStreamer->AddComment(
2150344779Sdim          Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2151344779Sdim          ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2152341825Sdim      Asm->emitInt8(Desc.toBits());
2153249423Sdim    }
2154249423Sdim
2155327952Sdim    Asm->OutStreamer->AddComment("External Name");
2156327952Sdim    Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2157249423Sdim  }
2158249423Sdim
2159327952Sdim  Asm->OutStreamer->AddComment("End Mark");
2160341825Sdim  Asm->emitInt32(0);
2161327952Sdim  Asm->OutStreamer->EmitLabel(EndLabel);
2162276479Sdim}
2163261991Sdim
2164309124Sdim/// Emit null-terminated strings into a debug str section.
2165276479Sdimvoid DwarfDebug::emitDebugStr() {
2166341825Sdim  MCSection *StringOffsetsSection = nullptr;
2167341825Sdim  if (useSegmentedStringOffsetsTable()) {
2168341825Sdim    emitStringOffsetsTableHeader();
2169341825Sdim    StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2170341825Sdim  }
2171276479Sdim  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2172341825Sdim  Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2173341825Sdim                     StringOffsetsSection, /* UseRelativeOffsets = */ true);
2174276479Sdim}
2175261991Sdim
2176276479Sdimvoid DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2177353358Sdim                                   const DebugLocStream::Entry &Entry,
2178353358Sdim                                   const DwarfCompileUnit *CU) {
2179288943Sdim  auto &&Comments = DebugLocs.getComments(Entry);
2180288943Sdim  auto Comment = Comments.begin();
2181288943Sdim  auto End = Comments.end();
2182353358Sdim
2183353358Sdim  // The expressions are inserted into a byte stream rather early (see
2184353358Sdim  // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2185353358Sdim  // need to reference a base_type DIE the offset of that DIE is not yet known.
2186353358Sdim  // To deal with this we instead insert a placeholder early and then extract
2187353358Sdim  // it here and replace it with the real reference.
2188353358Sdim  unsigned PtrSize = Asm->MAI->getCodePointerSize();
2189353358Sdim  DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2190353358Sdim                                    DebugLocs.getBytes(Entry).size()),
2191353358Sdim                          Asm->getDataLayout().isLittleEndian(), PtrSize);
2192353358Sdim  DWARFExpression Expr(Data, getDwarfVersion(), PtrSize);
2193353358Sdim
2194353358Sdim  using Encoding = DWARFExpression::Operation::Encoding;
2195360784Sdim  uint64_t Offset = 0;
2196353358Sdim  for (auto &Op : Expr) {
2197353358Sdim    assert(Op.getCode() != dwarf::DW_OP_const_type &&
2198353358Sdim           "3 operand ops not yet supported");
2199353358Sdim    Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2200353358Sdim    Offset++;
2201353358Sdim    for (unsigned I = 0; I < 2; ++I) {
2202353358Sdim      if (Op.getDescription().Op[I] == Encoding::SizeNA)
2203353358Sdim        continue;
2204353358Sdim      if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2205353358Sdim          if (CU) {
2206353358Sdim            uint64_t Offset = CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2207353358Sdim            assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
2208353358Sdim            Asm->EmitULEB128(Offset, nullptr, ULEB128PadSize);
2209353358Sdim          } else {
2210353358Sdim            // Emit a reference to the 'generic type'.
2211353358Sdim            Asm->EmitULEB128(0, nullptr, ULEB128PadSize);
2212353358Sdim          }
2213353358Sdim          // Make sure comments stay aligned.
2214353358Sdim          for (unsigned J = 0; J < ULEB128PadSize; ++J)
2215353358Sdim            if (Comment != End)
2216353358Sdim              Comment++;
2217353358Sdim      } else {
2218360784Sdim        for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2219353358Sdim          Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2220353358Sdim      }
2221353358Sdim      Offset = Op.getOperandEndOffset(I);
2222353358Sdim    }
2223353358Sdim    assert(Offset == Op.getEndOffset());
2224353358Sdim  }
2225280031Sdim}
2226280031Sdim
2227353358Sdimvoid DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2228353358Sdim                                   const DbgValueLoc &Value,
2229353358Sdim                                   DwarfExpression &DwarfExpr) {
2230321369Sdim  auto *DIExpr = Value.getExpression();
2231321369Sdim  DIExpressionCursor ExprCursor(DIExpr);
2232321369Sdim  DwarfExpr.addFragmentOffset(DIExpr);
2233280031Sdim  // Regular entry.
2234276479Sdim  if (Value.isInt()) {
2235288943Sdim    if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2236288943Sdim               BT->getEncoding() == dwarf::DW_ATE_signed_char))
2237321369Sdim      DwarfExpr.addSignedConstant(Value.getInt());
2238280031Sdim    else
2239321369Sdim      DwarfExpr.addUnsignedConstant(Value.getInt());
2240276479Sdim  } else if (Value.isLocation()) {
2241321369Sdim    MachineLocation Location = Value.getLoc();
2242321369Sdim    if (Location.isIndirect())
2243321369Sdim      DwarfExpr.setMemoryLocationKind();
2244327952Sdim    DIExpressionCursor Cursor(DIExpr);
2245353358Sdim
2246353358Sdim    if (DIExpr->isEntryValue()) {
2247353358Sdim      DwarfExpr.setEntryValueFlag();
2248360784Sdim      DwarfExpr.beginEntryValueExpression(Cursor);
2249353358Sdim    }
2250353358Sdim
2251314564Sdim    const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2252321369Sdim    if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2253321369Sdim      return;
2254321369Sdim    return DwarfExpr.addExpression(std::move(Cursor));
2255360784Sdim  } else if (Value.isTargetIndexLocation()) {
2256360784Sdim    TargetIndexLocation Loc = Value.getTargetIndexLocation();
2257360784Sdim    // TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific
2258360784Sdim    // encoding is supported.
2259360784Sdim    DwarfExpr.addWasmLocation(Loc.Index, Loc.Offset);
2260309124Sdim  } else if (Value.isConstantFP()) {
2261309124Sdim    APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2262321369Sdim    DwarfExpr.addUnsignedConstant(RawBytes);
2263199989Srdivacky  }
2264321369Sdim  DwarfExpr.addExpression(std::move(ExprCursor));
2265199989Srdivacky}
2266199989Srdivacky
2267288943Sdimvoid DebugLocEntry::finalize(const AsmPrinter &AP,
2268288943Sdim                             DebugLocStream::ListBuilder &List,
2269353358Sdim                             const DIBasicType *BT,
2270353358Sdim                             DwarfCompileUnit &TheCU) {
2271353358Sdim  assert(!Values.empty() &&
2272353358Sdim         "location list entries without values are redundant");
2273344779Sdim  assert(Begin != End && "unexpected location list entry with empty range");
2274288943Sdim  DebugLocStream::EntryBuilder Entry(List, Begin, End);
2275288943Sdim  BufferByteStreamer Streamer = Entry.getStreamer();
2276353358Sdim  DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2277353358Sdim  const DbgValueLoc &Value = Values[0];
2278314564Sdim  if (Value.isFragment()) {
2279314564Sdim    // Emit all fragments that belong to the same variable and range.
2280353358Sdim    assert(llvm::all_of(Values, [](DbgValueLoc P) {
2281314564Sdim          return P.isFragment();
2282314564Sdim        }) && "all values are expected to be fragments");
2283288943Sdim    assert(std::is_sorted(Values.begin(), Values.end()) &&
2284314564Sdim           "fragments are expected to be sorted");
2285288943Sdim
2286314564Sdim    for (auto Fragment : Values)
2287353358Sdim      DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2288314564Sdim
2289288943Sdim  } else {
2290314564Sdim    assert(Values.size() == 1 && "only fragments may have >1 value");
2291353358Sdim    DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2292288943Sdim  }
2293314564Sdim  DwarfExpr.finalize();
2294360784Sdim  if (DwarfExpr.TagOffset)
2295360784Sdim    List.setTagOffset(*DwarfExpr.TagOffset);
2296288943Sdim}
2297288943Sdim
2298353358Sdimvoid DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2299353358Sdim                                           const DwarfCompileUnit *CU) {
2300288943Sdim  // Emit the size.
2301288943Sdim  Asm->OutStreamer->AddComment("Loc expr size");
2302344779Sdim  if (getDwarfVersion() >= 5)
2303344779Sdim    Asm->EmitULEB128(DebugLocs.getBytes(Entry).size());
2304353358Sdim  else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2305344779Sdim    Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2306353358Sdim  else {
2307353358Sdim    // The entry is too big to fit into 16 bit, drop it as there is nothing we
2308353358Sdim    // can do.
2309353358Sdim    Asm->emitInt16(0);
2310353358Sdim    return;
2311353358Sdim  }
2312276479Sdim  // Emit the entry.
2313276479Sdim  APByteStreamer Streamer(*Asm);
2314353358Sdim  emitDebugLocEntry(Streamer, Entry, CU);
2315193323Sed}
2316193323Sed
2317344779Sdim// Emit the common part of the DWARF 5 range/locations list tables header.
2318360784Sdimstatic void emitListsTableHeaderStart(AsmPrinter *Asm,
2319344779Sdim                                      MCSymbol *TableStart,
2320344779Sdim                                      MCSymbol *TableEnd) {
2321344779Sdim  // Build the table header, which starts with the length field.
2322344779Sdim  Asm->OutStreamer->AddComment("Length");
2323344779Sdim  Asm->EmitLabelDifference(TableEnd, TableStart, 4);
2324344779Sdim  Asm->OutStreamer->EmitLabel(TableStart);
2325344779Sdim  // Version number (DWARF v5 and later).
2326344779Sdim  Asm->OutStreamer->AddComment("Version");
2327344779Sdim  Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
2328344779Sdim  // Address size.
2329344779Sdim  Asm->OutStreamer->AddComment("Address size");
2330344779Sdim  Asm->emitInt8(Asm->MAI->getCodePointerSize());
2331344779Sdim  // Segment selector size.
2332344779Sdim  Asm->OutStreamer->AddComment("Segment selector size");
2333344779Sdim  Asm->emitInt8(0);
2334344779Sdim}
2335344779Sdim
2336344779Sdim// Emit the header of a DWARF 5 range list table list table. Returns the symbol
2337344779Sdim// that designates the end of the table for the caller to emit when the table is
2338344779Sdim// complete.
2339344779Sdimstatic MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2340344779Sdim                                         const DwarfFile &Holder) {
2341344779Sdim  MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2342344779Sdim  MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2343360784Sdim  emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2344344779Sdim
2345344779Sdim  Asm->OutStreamer->AddComment("Offset entry count");
2346344779Sdim  Asm->emitInt32(Holder.getRangeLists().size());
2347344779Sdim  Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
2348344779Sdim
2349344779Sdim  for (const RangeSpanList &List : Holder.getRangeLists())
2350360784Sdim    Asm->EmitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2351344779Sdim                             4);
2352344779Sdim
2353344779Sdim  return TableEnd;
2354344779Sdim}
2355344779Sdim
2356344779Sdim// Emit the header of a DWARF 5 locations list table. Returns the symbol that
2357344779Sdim// designates the end of the table for the caller to emit when the table is
2358344779Sdim// complete.
2359344779Sdimstatic MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2360360784Sdim                                         const DwarfDebug &DD) {
2361344779Sdim  MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2362344779Sdim  MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2363360784Sdim  emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2364344779Sdim
2365360784Sdim  const auto &DebugLocs = DD.getDebugLocs();
2366360784Sdim
2367344779Sdim  Asm->OutStreamer->AddComment("Offset entry count");
2368360784Sdim  Asm->emitInt32(DebugLocs.getLists().size());
2369360784Sdim  Asm->OutStreamer->EmitLabel(DebugLocs.getSym());
2370344779Sdim
2371360784Sdim  for (const auto &List : DebugLocs.getLists())
2372360784Sdim    Asm->EmitLabelDifference(List.Label, DebugLocs.getSym(), 4);
2373360784Sdim
2374344779Sdim  return TableEnd;
2375344779Sdim}
2376344779Sdim
2377360784Sdimtemplate <typename Ranges, typename PayloadEmitter>
2378360784Sdimstatic void emitRangeList(
2379360784Sdim    DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2380360784Sdim    const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2381360784Sdim    unsigned StartxLength, unsigned EndOfList,
2382360784Sdim    StringRef (*StringifyEnum)(unsigned),
2383360784Sdim    bool ShouldUseBaseAddress,
2384360784Sdim    PayloadEmitter EmitPayload) {
2385321369Sdim
2386360784Sdim  auto Size = Asm->MAI->getCodePointerSize();
2387360784Sdim  bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2388344779Sdim
2389360784Sdim  // Emit our symbol so we can find the beginning of the range.
2390360784Sdim  Asm->OutStreamer->EmitLabel(Sym);
2391344779Sdim
2392360784Sdim  // Gather all the ranges that apply to the same section so they can share
2393360784Sdim  // a base address entry.
2394360784Sdim  MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2395360784Sdim
2396360784Sdim  for (const auto &Range : R)
2397360784Sdim    SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2398360784Sdim
2399360784Sdim  const MCSymbol *CUBase = CU.getBaseAddress();
2400360784Sdim  bool BaseIsSet = false;
2401360784Sdim  for (const auto &P : SectionRanges) {
2402360784Sdim    auto *Base = CUBase;
2403360784Sdim    if (!Base && ShouldUseBaseAddress) {
2404360784Sdim      const MCSymbol *Begin = P.second.front()->Begin;
2405360784Sdim      const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2406360784Sdim      if (!UseDwarf5) {
2407360784Sdim        Base = NewBase;
2408360784Sdim        BaseIsSet = true;
2409360784Sdim        Asm->OutStreamer->EmitIntValue(-1, Size);
2410360784Sdim        Asm->OutStreamer->AddComment("  base address");
2411360784Sdim        Asm->OutStreamer->EmitSymbolValue(Base, Size);
2412360784Sdim      } else if (NewBase != Begin || P.second.size() > 1) {
2413360784Sdim        // Only use a base address if
2414360784Sdim        //  * the existing pool address doesn't match (NewBase != Begin)
2415360784Sdim        //  * or, there's more than one entry to share the base address
2416360784Sdim        Base = NewBase;
2417360784Sdim        BaseIsSet = true;
2418360784Sdim        Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2419360784Sdim        Asm->emitInt8(BaseAddressx);
2420360784Sdim        Asm->OutStreamer->AddComment("  base address index");
2421360784Sdim        Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2422360784Sdim      }
2423360784Sdim    } else if (BaseIsSet && !UseDwarf5) {
2424360784Sdim      BaseIsSet = false;
2425360784Sdim      assert(!Base);
2426360784Sdim      Asm->OutStreamer->EmitIntValue(-1, Size);
2427360784Sdim      Asm->OutStreamer->EmitIntValue(0, Size);
2428360784Sdim    }
2429360784Sdim
2430360784Sdim    for (const auto *RS : P.second) {
2431360784Sdim      const MCSymbol *Begin = RS->Begin;
2432360784Sdim      const MCSymbol *End = RS->End;
2433360784Sdim      assert(Begin && "Range without a begin symbol?");
2434360784Sdim      assert(End && "Range without an end symbol?");
2435344779Sdim      if (Base) {
2436360784Sdim        if (UseDwarf5) {
2437360784Sdim          // Emit offset_pair when we have a base.
2438360784Sdim          Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2439360784Sdim          Asm->emitInt8(OffsetPair);
2440344779Sdim          Asm->OutStreamer->AddComment("  starting offset");
2441360784Sdim          Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2442344779Sdim          Asm->OutStreamer->AddComment("  ending offset");
2443360784Sdim          Asm->EmitLabelDifferenceAsULEB128(End, Base);
2444344779Sdim        } else {
2445360784Sdim          Asm->EmitLabelDifference(Begin, Base, Size);
2446360784Sdim          Asm->EmitLabelDifference(End, Base, Size);
2447344779Sdim        }
2448360784Sdim      } else if (UseDwarf5) {
2449360784Sdim        Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2450360784Sdim        Asm->emitInt8(StartxLength);
2451360784Sdim        Asm->OutStreamer->AddComment("  start index");
2452360784Sdim        Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2453344779Sdim        Asm->OutStreamer->AddComment("  length");
2454360784Sdim        Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2455276479Sdim      } else {
2456360784Sdim        Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2457360784Sdim        Asm->OutStreamer->EmitSymbolValue(End, Size);
2458276479Sdim      }
2459360784Sdim      EmitPayload(*RS);
2460208599Srdivacky    }
2461360784Sdim  }
2462344779Sdim
2463360784Sdim  if (UseDwarf5) {
2464360784Sdim    Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2465360784Sdim    Asm->emitInt8(EndOfList);
2466360784Sdim  } else {
2467360784Sdim    // Terminate the list with two 0 values.
2468360784Sdim    Asm->OutStreamer->EmitIntValue(0, Size);
2469360784Sdim    Asm->OutStreamer->EmitIntValue(0, Size);
2470208599Srdivacky  }
2471360784Sdim}
2472344779Sdim
2473360784Sdim// Handles emission of both debug_loclist / debug_loclist.dwo
2474360784Sdimstatic void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2475360784Sdim  emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2476360784Sdim                *List.CU, dwarf::DW_LLE_base_addressx,
2477360784Sdim                dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2478360784Sdim                dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2479360784Sdim                /* ShouldUseBaseAddress */ true,
2480360784Sdim                [&](const DebugLocStream::Entry &E) {
2481360784Sdim                  DD.emitDebugLocEntryLocation(E, List.CU);
2482360784Sdim                });
2483360784Sdim}
2484360784Sdim
2485360784Sdimvoid DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2486360784Sdim  if (DebugLocs.getLists().empty())
2487360784Sdim    return;
2488360784Sdim
2489360784Sdim  Asm->OutStreamer->SwitchSection(Sec);
2490360784Sdim
2491360784Sdim  MCSymbol *TableEnd = nullptr;
2492360784Sdim  if (getDwarfVersion() >= 5)
2493360784Sdim    TableEnd = emitLoclistsTableHeader(Asm, *this);
2494360784Sdim
2495360784Sdim  for (const auto &List : DebugLocs.getLists())
2496360784Sdim    emitLocList(*this, Asm, List);
2497360784Sdim
2498344779Sdim  if (TableEnd)
2499344779Sdim    Asm->OutStreamer->EmitLabel(TableEnd);
2500193323Sed}
2501193323Sed
2502360784Sdim// Emit locations into the .debug_loc/.debug_loclists section.
2503360784Sdimvoid DwarfDebug::emitDebugLoc() {
2504360784Sdim  emitDebugLocImpl(
2505360784Sdim      getDwarfVersion() >= 5
2506360784Sdim          ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2507360784Sdim          : Asm->getObjFileLowering().getDwarfLocSection());
2508360784Sdim}
2509360784Sdim
2510360784Sdim// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2511276479Sdimvoid DwarfDebug::emitDebugLocDWO() {
2512360784Sdim  if (getDwarfVersion() >= 5) {
2513360784Sdim    emitDebugLocImpl(
2514360784Sdim        Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2515360784Sdim
2516360784Sdim    return;
2517360784Sdim  }
2518360784Sdim
2519288943Sdim  for (const auto &List : DebugLocs.getLists()) {
2520353358Sdim    Asm->OutStreamer->SwitchSection(
2521353358Sdim        Asm->getObjFileLowering().getDwarfLocDWOSection());
2522288943Sdim    Asm->OutStreamer->EmitLabel(List.Label);
2523360784Sdim
2524288943Sdim    for (const auto &Entry : DebugLocs.getEntries(List)) {
2525344779Sdim      // GDB only supports startx_length in pre-standard split-DWARF.
2526344779Sdim      // (in v5 standard loclists, it currently* /only/ supports base_address +
2527344779Sdim      // offset_pair, so the implementations can't really share much since they
2528344779Sdim      // need to use different representations)
2529344779Sdim      // * as of October 2018, at least
2530344779Sdim      // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2531344779Sdim      // in the address pool to minimize object size/relocations.
2532341825Sdim      Asm->emitInt8(dwarf::DW_LLE_startx_length);
2533360784Sdim      unsigned idx = AddrPool.getIndex(Entry.Begin);
2534276479Sdim      Asm->EmitULEB128(idx);
2535360784Sdim      // Also the pre-standard encoding is slightly different, emitting this as
2536360784Sdim      // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2537360784Sdim      Asm->EmitLabelDifference(Entry.End, Entry.Begin, 4);
2538353358Sdim      emitDebugLocEntryLocation(Entry, List.CU);
2539276479Sdim    }
2540341825Sdim    Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2541261991Sdim  }
2542261991Sdim}
2543261991Sdim
2544261991Sdimstruct ArangeSpan {
2545261991Sdim  const MCSymbol *Start, *End;
2546261991Sdim};
2547261991Sdim
2548261991Sdim// Emit a debug aranges section, containing a CU lookup for any
2549261991Sdim// address we can tie back to a CU.
2550249423Sdimvoid DwarfDebug::emitDebugARanges() {
2551288943Sdim  // Provides a unique id per text section.
2552288943Sdim  MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2553261991Sdim
2554288943Sdim  // Filter labels by section.
2555288943Sdim  for (const SymbolCU &SCU : ArangeLabels) {
2556288943Sdim    if (SCU.Sym->isInSection()) {
2557288943Sdim      // Make a note of this symbol and it's section.
2558288943Sdim      MCSection *Section = &SCU.Sym->getSection();
2559288943Sdim      if (!Section->getKind().isMetadata())
2560288943Sdim        SectionMap[Section].push_back(SCU);
2561288943Sdim    } else {
2562288943Sdim      // Some symbols (e.g. common/bss on mach-o) can have no section but still
2563288943Sdim      // appear in the output. This sucks as we rely on sections to build
2564288943Sdim      // arange spans. We can do it without, but it's icky.
2565288943Sdim      SectionMap[nullptr].push_back(SCU);
2566288943Sdim    }
2567288943Sdim  }
2568261991Sdim
2569288943Sdim  DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2570261991Sdim
2571288943Sdim  for (auto &I : SectionMap) {
2572309124Sdim    MCSection *Section = I.first;
2573288943Sdim    SmallVector<SymbolCU, 8> &List = I.second;
2574309124Sdim    if (List.size() < 1)
2575261991Sdim      continue;
2576261991Sdim
2577288943Sdim    // If we have no section (e.g. common), just write out
2578288943Sdim    // individual spans for each symbol.
2579288943Sdim    if (!Section) {
2580288943Sdim      for (const SymbolCU &Cur : List) {
2581288943Sdim        ArangeSpan Span;
2582288943Sdim        Span.Start = Cur.Sym;
2583288943Sdim        Span.End = nullptr;
2584309124Sdim        assert(Cur.CU);
2585309124Sdim        Spans[Cur.CU].push_back(Span);
2586288943Sdim      }
2587288943Sdim      continue;
2588288943Sdim    }
2589288943Sdim
2590261991Sdim    // Sort the symbols by offset within the section.
2591353358Sdim    llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2592353358Sdim      unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2593353358Sdim      unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2594261991Sdim
2595353358Sdim      // Symbols with no order assigned should be placed at the end.
2596353358Sdim      // (e.g. section end labels)
2597353358Sdim      if (IA == 0)
2598353358Sdim        return false;
2599353358Sdim      if (IB == 0)
2600353358Sdim        return true;
2601353358Sdim      return IA < IB;
2602353358Sdim    });
2603276479Sdim
2604309124Sdim    // Insert a final terminator.
2605309124Sdim    List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2606309124Sdim
2607288943Sdim    // Build spans between each label.
2608288943Sdim    const MCSymbol *StartSym = List[0].Sym;
2609288943Sdim    for (size_t n = 1, e = List.size(); n < e; n++) {
2610288943Sdim      const SymbolCU &Prev = List[n - 1];
2611288943Sdim      const SymbolCU &Cur = List[n];
2612288943Sdim
2613288943Sdim      // Try and build the longest span we can within the same CU.
2614288943Sdim      if (Cur.CU != Prev.CU) {
2615261991Sdim        ArangeSpan Span;
2616288943Sdim        Span.Start = StartSym;
2617288943Sdim        Span.End = Cur.Sym;
2618309124Sdim        assert(Prev.CU);
2619288943Sdim        Spans[Prev.CU].push_back(Span);
2620288943Sdim        StartSym = Cur.Sym;
2621261991Sdim      }
2622261991Sdim    }
2623261991Sdim  }
2624261991Sdim
2625288943Sdim  // Start the dwarf aranges section.
2626288943Sdim  Asm->OutStreamer->SwitchSection(
2627288943Sdim      Asm->getObjFileLowering().getDwarfARangesSection());
2628288943Sdim
2629321369Sdim  unsigned PtrSize = Asm->MAI->getCodePointerSize();
2630261991Sdim
2631261991Sdim  // Build a list of CUs used.
2632276479Sdim  std::vector<DwarfCompileUnit *> CUs;
2633276479Sdim  for (const auto &it : Spans) {
2634276479Sdim    DwarfCompileUnit *CU = it.first;
2635261991Sdim    CUs.push_back(CU);
2636261991Sdim  }
2637261991Sdim
2638261991Sdim  // Sort the CU list (again, to ensure consistent output order).
2639344779Sdim  llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2640344779Sdim    return A->getUniqueID() < B->getUniqueID();
2641344779Sdim  });
2642261991Sdim
2643261991Sdim  // Emit an arange table for each CU we used.
2644276479Sdim  for (DwarfCompileUnit *CU : CUs) {
2645261991Sdim    std::vector<ArangeSpan> &List = Spans[CU];
2646261991Sdim
2647280031Sdim    // Describe the skeleton CU's offset and length, not the dwo file's.
2648280031Sdim    if (auto *Skel = CU->getSkeleton())
2649280031Sdim      CU = Skel;
2650280031Sdim
2651261991Sdim    // Emit size of content not including length itself.
2652276479Sdim    unsigned ContentSize =
2653276479Sdim        sizeof(int16_t) + // DWARF ARange version number
2654276479Sdim        sizeof(int32_t) + // Offset of CU in the .debug_info section
2655276479Sdim        sizeof(int8_t) +  // Pointer Size (in bytes)
2656276479Sdim        sizeof(int8_t);   // Segment Size (in bytes)
2657261991Sdim
2658261991Sdim    unsigned TupleSize = PtrSize * 2;
2659261991Sdim
2660261991Sdim    // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2661276479Sdim    unsigned Padding =
2662360784Sdim        offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
2663261991Sdim
2664261991Sdim    ContentSize += Padding;
2665261991Sdim    ContentSize += (List.size() + 1) * TupleSize;
2666261991Sdim
2667261991Sdim    // For each compile unit, write the list of spans it covers.
2668288943Sdim    Asm->OutStreamer->AddComment("Length of ARange Set");
2669341825Sdim    Asm->emitInt32(ContentSize);
2670288943Sdim    Asm->OutStreamer->AddComment("DWARF Arange version number");
2671341825Sdim    Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2672288943Sdim    Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2673341825Sdim    emitSectionReference(*CU);
2674288943Sdim    Asm->OutStreamer->AddComment("Address Size (in bytes)");
2675341825Sdim    Asm->emitInt8(PtrSize);
2676288943Sdim    Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2677341825Sdim    Asm->emitInt8(0);
2678261991Sdim
2679309124Sdim    Asm->OutStreamer->emitFill(Padding, 0xff);
2680261991Sdim
2681276479Sdim    for (const ArangeSpan &Span : List) {
2682261991Sdim      Asm->EmitLabelReference(Span.Start, PtrSize);
2683261991Sdim
2684261991Sdim      // Calculate the size as being from the span start to it's end.
2685261991Sdim      if (Span.End) {
2686261991Sdim        Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2687261991Sdim      } else {
2688261991Sdim        // For symbols without an end marker (e.g. common), we
2689261991Sdim        // write a single arange entry containing just that one symbol.
2690261991Sdim        uint64_t Size = SymSize[Span.Start];
2691261991Sdim        if (Size == 0)
2692261991Sdim          Size = 1;
2693261991Sdim
2694288943Sdim        Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2695261991Sdim      }
2696261991Sdim    }
2697261991Sdim
2698288943Sdim    Asm->OutStreamer->AddComment("ARange terminator");
2699288943Sdim    Asm->OutStreamer->EmitIntValue(0, PtrSize);
2700288943Sdim    Asm->OutStreamer->EmitIntValue(0, PtrSize);
2701261991Sdim  }
2702193323Sed}
2703193323Sed
2704341825Sdim/// Emit a single range list. We handle both DWARF v5 and earlier.
2705344779Sdimstatic void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2706341825Sdim                          const RangeSpanList &List) {
2707360784Sdim  emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
2708360784Sdim                dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
2709360784Sdim                dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
2710360784Sdim                llvm::dwarf::RangeListEncodingString,
2711360784Sdim                List.CU->getCUNode()->getRangesBaseAddress() ||
2712360784Sdim                    DD.getDwarfVersion() >= 5,
2713360784Sdim                [](auto) {});
2714360784Sdim}
2715341825Sdim
2716360784Sdimvoid DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2717360784Sdim  if (Holder.getRangeLists().empty())
2718360784Sdim    return;
2719341825Sdim
2720360784Sdim  assert(useRangesSection());
2721360784Sdim  assert(!CUMap.empty());
2722360784Sdim  assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2723360784Sdim    return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2724360784Sdim  }));
2725341825Sdim
2726360784Sdim  Asm->OutStreamer->SwitchSection(Section);
2727341825Sdim
2728360784Sdim  MCSymbol *TableEnd = nullptr;
2729360784Sdim  if (getDwarfVersion() >= 5)
2730360784Sdim    TableEnd = emitRnglistsTableHeader(Asm, Holder);
2731341825Sdim
2732344779Sdim  for (const RangeSpanList &List : Holder.getRangeLists())
2733360784Sdim    emitRangeList(*this, Asm, List);
2734341825Sdim
2735344779Sdim  if (TableEnd)
2736344779Sdim    Asm->OutStreamer->EmitLabel(TableEnd);
2737341825Sdim}
2738341825Sdim
2739341825Sdim/// Emit address ranges into the .debug_ranges section or into the DWARF v5
2740341825Sdim/// .debug_rnglists section.
2741199989Srdivackyvoid DwarfDebug::emitDebugRanges() {
2742344779Sdim  const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2743341825Sdim
2744360784Sdim  emitDebugRangesImpl(Holder,
2745360784Sdim                      getDwarfVersion() >= 5
2746360784Sdim                          ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2747360784Sdim                          : Asm->getObjFileLowering().getDwarfRangesSection());
2748344779Sdim}
2749276479Sdim
2750344779Sdimvoid DwarfDebug::emitDebugRangesDWO() {
2751360784Sdim  emitDebugRangesImpl(InfoHolder,
2752360784Sdim                      Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2753193323Sed}
2754193323Sed
2755309124Sdimvoid DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2756296417Sdim  for (auto *MN : Nodes) {
2757296417Sdim    if (auto *M = dyn_cast<DIMacro>(MN))
2758309124Sdim      emitMacro(*M);
2759296417Sdim    else if (auto *F = dyn_cast<DIMacroFile>(MN))
2760309124Sdim      emitMacroFile(*F, U);
2761296417Sdim    else
2762296417Sdim      llvm_unreachable("Unexpected DI type!");
2763296417Sdim  }
2764296417Sdim}
2765296417Sdim
2766309124Sdimvoid DwarfDebug::emitMacro(DIMacro &M) {
2767309124Sdim  Asm->EmitULEB128(M.getMacinfoType());
2768309124Sdim  Asm->EmitULEB128(M.getLine());
2769296417Sdim  StringRef Name = M.getName();
2770296417Sdim  StringRef Value = M.getValue();
2771309124Sdim  Asm->OutStreamer->EmitBytes(Name);
2772296417Sdim  if (!Value.empty()) {
2773296417Sdim    // There should be one space between macro name and macro value.
2774341825Sdim    Asm->emitInt8(' ');
2775309124Sdim    Asm->OutStreamer->EmitBytes(Value);
2776296417Sdim  }
2777341825Sdim  Asm->emitInt8('\0');
2778296417Sdim}
2779296417Sdim
2780309124Sdimvoid DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2781296417Sdim  assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2782309124Sdim  Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2783309124Sdim  Asm->EmitULEB128(F.getLine());
2784341825Sdim  Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2785309124Sdim  handleMacroNodes(F.getElements(), U);
2786309124Sdim  Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2787296417Sdim}
2788296417Sdim
2789360784Sdimvoid DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
2790296417Sdim  for (const auto &P : CUMap) {
2791296417Sdim    auto &TheCU = *P.second;
2792296417Sdim    auto *SkCU = TheCU.getSkeleton();
2793296417Sdim    DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2794296417Sdim    auto *CUNode = cast<DICompileUnit>(P.first);
2795341825Sdim    DIMacroNodeArray Macros = CUNode->getMacros();
2796360784Sdim    if (Macros.empty())
2797360784Sdim      continue;
2798360784Sdim    Asm->OutStreamer->SwitchSection(Section);
2799360784Sdim    Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2800360784Sdim    handleMacroNodes(Macros, U);
2801360784Sdim    Asm->OutStreamer->AddComment("End Of Macro List Mark");
2802360784Sdim    Asm->emitInt8(0);
2803296417Sdim  }
2804296417Sdim}
2805296417Sdim
2806360784Sdim/// Emit macros into a debug macinfo section.
2807360784Sdimvoid DwarfDebug::emitDebugMacinfo() {
2808360784Sdim  emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoSection());
2809360784Sdim}
2810360784Sdim
2811360784Sdimvoid DwarfDebug::emitDebugMacinfoDWO() {
2812360784Sdim  emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoDWOSection());
2813360784Sdim}
2814360784Sdim
2815249423Sdim// DWARF5 Experimental Separate Dwarf emitters.
2816249423Sdim
2817276479Sdimvoid DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2818309124Sdim                                  std::unique_ptr<DwarfCompileUnit> NewU) {
2819249423Sdim
2820276479Sdim  if (!CompilationDir.empty())
2821280031Sdim    NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2822249423Sdim
2823276479Sdim  addGnuPubAttributes(*NewU, Die);
2824249423Sdim
2825276479Sdim  SkeletonHolder.addUnit(std::move(NewU));
2826276479Sdim}
2827249423Sdim
2828276479SdimDwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2829249423Sdim
2830360784Sdim  auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
2831360784Sdim      CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
2832360784Sdim      UnitKind::Skeleton);
2833276479Sdim  DwarfCompileUnit &NewCU = *OwnedUnit;
2834314564Sdim  NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2835249423Sdim
2836288943Sdim  NewCU.initStmtList();
2837249423Sdim
2838341825Sdim  if (useSegmentedStringOffsetsTable())
2839341825Sdim    NewCU.addStringOffsetsStart();
2840341825Sdim
2841276479Sdim  initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2842261991Sdim
2843276479Sdim  return NewCU;
2844276479Sdim}
2845261991Sdim
2846249423Sdim// Emit the .debug_info.dwo section for separated dwarf. This contains the
2847249423Sdim// compile units that would normally be in debug_info.
2848249423Sdimvoid DwarfDebug::emitDebugInfoDWO() {
2849249423Sdim  assert(useSplitDwarf() && "No split dwarf debug info?");
2850288943Sdim  // Don't emit relocations into the dwo file.
2851288943Sdim  InfoHolder.emitUnits(/* UseOffsets */ true);
2852249423Sdim}
2853249423Sdim
2854249423Sdim// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2855249423Sdim// abbreviations for the .debug_info.dwo section.
2856249423Sdimvoid DwarfDebug::emitDebugAbbrevDWO() {
2857249423Sdim  assert(useSplitDwarf() && "No split dwarf?");
2858276479Sdim  InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2859249423Sdim}
2860249423Sdim
2861276479Sdimvoid DwarfDebug::emitDebugLineDWO() {
2862276479Sdim  assert(useSplitDwarf() && "No split dwarf?");
2863341825Sdim  SplitTypeUnitFileTable.Emit(
2864341825Sdim      *Asm->OutStreamer, MCDwarfLineTableParams(),
2865276479Sdim      Asm->getObjFileLowering().getDwarfLineDWOSection());
2866276479Sdim}
2867276479Sdim
2868341825Sdimvoid DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2869341825Sdim  assert(useSplitDwarf() && "No split dwarf?");
2870341825Sdim  InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2871341825Sdim      *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2872341825Sdim      InfoHolder.getStringOffsetsStartSym());
2873341825Sdim}
2874341825Sdim
2875249423Sdim// Emit the .debug_str.dwo section for separated dwarf. This contains the
2876249423Sdim// string section and is identical in format to traditional .debug_str
2877249423Sdim// sections.
2878249423Sdimvoid DwarfDebug::emitDebugStrDWO() {
2879341825Sdim  if (useSegmentedStringOffsetsTable())
2880341825Sdim    emitStringOffsetsTableHeaderDWO();
2881249423Sdim  assert(useSplitDwarf() && "No split dwarf?");
2882288943Sdim  MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2883249423Sdim  InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2884341825Sdim                         OffSec, /* UseRelativeOffsets = */ false);
2885249423Sdim}
2886276479Sdim
2887344779Sdim// Emit address pool.
2888341825Sdimvoid DwarfDebug::emitDebugAddr() {
2889341825Sdim  AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2890341825Sdim}
2891341825Sdim
2892276479SdimMCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2893276479Sdim  if (!useSplitDwarf())
2894276479Sdim    return nullptr;
2895341825Sdim  const DICompileUnit *DIUnit = CU.getCUNode();
2896341825Sdim  SplitTypeUnitFileTable.maybeSetRootFile(
2897341825Sdim      DIUnit->getDirectory(), DIUnit->getFilename(),
2898341825Sdim      CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2899276479Sdim  return &SplitTypeUnitFileTable;
2900276479Sdim}
2901276479Sdim
2902296417Sdimuint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2903276479Sdim  MD5 Hash;
2904276479Sdim  Hash.update(Identifier);
2905276479Sdim  // ... take the least significant 8 bytes and return those. Our MD5
2906321369Sdim  // implementation always returns its results in little endian, so we actually
2907321369Sdim  // need the "high" word.
2908276479Sdim  MD5::MD5Result Result;
2909276479Sdim  Hash.final(Result);
2910321369Sdim  return Result.high();
2911276479Sdim}
2912276479Sdim
2913276479Sdimvoid DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2914276479Sdim                                      StringRef Identifier, DIE &RefDie,
2915288943Sdim                                      const DICompositeType *CTy) {
2916276479Sdim  // Fast path if we're building some type units and one has already used the
2917276479Sdim  // address pool we know we're going to throw away all this work anyway, so
2918276479Sdim  // don't bother building dependent types.
2919276479Sdim  if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2920276479Sdim    return;
2921276479Sdim
2922309124Sdim  auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2923309124Sdim  if (!Ins.second) {
2924309124Sdim    CU.addDIETypeSignature(RefDie, Ins.first->second);
2925276479Sdim    return;
2926276479Sdim  }
2927276479Sdim
2928276479Sdim  bool TopLevelType = TypeUnitsUnderConstruction.empty();
2929276479Sdim  AddrPool.resetUsedFlag();
2930276479Sdim
2931360784Sdim  auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2932327952Sdim                                                    getDwoLineTable(CU));
2933276479Sdim  DwarfTypeUnit &NewTU = *OwnedUnit;
2934276479Sdim  DIE &UnitDie = NewTU.getUnitDie();
2935314564Sdim  TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2936276479Sdim
2937276479Sdim  NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2938276479Sdim                CU.getLanguage());
2939276479Sdim
2940276479Sdim  uint64_t Signature = makeTypeSignature(Identifier);
2941276479Sdim  NewTU.setTypeSignature(Signature);
2942309124Sdim  Ins.first->second = Signature;
2943276479Sdim
2944344779Sdim  if (useSplitDwarf()) {
2945344779Sdim    MCSection *Section =
2946344779Sdim        getDwarfVersion() <= 4
2947344779Sdim            ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2948344779Sdim            : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2949344779Sdim    NewTU.setSection(Section);
2950344779Sdim  } else {
2951344779Sdim    MCSection *Section =
2952344779Sdim        getDwarfVersion() <= 4
2953344779Sdim            ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2954344779Sdim            : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2955344779Sdim    NewTU.setSection(Section);
2956341825Sdim    // Non-split type units reuse the compile unit's line table.
2957276479Sdim    CU.applyStmtList(UnitDie);
2958280031Sdim  }
2959276479Sdim
2960341825Sdim  // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2961341825Sdim  // units.
2962341825Sdim  if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2963341825Sdim    NewTU.addStringOffsetsStart();
2964341825Sdim
2965276479Sdim  NewTU.setType(NewTU.createTypeDIE(CTy));
2966276479Sdim
2967276479Sdim  if (TopLevelType) {
2968276479Sdim    auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2969276479Sdim    TypeUnitsUnderConstruction.clear();
2970276479Sdim
2971276479Sdim    // Types referencing entries in the address table cannot be placed in type
2972276479Sdim    // units.
2973276479Sdim    if (AddrPool.hasBeenUsed()) {
2974276479Sdim
2975276479Sdim      // Remove all the types built while building this type.
2976276479Sdim      // This is pessimistic as some of these types might not be dependent on
2977276479Sdim      // the type that used an address.
2978276479Sdim      for (const auto &TU : TypeUnitsToAdd)
2979309124Sdim        TypeSignatures.erase(TU.second);
2980276479Sdim
2981276479Sdim      // Construct this type in the CU directly.
2982276479Sdim      // This is inefficient because all the dependent types will be rebuilt
2983276479Sdim      // from scratch, including building them in type units, discovering that
2984276479Sdim      // they depend on addresses, throwing them out and rebuilding them.
2985288943Sdim      CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2986276479Sdim      return;
2987276479Sdim    }
2988276479Sdim
2989276479Sdim    // If the type wasn't dependent on fission addresses, finish adding the type
2990276479Sdim    // and all its dependent types.
2991309124Sdim    for (auto &TU : TypeUnitsToAdd) {
2992309124Sdim      InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2993309124Sdim      InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2994309124Sdim    }
2995276479Sdim  }
2996309124Sdim  CU.addDIETypeSignature(RefDie, Signature);
2997276479Sdim}
2998276479Sdim
2999353358SdimDwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
3000353358Sdim    : DD(DD),
3001353358Sdim      TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
3002353358Sdim  DD->TypeUnitsUnderConstruction.clear();
3003353358Sdim  assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
3004353358Sdim}
3005353358Sdim
3006353358SdimDwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3007353358Sdim  DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3008353358Sdim  DD->AddrPool.resetUsedFlag();
3009353358Sdim}
3010353358Sdim
3011353358SdimDwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3012353358Sdim  return NonTypeUnitContext(this);
3013353358Sdim}
3014353358Sdim
3015341825Sdim// Add the Name along with its companion DIE to the appropriate accelerator
3016341825Sdim// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3017341825Sdim// AccelTableKind::Apple, we use the table we got as an argument). If
3018341825Sdim// accelerator tables are disabled, this function does nothing.
3019341825Sdimtemplate <typename DataT>
3020344779Sdimvoid DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3021344779Sdim                                  AccelTable<DataT> &AppleAccel, StringRef Name,
3022341825Sdim                                  const DIE &Die) {
3023341825Sdim  if (getAccelTableKind() == AccelTableKind::None)
3024276479Sdim    return;
3025341825Sdim
3026344779Sdim  if (getAccelTableKind() != AccelTableKind::Apple &&
3027353358Sdim      CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3028344779Sdim    return;
3029344779Sdim
3030341825Sdim  DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3031344779Sdim  DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3032341825Sdim
3033341825Sdim  switch (getAccelTableKind()) {
3034341825Sdim  case AccelTableKind::Apple:
3035341825Sdim    AppleAccel.addName(Ref, Die);
3036341825Sdim    break;
3037341825Sdim  case AccelTableKind::Dwarf:
3038341825Sdim    AccelDebugNames.addName(Ref, Die);
3039341825Sdim    break;
3040341825Sdim  case AccelTableKind::Default:
3041341825Sdim    llvm_unreachable("Default should have already been resolved.");
3042341825Sdim  case AccelTableKind::None:
3043341825Sdim    llvm_unreachable("None handled above");
3044341825Sdim  }
3045276479Sdim}
3046276479Sdim
3047344779Sdimvoid DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3048344779Sdim                              const DIE &Die) {
3049344779Sdim  addAccelNameImpl(CU, AccelNames, Name, Die);
3050341825Sdim}
3051341825Sdim
3052344779Sdimvoid DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3053344779Sdim                              const DIE &Die) {
3054341825Sdim  // ObjC names go only into the Apple accelerator tables.
3055341825Sdim  if (getAccelTableKind() == AccelTableKind::Apple)
3056344779Sdim    addAccelNameImpl(CU, AccelObjC, Name, Die);
3057276479Sdim}
3058276479Sdim
3059344779Sdimvoid DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3060344779Sdim                                   const DIE &Die) {
3061344779Sdim  addAccelNameImpl(CU, AccelNamespace, Name, Die);
3062276479Sdim}
3063276479Sdim
3064344779Sdimvoid DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3065344779Sdim                              const DIE &Die, char Flags) {
3066344779Sdim  addAccelNameImpl(CU, AccelTypes, Name, Die);
3067276479Sdim}
3068314564Sdim
3069314564Sdimuint16_t DwarfDebug::getDwarfVersion() const {
3070314564Sdim  return Asm->OutStreamer->getContext().getDwarfVersion();
3071314564Sdim}
3072344779Sdim
3073344779Sdimconst MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3074344779Sdim  return SectionLabels.find(S)->second;
3075344779Sdim}
3076