xref: /src/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1044eb2f6SDimitry Andric //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file contains support for writing dwarf debug info into asm files.
10009b1c42SEd Schouten //
11009b1c42SEd Schouten //===----------------------------------------------------------------------===//
12ea5b2dd1SRoman Divacky 
13009b1c42SEd Schouten #include "DwarfDebug.h"
1467c32a98SDimitry Andric #include "ByteStreamer.h"
15f8af5cf6SDimitry Andric #include "DIEHash.h"
1667c32a98SDimitry Andric #include "DwarfCompileUnit.h"
1767c32a98SDimitry Andric #include "DwarfExpression.h"
185ca98fd9SDimitry Andric #include "DwarfUnit.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/APInt.h"
201d5ae102SDimitry Andric #include "llvm/ADT/Statistic.h"
217fa27ce4SDimitry Andric #include "llvm/ADT/StringExtras.h"
22044eb2f6SDimitry Andric #include "llvm/ADT/Twine.h"
23044eb2f6SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
2467c32a98SDimitry Andric #include "llvm/CodeGen/DIE.h"
25044eb2f6SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
2759850d08SRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
28009b1c42SEd Schouten #include "llvm/CodeGen/MachineModuleInfo.h"
29044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
30d8e91e46SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
311d5ae102SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
32044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
33044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
34e6d15924SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
35145449b1SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
364a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
37044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
38044eb2f6SDimitry Andric #include "llvm/IR/GlobalVariable.h"
394a16efa3SDimitry Andric #include "llvm/IR/Module.h"
40ea5b2dd1SRoman Divacky #include "llvm/MC/MCAsmInfo.h"
41044eb2f6SDimitry Andric #include "llvm/MC/MCContext.h"
4259850d08SRoman Divacky #include "llvm/MC/MCSection.h"
4359850d08SRoman Divacky #include "llvm/MC/MCStreamer.h"
44ea5b2dd1SRoman Divacky #include "llvm/MC/MCSymbol.h"
45044eb2f6SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
46044eb2f6SDimitry Andric #include "llvm/MC/MachineLocation.h"
47044eb2f6SDimitry Andric #include "llvm/MC/SectionKind.h"
48044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
49d7f7719eSRoman Divacky #include "llvm/Support/CommandLine.h"
5059850d08SRoman Divacky #include "llvm/Support/Debug.h"
5159850d08SRoman Divacky #include "llvm/Support/ErrorHandling.h"
52f8af5cf6SDimitry Andric #include "llvm/Support/MD5.h"
535a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
54eb11fae6SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
554a16efa3SDimitry Andric #include "llvm/Target/TargetMachine.h"
567fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
57044eb2f6SDimitry Andric #include <algorithm>
58044eb2f6SDimitry Andric #include <cstddef>
59044eb2f6SDimitry Andric #include <iterator>
60e3b55780SDimitry Andric #include <optional>
61044eb2f6SDimitry Andric #include <string>
6201095a5dSDimitry Andric 
63009b1c42SEd Schouten using namespace llvm;
64009b1c42SEd Schouten 
655ca98fd9SDimitry Andric #define DEBUG_TYPE "dwarfdebug"
665ca98fd9SDimitry Andric 
671d5ae102SDimitry Andric STATISTIC(NumCSParams, "Number of dbg call site params created");
681d5ae102SDimitry Andric 
69044eb2f6SDimitry Andric static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
70044eb2f6SDimitry Andric     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
71044eb2f6SDimitry Andric     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
724a16efa3SDimitry Andric 
735ca98fd9SDimitry Andric static cl::opt<bool> GenerateARangeSection("generate-arange-section",
745ca98fd9SDimitry Andric                                            cl::Hidden,
755ca98fd9SDimitry Andric                                            cl::desc("Generate dwarf aranges"),
765ca98fd9SDimitry Andric                                            cl::init(false));
775ca98fd9SDimitry Andric 
78eb11fae6SDimitry Andric static cl::opt<bool>
79eb11fae6SDimitry Andric     GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
80eb11fae6SDimitry Andric                            cl::desc("Generate DWARF4 type units."),
81eb11fae6SDimitry Andric                            cl::init(false));
82eb11fae6SDimitry Andric 
836b3f41edSDimitry Andric static cl::opt<bool> SplitDwarfCrossCuReferences(
846b3f41edSDimitry Andric     "split-dwarf-cross-cu-references", cl::Hidden,
856b3f41edSDimitry Andric     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
866b3f41edSDimitry Andric 
875ca98fd9SDimitry Andric enum DefaultOnOff { Default, Enable, Disable };
88522600a2SDimitry Andric 
89b915e9e0SDimitry Andric static cl::opt<DefaultOnOff> UnknownLocations(
90b915e9e0SDimitry Andric     "use-unknown-locations", cl::Hidden,
91b915e9e0SDimitry Andric     cl::desc("Make an absence of debug location information explicit."),
92b915e9e0SDimitry Andric     cl::values(clEnumVal(Default, "At top of block or after label"),
93b915e9e0SDimitry Andric                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
94b915e9e0SDimitry Andric     cl::init(Default));
95b915e9e0SDimitry Andric 
96eb11fae6SDimitry Andric static cl::opt<AccelTableKind> AccelTables(
97eb11fae6SDimitry Andric     "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
98eb11fae6SDimitry Andric     cl::values(clEnumValN(AccelTableKind::Default, "Default",
99eb11fae6SDimitry Andric                           "Default for platform"),
100eb11fae6SDimitry Andric                clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
101eb11fae6SDimitry Andric                clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
102eb11fae6SDimitry Andric                clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
103eb11fae6SDimitry Andric     cl::init(AccelTableKind::Default));
104eb11fae6SDimitry Andric 
105f8af5cf6SDimitry Andric static cl::opt<DefaultOnOff>
106eb11fae6SDimitry Andric DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
107eb11fae6SDimitry Andric                  cl::desc("Use inlined strings rather than string section."),
108f8af5cf6SDimitry Andric                  cl::values(clEnumVal(Default, "Default for platform"),
109522600a2SDimitry Andric                             clEnumVal(Enable, "Enabled"),
110b915e9e0SDimitry Andric                             clEnumVal(Disable, "Disabled")),
111522600a2SDimitry Andric                  cl::init(Default));
112522600a2SDimitry Andric 
113eb11fae6SDimitry Andric static cl::opt<bool>
114eb11fae6SDimitry Andric     NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
115eb11fae6SDimitry Andric                          cl::desc("Disable emission .debug_ranges section."),
116eb11fae6SDimitry Andric                          cl::init(false));
117eb11fae6SDimitry Andric 
118eb11fae6SDimitry Andric static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
119eb11fae6SDimitry Andric     "dwarf-sections-as-references", cl::Hidden,
120eb11fae6SDimitry Andric     cl::desc("Use sections+offset as references rather than labels."),
121eb11fae6SDimitry Andric     cl::values(clEnumVal(Default, "Default for platform"),
122eb11fae6SDimitry Andric                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
123eb11fae6SDimitry Andric     cl::init(Default));
124eb11fae6SDimitry Andric 
125b60736ecSDimitry Andric static cl::opt<bool>
126b60736ecSDimitry Andric     UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
127b60736ecSDimitry Andric                      cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
128b60736ecSDimitry Andric                      cl::init(false));
129b60736ecSDimitry Andric 
130b60736ecSDimitry Andric static cl::opt<DefaultOnOff> DwarfOpConvert(
131b60736ecSDimitry Andric     "dwarf-op-convert", cl::Hidden,
132b60736ecSDimitry Andric     cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
133b60736ecSDimitry Andric     cl::values(clEnumVal(Default, "Default for platform"),
134b60736ecSDimitry Andric                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
135b60736ecSDimitry Andric     cl::init(Default));
136b60736ecSDimitry Andric 
13701095a5dSDimitry Andric enum LinkageNameOption {
13801095a5dSDimitry Andric   DefaultLinkageNames,
13901095a5dSDimitry Andric   AllLinkageNames,
14001095a5dSDimitry Andric   AbstractLinkageNames
14101095a5dSDimitry Andric };
142044eb2f6SDimitry Andric 
14301095a5dSDimitry Andric static cl::opt<LinkageNameOption>
144dd58ef01SDimitry Andric     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
14501095a5dSDimitry Andric                       cl::desc("Which DWARF linkage-name attributes to emit."),
14601095a5dSDimitry Andric                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
14701095a5dSDimitry Andric                                             "Default for platform"),
14801095a5dSDimitry Andric                                  clEnumValN(AllLinkageNames, "All", "All"),
14901095a5dSDimitry Andric                                  clEnumValN(AbstractLinkageNames, "Abstract",
150b915e9e0SDimitry Andric                                             "Abstract subprograms")),
15101095a5dSDimitry Andric                       cl::init(DefaultLinkageNames));
152dd58ef01SDimitry Andric 
153b60736ecSDimitry Andric static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
154b60736ecSDimitry Andric     "minimize-addr-in-v5", cl::Hidden,
155b60736ecSDimitry Andric     cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
156b60736ecSDimitry Andric              "address pool entry sharing to reduce relocations/object size"),
157b60736ecSDimitry Andric     cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",
158b60736ecSDimitry Andric                           "Default address minimization strategy"),
159b60736ecSDimitry Andric                clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",
160b60736ecSDimitry Andric                           "Use rnglists for contiguous ranges if that allows "
161b60736ecSDimitry Andric                           "using a pre-existing base address"),
162344a3780SDimitry Andric                clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,
163344a3780SDimitry Andric                           "Expressions",
164344a3780SDimitry Andric                           "Use exprloc addrx+offset expressions for any "
165344a3780SDimitry Andric                           "address with a prior base address"),
166344a3780SDimitry Andric                clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",
167344a3780SDimitry Andric                           "Use addrx+offset extension form for any address "
168344a3780SDimitry Andric                           "with a prior base address"),
169b60736ecSDimitry Andric                clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",
170b60736ecSDimitry Andric                           "Stuff")),
171b60736ecSDimitry Andric     cl::init(DwarfDebug::MinimizeAddrInV5::Default));
172cfca06d7SDimitry Andric 
173e6d15924SDimitry Andric static constexpr unsigned ULEB128PadSize = 4;
174d7f7719eSRoman Divacky 
emitOp(uint8_t Op,const char * Comment)17571d5a254SDimitry Andric void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
176b60736ecSDimitry Andric   getActiveStreamer().emitInt8(
1775a5ac124SDimitry Andric       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
1785a5ac124SDimitry Andric                   : dwarf::OperationEncodingString(Op));
1795a5ac124SDimitry Andric }
1805a5ac124SDimitry Andric 
emitSigned(int64_t Value)18171d5a254SDimitry Andric void DebugLocDwarfExpression::emitSigned(int64_t Value) {
182cfca06d7SDimitry Andric   getActiveStreamer().emitSLEB128(Value, Twine(Value));
1835a5ac124SDimitry Andric }
1845a5ac124SDimitry Andric 
emitUnsigned(uint64_t Value)18571d5a254SDimitry Andric void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
186cfca06d7SDimitry Andric   getActiveStreamer().emitULEB128(Value, Twine(Value));
1875a5ac124SDimitry Andric }
1885a5ac124SDimitry Andric 
emitData1(uint8_t Value)189e6d15924SDimitry Andric void DebugLocDwarfExpression::emitData1(uint8_t Value) {
190b60736ecSDimitry Andric   getActiveStreamer().emitInt8(Value, Twine(Value));
191e6d15924SDimitry Andric }
192e6d15924SDimitry Andric 
emitBaseTypeRef(uint64_t Idx)193e6d15924SDimitry Andric void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
194e6d15924SDimitry Andric   assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
195cfca06d7SDimitry Andric   getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
196e6d15924SDimitry Andric }
197e6d15924SDimitry Andric 
isFrameRegister(const TargetRegisterInfo & TRI,llvm::Register MachineReg)19801095a5dSDimitry Andric bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
199b60736ecSDimitry Andric                                               llvm::Register MachineReg) {
2005a5ac124SDimitry Andric   // This information is not available while emitting .debug_loc entries.
2015a5ac124SDimitry Andric   return false;
2025a5ac124SDimitry Andric }
2035a5ac124SDimitry Andric 
enableTemporaryBuffer()2041d5ae102SDimitry Andric void DebugLocDwarfExpression::enableTemporaryBuffer() {
2051d5ae102SDimitry Andric   assert(!IsBuffering && "Already buffering?");
2061d5ae102SDimitry Andric   if (!TmpBuf)
2071d5ae102SDimitry Andric     TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
2081d5ae102SDimitry Andric   IsBuffering = true;
2091d5ae102SDimitry Andric }
2101d5ae102SDimitry Andric 
disableTemporaryBuffer()2111d5ae102SDimitry Andric void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
2121d5ae102SDimitry Andric 
getTemporaryBufferSize()2131d5ae102SDimitry Andric unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
2141d5ae102SDimitry Andric   return TmpBuf ? TmpBuf->Bytes.size() : 0;
2151d5ae102SDimitry Andric }
2161d5ae102SDimitry Andric 
commitTemporaryBuffer()2171d5ae102SDimitry Andric void DebugLocDwarfExpression::commitTemporaryBuffer() {
2181d5ae102SDimitry Andric   if (!TmpBuf)
2191d5ae102SDimitry Andric     return;
2201d5ae102SDimitry Andric   for (auto Byte : enumerate(TmpBuf->Bytes)) {
2211d5ae102SDimitry Andric     const char *Comment = (Byte.index() < TmpBuf->Comments.size())
2221d5ae102SDimitry Andric                               ? TmpBuf->Comments[Byte.index()].c_str()
2231d5ae102SDimitry Andric                               : "";
224b60736ecSDimitry Andric     OutBS.emitInt8(Byte.value(), Comment);
2251d5ae102SDimitry Andric   }
2261d5ae102SDimitry Andric   TmpBuf->Bytes.clear();
2271d5ae102SDimitry Andric   TmpBuf->Comments.clear();
2285ca98fd9SDimitry Andric }
2295ca98fd9SDimitry Andric 
getType() const2305a5ac124SDimitry Andric const DIType *DbgVariable::getType() const {
2311d5ae102SDimitry Andric   return getVariable()->getType();
232d39c594dSDimitry Andric }
233009b1c42SEd Schouten 
234e6d15924SDimitry Andric /// Get .debug_loc entry for the instruction range starting at MI.
getDebugLocValue(const MachineInstr * MI)235e6d15924SDimitry Andric static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
236e6d15924SDimitry Andric   const DIExpression *Expr = MI->getDebugExpression();
237b1c73532SDimitry Andric   auto SingleLocExprOpt = DIExpression::convertToNonVariadicExpression(Expr);
238b1c73532SDimitry Andric   const bool IsVariadic = !SingleLocExprOpt;
239b1c73532SDimitry Andric   // If we have a variadic debug value instruction that is equivalent to a
240b1c73532SDimitry Andric   // non-variadic instruction, then convert it to non-variadic form here.
241b1c73532SDimitry Andric   if (!IsVariadic && !MI->isNonListDebugValue()) {
242b1c73532SDimitry Andric     assert(MI->getNumDebugOperands() == 1 &&
243b1c73532SDimitry Andric            "Mismatched DIExpression and debug operands for debug instruction.");
244b1c73532SDimitry Andric     Expr = *SingleLocExprOpt;
245b1c73532SDimitry Andric   }
246344a3780SDimitry Andric   assert(MI->getNumOperands() >= 3);
247344a3780SDimitry Andric   SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
248344a3780SDimitry Andric   for (const MachineOperand &Op : MI->debug_operands()) {
249344a3780SDimitry Andric     if (Op.isReg()) {
250344a3780SDimitry Andric       MachineLocation MLoc(Op.getReg(),
251344a3780SDimitry Andric                            MI->isNonListDebugValue() && MI->isDebugOffsetImm());
252344a3780SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
253344a3780SDimitry Andric     } else if (Op.isTargetIndex()) {
254344a3780SDimitry Andric       DbgValueLocEntries.push_back(
255344a3780SDimitry Andric           DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
256344a3780SDimitry Andric     } else if (Op.isImm())
257344a3780SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
258344a3780SDimitry Andric     else if (Op.isFPImm())
259344a3780SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
260344a3780SDimitry Andric     else if (Op.isCImm())
261344a3780SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
262344a3780SDimitry Andric     else
263344a3780SDimitry Andric       llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
264e6d15924SDimitry Andric   }
265344a3780SDimitry Andric   return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
266e6d15924SDimitry Andric }
267e6d15924SDimitry Andric 
getFragmentOffsetInBits(const DIExpression & Expr)268b1c73532SDimitry Andric static uint64_t getFragmentOffsetInBits(const DIExpression &Expr) {
269b1c73532SDimitry Andric   std::optional<DIExpression::FragmentInfo> Fragment = Expr.getFragmentInfo();
270b1c73532SDimitry Andric   return Fragment ? Fragment->OffsetInBits : 0;
271e6d15924SDimitry Andric }
272e6d15924SDimitry Andric 
operator <(const FrameIndexExpr & LHS,const FrameIndexExpr & RHS)273b1c73532SDimitry Andric bool llvm::operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS) {
274b1c73532SDimitry Andric   return getFragmentOffsetInBits(*LHS.Expr) <
275b1c73532SDimitry Andric          getFragmentOffsetInBits(*RHS.Expr);
276b1c73532SDimitry Andric }
27771d5a254SDimitry Andric 
operator <(const EntryValueInfo & LHS,const EntryValueInfo & RHS)278b1c73532SDimitry Andric bool llvm::operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS) {
279b1c73532SDimitry Andric   return getFragmentOffsetInBits(LHS.Expr) < getFragmentOffsetInBits(RHS.Expr);
280b1c73532SDimitry Andric }
281044eb2f6SDimitry Andric 
Single(DbgValueLoc ValueLoc)282b1c73532SDimitry Andric Loc::Single::Single(DbgValueLoc ValueLoc)
283b1c73532SDimitry Andric     : ValueLoc(std::make_unique<DbgValueLoc>(ValueLoc)),
284b1c73532SDimitry Andric       Expr(ValueLoc.getExpression()) {
285b1c73532SDimitry Andric   if (!Expr->getNumElements())
286b1c73532SDimitry Andric     Expr = nullptr;
287b1c73532SDimitry Andric }
288b1c73532SDimitry Andric 
Single(const MachineInstr * DbgValue)289b1c73532SDimitry Andric Loc::Single::Single(const MachineInstr *DbgValue)
290b1c73532SDimitry Andric     : Single(getDebugLocValue(DbgValue)) {}
291b1c73532SDimitry Andric 
getFrameIndexExprs() const292b1c73532SDimitry Andric const std::set<FrameIndexExpr> &Loc::MMI::getFrameIndexExprs() const {
293e49737ebSDimitry Andric   return FrameIndexExprs;
294e49737ebSDimitry Andric }
295e49737ebSDimitry Andric 
addFrameIndexExpr(const DIExpression * Expr,int FI)296b1c73532SDimitry Andric void Loc::MMI::addFrameIndexExpr(const DIExpression *Expr, int FI) {
297b1c73532SDimitry Andric   FrameIndexExprs.insert({FI, Expr});
298044eb2f6SDimitry Andric   assert((FrameIndexExprs.size() == 1 ||
299044eb2f6SDimitry Andric           llvm::all_of(FrameIndexExprs,
300b1c73532SDimitry Andric                        [](const FrameIndexExpr &FIE) {
301044eb2f6SDimitry Andric                          return FIE.Expr && FIE.Expr->isFragment();
302044eb2f6SDimitry Andric                        })) &&
303044eb2f6SDimitry Andric          "conflicting locations for variable");
304044eb2f6SDimitry Andric }
305044eb2f6SDimitry Andric 
computeAccelTableKind(unsigned DwarfVersion,bool GenerateTypeUnits,DebuggerKind Tuning,const Triple & TT)306eb11fae6SDimitry Andric static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
307eb11fae6SDimitry Andric                                             bool GenerateTypeUnits,
308eb11fae6SDimitry Andric                                             DebuggerKind Tuning,
309eb11fae6SDimitry Andric                                             const Triple &TT) {
310eb11fae6SDimitry Andric   // Honor an explicit request.
311eb11fae6SDimitry Andric   if (AccelTables != AccelTableKind::Default)
312eb11fae6SDimitry Andric     return AccelTables;
313eb11fae6SDimitry Andric 
314b1c73532SDimitry Andric   // Generating DWARF5 acceleration table.
315b1c73532SDimitry Andric   // Currently Split dwarf and non ELF format is not supported.
316b1c73532SDimitry Andric   if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
317eb11fae6SDimitry Andric     return AccelTableKind::None;
318eb11fae6SDimitry Andric 
319eb11fae6SDimitry Andric   // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
320eb11fae6SDimitry Andric   // always implies debug_names. For lower standard versions we use apple
321eb11fae6SDimitry Andric   // accelerator tables on apple platforms and debug_names elsewhere.
322eb11fae6SDimitry Andric   if (DwarfVersion >= 5)
323eb11fae6SDimitry Andric     return AccelTableKind::Dwarf;
324eb11fae6SDimitry Andric   if (Tuning == DebuggerKind::LLDB)
325eb11fae6SDimitry Andric     return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
326eb11fae6SDimitry Andric                                    : AccelTableKind::Dwarf;
327eb11fae6SDimitry Andric   return AccelTableKind::None;
328eb11fae6SDimitry Andric }
329f8af5cf6SDimitry Andric 
DwarfDebug(AsmPrinter * A)330b60736ecSDimitry Andric DwarfDebug::DwarfDebug(AsmPrinter *A)
33101095a5dSDimitry Andric     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
33201095a5dSDimitry Andric       InfoHolder(A, "info_string", DIEValueAllocator),
3335a5ac124SDimitry Andric       SkeletonHolder(A, "skel_string", DIEValueAllocator),
334eb11fae6SDimitry Andric       IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
335b915e9e0SDimitry Andric   const Triple &TT = Asm->TM.getTargetTriple();
33663faed5bSDimitry Andric 
337e6d15924SDimitry Andric   // Make sure we know our "debugger tuning".  The target option takes
338dd58ef01SDimitry Andric   // precedence; fall back to triple-based defaults.
339dd58ef01SDimitry Andric   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
340dd58ef01SDimitry Andric     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
341050e163aSDimitry Andric   else if (IsDarwin)
342dd58ef01SDimitry Andric     DebuggerTuning = DebuggerKind::LLDB;
343145449b1SDimitry Andric   else if (TT.isPS())
344dd58ef01SDimitry Andric     DebuggerTuning = DebuggerKind::SCE;
345344a3780SDimitry Andric   else if (TT.isOSAIX())
346344a3780SDimitry Andric     DebuggerTuning = DebuggerKind::DBX;
347dd58ef01SDimitry Andric   else
348dd58ef01SDimitry Andric     DebuggerTuning = DebuggerKind::GDB;
349dd58ef01SDimitry Andric 
350eb11fae6SDimitry Andric   if (DwarfInlinedStrings == Default)
351344a3780SDimitry Andric     UseInlineStrings = TT.isNVPTX() || tuneForDBX();
352522600a2SDimitry Andric   else
353eb11fae6SDimitry Andric     UseInlineStrings = DwarfInlinedStrings == Enable;
354eb11fae6SDimitry Andric 
355eb11fae6SDimitry Andric   UseLocSection = !TT.isNVPTX();
3564a16efa3SDimitry Andric 
35701095a5dSDimitry Andric   HasAppleExtensionAttributes = tuneForLLDB();
35801095a5dSDimitry Andric 
35912f3ca4cSDimitry Andric   // Handle split DWARF.
36012f3ca4cSDimitry Andric   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
361f8af5cf6SDimitry Andric 
36201095a5dSDimitry Andric   // SCE defaults to linkage names only for abstract subprograms.
36301095a5dSDimitry Andric   if (DwarfLinkageNames == DefaultLinkageNames)
36401095a5dSDimitry Andric     UseAllLinkageNames = !tuneForSCE();
365dd58ef01SDimitry Andric   else
36601095a5dSDimitry Andric     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
367dd58ef01SDimitry Andric 
3685ca98fd9SDimitry Andric   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
369b915e9e0SDimitry Andric   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
3705ca98fd9SDimitry Andric                                     : MMI->getModule()->getDwarfVersion();
371eb11fae6SDimitry Andric   // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
372eb11fae6SDimitry Andric   DwarfVersion =
373eb11fae6SDimitry Andric       TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
374eb11fae6SDimitry Andric 
375344a3780SDimitry Andric   bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
376344a3780SDimitry Andric                  TT.isArch64Bit();    // DWARF64 requires 64-bit relocations.
377344a3780SDimitry Andric 
378344a3780SDimitry Andric   // Support DWARF64
379344a3780SDimitry Andric   // 1: For ELF when requested.
380344a3780SDimitry Andric   // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
381344a3780SDimitry Andric   //    according to the DWARF64 format for 64-bit assembly, so we must use
382344a3780SDimitry Andric   //    DWARF64 in the compiler too for 64-bit mode.
383344a3780SDimitry Andric   Dwarf64 &=
384344a3780SDimitry Andric       ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
385344a3780SDimitry Andric        TT.isOSBinFormatELF()) ||
386344a3780SDimitry Andric       TT.isOSBinFormatXCOFF();
387344a3780SDimitry Andric 
388344a3780SDimitry Andric   if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
389344a3780SDimitry Andric     report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
390b60736ecSDimitry Andric 
391eb11fae6SDimitry Andric   UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
392eb11fae6SDimitry Andric 
393eb11fae6SDimitry Andric   // Use sections as references. Force for NVPTX.
394eb11fae6SDimitry Andric   if (DwarfSectionsAsReferences == Default)
395eb11fae6SDimitry Andric     UseSectionsAsReferences = TT.isNVPTX();
396eb11fae6SDimitry Andric   else
397eb11fae6SDimitry Andric     UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
398eb11fae6SDimitry Andric 
399b7eb8e35SDimitry Andric   // Don't generate type units for unsupported object file formats.
400b60736ecSDimitry Andric   GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
401b60736ecSDimitry Andric                        A->TM.getTargetTriple().isOSBinFormatWasm()) &&
402b60736ecSDimitry Andric                       GenerateDwarfTypeUnits;
403eb11fae6SDimitry Andric 
404eb11fae6SDimitry Andric   TheAccelTableKind = computeAccelTableKind(
405eb11fae6SDimitry Andric       DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
4065ca98fd9SDimitry Andric 
407dd58ef01SDimitry Andric   // Work around a GDB bug. GDB doesn't support the standard opcode;
408dd58ef01SDimitry Andric   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
409dd58ef01SDimitry Andric   // is defined as of DWARF 3.
410dd58ef01SDimitry Andric   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
411dd58ef01SDimitry Andric   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
412dd58ef01SDimitry Andric   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
4135a5ac124SDimitry Andric 
414e3b55780SDimitry Andric   UseDWARF2Bitfields = DwarfVersion < 4;
41563faed5bSDimitry Andric 
416eb11fae6SDimitry Andric   // The DWARF v5 string offsets table has - possibly shared - contributions
417eb11fae6SDimitry Andric   // from each compile and type unit each preceded by a header. The string
418eb11fae6SDimitry Andric   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
419eb11fae6SDimitry Andric   // a monolithic string offsets table without any header.
420eb11fae6SDimitry Andric   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
421eb11fae6SDimitry Andric 
422cfca06d7SDimitry Andric   // Emit call-site-param debug info for GDB and LLDB, if the target supports
423cfca06d7SDimitry Andric   // the debug entry values feature. It can also be enabled explicitly.
424b60736ecSDimitry Andric   EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
425b60736ecSDimitry Andric 
426b60736ecSDimitry Andric   // It is unclear if the GCC .debug_macro extension is well-specified
427b60736ecSDimitry Andric   // for split DWARF. For now, do not allow LLVM to emit it.
428b60736ecSDimitry Andric   UseDebugMacroSection =
429b60736ecSDimitry Andric       DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
430b60736ecSDimitry Andric   if (DwarfOpConvert == Default)
431b60736ecSDimitry Andric     EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
432b60736ecSDimitry Andric   else
433b60736ecSDimitry Andric     EnableOpConvert = (DwarfOpConvert == Enable);
434b60736ecSDimitry Andric 
435b60736ecSDimitry Andric   // Split DWARF would benefit object size significantly by trading reductions
436b60736ecSDimitry Andric   // in address pool usage for slightly increased range list encodings.
4377fa27ce4SDimitry Andric   if (DwarfVersion >= 5)
438b60736ecSDimitry Andric     MinimizeAddr = MinimizeAddrInV5Option;
439cfca06d7SDimitry Andric 
44001095a5dSDimitry Andric   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
441b60736ecSDimitry Andric   Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
442b60736ecSDimitry Andric                                                         : dwarf::DWARF32);
443009b1c42SEd Schouten }
444009b1c42SEd Schouten 
4455ca98fd9SDimitry Andric // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
446044eb2f6SDimitry Andric DwarfDebug::~DwarfDebug() = default;
4475ca98fd9SDimitry Andric 
isObjCClass(StringRef Name)44863faed5bSDimitry Andric static bool isObjCClass(StringRef Name) {
449b1c73532SDimitry Andric   return Name.starts_with("+") || Name.starts_with("-");
45063faed5bSDimitry Andric }
45163faed5bSDimitry Andric 
hasObjCCategory(StringRef Name)45263faed5bSDimitry Andric static bool hasObjCCategory(StringRef Name) {
4535ca98fd9SDimitry Andric   if (!isObjCClass(Name))
4545ca98fd9SDimitry Andric     return false;
45563faed5bSDimitry Andric 
456c0981da4SDimitry Andric   return Name.contains(") ");
45763faed5bSDimitry Andric }
45863faed5bSDimitry Andric 
getObjCClassCategory(StringRef In,StringRef & Class,StringRef & Category)45963faed5bSDimitry Andric static void getObjCClassCategory(StringRef In, StringRef &Class,
46063faed5bSDimitry Andric                                  StringRef &Category) {
46163faed5bSDimitry Andric   if (!hasObjCCategory(In)) {
46263faed5bSDimitry Andric     Class = In.slice(In.find('[') + 1, In.find(' '));
46363faed5bSDimitry Andric     Category = "";
46463faed5bSDimitry Andric     return;
46563faed5bSDimitry Andric   }
46663faed5bSDimitry Andric 
46763faed5bSDimitry Andric   Class = In.slice(In.find('[') + 1, In.find('('));
46863faed5bSDimitry Andric   Category = In.slice(In.find('[') + 1, In.find(' '));
46963faed5bSDimitry Andric }
47063faed5bSDimitry Andric 
getObjCMethodName(StringRef In)47163faed5bSDimitry Andric static StringRef getObjCMethodName(StringRef In) {
47263faed5bSDimitry Andric   return In.slice(In.find(' ') + 1, In.find(']'));
47363faed5bSDimitry Andric }
47463faed5bSDimitry Andric 
47563faed5bSDimitry Andric // Add the various names to the Dwarf accelerator table names.
addSubprogramNames(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,const DISubprogram * SP,DIE & Die)476b1c73532SDimitry Andric void DwarfDebug::addSubprogramNames(
477b1c73532SDimitry Andric     const DwarfUnit &Unit,
478b1c73532SDimitry Andric     const DICompileUnit::DebugNameTableKind NameTableKind,
479d8e91e46SDimitry Andric     const DISubprogram *SP, DIE &Die) {
480d8e91e46SDimitry Andric   if (getAccelTableKind() != AccelTableKind::Apple &&
481b1c73532SDimitry Andric       NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&
482b1c73532SDimitry Andric       NameTableKind == DICompileUnit::DebugNameTableKind::None)
483d8e91e46SDimitry Andric     return;
484d8e91e46SDimitry Andric 
4855a5ac124SDimitry Andric   if (!SP->isDefinition())
4865ca98fd9SDimitry Andric     return;
487eb11fae6SDimitry Andric 
488eb11fae6SDimitry Andric   if (SP->getName() != "")
489b1c73532SDimitry Andric     addAccelName(Unit, NameTableKind, SP->getName(), Die);
49063faed5bSDimitry Andric 
491eb11fae6SDimitry Andric   // If the linkage name is different than the name, go ahead and output that as
492eb11fae6SDimitry Andric   // well into the name table. Only do that if we are going to actually emit
493eb11fae6SDimitry Andric   // that name.
494eb11fae6SDimitry Andric   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
4957fa27ce4SDimitry Andric       (useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(SP)))
496b1c73532SDimitry Andric     addAccelName(Unit, NameTableKind, SP->getLinkageName(), Die);
49763faed5bSDimitry Andric 
49863faed5bSDimitry Andric   // If this is an Objective-C selector name add it to the ObjC accelerator
49963faed5bSDimitry Andric   // too.
5005a5ac124SDimitry Andric   if (isObjCClass(SP->getName())) {
50163faed5bSDimitry Andric     StringRef Class, Category;
5025a5ac124SDimitry Andric     getObjCClassCategory(SP->getName(), Class, Category);
503b1c73532SDimitry Andric     addAccelObjC(Unit, NameTableKind, Class, Die);
50463faed5bSDimitry Andric     if (Category != "")
505b1c73532SDimitry Andric       addAccelObjC(Unit, NameTableKind, Category, Die);
50663faed5bSDimitry Andric     // Also add the base method name to the name table.
507b1c73532SDimitry Andric     addAccelName(Unit, NameTableKind, getObjCMethodName(SP->getName()), Die);
50863faed5bSDimitry Andric   }
50963faed5bSDimitry Andric }
51063faed5bSDimitry Andric 
511f8af5cf6SDimitry Andric /// Check whether we should create a DIE for the given Scope, return true
512f8af5cf6SDimitry Andric /// if we don't create a DIE (the corresponding DIE is null).
isLexicalScopeDIENull(LexicalScope * Scope)513f8af5cf6SDimitry Andric bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
514f8af5cf6SDimitry Andric   if (Scope->isAbstractScope())
515f8af5cf6SDimitry Andric     return false;
516f8af5cf6SDimitry Andric 
517f8af5cf6SDimitry Andric   // We don't create a DIE if there is no Range.
518f8af5cf6SDimitry Andric   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
519f8af5cf6SDimitry Andric   if (Ranges.empty())
520f8af5cf6SDimitry Andric     return true;
521f8af5cf6SDimitry Andric 
522f8af5cf6SDimitry Andric   if (Ranges.size() > 1)
523f8af5cf6SDimitry Andric     return false;
524f8af5cf6SDimitry Andric 
525f8af5cf6SDimitry Andric   // We don't create a DIE if we have a single Range and the end label
526f8af5cf6SDimitry Andric   // is null.
52767c32a98SDimitry Andric   return !getLabelAfterInsn(Ranges.front().second);
528f8af5cf6SDimitry Andric }
529f8af5cf6SDimitry Andric 
forBothCUs(DwarfCompileUnit & CU,Func F)530b915e9e0SDimitry Andric template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
53167c32a98SDimitry Andric   F(CU);
53267c32a98SDimitry Andric   if (auto *SkelCU = CU.getSkeleton())
533b915e9e0SDimitry Andric     if (CU.getCUNode()->getSplitDebugInlining())
53467c32a98SDimitry Andric       F(*SkelCU);
5355ca98fd9SDimitry Andric }
5365ca98fd9SDimitry Andric 
shareAcrossDWOCUs() const5376b3f41edSDimitry Andric bool DwarfDebug::shareAcrossDWOCUs() const {
5386b3f41edSDimitry Andric   return SplitDwarfCrossCuReferences;
5396b3f41edSDimitry Andric }
5406b3f41edSDimitry Andric 
constructAbstractSubprogramScopeDIE(DwarfCompileUnit & SrcCU,LexicalScope * Scope)5416b3f41edSDimitry Andric void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
5426b3f41edSDimitry Andric                                                      LexicalScope *Scope) {
5435ca98fd9SDimitry Andric   assert(Scope && Scope->getScopeNode());
5445ca98fd9SDimitry Andric   assert(Scope->isAbstractScope());
5455ca98fd9SDimitry Andric   assert(!Scope->getInlinedAt());
5465ca98fd9SDimitry Andric 
547b915e9e0SDimitry Andric   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
5485ca98fd9SDimitry Andric 
5495ca98fd9SDimitry Andric   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
5505ca98fd9SDimitry Andric   // was inlined from another compile unit.
551ab44ce3dSDimitry Andric   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
552ab44ce3dSDimitry Andric     // Avoid building the original CU if it won't be used
553ab44ce3dSDimitry Andric     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
554ab44ce3dSDimitry Andric   else {
555ab44ce3dSDimitry Andric     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
5566b3f41edSDimitry Andric     if (auto *SkelCU = CU.getSkeleton()) {
5576b3f41edSDimitry Andric       (shareAcrossDWOCUs() ? CU : SrcCU)
5586b3f41edSDimitry Andric           .constructAbstractSubprogramScopeDIE(Scope);
5596b3f41edSDimitry Andric       if (CU.getCUNode()->getSplitDebugInlining())
5606b3f41edSDimitry Andric         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
561ab44ce3dSDimitry Andric     } else
56267c32a98SDimitry Andric       CU.constructAbstractSubprogramScopeDIE(Scope);
5636b3f41edSDimitry Andric   }
564009b1c42SEd Schouten }
565009b1c42SEd Schouten 
566cfca06d7SDimitry Andric /// Represents a parameter whose call site value can be described by applying a
567cfca06d7SDimitry Andric /// debug expression to a register in the forwarded register worklist.
568cfca06d7SDimitry Andric struct FwdRegParamInfo {
569cfca06d7SDimitry Andric   /// The described parameter register.
570cfca06d7SDimitry Andric   unsigned ParamReg;
571cfca06d7SDimitry Andric 
572cfca06d7SDimitry Andric   /// Debug expression that has been built up when walking through the
573cfca06d7SDimitry Andric   /// instruction chain that produces the parameter's value.
574cfca06d7SDimitry Andric   const DIExpression *Expr;
575cfca06d7SDimitry Andric };
576cfca06d7SDimitry Andric 
577cfca06d7SDimitry Andric /// Register worklist for finding call site values.
578cfca06d7SDimitry Andric using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
579e3b55780SDimitry Andric /// Container for the set of registers known to be clobbered on the path to a
580e3b55780SDimitry Andric /// call site.
581e3b55780SDimitry Andric using ClobberedRegSet = SmallSet<Register, 16>;
582cfca06d7SDimitry Andric 
583cfca06d7SDimitry Andric /// Append the expression \p Addition to \p Original and return the result.
combineDIExpressions(const DIExpression * Original,const DIExpression * Addition)584cfca06d7SDimitry Andric static const DIExpression *combineDIExpressions(const DIExpression *Original,
585cfca06d7SDimitry Andric                                                 const DIExpression *Addition) {
586cfca06d7SDimitry Andric   std::vector<uint64_t> Elts = Addition->getElements().vec();
587cfca06d7SDimitry Andric   // Avoid multiple DW_OP_stack_values.
588cfca06d7SDimitry Andric   if (Original->isImplicit() && Addition->isImplicit())
589b1c73532SDimitry Andric     llvm::erase(Elts, dwarf::DW_OP_stack_value);
590cfca06d7SDimitry Andric   const DIExpression *CombinedExpr =
591cfca06d7SDimitry Andric       (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
592cfca06d7SDimitry Andric   return CombinedExpr;
593cfca06d7SDimitry Andric }
594cfca06d7SDimitry Andric 
595cfca06d7SDimitry Andric /// Emit call site parameter entries that are described by the given value and
596cfca06d7SDimitry Andric /// debug expression.
597cfca06d7SDimitry Andric template <typename ValT>
finishCallSiteParams(ValT Val,const DIExpression * Expr,ArrayRef<FwdRegParamInfo> DescribedParams,ParamSet & Params)598cfca06d7SDimitry Andric static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
599cfca06d7SDimitry Andric                                  ArrayRef<FwdRegParamInfo> DescribedParams,
600cfca06d7SDimitry Andric                                  ParamSet &Params) {
601cfca06d7SDimitry Andric   for (auto Param : DescribedParams) {
602cfca06d7SDimitry Andric     bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
603cfca06d7SDimitry Andric 
604cfca06d7SDimitry Andric     // TODO: Entry value operations can currently not be combined with any
605cfca06d7SDimitry Andric     // other expressions, so we can't emit call site entries in those cases.
606cfca06d7SDimitry Andric     if (ShouldCombineExpressions && Expr->isEntryValue())
607cfca06d7SDimitry Andric       continue;
608cfca06d7SDimitry Andric 
609cfca06d7SDimitry Andric     // If a parameter's call site value is produced by a chain of
610cfca06d7SDimitry Andric     // instructions we may have already created an expression for the
611cfca06d7SDimitry Andric     // parameter when walking through the instructions. Append that to the
612cfca06d7SDimitry Andric     // base expression.
613cfca06d7SDimitry Andric     const DIExpression *CombinedExpr =
614cfca06d7SDimitry Andric         ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
615cfca06d7SDimitry Andric                                  : Expr;
616cfca06d7SDimitry Andric     assert((!CombinedExpr || CombinedExpr->isValid()) &&
617cfca06d7SDimitry Andric            "Combined debug expression is invalid");
618cfca06d7SDimitry Andric 
619344a3780SDimitry Andric     DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
620cfca06d7SDimitry Andric     DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
621cfca06d7SDimitry Andric     Params.push_back(CSParm);
622cfca06d7SDimitry Andric     ++NumCSParams;
623cfca06d7SDimitry Andric   }
624cfca06d7SDimitry Andric }
625cfca06d7SDimitry Andric 
626cfca06d7SDimitry Andric /// Add \p Reg to the worklist, if it's not already present, and mark that the
627cfca06d7SDimitry Andric /// given parameter registers' values can (potentially) be described using
628cfca06d7SDimitry Andric /// that register and an debug expression.
addToFwdRegWorklist(FwdRegWorklist & Worklist,unsigned Reg,const DIExpression * Expr,ArrayRef<FwdRegParamInfo> ParamsToAdd)629cfca06d7SDimitry Andric static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
630cfca06d7SDimitry Andric                                 const DIExpression *Expr,
631cfca06d7SDimitry Andric                                 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
632cfca06d7SDimitry Andric   auto I = Worklist.insert({Reg, {}});
633cfca06d7SDimitry Andric   auto &ParamsForFwdReg = I.first->second;
634cfca06d7SDimitry Andric   for (auto Param : ParamsToAdd) {
635cfca06d7SDimitry Andric     assert(none_of(ParamsForFwdReg,
636cfca06d7SDimitry Andric                    [Param](const FwdRegParamInfo &D) {
637cfca06d7SDimitry Andric                      return D.ParamReg == Param.ParamReg;
638cfca06d7SDimitry Andric                    }) &&
639cfca06d7SDimitry Andric            "Same parameter described twice by forwarding reg");
640cfca06d7SDimitry Andric 
641cfca06d7SDimitry Andric     // If a parameter's call site value is produced by a chain of
642cfca06d7SDimitry Andric     // instructions we may have already created an expression for the
643cfca06d7SDimitry Andric     // parameter when walking through the instructions. Append that to the
644cfca06d7SDimitry Andric     // new expression.
645cfca06d7SDimitry Andric     const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
646cfca06d7SDimitry Andric     ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
647cfca06d7SDimitry Andric   }
648cfca06d7SDimitry Andric }
649cfca06d7SDimitry Andric 
650cfca06d7SDimitry Andric /// Interpret values loaded into registers by \p CurMI.
interpretValues(const MachineInstr * CurMI,FwdRegWorklist & ForwardedRegWorklist,ParamSet & Params,ClobberedRegSet & ClobberedRegUnits)651cfca06d7SDimitry Andric static void interpretValues(const MachineInstr *CurMI,
652cfca06d7SDimitry Andric                             FwdRegWorklist &ForwardedRegWorklist,
653e3b55780SDimitry Andric                             ParamSet &Params,
654e3b55780SDimitry Andric                             ClobberedRegSet &ClobberedRegUnits) {
655cfca06d7SDimitry Andric 
656cfca06d7SDimitry Andric   const MachineFunction *MF = CurMI->getMF();
657cfca06d7SDimitry Andric   const DIExpression *EmptyExpr =
658cfca06d7SDimitry Andric       DIExpression::get(MF->getFunction().getContext(), {});
659cfca06d7SDimitry Andric   const auto &TRI = *MF->getSubtarget().getRegisterInfo();
660cfca06d7SDimitry Andric   const auto &TII = *MF->getSubtarget().getInstrInfo();
661cfca06d7SDimitry Andric   const auto &TLI = *MF->getSubtarget().getTargetLowering();
662cfca06d7SDimitry Andric 
663cfca06d7SDimitry Andric   // If an instruction defines more than one item in the worklist, we may run
664cfca06d7SDimitry Andric   // into situations where a worklist register's value is (potentially)
665cfca06d7SDimitry Andric   // described by the previous value of another register that is also defined
666cfca06d7SDimitry Andric   // by that instruction.
667cfca06d7SDimitry Andric   //
668cfca06d7SDimitry Andric   // This can for example occur in cases like this:
669cfca06d7SDimitry Andric   //
670cfca06d7SDimitry Andric   //   $r1 = mov 123
671cfca06d7SDimitry Andric   //   $r0, $r1 = mvrr $r1, 456
672cfca06d7SDimitry Andric   //   call @foo, $r0, $r1
673cfca06d7SDimitry Andric   //
674cfca06d7SDimitry Andric   // When describing $r1's value for the mvrr instruction, we need to make sure
675cfca06d7SDimitry Andric   // that we don't finalize an entry value for $r0, as that is dependent on the
676cfca06d7SDimitry Andric   // previous value of $r1 (123 rather than 456).
677cfca06d7SDimitry Andric   //
678cfca06d7SDimitry Andric   // In order to not have to distinguish between those cases when finalizing
679cfca06d7SDimitry Andric   // entry values, we simply postpone adding new parameter registers to the
680cfca06d7SDimitry Andric   // worklist, by first keeping them in this temporary container until the
681cfca06d7SDimitry Andric   // instruction has been handled.
682cfca06d7SDimitry Andric   FwdRegWorklist TmpWorklistItems;
683cfca06d7SDimitry Andric 
684cfca06d7SDimitry Andric   // If the MI is an instruction defining one or more parameters' forwarding
685cfca06d7SDimitry Andric   // registers, add those defines.
686e3b55780SDimitry Andric   ClobberedRegSet NewClobberedRegUnits;
687cfca06d7SDimitry Andric   auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
688cfca06d7SDimitry Andric                                           SmallSetVector<unsigned, 4> &Defs) {
689cfca06d7SDimitry Andric     if (MI.isDebugInstr())
690cfca06d7SDimitry Andric       return;
691cfca06d7SDimitry Andric 
6927fa27ce4SDimitry Andric     for (const MachineOperand &MO : MI.all_defs()) {
6937fa27ce4SDimitry Andric       if (MO.getReg().isPhysical()) {
694344a3780SDimitry Andric         for (auto &FwdReg : ForwardedRegWorklist)
695cfca06d7SDimitry Andric           if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
696cfca06d7SDimitry Andric             Defs.insert(FwdReg.first);
6977fa27ce4SDimitry Andric         for (MCRegUnit Unit : TRI.regunits(MO.getReg()))
6987fa27ce4SDimitry Andric           NewClobberedRegUnits.insert(Unit);
699cfca06d7SDimitry Andric       }
700cfca06d7SDimitry Andric     }
701cfca06d7SDimitry Andric   };
702cfca06d7SDimitry Andric 
703cfca06d7SDimitry Andric   // Set of worklist registers that are defined by this instruction.
704cfca06d7SDimitry Andric   SmallSetVector<unsigned, 4> FwdRegDefs;
705cfca06d7SDimitry Andric 
706cfca06d7SDimitry Andric   getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
707e3b55780SDimitry Andric   if (FwdRegDefs.empty()) {
708e3b55780SDimitry Andric     // Any definitions by this instruction will clobber earlier reg movements.
709e3b55780SDimitry Andric     ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
710e3b55780SDimitry Andric                              NewClobberedRegUnits.end());
711cfca06d7SDimitry Andric     return;
712e3b55780SDimitry Andric   }
713e3b55780SDimitry Andric 
714e3b55780SDimitry Andric   // It's possible that we find a copy from a non-volatile register to the param
715e3b55780SDimitry Andric   // register, which is clobbered in the meantime. Test for clobbered reg unit
716e3b55780SDimitry Andric   // overlaps before completing.
717e3b55780SDimitry Andric   auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
718e3b55780SDimitry Andric     for (auto &RegUnit : ClobberedRegUnits)
719e3b55780SDimitry Andric       if (TRI.hasRegUnit(Reg, RegUnit))
720e3b55780SDimitry Andric         return true;
721e3b55780SDimitry Andric     return false;
722e3b55780SDimitry Andric   };
723cfca06d7SDimitry Andric 
724cfca06d7SDimitry Andric   for (auto ParamFwdReg : FwdRegDefs) {
725cfca06d7SDimitry Andric     if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
726cfca06d7SDimitry Andric       if (ParamValue->first.isImm()) {
727cfca06d7SDimitry Andric         int64_t Val = ParamValue->first.getImm();
728cfca06d7SDimitry Andric         finishCallSiteParams(Val, ParamValue->second,
729cfca06d7SDimitry Andric                              ForwardedRegWorklist[ParamFwdReg], Params);
730cfca06d7SDimitry Andric       } else if (ParamValue->first.isReg()) {
731cfca06d7SDimitry Andric         Register RegLoc = ParamValue->first.getReg();
732b60736ecSDimitry Andric         Register SP = TLI.getStackPointerRegisterToSaveRestore();
733cfca06d7SDimitry Andric         Register FP = TRI.getFrameRegister(*MF);
734cfca06d7SDimitry Andric         bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
735e3b55780SDimitry Andric         if (!IsRegClobberedInMeantime(RegLoc) &&
736e3b55780SDimitry Andric             (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
737b60736ecSDimitry Andric           MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
738cfca06d7SDimitry Andric           finishCallSiteParams(MLoc, ParamValue->second,
739cfca06d7SDimitry Andric                                ForwardedRegWorklist[ParamFwdReg], Params);
740cfca06d7SDimitry Andric         } else {
741cfca06d7SDimitry Andric           // ParamFwdReg was described by the non-callee saved register
742cfca06d7SDimitry Andric           // RegLoc. Mark that the call site values for the parameters are
743cfca06d7SDimitry Andric           // dependent on that register instead of ParamFwdReg. Since RegLoc
744cfca06d7SDimitry Andric           // may be a register that will be handled in this iteration, we
745cfca06d7SDimitry Andric           // postpone adding the items to the worklist, and instead keep them
746cfca06d7SDimitry Andric           // in a temporary container.
747cfca06d7SDimitry Andric           addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
748cfca06d7SDimitry Andric                               ForwardedRegWorklist[ParamFwdReg]);
749cfca06d7SDimitry Andric         }
750cfca06d7SDimitry Andric       }
751cfca06d7SDimitry Andric     }
752cfca06d7SDimitry Andric   }
753cfca06d7SDimitry Andric 
754cfca06d7SDimitry Andric   // Remove all registers that this instruction defines from the worklist.
755cfca06d7SDimitry Andric   for (auto ParamFwdReg : FwdRegDefs)
756cfca06d7SDimitry Andric     ForwardedRegWorklist.erase(ParamFwdReg);
757cfca06d7SDimitry Andric 
758e3b55780SDimitry Andric   // Any definitions by this instruction will clobber earlier reg movements.
759e3b55780SDimitry Andric   ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
760e3b55780SDimitry Andric                            NewClobberedRegUnits.end());
761e3b55780SDimitry Andric 
762cfca06d7SDimitry Andric   // Now that we are done handling this instruction, add items from the
763cfca06d7SDimitry Andric   // temporary worklist to the real one.
764344a3780SDimitry Andric   for (auto &New : TmpWorklistItems)
765cfca06d7SDimitry Andric     addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
766cfca06d7SDimitry Andric   TmpWorklistItems.clear();
767cfca06d7SDimitry Andric }
768cfca06d7SDimitry Andric 
interpretNextInstr(const MachineInstr * CurMI,FwdRegWorklist & ForwardedRegWorklist,ParamSet & Params,ClobberedRegSet & ClobberedRegUnits)769cfca06d7SDimitry Andric static bool interpretNextInstr(const MachineInstr *CurMI,
770cfca06d7SDimitry Andric                                FwdRegWorklist &ForwardedRegWorklist,
771e3b55780SDimitry Andric                                ParamSet &Params,
772e3b55780SDimitry Andric                                ClobberedRegSet &ClobberedRegUnits) {
773cfca06d7SDimitry Andric   // Skip bundle headers.
774cfca06d7SDimitry Andric   if (CurMI->isBundle())
775cfca06d7SDimitry Andric     return true;
776cfca06d7SDimitry Andric 
777cfca06d7SDimitry Andric   // If the next instruction is a call we can not interpret parameter's
778cfca06d7SDimitry Andric   // forwarding registers or we finished the interpretation of all
779cfca06d7SDimitry Andric   // parameters.
780cfca06d7SDimitry Andric   if (CurMI->isCall())
781cfca06d7SDimitry Andric     return false;
782cfca06d7SDimitry Andric 
783cfca06d7SDimitry Andric   if (ForwardedRegWorklist.empty())
784cfca06d7SDimitry Andric     return false;
785cfca06d7SDimitry Andric 
786cfca06d7SDimitry Andric   // Avoid NOP description.
787cfca06d7SDimitry Andric   if (CurMI->getNumOperands() == 0)
788cfca06d7SDimitry Andric     return true;
789cfca06d7SDimitry Andric 
790e3b55780SDimitry Andric   interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
791cfca06d7SDimitry Andric 
792cfca06d7SDimitry Andric   return true;
793cfca06d7SDimitry Andric }
794cfca06d7SDimitry Andric 
7951d5ae102SDimitry Andric /// Try to interpret values loaded into registers that forward parameters
7961d5ae102SDimitry Andric /// for \p CallMI. Store parameters with interpreted value into \p Params.
collectCallSiteParameters(const MachineInstr * CallMI,ParamSet & Params)7971d5ae102SDimitry Andric static void collectCallSiteParameters(const MachineInstr *CallMI,
7981d5ae102SDimitry Andric                                       ParamSet &Params) {
799cfca06d7SDimitry Andric   const MachineFunction *MF = CallMI->getMF();
800344a3780SDimitry Andric   const auto &CalleesMap = MF->getCallSitesInfo();
801ac9a064cSDimitry Andric   auto CSInfo = CalleesMap.find(CallMI);
8021d5ae102SDimitry Andric 
8031d5ae102SDimitry Andric   // There is no information for the call instruction.
804ac9a064cSDimitry Andric   if (CSInfo == CalleesMap.end())
8051d5ae102SDimitry Andric     return;
8061d5ae102SDimitry Andric 
807cfca06d7SDimitry Andric   const MachineBasicBlock *MBB = CallMI->getParent();
8081d5ae102SDimitry Andric 
8091d5ae102SDimitry Andric   // Skip the call instruction.
8101d5ae102SDimitry Andric   auto I = std::next(CallMI->getReverseIterator());
8111d5ae102SDimitry Andric 
812cfca06d7SDimitry Andric   FwdRegWorklist ForwardedRegWorklist;
813cfca06d7SDimitry Andric 
814cfca06d7SDimitry Andric   const DIExpression *EmptyExpr =
815cfca06d7SDimitry Andric       DIExpression::get(MF->getFunction().getContext(), {});
816cfca06d7SDimitry Andric 
8171d5ae102SDimitry Andric   // Add all the forwarding registers into the ForwardedRegWorklist.
818ac9a064cSDimitry Andric   for (const auto &ArgReg : CSInfo->second.ArgRegPairs) {
819cfca06d7SDimitry Andric     bool InsertedReg =
820cfca06d7SDimitry Andric         ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
821cfca06d7SDimitry Andric             .second;
8221d5ae102SDimitry Andric     assert(InsertedReg && "Single register used to forward two arguments?");
8231d5ae102SDimitry Andric     (void)InsertedReg;
8241d5ae102SDimitry Andric   }
8251d5ae102SDimitry Andric 
826b60736ecSDimitry Andric   // Do not emit CSInfo for undef forwarding registers.
8274b4fe385SDimitry Andric   for (const auto &MO : CallMI->uses())
828b60736ecSDimitry Andric     if (MO.isReg() && MO.isUndef())
829b60736ecSDimitry Andric       ForwardedRegWorklist.erase(MO.getReg());
830b60736ecSDimitry Andric 
8311d5ae102SDimitry Andric   // We erase, from the ForwardedRegWorklist, those forwarding registers for
8321d5ae102SDimitry Andric   // which we successfully describe a loaded value (by using
8331d5ae102SDimitry Andric   // the describeLoadedValue()). For those remaining arguments in the working
8341d5ae102SDimitry Andric   // list, for which we do not describe a loaded value by
8351d5ae102SDimitry Andric   // the describeLoadedValue(), we try to generate an entry value expression
836cfca06d7SDimitry Andric   // for their call site value description, if the call is within the entry MBB.
8371d5ae102SDimitry Andric   // TODO: Handle situations when call site parameter value can be described
838cfca06d7SDimitry Andric   // as the entry value within basic blocks other than the first one.
8391d5ae102SDimitry Andric   bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
8401d5ae102SDimitry Andric 
841cfca06d7SDimitry Andric   // Search for a loading value in forwarding registers inside call delay slot.
842e3b55780SDimitry Andric   ClobberedRegSet ClobberedRegUnits;
843cfca06d7SDimitry Andric   if (CallMI->hasDelaySlot()) {
844cfca06d7SDimitry Andric     auto Suc = std::next(CallMI->getIterator());
845cfca06d7SDimitry Andric     // Only one-instruction delay slot is supported.
846cfca06d7SDimitry Andric     auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
847cfca06d7SDimitry Andric     (void)BundleEnd;
848cfca06d7SDimitry Andric     assert(std::next(Suc) == BundleEnd &&
849cfca06d7SDimitry Andric            "More than one instruction in call delay slot");
850cfca06d7SDimitry Andric     // Try to interpret value loaded by instruction.
851e3b55780SDimitry Andric     if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
8521d5ae102SDimitry Andric       return;
8531d5ae102SDimitry Andric   }
8541d5ae102SDimitry Andric 
855706b4fc4SDimitry Andric   // Search for a loading value in forwarding registers.
8561d5ae102SDimitry Andric   for (; I != MBB->rend(); ++I) {
857cfca06d7SDimitry Andric     // Try to interpret values loaded by instruction.
858e3b55780SDimitry Andric     if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
8591d5ae102SDimitry Andric       return;
8601d5ae102SDimitry Andric   }
8611d5ae102SDimitry Andric 
8621d5ae102SDimitry Andric   // Emit the call site parameter's value as an entry value.
8631d5ae102SDimitry Andric   if (ShouldTryEmitEntryVals) {
8641d5ae102SDimitry Andric     // Create an expression where the register's entry value is used.
8651d5ae102SDimitry Andric     DIExpression *EntryExpr = DIExpression::get(
8661d5ae102SDimitry Andric         MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
867344a3780SDimitry Andric     for (auto &RegEntry : ForwardedRegWorklist) {
868cfca06d7SDimitry Andric       MachineLocation MLoc(RegEntry.first);
869cfca06d7SDimitry Andric       finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
8701d5ae102SDimitry Andric     }
8711d5ae102SDimitry Andric   }
8721d5ae102SDimitry Andric }
8731d5ae102SDimitry Andric 
constructCallSiteEntryDIEs(const DISubprogram & SP,DwarfCompileUnit & CU,DIE & ScopeDIE,const MachineFunction & MF)874d8e91e46SDimitry Andric void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
875d8e91e46SDimitry Andric                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
876d8e91e46SDimitry Andric                                             const MachineFunction &MF) {
877d8e91e46SDimitry Andric   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
878d8e91e46SDimitry Andric   // the subprogram is required to have one.
879d8e91e46SDimitry Andric   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
880d8e91e46SDimitry Andric     return;
881d8e91e46SDimitry Andric 
882d8e91e46SDimitry Andric   // Use DW_AT_call_all_calls to express that call site entries are present
883d8e91e46SDimitry Andric   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
884d8e91e46SDimitry Andric   // because one of its requirements is not met: call site entries for
885d8e91e46SDimitry Andric   // optimized-out calls are elided.
8861d5ae102SDimitry Andric   CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
887d8e91e46SDimitry Andric 
888d8e91e46SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
889d8e91e46SDimitry Andric   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
890cfca06d7SDimitry Andric 
891cfca06d7SDimitry Andric   // Delay slot support check.
892cfca06d7SDimitry Andric   auto delaySlotSupported = [&](const MachineInstr &MI) {
893cfca06d7SDimitry Andric     if (!MI.isBundledWithSucc())
894cfca06d7SDimitry Andric       return false;
895cfca06d7SDimitry Andric     auto Suc = std::next(MI.getIterator());
896cfca06d7SDimitry Andric     auto CallInstrBundle = getBundleStart(MI.getIterator());
897cfca06d7SDimitry Andric     (void)CallInstrBundle;
898cfca06d7SDimitry Andric     auto DelaySlotBundle = getBundleStart(Suc);
899cfca06d7SDimitry Andric     (void)DelaySlotBundle;
900cfca06d7SDimitry Andric     // Ensure that label after call is following delay slot instruction.
901cfca06d7SDimitry Andric     // Ex. CALL_INSTRUCTION {
902cfca06d7SDimitry Andric     //       DELAY_SLOT_INSTRUCTION }
903cfca06d7SDimitry Andric     //      LABEL_AFTER_CALL
904cfca06d7SDimitry Andric     assert(getLabelAfterInsn(&*CallInstrBundle) ==
905cfca06d7SDimitry Andric                getLabelAfterInsn(&*DelaySlotBundle) &&
906cfca06d7SDimitry Andric            "Call and its successor instruction don't have same label after.");
907cfca06d7SDimitry Andric     return true;
908cfca06d7SDimitry Andric   };
909d8e91e46SDimitry Andric 
910d8e91e46SDimitry Andric   // Emit call site entries for each call or tail call in the function.
911d8e91e46SDimitry Andric   for (const MachineBasicBlock &MBB : MF) {
912d8e91e46SDimitry Andric     for (const MachineInstr &MI : MBB.instrs()) {
913706b4fc4SDimitry Andric       // Bundles with call in them will pass the isCall() test below but do not
914706b4fc4SDimitry Andric       // have callee operand information so skip them here. Iterator will
915706b4fc4SDimitry Andric       // eventually reach the call MI.
916706b4fc4SDimitry Andric       if (MI.isBundle())
917706b4fc4SDimitry Andric         continue;
918706b4fc4SDimitry Andric 
919d8e91e46SDimitry Andric       // Skip instructions which aren't calls. Both calls and tail-calling jump
920d8e91e46SDimitry Andric       // instructions (e.g TAILJMPd64) are classified correctly here.
921cfca06d7SDimitry Andric       if (!MI.isCandidateForCallSiteEntry())
922d8e91e46SDimitry Andric         continue;
923d8e91e46SDimitry Andric 
924cfca06d7SDimitry Andric       // Skip instructions marked as frame setup, as they are not interesting to
925cfca06d7SDimitry Andric       // the user.
926cfca06d7SDimitry Andric       if (MI.getFlag(MachineInstr::FrameSetup))
927cfca06d7SDimitry Andric         continue;
928cfca06d7SDimitry Andric 
929cfca06d7SDimitry Andric       // Check if delay slot support is enabled.
930cfca06d7SDimitry Andric       if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
931d8e91e46SDimitry Andric         return;
932d8e91e46SDimitry Andric 
933d8e91e46SDimitry Andric       // If this is a direct call, find the callee's subprogram.
9341d5ae102SDimitry Andric       // In the case of an indirect call find the register that holds
9351d5ae102SDimitry Andric       // the callee.
936344a3780SDimitry Andric       const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
937344a3780SDimitry Andric       if (!CalleeOp.isGlobal() &&
938e3b55780SDimitry Andric           (!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))
939d8e91e46SDimitry Andric         continue;
940d8e91e46SDimitry Andric 
9411d5ae102SDimitry Andric       unsigned CallReg = 0;
942c0981da4SDimitry Andric       const DISubprogram *CalleeSP = nullptr;
9431d5ae102SDimitry Andric       const Function *CalleeDecl = nullptr;
9441d5ae102SDimitry Andric       if (CalleeOp.isReg()) {
9451d5ae102SDimitry Andric         CallReg = CalleeOp.getReg();
9461d5ae102SDimitry Andric         if (!CallReg)
9471d5ae102SDimitry Andric           continue;
9481d5ae102SDimitry Andric       } else {
9491d5ae102SDimitry Andric         CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
9501d5ae102SDimitry Andric         if (!CalleeDecl || !CalleeDecl->getSubprogram())
9511d5ae102SDimitry Andric           continue;
952c0981da4SDimitry Andric         CalleeSP = CalleeDecl->getSubprogram();
9531d5ae102SDimitry Andric       }
9541d5ae102SDimitry Andric 
955d8e91e46SDimitry Andric       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
956d8e91e46SDimitry Andric 
957d8e91e46SDimitry Andric       bool IsTail = TII->isTailCall(MI);
958d8e91e46SDimitry Andric 
959706b4fc4SDimitry Andric       // If MI is in a bundle, the label was created after the bundle since
960706b4fc4SDimitry Andric       // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
961706b4fc4SDimitry Andric       // to search for that label below.
962706b4fc4SDimitry Andric       const MachineInstr *TopLevelCallMI =
963706b4fc4SDimitry Andric           MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
964706b4fc4SDimitry Andric 
965cfca06d7SDimitry Andric       // For non-tail calls, the return PC is needed to disambiguate paths in
966cfca06d7SDimitry Andric       // the call graph which could lead to some target function. For tail
967cfca06d7SDimitry Andric       // calls, no return PC information is needed, unless tuning for GDB in
968cfca06d7SDimitry Andric       // DWARF4 mode in which case we fake a return PC for compatibility.
9691d5ae102SDimitry Andric       const MCSymbol *PCAddr =
970cfca06d7SDimitry Andric           (!IsTail || CU.useGNUAnalogForDwarf5Feature())
971706b4fc4SDimitry Andric               ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
9721d5ae102SDimitry Andric               : nullptr;
9731d5ae102SDimitry Andric 
974cfca06d7SDimitry Andric       // For tail calls, it's necessary to record the address of the branch
975cfca06d7SDimitry Andric       // instruction so that the debugger can show where the tail call occurred.
976cfca06d7SDimitry Andric       const MCSymbol *CallAddr =
977cfca06d7SDimitry Andric           IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
978cfca06d7SDimitry Andric 
979cfca06d7SDimitry Andric       assert((IsTail || PCAddr) && "Non-tail call without return PC");
9801d5ae102SDimitry Andric 
981d8e91e46SDimitry Andric       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
9821d5ae102SDimitry Andric                         << (CalleeDecl ? CalleeDecl->getName()
9831d5ae102SDimitry Andric                                        : StringRef(MF.getSubtarget()
9841d5ae102SDimitry Andric                                                        .getRegisterInfo()
9851d5ae102SDimitry Andric                                                        ->getName(CallReg)))
9861d5ae102SDimitry Andric                         << (IsTail ? " [IsTail]" : "") << "\n");
9871d5ae102SDimitry Andric 
988cfca06d7SDimitry Andric       DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
989c0981da4SDimitry Andric           ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
9901d5ae102SDimitry Andric 
991cfca06d7SDimitry Andric       // Optionally emit call-site-param debug info.
992cfca06d7SDimitry Andric       if (emitDebugEntryValues()) {
9931d5ae102SDimitry Andric         ParamSet Params;
9941d5ae102SDimitry Andric         // Try to interpret values of call site parameters.
9951d5ae102SDimitry Andric         collectCallSiteParameters(&MI, Params);
9961d5ae102SDimitry Andric         CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
9971d5ae102SDimitry Andric       }
998d8e91e46SDimitry Andric     }
999d8e91e46SDimitry Andric   }
1000d8e91e46SDimitry Andric }
1001d8e91e46SDimitry Andric 
addGnuPubAttributes(DwarfCompileUnit & U,DIE & D) const1002ab44ce3dSDimitry Andric void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
1003044eb2f6SDimitry Andric   if (!U.hasDwarfPubSections())
10045ca98fd9SDimitry Andric     return;
1005f8af5cf6SDimitry Andric 
10065ca98fd9SDimitry Andric   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
1007009b1c42SEd Schouten }
1008009b1c42SEd Schouten 
finishUnitAttributes(const DICompileUnit * DIUnit,DwarfCompileUnit & NewCU)1009d8e91e46SDimitry Andric void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
1010d8e91e46SDimitry Andric                                       DwarfCompileUnit &NewCU) {
10115ca98fd9SDimitry Andric   DIE &Die = NewCU.getUnitDie();
1012d8e91e46SDimitry Andric   StringRef FN = DIUnit->getFilename();
10134a16efa3SDimitry Andric 
101471d5a254SDimitry Andric   StringRef Producer = DIUnit->getProducer();
101571d5a254SDimitry Andric   StringRef Flags = DIUnit->getFlags();
1016d8e91e46SDimitry Andric   if (!Flags.empty() && !useAppleExtensionAttributes()) {
101771d5a254SDimitry Andric     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
101871d5a254SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
101971d5a254SDimitry Andric   } else
102071d5a254SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
102171d5a254SDimitry Andric 
10225ca98fd9SDimitry Andric   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
10235a5ac124SDimitry Andric                 DIUnit->getSourceLanguage());
10245ca98fd9SDimitry Andric   NewCU.addString(Die, dwarf::DW_AT_name, FN);
1025cfca06d7SDimitry Andric   StringRef SysRoot = DIUnit->getSysRoot();
1026cfca06d7SDimitry Andric   if (!SysRoot.empty())
1027cfca06d7SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
1028cfca06d7SDimitry Andric   StringRef SDK = DIUnit->getSDK();
1029cfca06d7SDimitry Andric   if (!SDK.empty())
1030cfca06d7SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
103159d6cff9SDimitry Andric 
10327fa27ce4SDimitry Andric   if (!useSplitDwarf()) {
1033eb11fae6SDimitry Andric     // Add DW_str_offsets_base to the unit DIE, except for split units.
10347fa27ce4SDimitry Andric     if (useSegmentedStringOffsetsTable())
1035eb11fae6SDimitry Andric       NewCU.addStringOffsetsStart();
1036eb11fae6SDimitry Andric 
10375a5ac124SDimitry Andric     NewCU.initStmtList();
1038009b1c42SEd Schouten 
103959d6cff9SDimitry Andric     // If we're using split dwarf the compilation dir is going to be in the
104059d6cff9SDimitry Andric     // skeleton CU and so we don't need to duplicate it here.
1041f8af5cf6SDimitry Andric     if (!CompilationDir.empty())
10425ca98fd9SDimitry Andric       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
10435ca98fd9SDimitry Andric     addGnuPubAttributes(NewCU, Die);
1044f8af5cf6SDimitry Andric   }
1045f8af5cf6SDimitry Andric 
104601095a5dSDimitry Andric   if (useAppleExtensionAttributes()) {
10475a5ac124SDimitry Andric     if (DIUnit->isOptimized())
10485ca98fd9SDimitry Andric       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1049009b1c42SEd Schouten 
10505a5ac124SDimitry Andric     StringRef Flags = DIUnit->getFlags();
105106f9d401SRoman Divacky     if (!Flags.empty())
10525ca98fd9SDimitry Andric       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1053009b1c42SEd Schouten 
10545a5ac124SDimitry Andric     if (unsigned RVer = DIUnit->getRuntimeVersion())
10555ca98fd9SDimitry Andric       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1056009b1c42SEd Schouten                     dwarf::DW_FORM_data1, RVer);
105701095a5dSDimitry Andric   }
1058009b1c42SEd Schouten 
1059dd58ef01SDimitry Andric   if (DIUnit->getDWOId()) {
1060dd58ef01SDimitry Andric     // This CU is either a clang module DWO or a skeleton CU.
1061dd58ef01SDimitry Andric     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1062dd58ef01SDimitry Andric                   DIUnit->getDWOId());
1063706b4fc4SDimitry Andric     if (!DIUnit->getSplitDebugFilename().empty()) {
1064dd58ef01SDimitry Andric       // This is a prefabricated skeleton CU.
1065706b4fc4SDimitry Andric       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1066706b4fc4SDimitry Andric                                          ? dwarf::DW_AT_dwo_name
1067706b4fc4SDimitry Andric                                          : dwarf::DW_AT_GNU_dwo_name;
1068706b4fc4SDimitry Andric       NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1069706b4fc4SDimitry Andric     }
1070dd58ef01SDimitry Andric   }
1071d8e91e46SDimitry Andric }
1072d8e91e46SDimitry Andric // Create new DwarfCompileUnit for the given metadata node with tag
1073d8e91e46SDimitry Andric // DW_TAG_compile_unit.
1074d8e91e46SDimitry Andric DwarfCompileUnit &
getOrCreateDwarfCompileUnit(const DICompileUnit * DIUnit)1075d8e91e46SDimitry Andric DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
1076d8e91e46SDimitry Andric   if (auto *CU = CUMap.lookup(DIUnit))
1077d8e91e46SDimitry Andric     return *CU;
1078d8e91e46SDimitry Andric 
10797fa27ce4SDimitry Andric   if (useSplitDwarf() &&
10807fa27ce4SDimitry Andric       !shareAcrossDWOCUs() &&
10817fa27ce4SDimitry Andric       (!DIUnit->getSplitDebugInlining() ||
10827fa27ce4SDimitry Andric        DIUnit->getEmissionKind() == DICompileUnit::FullDebug) &&
10837fa27ce4SDimitry Andric       !CUMap.empty()) {
10847fa27ce4SDimitry Andric     return *CUMap.begin()->second;
10857fa27ce4SDimitry Andric   }
1086d8e91e46SDimitry Andric   CompilationDir = DIUnit->getDirectory();
1087d8e91e46SDimitry Andric 
10881d5ae102SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1089d8e91e46SDimitry Andric       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
1090d8e91e46SDimitry Andric   DwarfCompileUnit &NewCU = *OwnedUnit;
1091d8e91e46SDimitry Andric   InfoHolder.addUnit(std::move(OwnedUnit));
1092d8e91e46SDimitry Andric 
1093d8e91e46SDimitry Andric   // LTO with assembly output shares a single line table amongst multiple CUs.
1094d8e91e46SDimitry Andric   // To avoid the compilation directory being ambiguous, let the line table
1095d8e91e46SDimitry Andric   // explicitly describe the directory of all files, never relying on the
1096d8e91e46SDimitry Andric   // compilation directory.
1097d8e91e46SDimitry Andric   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1098d8e91e46SDimitry Andric     Asm->OutStreamer->emitDwarfFile0Directive(
1099b60736ecSDimitry Andric         CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1100b60736ecSDimitry Andric         DIUnit->getSource(), NewCU.getUniqueID());
1101d8e91e46SDimitry Andric 
1102d8e91e46SDimitry Andric   if (useSplitDwarf()) {
1103d8e91e46SDimitry Andric     NewCU.setSkeleton(constructSkeletonCU(NewCU));
1104d8e91e46SDimitry Andric     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1105d8e91e46SDimitry Andric   } else {
1106d8e91e46SDimitry Andric     finishUnitAttributes(DIUnit, NewCU);
1107d8e91e46SDimitry Andric     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1108d8e91e46SDimitry Andric   }
1109dd58ef01SDimitry Andric 
1110b915e9e0SDimitry Andric   CUMap.insert({DIUnit, &NewCU});
1111d8e91e46SDimitry Andric   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
111230815c53SDimitry Andric   return NewCU;
1113009b1c42SEd Schouten }
1114009b1c42SEd Schouten 
1115b915e9e0SDimitry Andric /// Sort and unique GVEs by comparing their fragment offset.
1116b915e9e0SDimitry Andric static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & GVEs)1117b915e9e0SDimitry Andric sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1118d8e91e46SDimitry Andric   llvm::sort(
1119d8e91e46SDimitry Andric       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1120044eb2f6SDimitry Andric         // Sort order: first null exprs, then exprs without fragment
1121044eb2f6SDimitry Andric         // info, then sort by fragment offset in bits.
1122044eb2f6SDimitry Andric         // FIXME: Come up with a more comprehensive comparator so
1123044eb2f6SDimitry Andric         // the sorting isn't non-deterministic, and so the following
1124044eb2f6SDimitry Andric         // std::unique call works correctly.
1125044eb2f6SDimitry Andric         if (!A.Expr || !B.Expr)
1126044eb2f6SDimitry Andric           return !!B.Expr;
1127b915e9e0SDimitry Andric         auto FragmentA = A.Expr->getFragmentInfo();
1128b915e9e0SDimitry Andric         auto FragmentB = B.Expr->getFragmentInfo();
1129044eb2f6SDimitry Andric         if (!FragmentA || !FragmentB)
1130044eb2f6SDimitry Andric           return !!FragmentB;
1131b915e9e0SDimitry Andric         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1132b915e9e0SDimitry Andric       });
1133ac9a064cSDimitry Andric   GVEs.erase(llvm::unique(GVEs,
1134b915e9e0SDimitry Andric                           [](DwarfCompileUnit::GlobalExpr A,
1135b915e9e0SDimitry Andric                              DwarfCompileUnit::GlobalExpr B) {
1136b915e9e0SDimitry Andric                             return A.Expr == B.Expr;
1137b915e9e0SDimitry Andric                           }),
1138b915e9e0SDimitry Andric              GVEs.end());
1139b915e9e0SDimitry Andric   return GVEs;
1140b915e9e0SDimitry Andric }
1141b915e9e0SDimitry Andric 
11424a16efa3SDimitry Andric // Emit all Dwarf sections that should come prior to the content. Create
11434a16efa3SDimitry Andric // global DIEs and emit initial debug info sections. This is invoked by
11444a16efa3SDimitry Andric // the target AsmPrinter.
beginModule(Module * M)1145b60736ecSDimitry Andric void DwarfDebug::beginModule(Module *M) {
1146b60736ecSDimitry Andric   DebugHandlerBase::beginModule(M);
114730815c53SDimitry Andric 
1148b60736ecSDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
1149b60736ecSDimitry Andric     return;
11504a16efa3SDimitry Andric 
115101095a5dSDimitry Andric   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
115201095a5dSDimitry Andric                                        M->debug_compile_units_end());
1153b60736ecSDimitry Andric   assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1154b60736ecSDimitry Andric   assert(MMI->hasDebugInfo() &&
1155b60736ecSDimitry Andric          "DebugInfoAvailabilty unexpectedly not initialized");
115601095a5dSDimitry Andric   SingleCU = NumDebugCUs == 1;
1157b915e9e0SDimitry Andric   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1158b915e9e0SDimitry Andric       GVMap;
1159b915e9e0SDimitry Andric   for (const GlobalVariable &Global : M->globals()) {
1160b915e9e0SDimitry Andric     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1161b915e9e0SDimitry Andric     Global.getDebugInfo(GVs);
1162b915e9e0SDimitry Andric     for (auto *GVE : GVs)
1163b915e9e0SDimitry Andric       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1164b915e9e0SDimitry Andric   }
11654a16efa3SDimitry Andric 
1166eb11fae6SDimitry Andric   // Create the symbol that designates the start of the unit's contribution
1167eb11fae6SDimitry Andric   // to the string offsets table. In a split DWARF scenario, only the skeleton
1168eb11fae6SDimitry Andric   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1169eb11fae6SDimitry Andric   if (useSegmentedStringOffsetsTable())
1170eb11fae6SDimitry Andric     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1171eb11fae6SDimitry Andric         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1172eb11fae6SDimitry Andric 
1173d8e91e46SDimitry Andric 
1174d8e91e46SDimitry Andric   // Create the symbols that designates the start of the DWARF v5 range list
1175d8e91e46SDimitry Andric   // and locations list tables. They are located past the table headers.
1176d8e91e46SDimitry Andric   if (getDwarfVersion() >= 5) {
1177d8e91e46SDimitry Andric     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1178d8e91e46SDimitry Andric     Holder.setRnglistsTableBaseSym(
1179d8e91e46SDimitry Andric         Asm->createTempSymbol("rnglists_table_base"));
1180d8e91e46SDimitry Andric 
1181d8e91e46SDimitry Andric     if (useSplitDwarf())
1182d8e91e46SDimitry Andric       InfoHolder.setRnglistsTableBaseSym(
1183d8e91e46SDimitry Andric           Asm->createTempSymbol("rnglists_dwo_table_base"));
1184d8e91e46SDimitry Andric   }
1185d8e91e46SDimitry Andric 
1186d8e91e46SDimitry Andric   // Create the symbol that points to the first entry following the debug
1187d8e91e46SDimitry Andric   // address table (.debug_addr) header.
1188d8e91e46SDimitry Andric   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1189706b4fc4SDimitry Andric   DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1190eb11fae6SDimitry Andric 
119101095a5dSDimitry Andric   for (DICompileUnit *CUNode : M->debug_compile_units()) {
11927fa27ce4SDimitry Andric     if (CUNode->getImportedEntities().empty() &&
11937fa27ce4SDimitry Andric         CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
1194044eb2f6SDimitry Andric         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1195ab44ce3dSDimitry Andric       continue;
1196ab44ce3dSDimitry Andric 
1197ab44ce3dSDimitry Andric     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1198b915e9e0SDimitry Andric 
1199b915e9e0SDimitry Andric     // Global Variables.
1200044eb2f6SDimitry Andric     for (auto *GVE : CUNode->getGlobalVariables()) {
1201044eb2f6SDimitry Andric       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1202044eb2f6SDimitry Andric       // already know about the variable and it isn't adding a constant
1203044eb2f6SDimitry Andric       // expression.
1204044eb2f6SDimitry Andric       auto &GVMapEntry = GVMap[GVE->getVariable()];
1205044eb2f6SDimitry Andric       auto *Expr = GVE->getExpression();
1206044eb2f6SDimitry Andric       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1207044eb2f6SDimitry Andric         GVMapEntry.push_back({nullptr, Expr});
1208044eb2f6SDimitry Andric     }
1209344a3780SDimitry Andric 
1210b915e9e0SDimitry Andric     DenseSet<DIGlobalVariable *> Processed;
1211b915e9e0SDimitry Andric     for (auto *GVE : CUNode->getGlobalVariables()) {
1212b915e9e0SDimitry Andric       DIGlobalVariable *GV = GVE->getVariable();
1213b915e9e0SDimitry Andric       if (Processed.insert(GV).second)
1214b915e9e0SDimitry Andric         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1215b915e9e0SDimitry Andric     }
1216b915e9e0SDimitry Andric 
121777fc4c14SDimitry Andric     for (auto *Ty : CUNode->getEnumTypes())
121801095a5dSDimitry Andric       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
121977fc4c14SDimitry Andric 
12205a5ac124SDimitry Andric     for (auto *Ty : CUNode->getRetainedTypes()) {
12215ca98fd9SDimitry Andric       // The retained types array by design contains pointers to
12225ca98fd9SDimitry Andric       // MDNodes rather than DIRefs. Unique them here.
122301095a5dSDimitry Andric       if (DIType *RT = dyn_cast<DIType>(Ty))
1224dd58ef01SDimitry Andric         // There is no point in force-emitting a forward declaration.
1225dd58ef01SDimitry Andric         CU.getOrCreateTypeDIE(RT);
12265ca98fd9SDimitry Andric     }
12274a16efa3SDimitry Andric   }
1228009b1c42SEd Schouten }
1229009b1c42SEd Schouten 
finishEntityDefinitions()1230d8e91e46SDimitry Andric void DwarfDebug::finishEntityDefinitions() {
1231d8e91e46SDimitry Andric   for (const auto &Entity : ConcreteEntities) {
1232d8e91e46SDimitry Andric     DIE *Die = Entity->getDIE();
1233d8e91e46SDimitry Andric     assert(Die);
12345ca98fd9SDimitry Andric     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1235d8e91e46SDimitry Andric     // in the ConcreteEntities list, rather than looking it up again here.
12365ca98fd9SDimitry Andric     // DIE::getUnit isn't simple - it walks parent pointers, etc.
1237d8e91e46SDimitry Andric     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
12385ca98fd9SDimitry Andric     assert(Unit);
1239d8e91e46SDimitry Andric     Unit->finishEntityDefinition(Entity.get());
12404a16efa3SDimitry Andric   }
12414a16efa3SDimitry Andric }
12424a16efa3SDimitry Andric 
finishSubprogramDefinitions()12435ca98fd9SDimitry Andric void DwarfDebug::finishSubprogramDefinitions() {
1244ab44ce3dSDimitry Andric   for (const DISubprogram *SP : ProcessedSPNodes) {
1245ab44ce3dSDimitry Andric     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1246ab44ce3dSDimitry Andric     forBothCUs(
1247ab44ce3dSDimitry Andric         getOrCreateDwarfCompileUnit(SP->getUnit()),
1248ab44ce3dSDimitry Andric         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1249ab44ce3dSDimitry Andric   }
12505ca98fd9SDimitry Andric }
12515ca98fd9SDimitry Andric 
finalizeModuleInfo()12524a16efa3SDimitry Andric void DwarfDebug::finalizeModuleInfo() {
12535a5ac124SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
12545a5ac124SDimitry Andric 
12555ca98fd9SDimitry Andric   finishSubprogramDefinitions();
12565ca98fd9SDimitry Andric 
1257d8e91e46SDimitry Andric   finishEntityDefinitions();
12585ca98fd9SDimitry Andric 
1259ab44ce3dSDimitry Andric   // Include the DWO file name in the hash if there's more than one CU.
1260ab44ce3dSDimitry Andric   // This handles ThinLTO's situation where imported CUs may very easily be
1261ab44ce3dSDimitry Andric   // duplicate with the same CU partially imported into another ThinLTO unit.
1262ab44ce3dSDimitry Andric   StringRef DWOName;
1263ab44ce3dSDimitry Andric   if (CUMap.size() > 1)
1264ab44ce3dSDimitry Andric     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1265ab44ce3dSDimitry Andric 
12667fa27ce4SDimitry Andric   bool HasEmittedSplitCU = false;
12677fa27ce4SDimitry Andric 
12685ca98fd9SDimitry Andric   // Handle anything that needs to be done on a per-unit basis after
12695ca98fd9SDimitry Andric   // all other generation.
127067c32a98SDimitry Andric   for (const auto &P : CUMap) {
127167c32a98SDimitry Andric     auto &TheCU = *P.second;
1272d8e91e46SDimitry Andric     if (TheCU.getCUNode()->isDebugDirectivesOnly())
1273d8e91e46SDimitry Andric       continue;
127430815c53SDimitry Andric     // Emit DW_AT_containing_type attribute to connect types with their
127530815c53SDimitry Andric     // vtable holding type.
127667c32a98SDimitry Andric     TheCU.constructContainingTypeDIEs();
1277f8af5cf6SDimitry Andric 
12785ca98fd9SDimitry Andric     // Add CU specific attributes if we need to add any.
1279f8af5cf6SDimitry Andric     // If we're splitting the dwarf out now that we've got the entire
12805ca98fd9SDimitry Andric     // CU then add the dwo id to it.
128167c32a98SDimitry Andric     auto *SkCU = TheCU.getSkeleton();
1282706b4fc4SDimitry Andric 
1283706b4fc4SDimitry Andric     bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1284706b4fc4SDimitry Andric 
1285706b4fc4SDimitry Andric     if (HasSplitUnit) {
12867fa27ce4SDimitry Andric       (void)HasEmittedSplitCU;
12877fa27ce4SDimitry Andric       assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
12887fa27ce4SDimitry Andric              "Multiple CUs emitted into a single dwo file");
12897fa27ce4SDimitry Andric       HasEmittedSplitCU = true;
1290706b4fc4SDimitry Andric       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1291706b4fc4SDimitry Andric                                          ? dwarf::DW_AT_dwo_name
1292706b4fc4SDimitry Andric                                          : dwarf::DW_AT_GNU_dwo_name;
1293d8e91e46SDimitry Andric       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1294706b4fc4SDimitry Andric       TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1295d8e91e46SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1296706b4fc4SDimitry Andric       SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1297d8e91e46SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
12985ca98fd9SDimitry Andric       // Emit a unique identifier for this CU.
1299ab44ce3dSDimitry Andric       uint64_t ID =
1300b60736ecSDimitry Andric           DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1301eb11fae6SDimitry Andric       if (getDwarfVersion() >= 5) {
1302eb11fae6SDimitry Andric         TheCU.setDWOId(ID);
1303eb11fae6SDimitry Andric         SkCU->setDWOId(ID);
1304eb11fae6SDimitry Andric       } else {
130567c32a98SDimitry Andric         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
13065ca98fd9SDimitry Andric                       dwarf::DW_FORM_data8, ID);
13075ca98fd9SDimitry Andric         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
13085ca98fd9SDimitry Andric                       dwarf::DW_FORM_data8, ID);
1309eb11fae6SDimitry Andric       }
1310d8e91e46SDimitry Andric 
1311d8e91e46SDimitry Andric       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
13125a5ac124SDimitry Andric         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
131367c32a98SDimitry Andric         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
13145a5ac124SDimitry Andric                               Sym, Sym);
13155a5ac124SDimitry Andric       }
1316d8e91e46SDimitry Andric     } else if (SkCU) {
1317d8e91e46SDimitry Andric       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1318f8af5cf6SDimitry Andric     }
13195ca98fd9SDimitry Andric 
13205ca98fd9SDimitry Andric     // If we have code split among multiple sections or non-contiguous
13215ca98fd9SDimitry Andric     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
13225ca98fd9SDimitry Andric     // remain in the .o file, otherwise add a DW_AT_low_pc.
13235ca98fd9SDimitry Andric     // FIXME: We should use ranges allow reordering of code ala
13245ca98fd9SDimitry Andric     // .subsections_via_symbols in mach-o. This would mean turning on
13255ca98fd9SDimitry Andric     // ranges for all subprogram DIEs for mach-o.
132667c32a98SDimitry Andric     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1327d8e91e46SDimitry Andric 
132867c32a98SDimitry Andric     if (unsigned NumRanges = TheCU.getRanges().size()) {
1329eb11fae6SDimitry Andric       if (NumRanges > 1 && useRangesSection())
13305ca98fd9SDimitry Andric         // A DW_AT_low_pc attribute may also be specified in combination with
13315ca98fd9SDimitry Andric         // DW_AT_ranges to specify the default base address for use in
13325ca98fd9SDimitry Andric         // location lists (see Section 2.6.2) and range lists (see Section
13335ca98fd9SDimitry Andric         // 2.17.3).
133467c32a98SDimitry Andric         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
133567c32a98SDimitry Andric       else
13361d5ae102SDimitry Andric         U.setBaseAddress(TheCU.getRanges().front().Begin);
133767c32a98SDimitry Andric       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1338f8af5cf6SDimitry Andric     }
1339050e163aSDimitry Andric 
1340e6d15924SDimitry Andric     // We don't keep track of which addresses are used in which CU so this
1341e6d15924SDimitry Andric     // is a bit pessimistic under LTO.
1342cfca06d7SDimitry Andric     if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1343e6d15924SDimitry Andric       U.addAddrTableBase();
1344e6d15924SDimitry Andric 
1345d8e91e46SDimitry Andric     if (getDwarfVersion() >= 5) {
1346d8e91e46SDimitry Andric       if (U.hasRangeLists())
1347eb11fae6SDimitry Andric         U.addRnglistsBase();
1348eb11fae6SDimitry Andric 
13497fa27ce4SDimitry Andric       if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
13501d5ae102SDimitry Andric         U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
13511d5ae102SDimitry Andric                           DebugLocs.getSym(),
13521d5ae102SDimitry Andric                           TLOF.getDwarfLoclistsSection()->getBeginSymbol());
13531d5ae102SDimitry Andric       }
1354d8e91e46SDimitry Andric     }
1355d8e91e46SDimitry Andric 
1356050e163aSDimitry Andric     auto *CUNode = cast<DICompileUnit>(P.first);
1357cfca06d7SDimitry Andric     // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1358cfca06d7SDimitry Andric     // attribute.
1359706b4fc4SDimitry Andric     if (CUNode->getMacros()) {
1360b60736ecSDimitry Andric       if (UseDebugMacroSection) {
1361706b4fc4SDimitry Andric         if (useSplitDwarf())
1362cfca06d7SDimitry Andric           TheCU.addSectionDelta(
1363cfca06d7SDimitry Andric               TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
1364cfca06d7SDimitry Andric               TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
1365b60736ecSDimitry Andric         else {
1366b60736ecSDimitry Andric           dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1367b60736ecSDimitry Andric                                             ? dwarf::DW_AT_macros
1368b60736ecSDimitry Andric                                             : dwarf::DW_AT_GNU_macros;
1369b60736ecSDimitry Andric           U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
1370cfca06d7SDimitry Andric                             TLOF.getDwarfMacroSection()->getBeginSymbol());
1371b60736ecSDimitry Andric         }
1372cfca06d7SDimitry Andric       } else {
1373cfca06d7SDimitry Andric         if (useSplitDwarf())
1374cfca06d7SDimitry Andric           TheCU.addSectionDelta(
1375cfca06d7SDimitry Andric               TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1376706b4fc4SDimitry Andric               U.getMacroLabelBegin(),
1377706b4fc4SDimitry Andric               TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1378706b4fc4SDimitry Andric         else
137901095a5dSDimitry Andric           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
138001095a5dSDimitry Andric                             U.getMacroLabelBegin(),
138101095a5dSDimitry Andric                             TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1382571945e6SRoman Divacky       }
1383706b4fc4SDimitry Andric     }
1384cfca06d7SDimitry Andric     }
1385571945e6SRoman Divacky 
1386044eb2f6SDimitry Andric   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1387044eb2f6SDimitry Andric   for (auto *CUNode : MMI->getModule()->debug_compile_units())
1388044eb2f6SDimitry Andric     if (CUNode->getDWOId())
1389044eb2f6SDimitry Andric       getOrCreateDwarfCompileUnit(CUNode);
1390044eb2f6SDimitry Andric 
13914a16efa3SDimitry Andric   // Compute DIE offsets and sizes.
13924a16efa3SDimitry Andric   InfoHolder.computeSizeAndOffsets();
13934a16efa3SDimitry Andric   if (useSplitDwarf())
13944a16efa3SDimitry Andric     SkeletonHolder.computeSizeAndOffsets();
1395b1c73532SDimitry Andric 
1396b1c73532SDimitry Andric   // Now that offsets are computed, can replace DIEs in debug_names Entry with
1397b1c73532SDimitry Andric   // an actual offset.
1398b1c73532SDimitry Andric   AccelDebugNames.convertDieToOffset();
13994a16efa3SDimitry Andric }
14004a16efa3SDimitry Andric 
14014a16efa3SDimitry Andric // Emit all Dwarf sections that should come after the content.
endModule()14024a16efa3SDimitry Andric void DwarfDebug::endModule() {
1403c0981da4SDimitry Andric   // Terminate the pending line table.
1404c0981da4SDimitry Andric   if (PrevCU)
1405c0981da4SDimitry Andric     terminateLineTable(PrevCU);
1406c0981da4SDimitry Andric   PrevCU = nullptr;
14075ca98fd9SDimitry Andric   assert(CurFn == nullptr);
14085ca98fd9SDimitry Andric   assert(CurMI == nullptr);
1409009b1c42SEd Schouten 
1410e6d15924SDimitry Andric   for (const auto &P : CUMap) {
14117fa27ce4SDimitry Andric     const auto *CUNode = cast<DICompileUnit>(P.first);
14127fa27ce4SDimitry Andric     DwarfCompileUnit *CU = &*P.second;
14137fa27ce4SDimitry Andric 
14147fa27ce4SDimitry Andric     // Emit imported entities.
14157fa27ce4SDimitry Andric     for (auto *IE : CUNode->getImportedEntities()) {
14167fa27ce4SDimitry Andric       assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
14177fa27ce4SDimitry Andric              "Unexpected function-local entity in 'imports' CU field.");
14187fa27ce4SDimitry Andric       CU->getOrCreateImportedEntityDIE(IE);
14197fa27ce4SDimitry Andric     }
14207fa27ce4SDimitry Andric     for (const auto *D : CU->getDeferredLocalDecls()) {
14217fa27ce4SDimitry Andric       if (auto *IE = dyn_cast<DIImportedEntity>(D))
14227fa27ce4SDimitry Andric         CU->getOrCreateImportedEntityDIE(IE);
14237fa27ce4SDimitry Andric       else
14247fa27ce4SDimitry Andric         llvm_unreachable("Unexpected local retained node!");
14257fa27ce4SDimitry Andric     }
14267fa27ce4SDimitry Andric 
14277fa27ce4SDimitry Andric     // Emit base types.
14287fa27ce4SDimitry Andric     CU->createBaseTypeDIEs();
1429e6d15924SDimitry Andric   }
1430e6d15924SDimitry Andric 
143167c32a98SDimitry Andric   // If we aren't actually generating debug info (check beginModule -
1432b60736ecSDimitry Andric   // conditionalized on the presence of the llvm.dbg.cu metadata node)
1433b60736ecSDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
14345ca98fd9SDimitry Andric     return;
14354a16efa3SDimitry Andric 
14364a16efa3SDimitry Andric   // Finalize the debug info for the module.
14374a16efa3SDimitry Andric   finalizeModuleInfo();
14384a16efa3SDimitry Andric 
14395a5ac124SDimitry Andric   if (useSplitDwarf())
1440706b4fc4SDimitry Andric     // Emit debug_loc.dwo/debug_loclists.dwo section.
14415a5ac124SDimitry Andric     emitDebugLocDWO();
14425a5ac124SDimitry Andric   else
1443706b4fc4SDimitry Andric     // Emit debug_loc/debug_loclists section.
14445a5ac124SDimitry Andric     emitDebugLoc();
1445009b1c42SEd Schouten 
1446009b1c42SEd Schouten   // Corresponding abbreviations into a abbrev section.
144706f9d401SRoman Divacky   emitAbbreviations();
1448009b1c42SEd Schouten 
14495a5ac124SDimitry Andric   // Emit all the DIEs into a debug info section.
14505a5ac124SDimitry Andric   emitDebugInfo();
14515a5ac124SDimitry Andric 
1452009b1c42SEd Schouten   // Emit info into a debug aranges section.
14535ca98fd9SDimitry Andric   if (GenerateARangeSection)
14544a16efa3SDimitry Andric     emitDebugARanges();
1455009b1c42SEd Schouten 
1456009b1c42SEd Schouten   // Emit info into a debug ranges section.
145706f9d401SRoman Divacky   emitDebugRanges();
1458009b1c42SEd Schouten 
1459706b4fc4SDimitry Andric   if (useSplitDwarf())
1460706b4fc4SDimitry Andric   // Emit info into a debug macinfo.dwo section.
1461706b4fc4SDimitry Andric     emitDebugMacinfoDWO();
1462706b4fc4SDimitry Andric   else
1463cfca06d7SDimitry Andric     // Emit info into a debug macinfo/macro section.
1464050e163aSDimitry Andric     emitDebugMacinfo();
1465050e163aSDimitry Andric 
1466cfca06d7SDimitry Andric   emitDebugStr();
1467cfca06d7SDimitry Andric 
14685ca98fd9SDimitry Andric   if (useSplitDwarf()) {
1469f8af5cf6SDimitry Andric     emitDebugStrDWO();
14704a16efa3SDimitry Andric     emitDebugInfoDWO();
14714a16efa3SDimitry Andric     emitDebugAbbrevDWO();
14725ca98fd9SDimitry Andric     emitDebugLineDWO();
1473d8e91e46SDimitry Andric     emitDebugRangesDWO();
14745a5ac124SDimitry Andric   }
14754a16efa3SDimitry Andric 
1476d8e91e46SDimitry Andric   emitDebugAddr();
1477d8e91e46SDimitry Andric 
14784a16efa3SDimitry Andric   // Emit info into the dwarf accelerator table sections.
1479eb11fae6SDimitry Andric   switch (getAccelTableKind()) {
1480eb11fae6SDimitry Andric   case AccelTableKind::Apple:
14814a16efa3SDimitry Andric     emitAccelNames();
14824a16efa3SDimitry Andric     emitAccelObjC();
14834a16efa3SDimitry Andric     emitAccelNamespaces();
14844a16efa3SDimitry Andric     emitAccelTypes();
1485eb11fae6SDimitry Andric     break;
1486eb11fae6SDimitry Andric   case AccelTableKind::Dwarf:
1487eb11fae6SDimitry Andric     emitAccelDebugNames();
1488eb11fae6SDimitry Andric     break;
1489eb11fae6SDimitry Andric   case AccelTableKind::None:
1490eb11fae6SDimitry Andric     break;
1491eb11fae6SDimitry Andric   case AccelTableKind::Default:
1492eb11fae6SDimitry Andric     llvm_unreachable("Default should have already been resolved.");
14934a16efa3SDimitry Andric   }
14944a16efa3SDimitry Andric 
1495f8af5cf6SDimitry Andric   // Emit the pubnames and pubtypes sections if requested.
1496044eb2f6SDimitry Andric   emitDebugPubSections();
1497c6910277SRoman Divacky 
1498d39c594dSDimitry Andric   // clean up.
14996b3f41edSDimitry Andric   // FIXME: AbstractVariables.clear();
1500009b1c42SEd Schouten }
1501009b1c42SEd Schouten 
ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit & CU,const DINode * Node,const MDNode * ScopeNode)1502d8e91e46SDimitry Andric void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1503d8e91e46SDimitry Andric     const DINode *Node, const MDNode *ScopeNode) {
1504d8e91e46SDimitry Andric   if (CU.getExistingAbstractEntity(Node))
15055ca98fd9SDimitry Andric     return;
15065ca98fd9SDimitry Andric 
15075a5ac124SDimitry Andric   if (LexicalScope *Scope =
15085a5ac124SDimitry Andric           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1509d8e91e46SDimitry Andric     CU.createAbstractEntity(Node, Scope);
1510c6910277SRoman Divacky }
1511044eb2f6SDimitry Andric 
getRetainedNodeScope(const MDNode * N)15127fa27ce4SDimitry Andric static const DILocalScope *getRetainedNodeScope(const MDNode *N) {
15137fa27ce4SDimitry Andric   const DIScope *S;
15147fa27ce4SDimitry Andric   if (const auto *LV = dyn_cast<DILocalVariable>(N))
15157fa27ce4SDimitry Andric     S = LV->getScope();
15167fa27ce4SDimitry Andric   else if (const auto *L = dyn_cast<DILabel>(N))
15177fa27ce4SDimitry Andric     S = L->getScope();
15187fa27ce4SDimitry Andric   else if (const auto *IE = dyn_cast<DIImportedEntity>(N))
15197fa27ce4SDimitry Andric     S = IE->getScope();
15207fa27ce4SDimitry Andric   else
15217fa27ce4SDimitry Andric     llvm_unreachable("Unexpected retained node!");
15227fa27ce4SDimitry Andric 
15237fa27ce4SDimitry Andric   // Ensure the scope is not a DILexicalBlockFile.
15247fa27ce4SDimitry Andric   return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();
15257fa27ce4SDimitry Andric }
15267fa27ce4SDimitry Andric 
1527b915e9e0SDimitry Andric // Collect variable information from side table maintained by MF.
collectVariableInfoFromMFTable(DwarfCompileUnit & TheCU,DenseSet<InlinedEntity> & Processed)1528b915e9e0SDimitry Andric void DwarfDebug::collectVariableInfoFromMFTable(
1529d8e91e46SDimitry Andric     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1530d8e91e46SDimitry Andric   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1531cfca06d7SDimitry Andric   LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1532b915e9e0SDimitry Andric   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
15335ca98fd9SDimitry Andric     if (!VI.Var)
15345ca98fd9SDimitry Andric       continue;
15355a5ac124SDimitry Andric     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
15365a5ac124SDimitry Andric            "Expected inlined-at fields to agree");
15375a5ac124SDimitry Andric 
1538d8e91e46SDimitry Andric     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
15395a5ac124SDimitry Andric     Processed.insert(Var);
15405ca98fd9SDimitry Andric     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1541b5efedafSRoman Divacky 
1542907da171SRoman Divacky     // If variable scope is not found then skip this variable.
1543cfca06d7SDimitry Andric     if (!Scope) {
1544cfca06d7SDimitry Andric       LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1545cfca06d7SDimitry Andric                         << ", no variable scope found\n");
1546907da171SRoman Divacky       continue;
1547cfca06d7SDimitry Andric     }
1548907da171SRoman Divacky 
1549d8e91e46SDimitry Andric     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1550b1c73532SDimitry Andric 
1551b1c73532SDimitry Andric     // If we have already seen information for this variable, add to what we
1552b1c73532SDimitry Andric     // already know.
1553b1c73532SDimitry Andric     if (DbgVariable *PreviousLoc = MFVars.lookup(Var)) {
1554b1c73532SDimitry Andric       auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
1555b1c73532SDimitry Andric       auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
1556b1c73532SDimitry Andric       // Previous and new locations are both stack slots (MMI).
1557b1c73532SDimitry Andric       if (PreviousMMI && VI.inStackSlot())
1558b1c73532SDimitry Andric         PreviousMMI->addFrameIndexExpr(VI.Expr, VI.getStackSlot());
1559b1c73532SDimitry Andric       // Previous and new locations are both entry values.
1560b1c73532SDimitry Andric       else if (PreviousEntryValue && VI.inEntryValueRegister())
1561b1c73532SDimitry Andric         PreviousEntryValue->addExpr(VI.getEntryValueRegister(), *VI.Expr);
1562b1c73532SDimitry Andric       else {
1563b1c73532SDimitry Andric         // Locations differ, this should (rarely) happen in optimized async
1564b1c73532SDimitry Andric         // coroutines.
1565b1c73532SDimitry Andric         // Prefer whichever location has an EntryValue.
1566b1c73532SDimitry Andric         if (PreviousLoc->holds<Loc::MMI>())
1567b1c73532SDimitry Andric           PreviousLoc->emplace<Loc::EntryValue>(VI.getEntryValueRegister(),
1568b1c73532SDimitry Andric                                                 *VI.Expr);
1569b1c73532SDimitry Andric         LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1570b1c73532SDimitry Andric                           << ", conflicting fragment location types\n");
1571b1c73532SDimitry Andric       }
1572b1c73532SDimitry Andric       continue;
1573b1c73532SDimitry Andric     }
1574b1c73532SDimitry Andric 
15751d5ae102SDimitry Andric     auto RegVar = std::make_unique<DbgVariable>(
1576d8e91e46SDimitry Andric                     cast<DILocalVariable>(Var.first), Var.second);
15777fa27ce4SDimitry Andric     if (VI.inStackSlot())
1578b1c73532SDimitry Andric       RegVar->emplace<Loc::MMI>(VI.Expr, VI.getStackSlot());
1579b1c73532SDimitry Andric     else
1580b1c73532SDimitry Andric       RegVar->emplace<Loc::EntryValue>(VI.getEntryValueRegister(), *VI.Expr);
1581cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1582cfca06d7SDimitry Andric                       << "\n");
1583b1c73532SDimitry Andric     InfoHolder.addScopeVariable(Scope, RegVar.get());
1584044eb2f6SDimitry Andric     MFVars.insert({Var, RegVar.get()});
1585d8e91e46SDimitry Andric     ConcreteEntities.push_back(std::move(RegVar));
1586abdf259dSRoman Divacky   }
1587c6910277SRoman Divacky }
1588c6910277SRoman Divacky 
158908bbd35aSDimitry Andric /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
159008bbd35aSDimitry Andric /// enclosing lexical scope. The check ensures there are no other instructions
159108bbd35aSDimitry Andric /// in the same lexical scope preceding the DBG_VALUE and that its range is
159208bbd35aSDimitry Andric /// either open or otherwise rolls off the end of the scope.
validThroughout(LexicalScopes & LScopes,const MachineInstr * DbgValue,const MachineInstr * RangeEnd,const InstructionOrdering & Ordering)159308bbd35aSDimitry Andric static bool validThroughout(LexicalScopes &LScopes,
159408bbd35aSDimitry Andric                             const MachineInstr *DbgValue,
1595b60736ecSDimitry Andric                             const MachineInstr *RangeEnd,
1596b60736ecSDimitry Andric                             const InstructionOrdering &Ordering) {
159708bbd35aSDimitry Andric   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
159808bbd35aSDimitry Andric   auto MBB = DbgValue->getParent();
159908bbd35aSDimitry Andric   auto DL = DbgValue->getDebugLoc();
160008bbd35aSDimitry Andric   auto *LScope = LScopes.findLexicalScope(DL);
160108bbd35aSDimitry Andric   // Scope doesn't exist; this is a dead DBG_VALUE.
160208bbd35aSDimitry Andric   if (!LScope)
160301095a5dSDimitry Andric     return false;
160408bbd35aSDimitry Andric   auto &LSRange = LScope->getRanges();
160508bbd35aSDimitry Andric   if (LSRange.size() == 0)
160601095a5dSDimitry Andric     return false;
160708bbd35aSDimitry Andric 
160808bbd35aSDimitry Andric   const MachineInstr *LScopeBegin = LSRange.front().first;
1609b60736ecSDimitry Andric   // If the scope starts before the DBG_VALUE then we may have a negative
1610b60736ecSDimitry Andric   // result. Otherwise the location is live coming into the scope and we
1611b60736ecSDimitry Andric   // can skip the following checks.
1612b60736ecSDimitry Andric   if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1613b60736ecSDimitry Andric     // Exit if the lexical scope begins outside of the current block.
161408bbd35aSDimitry Andric     if (LScopeBegin->getParent() != MBB)
161508bbd35aSDimitry Andric       return false;
1616cfca06d7SDimitry Andric 
161708bbd35aSDimitry Andric     MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
161808bbd35aSDimitry Andric     for (++Pred; Pred != MBB->rend(); ++Pred) {
161908bbd35aSDimitry Andric       if (Pred->getFlag(MachineInstr::FrameSetup))
162008bbd35aSDimitry Andric         break;
162108bbd35aSDimitry Andric       auto PredDL = Pred->getDebugLoc();
162208bbd35aSDimitry Andric       if (!PredDL || Pred->isMetaInstruction())
162308bbd35aSDimitry Andric         continue;
162408bbd35aSDimitry Andric       // Check whether the instruction preceding the DBG_VALUE is in the same
162508bbd35aSDimitry Andric       // (sub)scope as the DBG_VALUE.
162608bbd35aSDimitry Andric       if (DL->getScope() == PredDL->getScope())
162708bbd35aSDimitry Andric         return false;
162808bbd35aSDimitry Andric       auto *PredScope = LScopes.findLexicalScope(PredDL);
162908bbd35aSDimitry Andric       if (!PredScope || LScope->dominates(PredScope))
163008bbd35aSDimitry Andric         return false;
163108bbd35aSDimitry Andric     }
1632b60736ecSDimitry Andric   }
163308bbd35aSDimitry Andric 
163408bbd35aSDimitry Andric   // If the range of the DBG_VALUE is open-ended, report success.
163508bbd35aSDimitry Andric   if (!RangeEnd)
163601095a5dSDimitry Andric     return true;
163708bbd35aSDimitry Andric 
163808bbd35aSDimitry Andric   // Single, constant DBG_VALUEs in the prologue are promoted to be live
163908bbd35aSDimitry Andric   // throughout the function. This is a hack, presumably for DWARF v2 and not
164008bbd35aSDimitry Andric   // necessarily correct. It would be much better to use a dbg.declare instead
164108bbd35aSDimitry Andric   // if we know the constant is live throughout the scope.
1642344a3780SDimitry Andric   if (MBB->pred_empty() &&
1643344a3780SDimitry Andric       all_of(DbgValue->debug_operands(),
1644344a3780SDimitry Andric              [](const MachineOperand &Op) { return Op.isImm(); }))
164508bbd35aSDimitry Andric     return true;
164608bbd35aSDimitry Andric 
1647b60736ecSDimitry Andric   // Test if the location terminates before the end of the scope.
1648b60736ecSDimitry Andric   const MachineInstr *LScopeEnd = LSRange.back().second;
1649b60736ecSDimitry Andric   if (Ordering.isBefore(RangeEnd, LScopeEnd))
165008bbd35aSDimitry Andric     return false;
1651cfca06d7SDimitry Andric 
1652cfca06d7SDimitry Andric   // There's a single location which starts at the scope start, and ends at or
1653cfca06d7SDimitry Andric   // after the scope end.
1654cfca06d7SDimitry Andric   return true;
165501095a5dSDimitry Andric }
165601095a5dSDimitry Andric 
1657e6d15924SDimitry Andric /// Build the location list for all DBG_VALUEs in the function that
1658e6d15924SDimitry Andric /// describe the same variable. The resulting DebugLocEntries will have
1659e6d15924SDimitry Andric /// strict monotonically increasing begin addresses and will never
1660e6d15924SDimitry Andric /// overlap. If the resulting list has only one entry that is valid
1661e6d15924SDimitry Andric /// throughout variable's scope return true.
1662e6d15924SDimitry Andric //
1663e6d15924SDimitry Andric // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1664e6d15924SDimitry Andric // different kinds of history map entries. One thing to be aware of is that if
1665e6d15924SDimitry Andric // a debug value is ended by another entry (rather than being valid until the
1666e6d15924SDimitry Andric // end of the function), that entry's instruction may or may not be included in
1667e6d15924SDimitry Andric // the range, depending on if the entry is a clobbering entry (it has an
1668e6d15924SDimitry Andric // instruction that clobbers one or more preceding locations), or if it is an
1669e6d15924SDimitry Andric // (overlapping) debug value entry. This distinction can be seen in the example
1670e6d15924SDimitry Andric // below. The first debug value is ended by the clobbering entry 2, and the
1671e6d15924SDimitry Andric // second and third debug values are ended by the overlapping debug value entry
1672e6d15924SDimitry Andric // 4.
1673e6d15924SDimitry Andric //
1674e6d15924SDimitry Andric // Input:
1675e6d15924SDimitry Andric //
1676e6d15924SDimitry Andric //   History map entries [type, end index, mi]
1677e6d15924SDimitry Andric //
1678e6d15924SDimitry Andric // 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1679e6d15924SDimitry Andric // 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1680e6d15924SDimitry Andric // 2 | |    [Clobber, $reg0 = [...], -, -]
1681e6d15924SDimitry Andric // 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1682e6d15924SDimitry Andric // 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1683e6d15924SDimitry Andric //
1684e6d15924SDimitry Andric // Output [start, end) [Value...]:
1685e6d15924SDimitry Andric //
1686e6d15924SDimitry Andric // [0-1)    [(reg0, fragment 0, 32)]
1687e6d15924SDimitry Andric // [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1688e6d15924SDimitry Andric // [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1689e6d15924SDimitry Andric // [4-)     [(@g, fragment 0, 96)]
buildLocationList(SmallVectorImpl<DebugLocEntry> & DebugLoc,const DbgValueHistoryMap::Entries & Entries)1690b60736ecSDimitry Andric bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1691b60736ecSDimitry Andric                                    const DbgValueHistoryMap::Entries &Entries) {
1692e6d15924SDimitry Andric   using OpenRange =
1693e6d15924SDimitry Andric       std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1694e6d15924SDimitry Andric   SmallVector<OpenRange, 4> OpenRanges;
1695e6d15924SDimitry Andric   bool isSafeForSingleLocation = true;
1696e6d15924SDimitry Andric   const MachineInstr *StartDebugMI = nullptr;
1697e6d15924SDimitry Andric   const MachineInstr *EndMI = nullptr;
1698e6d15924SDimitry Andric 
1699e6d15924SDimitry Andric   for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1700e6d15924SDimitry Andric     const MachineInstr *Instr = EI->getInstr();
1701e6d15924SDimitry Andric 
1702e6d15924SDimitry Andric     // Remove all values that are no longer live.
1703e6d15924SDimitry Andric     size_t Index = std::distance(EB, EI);
1704b60736ecSDimitry Andric     erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1705e6d15924SDimitry Andric 
1706e6d15924SDimitry Andric     // If we are dealing with a clobbering entry, this iteration will result in
1707e6d15924SDimitry Andric     // a location list entry starting after the clobbering instruction.
1708e6d15924SDimitry Andric     const MCSymbol *StartLabel =
1709e6d15924SDimitry Andric         EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1710e6d15924SDimitry Andric     assert(StartLabel &&
1711e6d15924SDimitry Andric            "Forgot label before/after instruction starting a range!");
1712e6d15924SDimitry Andric 
1713e6d15924SDimitry Andric     const MCSymbol *EndLabel;
1714e6d15924SDimitry Andric     if (std::next(EI) == Entries.end()) {
1715cfca06d7SDimitry Andric       const MachineBasicBlock &EndMBB = Asm->MF->back();
1716ac9a064cSDimitry Andric       EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionID()].EndLabel;
1717e6d15924SDimitry Andric       if (EI->isClobber())
1718e6d15924SDimitry Andric         EndMI = EI->getInstr();
1719e6d15924SDimitry Andric     }
1720e6d15924SDimitry Andric     else if (std::next(EI)->isClobber())
1721e6d15924SDimitry Andric       EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1722e6d15924SDimitry Andric     else
1723e6d15924SDimitry Andric       EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1724e6d15924SDimitry Andric     assert(EndLabel && "Forgot label after instruction ending a range!");
1725e6d15924SDimitry Andric 
1726e6d15924SDimitry Andric     if (EI->isDbgValue())
1727e6d15924SDimitry Andric       LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1728e6d15924SDimitry Andric 
1729e6d15924SDimitry Andric     // If this history map entry has a debug value, add that to the list of
1730e6d15924SDimitry Andric     // open ranges and check if its location is valid for a single value
1731e6d15924SDimitry Andric     // location.
1732e6d15924SDimitry Andric     if (EI->isDbgValue()) {
1733e6d15924SDimitry Andric       // Do not add undef debug values, as they are redundant information in
1734e6d15924SDimitry Andric       // the location list entries. An undef debug results in an empty location
1735e6d15924SDimitry Andric       // description. If there are any non-undef fragments then padding pieces
1736e6d15924SDimitry Andric       // with empty location descriptions will automatically be inserted, and if
1737e6d15924SDimitry Andric       // all fragments are undef then the whole location list entry is
1738e6d15924SDimitry Andric       // redundant.
1739e6d15924SDimitry Andric       if (!Instr->isUndefDebugValue()) {
1740e6d15924SDimitry Andric         auto Value = getDebugLocValue(Instr);
1741e6d15924SDimitry Andric         OpenRanges.emplace_back(EI->getEndIndex(), Value);
1742e6d15924SDimitry Andric 
1743e6d15924SDimitry Andric         // TODO: Add support for single value fragment locations.
1744e6d15924SDimitry Andric         if (Instr->getDebugExpression()->isFragment())
1745e6d15924SDimitry Andric           isSafeForSingleLocation = false;
1746e6d15924SDimitry Andric 
1747e6d15924SDimitry Andric         if (!StartDebugMI)
1748e6d15924SDimitry Andric           StartDebugMI = Instr;
1749e6d15924SDimitry Andric       } else {
1750e6d15924SDimitry Andric         isSafeForSingleLocation = false;
1751e6d15924SDimitry Andric       }
1752e6d15924SDimitry Andric     }
1753e6d15924SDimitry Andric 
1754e6d15924SDimitry Andric     // Location list entries with empty location descriptions are redundant
1755e6d15924SDimitry Andric     // information in DWARF, so do not emit those.
1756e6d15924SDimitry Andric     if (OpenRanges.empty())
1757e6d15924SDimitry Andric       continue;
1758e6d15924SDimitry Andric 
1759e6d15924SDimitry Andric     // Omit entries with empty ranges as they do not have any effect in DWARF.
1760e6d15924SDimitry Andric     if (StartLabel == EndLabel) {
1761e6d15924SDimitry Andric       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1762e6d15924SDimitry Andric       continue;
1763e6d15924SDimitry Andric     }
1764e6d15924SDimitry Andric 
1765e6d15924SDimitry Andric     SmallVector<DbgValueLoc, 4> Values;
1766e6d15924SDimitry Andric     for (auto &R : OpenRanges)
1767e6d15924SDimitry Andric       Values.push_back(R.second);
1768344a3780SDimitry Andric 
1769344a3780SDimitry Andric     // With Basic block sections, it is posssible that the StartLabel and the
1770344a3780SDimitry Andric     // Instr are not in the same section.  This happens when the StartLabel is
1771344a3780SDimitry Andric     // the function begin label and the dbg value appears in a basic block
1772344a3780SDimitry Andric     // that is not the entry.  In this case, the range needs to be split to
1773344a3780SDimitry Andric     // span each individual section in the range from StartLabel to EndLabel.
1774344a3780SDimitry Andric     if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1775344a3780SDimitry Andric         !Instr->getParent()->sameSection(&Asm->MF->front())) {
1776344a3780SDimitry Andric       const MCSymbol *BeginSectionLabel = StartLabel;
1777344a3780SDimitry Andric 
1778344a3780SDimitry Andric       for (const MachineBasicBlock &MBB : *Asm->MF) {
1779344a3780SDimitry Andric         if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
1780344a3780SDimitry Andric           BeginSectionLabel = MBB.getSymbol();
1781344a3780SDimitry Andric 
1782344a3780SDimitry Andric         if (MBB.sameSection(Instr->getParent())) {
1783344a3780SDimitry Andric           DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
1784344a3780SDimitry Andric           break;
1785344a3780SDimitry Andric         }
1786344a3780SDimitry Andric         if (MBB.isEndSection())
1787344a3780SDimitry Andric           DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
1788344a3780SDimitry Andric       }
1789344a3780SDimitry Andric     } else {
1790e6d15924SDimitry Andric       DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1791344a3780SDimitry Andric     }
1792e6d15924SDimitry Andric 
1793e6d15924SDimitry Andric     // Attempt to coalesce the ranges of two otherwise identical
1794e6d15924SDimitry Andric     // DebugLocEntries.
1795e6d15924SDimitry Andric     auto CurEntry = DebugLoc.rbegin();
1796e6d15924SDimitry Andric     LLVM_DEBUG({
1797e6d15924SDimitry Andric       dbgs() << CurEntry->getValues().size() << " Values:\n";
1798e6d15924SDimitry Andric       for (auto &Value : CurEntry->getValues())
1799e6d15924SDimitry Andric         Value.dump();
1800e6d15924SDimitry Andric       dbgs() << "-----\n";
1801e6d15924SDimitry Andric     });
1802e6d15924SDimitry Andric 
1803e6d15924SDimitry Andric     auto PrevEntry = std::next(CurEntry);
1804e6d15924SDimitry Andric     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1805e6d15924SDimitry Andric       DebugLoc.pop_back();
1806e6d15924SDimitry Andric   }
1807e6d15924SDimitry Andric 
1808344a3780SDimitry Andric   if (!isSafeForSingleLocation ||
1809344a3780SDimitry Andric       !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
1810344a3780SDimitry Andric     return false;
1811344a3780SDimitry Andric 
1812344a3780SDimitry Andric   if (DebugLoc.size() == 1)
1813344a3780SDimitry Andric     return true;
1814344a3780SDimitry Andric 
1815344a3780SDimitry Andric   if (!Asm->MF->hasBBSections())
1816344a3780SDimitry Andric     return false;
1817344a3780SDimitry Andric 
1818344a3780SDimitry Andric   // Check here to see if loclist can be merged into a single range. If not,
1819344a3780SDimitry Andric   // we must keep the split loclists per section.  This does exactly what
1820344a3780SDimitry Andric   // MergeRanges does without sections.  We don't actually merge the ranges
1821344a3780SDimitry Andric   // as the split ranges must be kept intact if this cannot be collapsed
1822344a3780SDimitry Andric   // into a single range.
1823344a3780SDimitry Andric   const MachineBasicBlock *RangeMBB = nullptr;
1824344a3780SDimitry Andric   if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1825344a3780SDimitry Andric     RangeMBB = &Asm->MF->front();
1826344a3780SDimitry Andric   else
1827344a3780SDimitry Andric     RangeMBB = Entries.begin()->getInstr()->getParent();
1828344a3780SDimitry Andric   auto *CurEntry = DebugLoc.begin();
1829344a3780SDimitry Andric   auto *NextEntry = std::next(CurEntry);
1830344a3780SDimitry Andric   while (NextEntry != DebugLoc.end()) {
1831344a3780SDimitry Andric     // Get the last machine basic block of this section.
1832344a3780SDimitry Andric     while (!RangeMBB->isEndSection())
1833344a3780SDimitry Andric       RangeMBB = RangeMBB->getNextNode();
1834344a3780SDimitry Andric     if (!RangeMBB->getNextNode())
1835344a3780SDimitry Andric       return false;
1836344a3780SDimitry Andric     // CurEntry should end the current section and NextEntry should start
1837344a3780SDimitry Andric     // the next section and the Values must match for these two ranges to be
1838344a3780SDimitry Andric     // merged.
1839344a3780SDimitry Andric     if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
1840344a3780SDimitry Andric         NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
1841344a3780SDimitry Andric         CurEntry->getValues() != NextEntry->getValues())
1842344a3780SDimitry Andric       return false;
1843344a3780SDimitry Andric     RangeMBB = RangeMBB->getNextNode();
1844344a3780SDimitry Andric     CurEntry = NextEntry;
1845344a3780SDimitry Andric     NextEntry = std::next(CurEntry);
1846344a3780SDimitry Andric   }
1847344a3780SDimitry Andric   return true;
1848e6d15924SDimitry Andric }
1849e6d15924SDimitry Andric 
createConcreteEntity(DwarfCompileUnit & TheCU,LexicalScope & Scope,const DINode * Node,const DILocation * Location,const MCSymbol * Sym)1850e6d15924SDimitry Andric DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1851e6d15924SDimitry Andric                                             LexicalScope &Scope,
1852e6d15924SDimitry Andric                                             const DINode *Node,
1853e6d15924SDimitry Andric                                             const DILocation *Location,
1854e6d15924SDimitry Andric                                             const MCSymbol *Sym) {
1855e6d15924SDimitry Andric   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1856e6d15924SDimitry Andric   if (isa<const DILocalVariable>(Node)) {
1857e6d15924SDimitry Andric     ConcreteEntities.push_back(
18581d5ae102SDimitry Andric         std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1859e6d15924SDimitry Andric                                        Location));
1860e6d15924SDimitry Andric     InfoHolder.addScopeVariable(&Scope,
1861e6d15924SDimitry Andric         cast<DbgVariable>(ConcreteEntities.back().get()));
1862e6d15924SDimitry Andric   } else if (isa<const DILabel>(Node)) {
1863e6d15924SDimitry Andric     ConcreteEntities.push_back(
18641d5ae102SDimitry Andric         std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1865e6d15924SDimitry Andric                                     Location, Sym));
1866e6d15924SDimitry Andric     InfoHolder.addScopeLabel(&Scope,
1867e6d15924SDimitry Andric         cast<DbgLabel>(ConcreteEntities.back().get()));
1868e6d15924SDimitry Andric   }
1869e6d15924SDimitry Andric   return ConcreteEntities.back().get();
1870e6d15924SDimitry Andric }
1871e6d15924SDimitry Andric 
18724a16efa3SDimitry Andric // Find variables for each lexical scope.
collectEntityInfo(DwarfCompileUnit & TheCU,const DISubprogram * SP,DenseSet<InlinedEntity> & Processed)1873d8e91e46SDimitry Andric void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
18745a5ac124SDimitry Andric                                    const DISubprogram *SP,
1875d8e91e46SDimitry Andric                                    DenseSet<InlinedEntity> &Processed) {
1876f8af5cf6SDimitry Andric   // Grab the variable info that was squirreled away in the MMI side-table.
18776b3f41edSDimitry Andric   collectVariableInfoFromMFTable(TheCU, Processed);
1878abdf259dSRoman Divacky 
18795ca98fd9SDimitry Andric   for (const auto &I : DbgValues) {
1880d8e91e46SDimitry Andric     InlinedEntity IV = I.first;
18815a5ac124SDimitry Andric     if (Processed.count(IV))
1882abdf259dSRoman Divacky       continue;
1883b5efedafSRoman Divacky 
18845a5ac124SDimitry Andric     // Instruction ranges, specifying where IV is accessible.
1885e6d15924SDimitry Andric     const auto &HistoryMapEntries = I.second;
1886344a3780SDimitry Andric 
1887344a3780SDimitry Andric     // Try to find any non-empty variable location. Do not create a concrete
1888344a3780SDimitry Andric     // entity if there are no locations.
1889344a3780SDimitry Andric     if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
18906b943ff3SDimitry Andric       continue;
1891abdf259dSRoman Divacky 
18925ca98fd9SDimitry Andric     LexicalScope *Scope = nullptr;
1893d8e91e46SDimitry Andric     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
18945a5ac124SDimitry Andric     if (const DILocation *IA = IV.second)
1895d8e91e46SDimitry Andric       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
18965a5ac124SDimitry Andric     else
1897d8e91e46SDimitry Andric       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1898c6910277SRoman Divacky     // If variable scope is not found then skip this variable.
1899abdf259dSRoman Divacky     if (!Scope)
1900c6910277SRoman Divacky       continue;
1901c6910277SRoman Divacky 
19025a5ac124SDimitry Andric     Processed.insert(IV);
1903d8e91e46SDimitry Andric     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1904d8e91e46SDimitry Andric                                             *Scope, LocalVar, IV.second));
19051a82d4c0SDimitry Andric 
1906e6d15924SDimitry Andric     const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
19076b943ff3SDimitry Andric     assert(MInsn->isDebugValue() && "History must begin with debug value");
19086b943ff3SDimitry Andric 
190908bbd35aSDimitry Andric     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1910e6d15924SDimitry Andric     // If the history map contains a single debug value, there may be an
1911e6d15924SDimitry Andric     // additional entry which clobbers the debug value.
1912e6d15924SDimitry Andric     size_t HistSize = HistoryMapEntries.size();
1913e6d15924SDimitry Andric     bool SingleValueWithClobber =
1914e6d15924SDimitry Andric         HistSize == 2 && HistoryMapEntries[1].isClobber();
1915e6d15924SDimitry Andric     if (HistSize == 1 || SingleValueWithClobber) {
1916e6d15924SDimitry Andric       const auto *End =
1917e6d15924SDimitry Andric           SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1918b60736ecSDimitry Andric       if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
1919b1c73532SDimitry Andric         RegVar->emplace<Loc::Single>(MInsn);
1920abdf259dSRoman Divacky         continue;
19211a82d4c0SDimitry Andric       }
1922e6d15924SDimitry Andric     }
1923e6d15924SDimitry Andric 
1924eb11fae6SDimitry Andric     // Do not emit location lists if .debug_loc secton is disabled.
1925eb11fae6SDimitry Andric     if (!useLocSection())
1926eb11fae6SDimitry Andric       continue;
1927abdf259dSRoman Divacky 
19284a16efa3SDimitry Andric     // Handle multiple DBG_VALUE instructions describing one variable.
1929b1c73532SDimitry Andric     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);
1930d39c594dSDimitry Andric 
193167c32a98SDimitry Andric     // Build the location list for this variable.
19325a5ac124SDimitry Andric     SmallVector<DebugLocEntry, 8> Entries;
1933b60736ecSDimitry Andric     bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1934e6d15924SDimitry Andric 
1935e6d15924SDimitry Andric     // Check whether buildLocationList managed to merge all locations to one
1936e6d15924SDimitry Andric     // that is valid throughout the variable's scope. If so, produce single
1937e6d15924SDimitry Andric     // value location.
1938e6d15924SDimitry Andric     if (isValidSingleLocation) {
1939b1c73532SDimitry Andric       RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);
1940e6d15924SDimitry Andric       continue;
1941e6d15924SDimitry Andric     }
19425a5ac124SDimitry Andric 
194301095a5dSDimitry Andric     // If the variable has a DIBasicType, extract it.  Basic types cannot have
19445a5ac124SDimitry Andric     // unique identifiers, so don't bother resolving the type with the
19455a5ac124SDimitry Andric     // identifier map.
19465a5ac124SDimitry Andric     const DIBasicType *BT = dyn_cast<DIBasicType>(
1947d8e91e46SDimitry Andric         static_cast<const Metadata *>(LocalVar->getType()));
19485a5ac124SDimitry Andric 
19495a5ac124SDimitry Andric     // Finalize the entry by lowering it into a DWARF bytestream.
19505a5ac124SDimitry Andric     for (auto &Entry : Entries)
1951e6d15924SDimitry Andric       Entry.finalize(*Asm, List, BT, TheCU);
1952abdf259dSRoman Divacky   }
1953abdf259dSRoman Divacky 
1954d8e91e46SDimitry Andric   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1955d8e91e46SDimitry Andric   // DWARF-related DbgLabel.
1956d8e91e46SDimitry Andric   for (const auto &I : DbgLabels) {
1957d8e91e46SDimitry Andric     InlinedEntity IL = I.first;
1958d8e91e46SDimitry Andric     const MachineInstr *MI = I.second;
1959d8e91e46SDimitry Andric     if (MI == nullptr)
1960d8e91e46SDimitry Andric       continue;
1961d8e91e46SDimitry Andric 
1962d8e91e46SDimitry Andric     LexicalScope *Scope = nullptr;
1963d8e91e46SDimitry Andric     const DILabel *Label = cast<DILabel>(IL.first);
19641d5ae102SDimitry Andric     // The scope could have an extra lexical block file.
19651d5ae102SDimitry Andric     const DILocalScope *LocalScope =
19661d5ae102SDimitry Andric         Label->getScope()->getNonLexicalBlockFileScope();
1967d8e91e46SDimitry Andric     // Get inlined DILocation if it is inlined label.
1968d8e91e46SDimitry Andric     if (const DILocation *IA = IL.second)
19691d5ae102SDimitry Andric       Scope = LScopes.findInlinedScope(LocalScope, IA);
1970d8e91e46SDimitry Andric     else
19711d5ae102SDimitry Andric       Scope = LScopes.findLexicalScope(LocalScope);
1972d8e91e46SDimitry Andric     // If label scope is not found then skip this label.
1973d8e91e46SDimitry Andric     if (!Scope)
1974d8e91e46SDimitry Andric       continue;
1975d8e91e46SDimitry Andric 
1976d8e91e46SDimitry Andric     Processed.insert(IL);
1977d8e91e46SDimitry Andric     /// At this point, the temporary label is created.
1978d8e91e46SDimitry Andric     /// Save the temporary label to DbgLabel entity to get the
1979d8e91e46SDimitry Andric     /// actually address when generating Dwarf DIE.
1980d8e91e46SDimitry Andric     MCSymbol *Sym = getLabelBeforeInsn(MI);
1981d8e91e46SDimitry Andric     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1982abdf259dSRoman Divacky   }
1983d8e91e46SDimitry Andric 
19847fa27ce4SDimitry Andric   // Collect info for retained nodes.
1985d8e91e46SDimitry Andric   for (const DINode *DN : SP->getRetainedNodes()) {
19867fa27ce4SDimitry Andric     const auto *LS = getRetainedNodeScope(DN);
19877fa27ce4SDimitry Andric     if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
1988d8e91e46SDimitry Andric       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1989d8e91e46SDimitry Andric         continue;
19907fa27ce4SDimitry Andric       LexicalScope *LexS = LScopes.findLexicalScope(LS);
19917fa27ce4SDimitry Andric       if (LexS)
19927fa27ce4SDimitry Andric         createConcreteEntity(TheCU, *LexS, DN, nullptr);
19937fa27ce4SDimitry Andric     } else {
19947fa27ce4SDimitry Andric       LocalDeclsPerLS[LS].insert(DN);
1995d8e91e46SDimitry Andric     }
1996abdf259dSRoman Divacky   }
1997eb11fae6SDimitry Andric }
1998abdf259dSRoman Divacky 
19994a16efa3SDimitry Andric // Process beginning of an instruction.
beginInstruction(const MachineInstr * MI)2000cf099d11SDimitry Andric void DwarfDebug::beginInstruction(const MachineInstr *MI) {
2001cfca06d7SDimitry Andric   const MachineFunction &MF = *MI->getMF();
2002cfca06d7SDimitry Andric   const auto *SP = MF.getFunction().getSubprogram();
2003cfca06d7SDimitry Andric   bool NoDebug =
2004cfca06d7SDimitry Andric       !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
2005cfca06d7SDimitry Andric 
2006cfca06d7SDimitry Andric   // Delay slot support check.
2007cfca06d7SDimitry Andric   auto delaySlotSupported = [](const MachineInstr &MI) {
2008cfca06d7SDimitry Andric     if (!MI.isBundledWithSucc())
2009cfca06d7SDimitry Andric       return false;
2010cfca06d7SDimitry Andric     auto Suc = std::next(MI.getIterator());
2011cfca06d7SDimitry Andric     (void)Suc;
2012cfca06d7SDimitry Andric     // Ensure that delay slot instruction is successor of the call instruction.
2013cfca06d7SDimitry Andric     // Ex. CALL_INSTRUCTION {
2014cfca06d7SDimitry Andric     //        DELAY_SLOT_INSTRUCTION }
2015cfca06d7SDimitry Andric     assert(Suc->isBundledWithPred() &&
2016cfca06d7SDimitry Andric            "Call bundle instructions are out of order");
2017cfca06d7SDimitry Andric     return true;
2018cfca06d7SDimitry Andric   };
2019cfca06d7SDimitry Andric 
2020cfca06d7SDimitry Andric   // When describing calls, we need a label for the call instruction.
2021cfca06d7SDimitry Andric   if (!NoDebug && SP->areAllCallsDescribed() &&
2022cfca06d7SDimitry Andric       MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
2023cfca06d7SDimitry Andric       (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
2024cfca06d7SDimitry Andric     const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2025cfca06d7SDimitry Andric     bool IsTail = TII->isTailCall(*MI);
2026cfca06d7SDimitry Andric     // For tail calls, we need the address of the branch instruction for
2027cfca06d7SDimitry Andric     // DW_AT_call_pc.
2028cfca06d7SDimitry Andric     if (IsTail)
2029cfca06d7SDimitry Andric       requestLabelBeforeInsn(MI);
2030cfca06d7SDimitry Andric     // For non-tail calls, we need the return address for the call for
2031cfca06d7SDimitry Andric     // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
2032cfca06d7SDimitry Andric     // tail calls as well.
2033cfca06d7SDimitry Andric     requestLabelAfterInsn(MI);
2034cfca06d7SDimitry Andric   }
2035cfca06d7SDimitry Andric 
203601095a5dSDimitry Andric   DebugHandlerBase::beginInstruction(MI);
2037b60736ecSDimitry Andric   if (!CurMI)
2038b60736ecSDimitry Andric     return;
203901095a5dSDimitry Andric 
2040cfca06d7SDimitry Andric   if (NoDebug)
2041ab44ce3dSDimitry Andric     return;
2042ab44ce3dSDimitry Andric 
2043b915e9e0SDimitry Andric   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
2044eb11fae6SDimitry Andric   // If the instruction is part of the function frame setup code, do not emit
2045eb11fae6SDimitry Andric   // any line record, as there is no correspondence with any user code.
2046eb11fae6SDimitry Andric   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
2047b915e9e0SDimitry Andric     return;
204801095a5dSDimitry Andric   const DebugLoc &DL = MI->getDebugLoc();
2049e3b55780SDimitry Andric   unsigned Flags = 0;
2050e3b55780SDimitry Andric 
2051e3b55780SDimitry Andric   if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
2052e3b55780SDimitry Andric     const MachineBasicBlock *MBB = MI->getParent();
2053e3b55780SDimitry Andric     if (MBB && (MBB != EpilogBeginBlock)) {
2054e3b55780SDimitry Andric       // First time FrameDestroy has been seen in this basic block
2055e3b55780SDimitry Andric       EpilogBeginBlock = MBB;
2056e3b55780SDimitry Andric       Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2057e3b55780SDimitry Andric     }
2058e3b55780SDimitry Andric   }
2059e3b55780SDimitry Andric 
2060b915e9e0SDimitry Andric   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
2061b915e9e0SDimitry Andric   // the last line number actually emitted, to see if it was line 0.
2062b915e9e0SDimitry Andric   unsigned LastAsmLine =
2063b915e9e0SDimitry Andric       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
2064b915e9e0SDimitry Andric 
20657fa27ce4SDimitry Andric   bool PrevInstInSameSection =
20667fa27ce4SDimitry Andric       (!PrevInstBB ||
2067ac9a064cSDimitry Andric        PrevInstBB->getSectionID() == MI->getParent()->getSectionID());
20687fa27ce4SDimitry Andric   if (DL == PrevInstLoc && PrevInstInSameSection) {
2069b915e9e0SDimitry Andric     // If we have an ongoing unspecified location, nothing to do here.
2070b915e9e0SDimitry Andric     if (!DL)
2071b915e9e0SDimitry Andric       return;
2072b915e9e0SDimitry Andric     // We have an explicit location, same as the previous location.
2073b915e9e0SDimitry Andric     // But we might be coming back to it after a line 0 record.
2074e3b55780SDimitry Andric     if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
2075b915e9e0SDimitry Andric       // Reinstate the source location but not marked as a statement.
2076b915e9e0SDimitry Andric       const MDNode *Scope = DL.getScope();
2077e3b55780SDimitry Andric       recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
207856fe8f14SDimitry Andric     }
2079b915e9e0SDimitry Andric     return;
2080b915e9e0SDimitry Andric   }
2081b915e9e0SDimitry Andric 
2082b915e9e0SDimitry Andric   if (!DL) {
2083b915e9e0SDimitry Andric     // We have an unspecified location, which might want to be line 0.
2084b915e9e0SDimitry Andric     // If we have already emitted a line-0 record, don't repeat it.
2085b915e9e0SDimitry Andric     if (LastAsmLine == 0)
2086b915e9e0SDimitry Andric       return;
2087b915e9e0SDimitry Andric     // If user said Don't Do That, don't do that.
2088b915e9e0SDimitry Andric     if (UnknownLocations == Disable)
2089b915e9e0SDimitry Andric       return;
2090b915e9e0SDimitry Andric     // See if we have a reason to emit a line-0 record now.
2091b915e9e0SDimitry Andric     // Reasons to emit a line-0 record include:
2092b915e9e0SDimitry Andric     // - User asked for it (UnknownLocations).
2093b915e9e0SDimitry Andric     // - Instruction has a label, so it's referenced from somewhere else,
2094b915e9e0SDimitry Andric     //   possibly debug information; we want it to have a source location.
2095b915e9e0SDimitry Andric     // - Instruction is at the top of a block; we don't want to inherit the
2096b915e9e0SDimitry Andric     //   location from the physically previous (maybe unrelated) block.
2097b915e9e0SDimitry Andric     if (UnknownLocations == Enable || PrevLabel ||
2098b915e9e0SDimitry Andric         (PrevInstBB && PrevInstBB != MI->getParent())) {
2099b915e9e0SDimitry Andric       // Preserve the file and column numbers, if we can, to save space in
2100b915e9e0SDimitry Andric       // the encoded line table.
2101b915e9e0SDimitry Andric       // Do not update PrevInstLoc, it remembers the last non-0 line.
2102b915e9e0SDimitry Andric       const MDNode *Scope = nullptr;
2103b915e9e0SDimitry Andric       unsigned Column = 0;
2104b915e9e0SDimitry Andric       if (PrevInstLoc) {
2105b915e9e0SDimitry Andric         Scope = PrevInstLoc.getScope();
2106b915e9e0SDimitry Andric         Column = PrevInstLoc.getCol();
2107b915e9e0SDimitry Andric       }
2108b915e9e0SDimitry Andric       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
2109b915e9e0SDimitry Andric     }
2110b915e9e0SDimitry Andric     return;
2111b915e9e0SDimitry Andric   }
2112b915e9e0SDimitry Andric 
2113b915e9e0SDimitry Andric   // We have an explicit location, different from the previous location.
2114b915e9e0SDimitry Andric   // Don't repeat a line-0 record, but otherwise emit the new location.
2115b915e9e0SDimitry Andric   // (The new location might be an explicit line 0, which we do emit.)
2116e6d15924SDimitry Andric   if (DL.getLine() == 0 && LastAsmLine == 0)
2117b915e9e0SDimitry Andric     return;
2118b915e9e0SDimitry Andric   if (DL == PrologEndLoc) {
2119b915e9e0SDimitry Andric     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
2120b915e9e0SDimitry Andric     PrologEndLoc = DebugLoc();
2121b915e9e0SDimitry Andric   }
2122b915e9e0SDimitry Andric   // If the line changed, we call that a new statement; unless we went to
2123b915e9e0SDimitry Andric   // line 0 and came back, in which case it is not a new statement.
2124b915e9e0SDimitry Andric   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2125b915e9e0SDimitry Andric   if (DL.getLine() && DL.getLine() != OldLine)
212663faed5bSDimitry Andric     Flags |= DWARF2_FLAG_IS_STMT;
212763faed5bSDimitry Andric 
21285a5ac124SDimitry Andric   const MDNode *Scope = DL.getScope();
212956fe8f14SDimitry Andric   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2130b915e9e0SDimitry Andric 
2131b915e9e0SDimitry Andric   // If we're not at line 0, remember this location.
2132b915e9e0SDimitry Andric   if (DL.getLine())
21335a5ac124SDimitry Andric     PrevInstLoc = DL;
213459850d08SRoman Divacky }
213559850d08SRoman Divacky 
findPrologueEndLoc(const MachineFunction * MF)21367fa27ce4SDimitry Andric static std::pair<DebugLoc, bool> findPrologueEndLoc(const MachineFunction *MF) {
21375ca98fd9SDimitry Andric   // First known non-DBG_VALUE and non-frame setup location marks
21385ca98fd9SDimitry Andric   // the beginning of the function body.
2139c0981da4SDimitry Andric   DebugLoc LineZeroLoc;
21407fa27ce4SDimitry Andric   const Function &F = MF->getFunction();
21417fa27ce4SDimitry Andric 
21427fa27ce4SDimitry Andric   // Some instructions may be inserted into prologue after this function. Must
21437fa27ce4SDimitry Andric   // keep prologue for these cases.
21447fa27ce4SDimitry Andric   bool IsEmptyPrologue =
21457fa27ce4SDimitry Andric       !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2146c0981da4SDimitry Andric   for (const auto &MBB : *MF) {
2147c0981da4SDimitry Andric     for (const auto &MI : MBB) {
21487fa27ce4SDimitry Andric       if (!MI.isMetaInstruction()) {
21497fa27ce4SDimitry Andric         if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {
21507fa27ce4SDimitry Andric           // Scan forward to try to find a non-zero line number. The
21517fa27ce4SDimitry Andric           // prologue_end marks the first breakpoint in the function after the
21527fa27ce4SDimitry Andric           // frame setup, and a compiler-generated line 0 location is not a
21537fa27ce4SDimitry Andric           // meaningful breakpoint. If none is found, return the first
21547fa27ce4SDimitry Andric           // location after the frame setup.
2155c0981da4SDimitry Andric           if (MI.getDebugLoc().getLine())
21567fa27ce4SDimitry Andric             return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);
21577fa27ce4SDimitry Andric 
2158c0981da4SDimitry Andric           LineZeroLoc = MI.getDebugLoc();
2159c0981da4SDimitry Andric         }
21607fa27ce4SDimitry Andric         IsEmptyPrologue = false;
2161c0981da4SDimitry Andric       }
2162c0981da4SDimitry Andric     }
21637fa27ce4SDimitry Andric   }
21647fa27ce4SDimitry Andric   return std::make_pair(LineZeroLoc, IsEmptyPrologue);
2165cf099d11SDimitry Andric }
2166cf099d11SDimitry Andric 
2167e6d15924SDimitry Andric /// Register a source line with debug info. Returns the  unique label that was
2168e6d15924SDimitry Andric /// emitted and which provides correspondence to the source line list.
recordSourceLine(AsmPrinter & Asm,unsigned Line,unsigned Col,const MDNode * S,unsigned Flags,unsigned CUID,uint16_t DwarfVersion,ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs)2169e6d15924SDimitry Andric static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2170e6d15924SDimitry Andric                              const MDNode *S, unsigned Flags, unsigned CUID,
2171e6d15924SDimitry Andric                              uint16_t DwarfVersion,
2172e6d15924SDimitry Andric                              ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2173e6d15924SDimitry Andric   StringRef Fn;
2174e6d15924SDimitry Andric   unsigned FileNo = 1;
2175e6d15924SDimitry Andric   unsigned Discriminator = 0;
2176e6d15924SDimitry Andric   if (auto *Scope = cast_or_null<DIScope>(S)) {
2177e6d15924SDimitry Andric     Fn = Scope->getFilename();
2178e6d15924SDimitry Andric     if (Line != 0 && DwarfVersion >= 4)
2179e6d15924SDimitry Andric       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2180e6d15924SDimitry Andric         Discriminator = LBF->getDiscriminator();
2181e6d15924SDimitry Andric 
2182e6d15924SDimitry Andric     FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2183e6d15924SDimitry Andric                  .getOrCreateSourceID(Scope->getFile());
2184e6d15924SDimitry Andric   }
2185cfca06d7SDimitry Andric   Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2186e6d15924SDimitry Andric                                          Discriminator, Fn);
2187e6d15924SDimitry Andric }
2188e6d15924SDimitry Andric 
emitInitialLocDirective(const MachineFunction & MF,unsigned CUID)2189e6d15924SDimitry Andric DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
2190e6d15924SDimitry Andric                                              unsigned CUID) {
21917fa27ce4SDimitry Andric   std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);
21927fa27ce4SDimitry Andric   DebugLoc PrologEndLoc = PrologEnd.first;
21937fa27ce4SDimitry Andric   bool IsEmptyPrologue = PrologEnd.second;
21947fa27ce4SDimitry Andric 
2195e6d15924SDimitry Andric   // Get beginning of function.
21967fa27ce4SDimitry Andric   if (PrologEndLoc) {
21977fa27ce4SDimitry Andric     // If the prolog is empty, no need to generate scope line for the proc.
21987fa27ce4SDimitry Andric     if (IsEmptyPrologue)
21997fa27ce4SDimitry Andric       return PrologEndLoc;
22007fa27ce4SDimitry Andric 
2201e6d15924SDimitry Andric     // Ensure the compile unit is created if the function is called before
2202e6d15924SDimitry Andric     // beginFunction().
2203e6d15924SDimitry Andric     (void)getOrCreateDwarfCompileUnit(
2204e6d15924SDimitry Andric         MF.getFunction().getSubprogram()->getUnit());
2205e6d15924SDimitry Andric     // We'd like to list the prologue as "not statements" but GDB behaves
2206e6d15924SDimitry Andric     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2207e6d15924SDimitry Andric     const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
2208e6d15924SDimitry Andric     ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
2209e6d15924SDimitry Andric                        CUID, getDwarfVersion(), getUnits());
2210e6d15924SDimitry Andric     return PrologEndLoc;
2211e6d15924SDimitry Andric   }
2212e6d15924SDimitry Andric   return DebugLoc();
2213e6d15924SDimitry Andric }
2214e6d15924SDimitry Andric 
22154a16efa3SDimitry Andric // Gather pre-function debug information.  Assumes being called immediately
22164a16efa3SDimitry Andric // after the function entry point has been emitted.
beginFunctionImpl(const MachineFunction * MF)221771d5a254SDimitry Andric void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
22185ca98fd9SDimitry Andric   CurFn = MF;
2219f8af5cf6SDimitry Andric 
2220044eb2f6SDimitry Andric   auto *SP = MF->getFunction().getSubprogram();
2221ab44ce3dSDimitry Andric   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
2222ab44ce3dSDimitry Andric   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2223f8af5cf6SDimitry Andric     return;
2224f8af5cf6SDimitry Andric 
2225ab44ce3dSDimitry Andric   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2226ab44ce3dSDimitry Andric 
2227c0981da4SDimitry Andric   Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2228c0981da4SDimitry Andric       getDwarfCompileUnitIDForLineTable(CU));
2229009b1c42SEd Schouten 
223056fe8f14SDimitry Andric   // Record beginning of function.
2231e6d15924SDimitry Andric   PrologEndLoc = emitInitialLocDirective(
2232e6d15924SDimitry Andric       *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2233009b1c42SEd Schouten }
2234009b1c42SEd Schouten 
2235c0981da4SDimitry Andric unsigned
getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit & CU)2236c0981da4SDimitry Andric DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {
2237c0981da4SDimitry Andric   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2238c0981da4SDimitry Andric   // belongs to so that we add to the correct per-cu line table in the
2239c0981da4SDimitry Andric   // non-asm case.
2240c0981da4SDimitry Andric   if (Asm->OutStreamer->hasRawTextSupport())
2241c0981da4SDimitry Andric     // Use a single line table if we are generating assembly.
2242c0981da4SDimitry Andric     return 0;
2243c0981da4SDimitry Andric   else
2244c0981da4SDimitry Andric     return CU.getUniqueID();
2245c0981da4SDimitry Andric }
2246c0981da4SDimitry Andric 
terminateLineTable(const DwarfCompileUnit * CU)2247c0981da4SDimitry Andric void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {
2248c0981da4SDimitry Andric   const auto &CURanges = CU->getRanges();
2249c0981da4SDimitry Andric   auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2250c0981da4SDimitry Andric       getDwarfCompileUnitIDForLineTable(*CU));
2251c0981da4SDimitry Andric   // Add the last range label for the given CU.
2252c0981da4SDimitry Andric   LineTable.getMCLineSections().addEndEntry(
2253c0981da4SDimitry Andric       const_cast<MCSymbol *>(CURanges.back().End));
2254c0981da4SDimitry Andric }
2255c0981da4SDimitry Andric 
skippedNonDebugFunction()225671d5a254SDimitry Andric void DwarfDebug::skippedNonDebugFunction() {
2257b915e9e0SDimitry Andric   // If we don't have a subprogram for this function then there will be a hole
225871d5a254SDimitry Andric   // in the range information. Keep note of this by setting the previously used
225971d5a254SDimitry Andric   // section to nullptr.
2260c0981da4SDimitry Andric   // Terminate the pending line table.
2261c0981da4SDimitry Andric   if (PrevCU)
2262c0981da4SDimitry Andric     terminateLineTable(PrevCU);
22635ca98fd9SDimitry Andric   PrevCU = nullptr;
22645ca98fd9SDimitry Andric   CurFn = nullptr;
22655ca98fd9SDimitry Andric }
2266abdf259dSRoman Divacky 
226771d5a254SDimitry Andric // Gather and emit post-function debug information.
endFunctionImpl(const MachineFunction * MF)226871d5a254SDimitry Andric void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
2269044eb2f6SDimitry Andric   const DISubprogram *SP = MF->getFunction().getSubprogram();
227071d5a254SDimitry Andric 
227171d5a254SDimitry Andric   assert(CurFn == MF &&
227271d5a254SDimitry Andric       "endFunction should be called with the same function as beginFunction");
227371d5a254SDimitry Andric 
22745ca98fd9SDimitry Andric   // Set DwarfDwarfCompileUnitID in MCContext to default value.
22755a5ac124SDimitry Andric   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2276abdf259dSRoman Divacky 
227730815c53SDimitry Andric   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
2278b915e9e0SDimitry Andric   assert(!FnScope || SP == FnScope->getScopeNode());
22797fa27ce4SDimitry Andric   DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(SP->getUnit());
2280d8e91e46SDimitry Andric   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2281d8e91e46SDimitry Andric     PrevLabel = nullptr;
2282d8e91e46SDimitry Andric     CurFn = nullptr;
2283d8e91e46SDimitry Andric     return;
2284d8e91e46SDimitry Andric   }
228530815c53SDimitry Andric 
2286d8e91e46SDimitry Andric   DenseSet<InlinedEntity> Processed;
2287d8e91e46SDimitry Andric   collectEntityInfo(TheCU, SP, Processed);
228867c32a98SDimitry Andric 
228967c32a98SDimitry Andric   // Add the range of this function to the list of ranges for the CU.
2290cfca06d7SDimitry Andric   // With basic block sections, add ranges for all basic block sections.
2291cfca06d7SDimitry Andric   for (const auto &R : Asm->MBBSectionRanges)
2292cfca06d7SDimitry Andric     TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
229367c32a98SDimitry Andric 
229467c32a98SDimitry Andric   // Under -gmlt, skip building the subprogram if there are no inlined
229571d5a254SDimitry Andric   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
229671d5a254SDimitry Andric   // is still needed as we need its source location.
229771d5a254SDimitry Andric   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
229871d5a254SDimitry Andric       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
229967c32a98SDimitry Andric       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
23007fa27ce4SDimitry Andric     for (const auto &R : Asm->MBBSectionRanges)
23017fa27ce4SDimitry Andric       addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
23027fa27ce4SDimitry Andric 
230367c32a98SDimitry Andric     assert(InfoHolder.getScopeVariables().empty());
230467c32a98SDimitry Andric     PrevLabel = nullptr;
230567c32a98SDimitry Andric     CurFn = nullptr;
230667c32a98SDimitry Andric     return;
230767c32a98SDimitry Andric   }
230867c32a98SDimitry Andric 
230967c32a98SDimitry Andric #ifndef NDEBUG
23107fa27ce4SDimitry Andric   size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();
231167c32a98SDimitry Andric #endif
23125ca98fd9SDimitry Andric   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
23134b4fe385SDimitry Andric     const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2314eb11fae6SDimitry Andric     for (const DINode *DN : SP->getRetainedNodes()) {
23157fa27ce4SDimitry Andric       const auto *LS = getRetainedNodeScope(DN);
23167fa27ce4SDimitry Andric       // Ensure LexicalScope is created for the scope of this node.
23177fa27ce4SDimitry Andric       auto *LexS = LScopes.getOrCreateAbstractScope(LS);
23187fa27ce4SDimitry Andric       assert(LexS && "Expected the LexicalScope to be created.");
23197fa27ce4SDimitry Andric       if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
2320d8e91e46SDimitry Andric         // Collect info for variables/labels that were optimized out.
23217fa27ce4SDimitry Andric         if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||
23227fa27ce4SDimitry Andric             TheCU.getExistingAbstractEntity(DN))
23237fa27ce4SDimitry Andric           continue;
23247fa27ce4SDimitry Andric         TheCU.createAbstractEntity(DN, LexS);
23257fa27ce4SDimitry Andric       } else {
23267fa27ce4SDimitry Andric         // Remember the node if this is a local declarations.
23277fa27ce4SDimitry Andric         LocalDeclsPerLS[LS].insert(DN);
23287fa27ce4SDimitry Andric       }
23297fa27ce4SDimitry Andric       assert(
23307fa27ce4SDimitry Andric           LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
23317fa27ce4SDimitry Andric           "getOrCreateAbstractScope() inserted an abstract subprogram scope");
2332eb11fae6SDimitry Andric     }
23336b3f41edSDimitry Andric     constructAbstractSubprogramScopeDIE(TheCU, AScope);
233466e41e3cSRoman Divacky   }
2335009b1c42SEd Schouten 
2336b915e9e0SDimitry Andric   ProcessedSPNodes.insert(SP);
2337d8e91e46SDimitry Andric   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
233867c32a98SDimitry Andric   if (auto *SkelCU = TheCU.getSkeleton())
2339b915e9e0SDimitry Andric     if (!LScopes.getAbstractScopesList().empty() &&
2340b915e9e0SDimitry Andric         TheCU.getCUNode()->getSplitDebugInlining())
2341b915e9e0SDimitry Andric       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2342d7f7719eSRoman Divacky 
2343d8e91e46SDimitry Andric   // Construct call site entries.
2344d8e91e46SDimitry Andric   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2345d8e91e46SDimitry Andric 
2346009b1c42SEd Schouten   // Clear debug info
23475ca98fd9SDimitry Andric   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
23485ca98fd9SDimitry Andric   // DbgVariables except those that are also in AbstractVariables (since they
23495ca98fd9SDimitry Andric   // can be used cross-function)
235067c32a98SDimitry Andric   InfoHolder.getScopeVariables().clear();
2351d8e91e46SDimitry Andric   InfoHolder.getScopeLabels().clear();
23527fa27ce4SDimitry Andric   LocalDeclsPerLS.clear();
23535ca98fd9SDimitry Andric   PrevLabel = nullptr;
23545ca98fd9SDimitry Andric   CurFn = nullptr;
2355009b1c42SEd Schouten }
2356009b1c42SEd Schouten 
23574a16efa3SDimitry Andric // Register a source line with debug info. Returns the  unique label that was
23584a16efa3SDimitry Andric // emitted and which provides correspondence to the source line list.
recordSourceLine(unsigned Line,unsigned Col,const MDNode * S,unsigned Flags)235956fe8f14SDimitry Andric void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
236056fe8f14SDimitry Andric                                   unsigned Flags) {
2361e6d15924SDimitry Andric   ::recordSourceLine(*Asm, Line, Col, S, Flags,
2362e6d15924SDimitry Andric                      Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2363e6d15924SDimitry Andric                      getDwarfVersion(), getUnits());
2364009b1c42SEd Schouten }
2365009b1c42SEd Schouten 
2366009b1c42SEd Schouten //===----------------------------------------------------------------------===//
2367009b1c42SEd Schouten // Emit Methods
2368009b1c42SEd Schouten //===----------------------------------------------------------------------===//
2369009b1c42SEd Schouten 
23704a16efa3SDimitry Andric // Emit the debug info section.
emitDebugInfo()23714a16efa3SDimitry Andric void DwarfDebug::emitDebugInfo() {
23725ca98fd9SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
23735a5ac124SDimitry Andric   Holder.emitUnits(/* UseOffsets */ false);
23744a16efa3SDimitry Andric }
23754a16efa3SDimitry Andric 
23764a16efa3SDimitry Andric // Emit the abbreviation section.
emitAbbreviations()23774a16efa3SDimitry Andric void DwarfDebug::emitAbbreviations() {
23785ca98fd9SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
23794a16efa3SDimitry Andric 
23805ca98fd9SDimitry Andric   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2381009b1c42SEd Schouten }
2382009b1c42SEd Schouten 
emitStringOffsetsTableHeader()2383eb11fae6SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeader() {
2384eb11fae6SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2385eb11fae6SDimitry Andric   Holder.getStringPool().emitStringOffsetsTableHeader(
2386eb11fae6SDimitry Andric       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2387eb11fae6SDimitry Andric       Holder.getStringOffsetsStartSym());
2388eb11fae6SDimitry Andric }
2389eb11fae6SDimitry Andric 
2390eb11fae6SDimitry Andric template <typename AccelTableT>
emitAccel(AccelTableT & Accel,MCSection * Section,StringRef TableName)2391eb11fae6SDimitry Andric void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
23925a5ac124SDimitry Andric                            StringRef TableName) {
2393145449b1SDimitry Andric   Asm->OutStreamer->switchSection(Section);
239463faed5bSDimitry Andric 
239563faed5bSDimitry Andric   // Emit the full data.
2396eb11fae6SDimitry Andric   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2397eb11fae6SDimitry Andric }
2398eb11fae6SDimitry Andric 
emitAccelDebugNames()2399eb11fae6SDimitry Andric void DwarfDebug::emitAccelDebugNames() {
2400eb11fae6SDimitry Andric   // Don't emit anything if we have no compilation units to index.
2401eb11fae6SDimitry Andric   if (getUnits().empty())
2402eb11fae6SDimitry Andric     return;
2403eb11fae6SDimitry Andric 
2404eb11fae6SDimitry Andric   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
240567c32a98SDimitry Andric }
240667c32a98SDimitry Andric 
240767c32a98SDimitry Andric // Emit visible names into a hashed accelerator table section.
emitAccelNames()240867c32a98SDimitry Andric void DwarfDebug::emitAccelNames() {
240967c32a98SDimitry Andric   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
24105a5ac124SDimitry Andric             "Names");
2411abdf259dSRoman Divacky }
241263faed5bSDimitry Andric 
24134a16efa3SDimitry Andric // Emit objective C classes and categories into a hashed accelerator table
24144a16efa3SDimitry Andric // section.
emitAccelObjC()241563faed5bSDimitry Andric void DwarfDebug::emitAccelObjC() {
241667c32a98SDimitry Andric   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
24175a5ac124SDimitry Andric             "ObjC");
241863faed5bSDimitry Andric }
241963faed5bSDimitry Andric 
24204a16efa3SDimitry Andric // Emit namespace dies into a hashed accelerator table.
emitAccelNamespaces()242163faed5bSDimitry Andric void DwarfDebug::emitAccelNamespaces() {
242267c32a98SDimitry Andric   emitAccel(AccelNamespace,
242367c32a98SDimitry Andric             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
24245a5ac124SDimitry Andric             "namespac");
242563faed5bSDimitry Andric }
242663faed5bSDimitry Andric 
24274a16efa3SDimitry Andric // Emit type dies into a hashed accelerator table.
emitAccelTypes()242863faed5bSDimitry Andric void DwarfDebug::emitAccelTypes() {
242967c32a98SDimitry Andric   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
24305a5ac124SDimitry Andric             "types");
24314a16efa3SDimitry Andric }
24324a16efa3SDimitry Andric 
2433f8af5cf6SDimitry Andric // Public name handling.
2434f8af5cf6SDimitry Andric // The format for the various pubnames:
2435f8af5cf6SDimitry Andric //
2436f8af5cf6SDimitry Andric // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2437f8af5cf6SDimitry Andric // for the DIE that is named.
2438f8af5cf6SDimitry Andric //
2439f8af5cf6SDimitry Andric // gnu pubnames - offset/index value/name tuples where the offset is the offset
2440f8af5cf6SDimitry Andric // into the CU and the index value is computed according to the type of value
2441f8af5cf6SDimitry Andric // for the DIE that is named.
2442f8af5cf6SDimitry Andric //
2443f8af5cf6SDimitry Andric // For type units the offset is the offset of the skeleton DIE. For split dwarf
2444f8af5cf6SDimitry Andric // it's the offset within the debug_info/debug_types dwo section, however, the
2445f8af5cf6SDimitry Andric // reference in the pubname header doesn't change.
2446f8af5cf6SDimitry Andric 
2447f8af5cf6SDimitry Andric /// computeIndexValue - Compute the gdb index value for the DIE and CU.
computeIndexValue(DwarfUnit * CU,const DIE * Die)24485ca98fd9SDimitry Andric static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
24495ca98fd9SDimitry Andric                                                         const DIE *Die) {
245071d5a254SDimitry Andric   // Entities that ended up only in a Type Unit reference the CU instead (since
245171d5a254SDimitry Andric   // the pub entry has offsets within the CU there's no real offset that can be
245271d5a254SDimitry Andric   // provided anyway). As it happens all such entities (namespaces and types,
245371d5a254SDimitry Andric   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
245471d5a254SDimitry Andric   // not to be true it would be necessary to persist this information from the
245571d5a254SDimitry Andric   // point at which the entry is added to the index data structure - since by
245671d5a254SDimitry Andric   // the time the index is built from that, the original type/namespace DIE in a
245771d5a254SDimitry Andric   // type unit has already been destroyed so it can't be queried for properties
245871d5a254SDimitry Andric   // like tag, etc.
245971d5a254SDimitry Andric   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
246071d5a254SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
246171d5a254SDimitry Andric                                           dwarf::GIEL_EXTERNAL);
2462f8af5cf6SDimitry Andric   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2463f8af5cf6SDimitry Andric 
2464f8af5cf6SDimitry Andric   // We could have a specification DIE that has our most of our knowledge,
2465f8af5cf6SDimitry Andric   // look for that now.
246685d8b2bbSDimitry Andric   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
246785d8b2bbSDimitry Andric     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
24685ca98fd9SDimitry Andric     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2469f8af5cf6SDimitry Andric       Linkage = dwarf::GIEL_EXTERNAL;
2470f8af5cf6SDimitry Andric   } else if (Die->findAttribute(dwarf::DW_AT_external))
2471f8af5cf6SDimitry Andric     Linkage = dwarf::GIEL_EXTERNAL;
2472f8af5cf6SDimitry Andric 
2473f8af5cf6SDimitry Andric   switch (Die->getTag()) {
2474f8af5cf6SDimitry Andric   case dwarf::DW_TAG_class_type:
2475f8af5cf6SDimitry Andric   case dwarf::DW_TAG_structure_type:
2476f8af5cf6SDimitry Andric   case dwarf::DW_TAG_union_type:
2477f8af5cf6SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
2478f8af5cf6SDimitry Andric     return dwarf::PubIndexEntryDescriptor(
24791d5ae102SDimitry Andric         dwarf::GIEK_TYPE,
24801d5ae102SDimitry Andric         dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
24811d5ae102SDimitry Andric             ? dwarf::GIEL_EXTERNAL
24821d5ae102SDimitry Andric             : dwarf::GIEL_STATIC);
2483f8af5cf6SDimitry Andric   case dwarf::DW_TAG_typedef:
2484f8af5cf6SDimitry Andric   case dwarf::DW_TAG_base_type:
2485f8af5cf6SDimitry Andric   case dwarf::DW_TAG_subrange_type:
2486ac9a064cSDimitry Andric   case dwarf::DW_TAG_template_alias:
2487f8af5cf6SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2488f8af5cf6SDimitry Andric   case dwarf::DW_TAG_namespace:
2489f8af5cf6SDimitry Andric     return dwarf::GIEK_TYPE;
2490f8af5cf6SDimitry Andric   case dwarf::DW_TAG_subprogram:
2491f8af5cf6SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2492f8af5cf6SDimitry Andric   case dwarf::DW_TAG_variable:
2493f8af5cf6SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2494f8af5cf6SDimitry Andric   case dwarf::DW_TAG_enumerator:
2495f8af5cf6SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2496f8af5cf6SDimitry Andric                                           dwarf::GIEL_STATIC);
2497f8af5cf6SDimitry Andric   default:
2498f8af5cf6SDimitry Andric     return dwarf::GIEK_NONE;
2499f8af5cf6SDimitry Andric   }
2500f8af5cf6SDimitry Andric }
2501f8af5cf6SDimitry Andric 
2502044eb2f6SDimitry Andric /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2503044eb2f6SDimitry Andric /// pubtypes sections.
emitDebugPubSections()2504044eb2f6SDimitry Andric void DwarfDebug::emitDebugPubSections() {
25055ca98fd9SDimitry Andric   for (const auto &NU : CUMap) {
25065ca98fd9SDimitry Andric     DwarfCompileUnit *TheU = NU.second;
2507044eb2f6SDimitry Andric     if (!TheU->hasDwarfPubSections())
25085ca98fd9SDimitry Andric       continue;
25095ca98fd9SDimitry Andric 
2510d8e91e46SDimitry Andric     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2511d8e91e46SDimitry Andric                     DICompileUnit::DebugNameTableKind::GNU;
2512044eb2f6SDimitry Andric 
2513145449b1SDimitry Andric     Asm->OutStreamer->switchSection(
2514044eb2f6SDimitry Andric         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2515044eb2f6SDimitry Andric                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
2516044eb2f6SDimitry Andric     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2517044eb2f6SDimitry Andric 
2518145449b1SDimitry Andric     Asm->OutStreamer->switchSection(
2519044eb2f6SDimitry Andric         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2520044eb2f6SDimitry Andric                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
2521044eb2f6SDimitry Andric     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2522044eb2f6SDimitry Andric   }
2523044eb2f6SDimitry Andric }
2524044eb2f6SDimitry Andric 
emitSectionReference(const DwarfCompileUnit & CU)2525eb11fae6SDimitry Andric void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2526eb11fae6SDimitry Andric   if (useSectionsAsReferences())
2527cfca06d7SDimitry Andric     Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2528eb11fae6SDimitry Andric                          CU.getDebugSectionOffset());
2529eb11fae6SDimitry Andric   else
2530eb11fae6SDimitry Andric     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2531eb11fae6SDimitry Andric }
2532eb11fae6SDimitry Andric 
emitDebugPubSection(bool GnuStyle,StringRef Name,DwarfCompileUnit * TheU,const StringMap<const DIE * > & Globals)2533044eb2f6SDimitry Andric void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2534044eb2f6SDimitry Andric                                      DwarfCompileUnit *TheU,
2535044eb2f6SDimitry Andric                                      const StringMap<const DIE *> &Globals) {
253667c32a98SDimitry Andric   if (auto *Skeleton = TheU->getSkeleton())
25375ca98fd9SDimitry Andric     TheU = Skeleton;
25384a16efa3SDimitry Andric 
2539f8af5cf6SDimitry Andric   // Emit the header.
2540344a3780SDimitry Andric   MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
2541344a3780SDimitry Andric       "pub" + Name, "Length of Public " + Name + " Info");
25424a16efa3SDimitry Andric 
25435a5ac124SDimitry Andric   Asm->OutStreamer->AddComment("DWARF Version");
2544eb11fae6SDimitry Andric   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
25454a16efa3SDimitry Andric 
25465a5ac124SDimitry Andric   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2547eb11fae6SDimitry Andric   emitSectionReference(*TheU);
25484a16efa3SDimitry Andric 
25495a5ac124SDimitry Andric   Asm->OutStreamer->AddComment("Compilation Unit Length");
2550b60736ecSDimitry Andric   Asm->emitDwarfLengthOrOffset(TheU->getLength());
25514a16efa3SDimitry Andric 
2552f8af5cf6SDimitry Andric   // Emit the pubnames for this compilation unit.
25537fa27ce4SDimitry Andric   SmallVector<std::pair<StringRef, const DIE *>, 0> Vec;
25547fa27ce4SDimitry Andric   for (const auto &GI : Globals)
25557fa27ce4SDimitry Andric     Vec.emplace_back(GI.first(), GI.second);
25567fa27ce4SDimitry Andric   llvm::sort(Vec, [](auto &A, auto &B) {
25577fa27ce4SDimitry Andric     return A.second->getOffset() < B.second->getOffset();
25587fa27ce4SDimitry Andric   });
25597fa27ce4SDimitry Andric   for (const auto &[Name, Entity] : Vec) {
25605a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("DIE offset");
2561b60736ecSDimitry Andric     Asm->emitDwarfLengthOrOffset(Entity->getOffset());
25624a16efa3SDimitry Andric 
2563f8af5cf6SDimitry Andric     if (GnuStyle) {
25645ca98fd9SDimitry Andric       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
25655a5ac124SDimitry Andric       Asm->OutStreamer->AddComment(
2566d8e91e46SDimitry Andric           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2567d8e91e46SDimitry Andric           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2568eb11fae6SDimitry Andric       Asm->emitInt8(Desc.toBits());
2569f8af5cf6SDimitry Andric     }
2570f8af5cf6SDimitry Andric 
25715a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("External Name");
25727fa27ce4SDimitry Andric     Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));
25734a16efa3SDimitry Andric   }
25744a16efa3SDimitry Andric 
25755a5ac124SDimitry Andric   Asm->OutStreamer->AddComment("End Mark");
2576b60736ecSDimitry Andric   Asm->emitDwarfLengthOrOffset(0);
2577cfca06d7SDimitry Andric   Asm->OutStreamer->emitLabel(EndLabel);
25784a16efa3SDimitry Andric }
25794a16efa3SDimitry Andric 
258001095a5dSDimitry Andric /// Emit null-terminated strings into a debug str section.
emitDebugStr()25814a16efa3SDimitry Andric void DwarfDebug::emitDebugStr() {
2582eb11fae6SDimitry Andric   MCSection *StringOffsetsSection = nullptr;
2583eb11fae6SDimitry Andric   if (useSegmentedStringOffsetsTable()) {
2584eb11fae6SDimitry Andric     emitStringOffsetsTableHeader();
2585eb11fae6SDimitry Andric     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2586eb11fae6SDimitry Andric   }
25875ca98fd9SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2588eb11fae6SDimitry Andric   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2589eb11fae6SDimitry Andric                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
25904a16efa3SDimitry Andric }
25914a16efa3SDimitry Andric 
emitDebugLocEntry(ByteStreamer & Streamer,const DebugLocStream::Entry & Entry,const DwarfCompileUnit * CU)25925ca98fd9SDimitry Andric void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2593e6d15924SDimitry Andric                                    const DebugLocStream::Entry &Entry,
2594e6d15924SDimitry Andric                                    const DwarfCompileUnit *CU) {
25955a5ac124SDimitry Andric   auto &&Comments = DebugLocs.getComments(Entry);
25965a5ac124SDimitry Andric   auto Comment = Comments.begin();
25975a5ac124SDimitry Andric   auto End = Comments.end();
2598e6d15924SDimitry Andric 
2599e6d15924SDimitry Andric   // The expressions are inserted into a byte stream rather early (see
2600e6d15924SDimitry Andric   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2601e6d15924SDimitry Andric   // need to reference a base_type DIE the offset of that DIE is not yet known.
2602e6d15924SDimitry Andric   // To deal with this we instead insert a placeholder early and then extract
2603e6d15924SDimitry Andric   // it here and replace it with the real reference.
2604e6d15924SDimitry Andric   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2605e6d15924SDimitry Andric   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2606e6d15924SDimitry Andric                                     DebugLocs.getBytes(Entry).size()),
2607e6d15924SDimitry Andric                           Asm->getDataLayout().isLittleEndian(), PtrSize);
2608cfca06d7SDimitry Andric   DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
2609e6d15924SDimitry Andric 
2610e6d15924SDimitry Andric   using Encoding = DWARFExpression::Operation::Encoding;
26111d5ae102SDimitry Andric   uint64_t Offset = 0;
26124b4fe385SDimitry Andric   for (const auto &Op : Expr) {
2613e6d15924SDimitry Andric     assert(Op.getCode() != dwarf::DW_OP_const_type &&
2614e6d15924SDimitry Andric            "3 operand ops not yet supported");
26157fa27ce4SDimitry Andric     assert(!Op.getSubCode() && "SubOps not yet supported");
2616b60736ecSDimitry Andric     Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2617e6d15924SDimitry Andric     Offset++;
26187fa27ce4SDimitry Andric     for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
2619e6d15924SDimitry Andric       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
26206f8fc217SDimitry Andric         unsigned Length =
26216f8fc217SDimitry Andric           Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
2622e6d15924SDimitry Andric         // Make sure comments stay aligned.
26236f8fc217SDimitry Andric         for (unsigned J = 0; J < Length; ++J)
2624e6d15924SDimitry Andric           if (Comment != End)
2625e6d15924SDimitry Andric             Comment++;
2626e6d15924SDimitry Andric       } else {
26271d5ae102SDimitry Andric         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2628b60736ecSDimitry Andric           Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2629e6d15924SDimitry Andric       }
2630e6d15924SDimitry Andric       Offset = Op.getOperandEndOffset(I);
2631e6d15924SDimitry Andric     }
2632e6d15924SDimitry Andric     assert(Offset == Op.getEndOffset());
2633e6d15924SDimitry Andric   }
263467c32a98SDimitry Andric }
263567c32a98SDimitry Andric 
emitDebugLocValue(const AsmPrinter & AP,const DIBasicType * BT,const DbgValueLoc & Value,DwarfExpression & DwarfExpr)2636e6d15924SDimitry Andric void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2637e6d15924SDimitry Andric                                    const DbgValueLoc &Value,
2638b915e9e0SDimitry Andric                                    DwarfExpression &DwarfExpr) {
263971d5a254SDimitry Andric   auto *DIExpr = Value.getExpression();
264071d5a254SDimitry Andric   DIExpressionCursor ExprCursor(DIExpr);
264171d5a254SDimitry Andric   DwarfExpr.addFragmentOffset(DIExpr);
2642344a3780SDimitry Andric 
2643b1c73532SDimitry Andric   // If the DIExpr is an Entry Value, we want to follow the same code path
2644344a3780SDimitry Andric   // regardless of whether the DBG_VALUE is variadic or not.
2645344a3780SDimitry Andric   if (DIExpr && DIExpr->isEntryValue()) {
2646344a3780SDimitry Andric     // Entry values can only be a single register with no additional DIExpr,
2647344a3780SDimitry Andric     // so just add it directly.
2648344a3780SDimitry Andric     assert(Value.getLocEntries().size() == 1);
2649344a3780SDimitry Andric     assert(Value.getLocEntries()[0].isLocation());
2650344a3780SDimitry Andric     MachineLocation Location = Value.getLocEntries()[0].getLoc();
2651344a3780SDimitry Andric     DwarfExpr.setLocation(Location, DIExpr);
2652344a3780SDimitry Andric 
2653344a3780SDimitry Andric     DwarfExpr.beginEntryValueExpression(ExprCursor);
2654344a3780SDimitry Andric 
2655344a3780SDimitry Andric     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2656344a3780SDimitry Andric     if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
2657344a3780SDimitry Andric       return;
2658344a3780SDimitry Andric     return DwarfExpr.addExpression(std::move(ExprCursor));
2659344a3780SDimitry Andric   }
2660344a3780SDimitry Andric 
266167c32a98SDimitry Andric   // Regular entry.
2662344a3780SDimitry Andric   auto EmitValueLocEntry = [&DwarfExpr, &BT,
2663344a3780SDimitry Andric                             &AP](const DbgValueLocEntry &Entry,
2664344a3780SDimitry Andric                                  DIExpressionCursor &Cursor) -> bool {
2665344a3780SDimitry Andric     if (Entry.isInt()) {
26665a5ac124SDimitry Andric       if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
26675a5ac124SDimitry Andric                  BT->getEncoding() == dwarf::DW_ATE_signed_char))
2668344a3780SDimitry Andric         DwarfExpr.addSignedConstant(Entry.getInt());
266967c32a98SDimitry Andric       else
2670344a3780SDimitry Andric         DwarfExpr.addUnsignedConstant(Entry.getInt());
2671344a3780SDimitry Andric     } else if (Entry.isLocation()) {
2672344a3780SDimitry Andric       MachineLocation Location = Entry.getLoc();
2673344a3780SDimitry Andric       if (Location.isIndirect())
2674344a3780SDimitry Andric         DwarfExpr.setMemoryLocationKind();
2675e6d15924SDimitry Andric 
267601095a5dSDimitry Andric       const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
267771d5a254SDimitry Andric       if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2678344a3780SDimitry Andric         return false;
2679344a3780SDimitry Andric     } else if (Entry.isTargetIndexLocation()) {
2680344a3780SDimitry Andric       TargetIndexLocation Loc = Entry.getTargetIndexLocation();
2681344a3780SDimitry Andric       // TODO TargetIndexLocation is a target-independent. Currently only the
2682344a3780SDimitry Andric       // WebAssembly-specific encoding is supported.
2683b60736ecSDimitry Andric       assert(AP.TM.getTargetTriple().isWasm());
2684cfca06d7SDimitry Andric       DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2685344a3780SDimitry Andric     } else if (Entry.isConstantFP()) {
2686b60736ecSDimitry Andric       if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2687344a3780SDimitry Andric           !Cursor) {
2688344a3780SDimitry Andric         DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2689344a3780SDimitry Andric       } else if (Entry.getConstantFP()
2690344a3780SDimitry Andric                      ->getValueAPF()
2691344a3780SDimitry Andric                      .bitcastToAPInt()
2692344a3780SDimitry Andric                      .getBitWidth() <= 64 /*bits*/) {
2693344a3780SDimitry Andric         DwarfExpr.addUnsignedConstant(
2694344a3780SDimitry Andric             Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2695344a3780SDimitry Andric       } else {
2696344a3780SDimitry Andric         LLVM_DEBUG(
2697344a3780SDimitry Andric             dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
2698344a3780SDimitry Andric                    << Entry.getConstantFP()
2699344a3780SDimitry Andric                           ->getValueAPF()
2700344a3780SDimitry Andric                           .bitcastToAPInt()
2701344a3780SDimitry Andric                           .getBitWidth()
2702344a3780SDimitry Andric                    << " bits\n");
2703344a3780SDimitry Andric         return false;
2704344a3780SDimitry Andric       }
2705344a3780SDimitry Andric     }
2706344a3780SDimitry Andric     return true;
2707344a3780SDimitry Andric   };
2708344a3780SDimitry Andric 
2709344a3780SDimitry Andric   if (!Value.isVariadic()) {
2710344a3780SDimitry Andric     if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
2711344a3780SDimitry Andric       return;
2712344a3780SDimitry Andric     DwarfExpr.addExpression(std::move(ExprCursor));
2713b60736ecSDimitry Andric     return;
2714b60736ecSDimitry Andric   }
2715344a3780SDimitry Andric 
2716344a3780SDimitry Andric   // If any of the location entries are registers with the value 0, then the
2717344a3780SDimitry Andric   // location is undefined.
2718344a3780SDimitry Andric   if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
2719344a3780SDimitry Andric         return Entry.isLocation() && !Entry.getLoc().getReg();
2720344a3780SDimitry Andric       }))
2721344a3780SDimitry Andric     return;
2722344a3780SDimitry Andric 
2723344a3780SDimitry Andric   DwarfExpr.addExpression(
2724344a3780SDimitry Andric       std::move(ExprCursor),
2725344a3780SDimitry Andric       [EmitValueLocEntry, &Value](unsigned Idx,
2726344a3780SDimitry Andric                                   DIExpressionCursor &Cursor) -> bool {
2727344a3780SDimitry Andric         return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
2728344a3780SDimitry Andric       });
27295ca98fd9SDimitry Andric }
27305ca98fd9SDimitry Andric 
finalize(const AsmPrinter & AP,DebugLocStream::ListBuilder & List,const DIBasicType * BT,DwarfCompileUnit & TheCU)27311a82d4c0SDimitry Andric void DebugLocEntry::finalize(const AsmPrinter &AP,
27321a82d4c0SDimitry Andric                              DebugLocStream::ListBuilder &List,
2733e6d15924SDimitry Andric                              const DIBasicType *BT,
2734e6d15924SDimitry Andric                              DwarfCompileUnit &TheCU) {
2735e6d15924SDimitry Andric   assert(!Values.empty() &&
2736e6d15924SDimitry Andric          "location list entries without values are redundant");
2737d8e91e46SDimitry Andric   assert(Begin != End && "unexpected location list entry with empty range");
27381a82d4c0SDimitry Andric   DebugLocStream::EntryBuilder Entry(List, Begin, End);
27391a82d4c0SDimitry Andric   BufferByteStreamer Streamer = Entry.getStreamer();
2740e6d15924SDimitry Andric   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2741e6d15924SDimitry Andric   const DbgValueLoc &Value = Values[0];
2742b915e9e0SDimitry Andric   if (Value.isFragment()) {
2743b915e9e0SDimitry Andric     // Emit all fragments that belong to the same variable and range.
2744e6d15924SDimitry Andric     assert(llvm::all_of(Values, [](DbgValueLoc P) {
2745b915e9e0SDimitry Andric           return P.isFragment();
2746b915e9e0SDimitry Andric         }) && "all values are expected to be fragments");
2747cfca06d7SDimitry Andric     assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
27485a5ac124SDimitry Andric 
2749b60736ecSDimitry Andric     for (const auto &Fragment : Values)
2750e6d15924SDimitry Andric       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
27515a5ac124SDimitry Andric 
27525a5ac124SDimitry Andric   } else {
2753b915e9e0SDimitry Andric     assert(Values.size() == 1 && "only fragments may have >1 value");
2754e6d15924SDimitry Andric     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
27555a5ac124SDimitry Andric   }
2756b915e9e0SDimitry Andric   DwarfExpr.finalize();
2757706b4fc4SDimitry Andric   if (DwarfExpr.TagOffset)
2758706b4fc4SDimitry Andric     List.setTagOffset(*DwarfExpr.TagOffset);
27595a5ac124SDimitry Andric }
27605a5ac124SDimitry Andric 
emitDebugLocEntryLocation(const DebugLocStream::Entry & Entry,const DwarfCompileUnit * CU)2761e6d15924SDimitry Andric void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2762e6d15924SDimitry Andric                                            const DwarfCompileUnit *CU) {
27635a5ac124SDimitry Andric   // Emit the size.
27645a5ac124SDimitry Andric   Asm->OutStreamer->AddComment("Loc expr size");
2765e6d15924SDimitry Andric   if (getDwarfVersion() >= 5)
2766cfca06d7SDimitry Andric     Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2767e6d15924SDimitry Andric   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2768eb11fae6SDimitry Andric     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2769e6d15924SDimitry Andric   else {
2770e6d15924SDimitry Andric     // The entry is too big to fit into 16 bit, drop it as there is nothing we
2771e6d15924SDimitry Andric     // can do.
2772e6d15924SDimitry Andric     Asm->emitInt16(0);
2773e6d15924SDimitry Andric     return;
2774e6d15924SDimitry Andric   }
27755ca98fd9SDimitry Andric   // Emit the entry.
27765ca98fd9SDimitry Andric   APByteStreamer Streamer(*Asm);
2777e6d15924SDimitry Andric   emitDebugLocEntry(Streamer, Entry, CU);
2778abdf259dSRoman Divacky }
27795ca98fd9SDimitry Andric 
2780d8e91e46SDimitry Andric // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2781d8e91e46SDimitry Andric // that designates the end of the table for the caller to emit when the table is
2782d8e91e46SDimitry Andric // complete.
emitRnglistsTableHeader(AsmPrinter * Asm,const DwarfFile & Holder)2783d8e91e46SDimitry Andric static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2784d8e91e46SDimitry Andric                                          const DwarfFile &Holder) {
2785cfca06d7SDimitry Andric   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2786d8e91e46SDimitry Andric 
2787d8e91e46SDimitry Andric   Asm->OutStreamer->AddComment("Offset entry count");
2788d8e91e46SDimitry Andric   Asm->emitInt32(Holder.getRangeLists().size());
2789cfca06d7SDimitry Andric   Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2790d8e91e46SDimitry Andric 
2791d8e91e46SDimitry Andric   for (const RangeSpanList &List : Holder.getRangeLists())
2792b60736ecSDimitry Andric     Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2793b60736ecSDimitry Andric                              Asm->getDwarfOffsetByteSize());
2794d8e91e46SDimitry Andric 
2795d8e91e46SDimitry Andric   return TableEnd;
2796d8e91e46SDimitry Andric }
2797d8e91e46SDimitry Andric 
2798d8e91e46SDimitry Andric // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2799d8e91e46SDimitry Andric // designates the end of the table for the caller to emit when the table is
2800d8e91e46SDimitry Andric // complete.
emitLoclistsTableHeader(AsmPrinter * Asm,const DwarfDebug & DD)2801d8e91e46SDimitry Andric static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
28021d5ae102SDimitry Andric                                          const DwarfDebug &DD) {
2803cfca06d7SDimitry Andric   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
28041d5ae102SDimitry Andric 
28051d5ae102SDimitry Andric   const auto &DebugLocs = DD.getDebugLocs();
2806d8e91e46SDimitry Andric 
2807d8e91e46SDimitry Andric   Asm->OutStreamer->AddComment("Offset entry count");
2808706b4fc4SDimitry Andric   Asm->emitInt32(DebugLocs.getLists().size());
2809cfca06d7SDimitry Andric   Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2810d8e91e46SDimitry Andric 
2811706b4fc4SDimitry Andric   for (const auto &List : DebugLocs.getLists())
2812b60736ecSDimitry Andric     Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2813b60736ecSDimitry Andric                              Asm->getDwarfOffsetByteSize());
2814706b4fc4SDimitry Andric 
2815d8e91e46SDimitry Andric   return TableEnd;
2816d8e91e46SDimitry Andric }
2817d8e91e46SDimitry Andric 
28181d5ae102SDimitry Andric template <typename Ranges, typename PayloadEmitter>
emitRangeList(DwarfDebug & DD,AsmPrinter * Asm,MCSymbol * Sym,const Ranges & R,const DwarfCompileUnit & CU,unsigned BaseAddressx,unsigned OffsetPair,unsigned StartxLength,unsigned EndOfList,StringRef (* StringifyEnum)(unsigned),bool ShouldUseBaseAddress,PayloadEmitter EmitPayload)28191d5ae102SDimitry Andric static void emitRangeList(
28201d5ae102SDimitry Andric     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
28211d5ae102SDimitry Andric     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
28221d5ae102SDimitry Andric     unsigned StartxLength, unsigned EndOfList,
28231d5ae102SDimitry Andric     StringRef (*StringifyEnum)(unsigned),
28241d5ae102SDimitry Andric     bool ShouldUseBaseAddress,
28251d5ae102SDimitry Andric     PayloadEmitter EmitPayload) {
28261d5ae102SDimitry Andric 
28271d5ae102SDimitry Andric   auto Size = Asm->MAI->getCodePointerSize();
28281d5ae102SDimitry Andric   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
28291d5ae102SDimitry Andric 
28301d5ae102SDimitry Andric   // Emit our symbol so we can find the beginning of the range.
2831cfca06d7SDimitry Andric   Asm->OutStreamer->emitLabel(Sym);
28321d5ae102SDimitry Andric 
28331d5ae102SDimitry Andric   // Gather all the ranges that apply to the same section so they can share
28341d5ae102SDimitry Andric   // a base address entry.
28351d5ae102SDimitry Andric   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
28361d5ae102SDimitry Andric 
28371d5ae102SDimitry Andric   for (const auto &Range : R)
28381d5ae102SDimitry Andric     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
28391d5ae102SDimitry Andric 
28401d5ae102SDimitry Andric   const MCSymbol *CUBase = CU.getBaseAddress();
28411d5ae102SDimitry Andric   bool BaseIsSet = false;
28421d5ae102SDimitry Andric   for (const auto &P : SectionRanges) {
28431d5ae102SDimitry Andric     auto *Base = CUBase;
28441d5ae102SDimitry Andric     if (!Base && ShouldUseBaseAddress) {
28451d5ae102SDimitry Andric       const MCSymbol *Begin = P.second.front()->Begin;
28461d5ae102SDimitry Andric       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
28471d5ae102SDimitry Andric       if (!UseDwarf5) {
28481d5ae102SDimitry Andric         Base = NewBase;
28491d5ae102SDimitry Andric         BaseIsSet = true;
2850cfca06d7SDimitry Andric         Asm->OutStreamer->emitIntValue(-1, Size);
28511d5ae102SDimitry Andric         Asm->OutStreamer->AddComment("  base address");
2852cfca06d7SDimitry Andric         Asm->OutStreamer->emitSymbolValue(Base, Size);
28531d5ae102SDimitry Andric       } else if (NewBase != Begin || P.second.size() > 1) {
28541d5ae102SDimitry Andric         // Only use a base address if
28551d5ae102SDimitry Andric         //  * the existing pool address doesn't match (NewBase != Begin)
28561d5ae102SDimitry Andric         //  * or, there's more than one entry to share the base address
28571d5ae102SDimitry Andric         Base = NewBase;
28581d5ae102SDimitry Andric         BaseIsSet = true;
28591d5ae102SDimitry Andric         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
28601d5ae102SDimitry Andric         Asm->emitInt8(BaseAddressx);
28611d5ae102SDimitry Andric         Asm->OutStreamer->AddComment("  base address index");
2862cfca06d7SDimitry Andric         Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
28631d5ae102SDimitry Andric       }
28641d5ae102SDimitry Andric     } else if (BaseIsSet && !UseDwarf5) {
28651d5ae102SDimitry Andric       BaseIsSet = false;
28661d5ae102SDimitry Andric       assert(!Base);
2867cfca06d7SDimitry Andric       Asm->OutStreamer->emitIntValue(-1, Size);
2868cfca06d7SDimitry Andric       Asm->OutStreamer->emitIntValue(0, Size);
28691d5ae102SDimitry Andric     }
28701d5ae102SDimitry Andric 
28711d5ae102SDimitry Andric     for (const auto *RS : P.second) {
28721d5ae102SDimitry Andric       const MCSymbol *Begin = RS->Begin;
28731d5ae102SDimitry Andric       const MCSymbol *End = RS->End;
28741d5ae102SDimitry Andric       assert(Begin && "Range without a begin symbol?");
28751d5ae102SDimitry Andric       assert(End && "Range without an end symbol?");
28761d5ae102SDimitry Andric       if (Base) {
28771d5ae102SDimitry Andric         if (UseDwarf5) {
28781d5ae102SDimitry Andric           // Emit offset_pair when we have a base.
28791d5ae102SDimitry Andric           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
28801d5ae102SDimitry Andric           Asm->emitInt8(OffsetPair);
28811d5ae102SDimitry Andric           Asm->OutStreamer->AddComment("  starting offset");
2882cfca06d7SDimitry Andric           Asm->emitLabelDifferenceAsULEB128(Begin, Base);
28831d5ae102SDimitry Andric           Asm->OutStreamer->AddComment("  ending offset");
2884cfca06d7SDimitry Andric           Asm->emitLabelDifferenceAsULEB128(End, Base);
28851d5ae102SDimitry Andric         } else {
2886cfca06d7SDimitry Andric           Asm->emitLabelDifference(Begin, Base, Size);
2887cfca06d7SDimitry Andric           Asm->emitLabelDifference(End, Base, Size);
28881d5ae102SDimitry Andric         }
28891d5ae102SDimitry Andric       } else if (UseDwarf5) {
28901d5ae102SDimitry Andric         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
28911d5ae102SDimitry Andric         Asm->emitInt8(StartxLength);
28921d5ae102SDimitry Andric         Asm->OutStreamer->AddComment("  start index");
2893cfca06d7SDimitry Andric         Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
28941d5ae102SDimitry Andric         Asm->OutStreamer->AddComment("  length");
2895cfca06d7SDimitry Andric         Asm->emitLabelDifferenceAsULEB128(End, Begin);
28961d5ae102SDimitry Andric       } else {
2897cfca06d7SDimitry Andric         Asm->OutStreamer->emitSymbolValue(Begin, Size);
2898cfca06d7SDimitry Andric         Asm->OutStreamer->emitSymbolValue(End, Size);
28991d5ae102SDimitry Andric       }
29001d5ae102SDimitry Andric       EmitPayload(*RS);
29011d5ae102SDimitry Andric     }
29021d5ae102SDimitry Andric   }
29031d5ae102SDimitry Andric 
29041d5ae102SDimitry Andric   if (UseDwarf5) {
29051d5ae102SDimitry Andric     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
29061d5ae102SDimitry Andric     Asm->emitInt8(EndOfList);
29071d5ae102SDimitry Andric   } else {
29081d5ae102SDimitry Andric     // Terminate the list with two 0 values.
2909cfca06d7SDimitry Andric     Asm->OutStreamer->emitIntValue(0, Size);
2910cfca06d7SDimitry Andric     Asm->OutStreamer->emitIntValue(0, Size);
29111d5ae102SDimitry Andric   }
29121d5ae102SDimitry Andric }
29131d5ae102SDimitry Andric 
2914706b4fc4SDimitry Andric // Handles emission of both debug_loclist / debug_loclist.dwo
emitLocList(DwarfDebug & DD,AsmPrinter * Asm,const DebugLocStream::List & List)29151d5ae102SDimitry Andric static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2916706b4fc4SDimitry Andric   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2917706b4fc4SDimitry Andric                 *List.CU, dwarf::DW_LLE_base_addressx,
2918706b4fc4SDimitry Andric                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2919706b4fc4SDimitry Andric                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
29201d5ae102SDimitry Andric                 /* ShouldUseBaseAddress */ true,
29211d5ae102SDimitry Andric                 [&](const DebugLocStream::Entry &E) {
29221d5ae102SDimitry Andric                   DD.emitDebugLocEntryLocation(E, List.CU);
29231d5ae102SDimitry Andric                 });
29241d5ae102SDimitry Andric }
29251d5ae102SDimitry Andric 
emitDebugLocImpl(MCSection * Sec)2926706b4fc4SDimitry Andric void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2927ab44ce3dSDimitry Andric   if (DebugLocs.getLists().empty())
2928ab44ce3dSDimitry Andric     return;
2929ab44ce3dSDimitry Andric 
2930145449b1SDimitry Andric   Asm->OutStreamer->switchSection(Sec);
2931706b4fc4SDimitry Andric 
2932d8e91e46SDimitry Andric   MCSymbol *TableEnd = nullptr;
2933706b4fc4SDimitry Andric   if (getDwarfVersion() >= 5)
29341d5ae102SDimitry Andric     TableEnd = emitLoclistsTableHeader(Asm, *this);
2935d8e91e46SDimitry Andric 
29361d5ae102SDimitry Andric   for (const auto &List : DebugLocs.getLists())
29371d5ae102SDimitry Andric     emitLocList(*this, Asm, List);
2938009b1c42SEd Schouten 
2939d8e91e46SDimitry Andric   if (TableEnd)
2940cfca06d7SDimitry Andric     Asm->OutStreamer->emitLabel(TableEnd);
2941d8e91e46SDimitry Andric }
2942d8e91e46SDimitry Andric 
2943706b4fc4SDimitry Andric // Emit locations into the .debug_loc/.debug_loclists section.
emitDebugLoc()2944706b4fc4SDimitry Andric void DwarfDebug::emitDebugLoc() {
2945706b4fc4SDimitry Andric   emitDebugLocImpl(
2946706b4fc4SDimitry Andric       getDwarfVersion() >= 5
2947706b4fc4SDimitry Andric           ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2948706b4fc4SDimitry Andric           : Asm->getObjFileLowering().getDwarfLocSection());
2949706b4fc4SDimitry Andric }
2950706b4fc4SDimitry Andric 
2951706b4fc4SDimitry Andric // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
emitDebugLocDWO()29525ca98fd9SDimitry Andric void DwarfDebug::emitDebugLocDWO() {
2953706b4fc4SDimitry Andric   if (getDwarfVersion() >= 5) {
2954706b4fc4SDimitry Andric     emitDebugLocImpl(
2955706b4fc4SDimitry Andric         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2956706b4fc4SDimitry Andric 
2957706b4fc4SDimitry Andric     return;
2958706b4fc4SDimitry Andric   }
2959706b4fc4SDimitry Andric 
2960e6d15924SDimitry Andric   for (const auto &List : DebugLocs.getLists()) {
2961145449b1SDimitry Andric     Asm->OutStreamer->switchSection(
29625ca98fd9SDimitry Andric         Asm->getObjFileLowering().getDwarfLocDWOSection());
2963cfca06d7SDimitry Andric     Asm->OutStreamer->emitLabel(List.Label);
2964706b4fc4SDimitry Andric 
29655a5ac124SDimitry Andric     for (const auto &Entry : DebugLocs.getEntries(List)) {
2966d8e91e46SDimitry Andric       // GDB only supports startx_length in pre-standard split-DWARF.
2967d8e91e46SDimitry Andric       // (in v5 standard loclists, it currently* /only/ supports base_address +
2968d8e91e46SDimitry Andric       // offset_pair, so the implementations can't really share much since they
2969d8e91e46SDimitry Andric       // need to use different representations)
2970d8e91e46SDimitry Andric       // * as of October 2018, at least
2971cfca06d7SDimitry Andric       //
2972cfca06d7SDimitry Andric       // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2973cfca06d7SDimitry Andric       // addresses in the address pool to minimize object size/relocations.
2974eb11fae6SDimitry Andric       Asm->emitInt8(dwarf::DW_LLE_startx_length);
29751d5ae102SDimitry Andric       unsigned idx = AddrPool.getIndex(Entry.Begin);
2976cfca06d7SDimitry Andric       Asm->emitULEB128(idx);
2977706b4fc4SDimitry Andric       // Also the pre-standard encoding is slightly different, emitting this as
2978706b4fc4SDimitry Andric       // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2979cfca06d7SDimitry Andric       Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2980e6d15924SDimitry Andric       emitDebugLocEntryLocation(Entry, List.CU);
2981f8af5cf6SDimitry Andric     }
2982eb11fae6SDimitry Andric     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
29835ca98fd9SDimitry Andric   }
2984f8af5cf6SDimitry Andric }
2985f8af5cf6SDimitry Andric 
2986f8af5cf6SDimitry Andric struct ArangeSpan {
2987f8af5cf6SDimitry Andric   const MCSymbol *Start, *End;
2988f8af5cf6SDimitry Andric };
2989f8af5cf6SDimitry Andric 
2990f8af5cf6SDimitry Andric // Emit a debug aranges section, containing a CU lookup for any
2991f8af5cf6SDimitry Andric // address we can tie back to a CU.
emitDebugARanges()29924a16efa3SDimitry Andric void DwarfDebug::emitDebugARanges() {
2993ac9a064cSDimitry Andric   if (ArangeLabels.empty())
2994ac9a064cSDimitry Andric     return;
2995ac9a064cSDimitry Andric 
29965a5ac124SDimitry Andric   // Provides a unique id per text section.
29975a5ac124SDimitry Andric   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2998f8af5cf6SDimitry Andric 
29995a5ac124SDimitry Andric   // Filter labels by section.
30005a5ac124SDimitry Andric   for (const SymbolCU &SCU : ArangeLabels) {
30015a5ac124SDimitry Andric     if (SCU.Sym->isInSection()) {
30025a5ac124SDimitry Andric       // Make a note of this symbol and it's section.
30035a5ac124SDimitry Andric       MCSection *Section = &SCU.Sym->getSection();
30045a5ac124SDimitry Andric       SectionMap[Section].push_back(SCU);
30055a5ac124SDimitry Andric     } else {
30065a5ac124SDimitry Andric       // Some symbols (e.g. common/bss on mach-o) can have no section but still
30075a5ac124SDimitry Andric       // appear in the output. This sucks as we rely on sections to build
30085a5ac124SDimitry Andric       // arange spans. We can do it without, but it's icky.
30095a5ac124SDimitry Andric       SectionMap[nullptr].push_back(SCU);
30105a5ac124SDimitry Andric     }
3011f8af5cf6SDimitry Andric   }
3012f8af5cf6SDimitry Andric 
30135a5ac124SDimitry Andric   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
30145a5ac124SDimitry Andric 
30155a5ac124SDimitry Andric   for (auto &I : SectionMap) {
301601095a5dSDimitry Andric     MCSection *Section = I.first;
30175a5ac124SDimitry Andric     SmallVector<SymbolCU, 8> &List = I.second;
3018ac9a064cSDimitry Andric     assert(!List.empty());
3019f8af5cf6SDimitry Andric 
3020f8af5cf6SDimitry Andric     // If we have no section (e.g. common), just write out
3021f8af5cf6SDimitry Andric     // individual spans for each symbol.
30225ca98fd9SDimitry Andric     if (!Section) {
30235ca98fd9SDimitry Andric       for (const SymbolCU &Cur : List) {
3024f8af5cf6SDimitry Andric         ArangeSpan Span;
3025f8af5cf6SDimitry Andric         Span.Start = Cur.Sym;
30265ca98fd9SDimitry Andric         Span.End = nullptr;
302701095a5dSDimitry Andric         assert(Cur.CU);
3028f8af5cf6SDimitry Andric         Spans[Cur.CU].push_back(Span);
3029f8af5cf6SDimitry Andric       }
30305a5ac124SDimitry Andric       continue;
30315a5ac124SDimitry Andric     }
30325a5ac124SDimitry Andric 
303301095a5dSDimitry Andric     // Insert a final terminator.
303401095a5dSDimitry Andric     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
303501095a5dSDimitry Andric 
3036f8af5cf6SDimitry Andric     // Build spans between each label.
3037f8af5cf6SDimitry Andric     const MCSymbol *StartSym = List[0].Sym;
30385ca98fd9SDimitry Andric     for (size_t n = 1, e = List.size(); n < e; n++) {
3039f8af5cf6SDimitry Andric       const SymbolCU &Prev = List[n - 1];
3040f8af5cf6SDimitry Andric       const SymbolCU &Cur = List[n];
3041f8af5cf6SDimitry Andric 
3042f8af5cf6SDimitry Andric       // Try and build the longest span we can within the same CU.
3043f8af5cf6SDimitry Andric       if (Cur.CU != Prev.CU) {
3044f8af5cf6SDimitry Andric         ArangeSpan Span;
3045f8af5cf6SDimitry Andric         Span.Start = StartSym;
3046f8af5cf6SDimitry Andric         Span.End = Cur.Sym;
304701095a5dSDimitry Andric         assert(Prev.CU);
3048f8af5cf6SDimitry Andric         Spans[Prev.CU].push_back(Span);
3049f8af5cf6SDimitry Andric         StartSym = Cur.Sym;
3050f8af5cf6SDimitry Andric       }
3051f8af5cf6SDimitry Andric     }
3052f8af5cf6SDimitry Andric   }
30535a5ac124SDimitry Andric 
30545a5ac124SDimitry Andric   // Start the dwarf aranges section.
3055145449b1SDimitry Andric   Asm->OutStreamer->switchSection(
30565a5ac124SDimitry Andric       Asm->getObjFileLowering().getDwarfARangesSection());
3057f8af5cf6SDimitry Andric 
3058d99dafe2SDimitry Andric   unsigned PtrSize = Asm->MAI->getCodePointerSize();
3059f8af5cf6SDimitry Andric 
3060f8af5cf6SDimitry Andric   // Build a list of CUs used.
30615ca98fd9SDimitry Andric   std::vector<DwarfCompileUnit *> CUs;
30625ca98fd9SDimitry Andric   for (const auto &it : Spans) {
30635ca98fd9SDimitry Andric     DwarfCompileUnit *CU = it.first;
3064f8af5cf6SDimitry Andric     CUs.push_back(CU);
3065f8af5cf6SDimitry Andric   }
3066f8af5cf6SDimitry Andric 
3067f8af5cf6SDimitry Andric   // Sort the CU list (again, to ensure consistent output order).
3068d8e91e46SDimitry Andric   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
30695ca98fd9SDimitry Andric     return A->getUniqueID() < B->getUniqueID();
30705ca98fd9SDimitry Andric   });
3071f8af5cf6SDimitry Andric 
3072f8af5cf6SDimitry Andric   // Emit an arange table for each CU we used.
30735ca98fd9SDimitry Andric   for (DwarfCompileUnit *CU : CUs) {
3074f8af5cf6SDimitry Andric     std::vector<ArangeSpan> &List = Spans[CU];
3075f8af5cf6SDimitry Andric 
307667c32a98SDimitry Andric     // Describe the skeleton CU's offset and length, not the dwo file's.
307767c32a98SDimitry Andric     if (auto *Skel = CU->getSkeleton())
307867c32a98SDimitry Andric       CU = Skel;
307967c32a98SDimitry Andric 
3080f8af5cf6SDimitry Andric     // Emit size of content not including length itself.
30815ca98fd9SDimitry Andric     unsigned ContentSize =
30825ca98fd9SDimitry Andric         sizeof(int16_t) +               // DWARF ARange version number
3083b60736ecSDimitry Andric         Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3084b60736ecSDimitry Andric                                         // section
30855ca98fd9SDimitry Andric         sizeof(int8_t) +                // Pointer Size (in bytes)
30865ca98fd9SDimitry Andric         sizeof(int8_t);                 // Segment Size (in bytes)
3087f8af5cf6SDimitry Andric 
3088f8af5cf6SDimitry Andric     unsigned TupleSize = PtrSize * 2;
3089f8af5cf6SDimitry Andric 
3090f8af5cf6SDimitry Andric     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3091b60736ecSDimitry Andric     unsigned Padding = offsetToAlignment(
3092b60736ecSDimitry Andric         Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
3093f8af5cf6SDimitry Andric 
3094f8af5cf6SDimitry Andric     ContentSize += Padding;
3095f8af5cf6SDimitry Andric     ContentSize += (List.size() + 1) * TupleSize;
3096f8af5cf6SDimitry Andric 
3097f8af5cf6SDimitry Andric     // For each compile unit, write the list of spans it covers.
3098b60736ecSDimitry Andric     Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
30995a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("DWARF Arange version number");
3100eb11fae6SDimitry Andric     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
31015a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
3102eb11fae6SDimitry Andric     emitSectionReference(*CU);
31035a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("Address Size (in bytes)");
3104eb11fae6SDimitry Andric     Asm->emitInt8(PtrSize);
31055a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
3106eb11fae6SDimitry Andric     Asm->emitInt8(0);
3107f8af5cf6SDimitry Andric 
310801095a5dSDimitry Andric     Asm->OutStreamer->emitFill(Padding, 0xff);
3109f8af5cf6SDimitry Andric 
31105ca98fd9SDimitry Andric     for (const ArangeSpan &Span : List) {
3111cfca06d7SDimitry Andric       Asm->emitLabelReference(Span.Start, PtrSize);
3112f8af5cf6SDimitry Andric 
3113145449b1SDimitry Andric       // Calculate the size as being from the span start to its end.
3114145449b1SDimitry Andric       //
3115145449b1SDimitry Andric       // If the size is zero, then round it up to one byte. The DWARF
3116145449b1SDimitry Andric       // specification requires that entries in this table have nonzero
3117145449b1SDimitry Andric       // lengths.
3118145449b1SDimitry Andric       auto SizeRef = SymSize.find(Span.Start);
3119145449b1SDimitry Andric       if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
3120cfca06d7SDimitry Andric         Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
3121f8af5cf6SDimitry Andric       } else {
3122f8af5cf6SDimitry Andric         // For symbols without an end marker (e.g. common), we
3123f8af5cf6SDimitry Andric         // write a single arange entry containing just that one symbol.
3124145449b1SDimitry Andric         uint64_t Size;
3125145449b1SDimitry Andric         if (SizeRef == SymSize.end() || SizeRef->second == 0)
3126f8af5cf6SDimitry Andric           Size = 1;
3127145449b1SDimitry Andric         else
3128145449b1SDimitry Andric           Size = SizeRef->second;
3129f8af5cf6SDimitry Andric 
3130cfca06d7SDimitry Andric         Asm->OutStreamer->emitIntValue(Size, PtrSize);
3131f8af5cf6SDimitry Andric       }
3132f8af5cf6SDimitry Andric     }
3133f8af5cf6SDimitry Andric 
31345a5ac124SDimitry Andric     Asm->OutStreamer->AddComment("ARange terminator");
3135cfca06d7SDimitry Andric     Asm->OutStreamer->emitIntValue(0, PtrSize);
3136cfca06d7SDimitry Andric     Asm->OutStreamer->emitIntValue(0, PtrSize);
3137f8af5cf6SDimitry Andric   }
3138009b1c42SEd Schouten }
3139009b1c42SEd Schouten 
3140eb11fae6SDimitry Andric /// Emit a single range list. We handle both DWARF v5 and earlier.
emitRangeList(DwarfDebug & DD,AsmPrinter * Asm,const RangeSpanList & List)3141d8e91e46SDimitry Andric static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
3142eb11fae6SDimitry Andric                           const RangeSpanList &List) {
3143706b4fc4SDimitry Andric   emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
31441d5ae102SDimitry Andric                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
31451d5ae102SDimitry Andric                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
31461d5ae102SDimitry Andric                 llvm::dwarf::RangeListEncodingString,
3147706b4fc4SDimitry Andric                 List.CU->getCUNode()->getRangesBaseAddress() ||
31481d5ae102SDimitry Andric                     DD.getDwarfVersion() >= 5,
31491d5ae102SDimitry Andric                 [](auto) {});
3150eb11fae6SDimitry Andric }
3151009b1c42SEd Schouten 
emitDebugRangesImpl(const DwarfFile & Holder,MCSection * Section)3152706b4fc4SDimitry Andric void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3153706b4fc4SDimitry Andric   if (Holder.getRangeLists().empty())
3154706b4fc4SDimitry Andric     return;
3155706b4fc4SDimitry Andric 
3156706b4fc4SDimitry Andric   assert(useRangesSection());
3157706b4fc4SDimitry Andric   assert(!CUMap.empty());
3158706b4fc4SDimitry Andric   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3159706b4fc4SDimitry Andric     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3160706b4fc4SDimitry Andric   }));
3161706b4fc4SDimitry Andric 
3162145449b1SDimitry Andric   Asm->OutStreamer->switchSection(Section);
3163706b4fc4SDimitry Andric 
3164706b4fc4SDimitry Andric   MCSymbol *TableEnd = nullptr;
3165706b4fc4SDimitry Andric   if (getDwarfVersion() >= 5)
3166706b4fc4SDimitry Andric     TableEnd = emitRnglistsTableHeader(Asm, Holder);
3167706b4fc4SDimitry Andric 
3168d8e91e46SDimitry Andric   for (const RangeSpanList &List : Holder.getRangeLists())
3169706b4fc4SDimitry Andric     emitRangeList(*this, Asm, List);
3170eb11fae6SDimitry Andric 
3171d8e91e46SDimitry Andric   if (TableEnd)
3172cfca06d7SDimitry Andric     Asm->OutStreamer->emitLabel(TableEnd);
31735ca98fd9SDimitry Andric }
3174eb11fae6SDimitry Andric 
3175eb11fae6SDimitry Andric /// Emit address ranges into the .debug_ranges section or into the DWARF v5
3176eb11fae6SDimitry Andric /// .debug_rnglists section.
emitDebugRanges()3177eb11fae6SDimitry Andric void DwarfDebug::emitDebugRanges() {
3178d8e91e46SDimitry Andric   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3179eb11fae6SDimitry Andric 
3180706b4fc4SDimitry Andric   emitDebugRangesImpl(Holder,
3181706b4fc4SDimitry Andric                       getDwarfVersion() >= 5
3182706b4fc4SDimitry Andric                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
3183706b4fc4SDimitry Andric                           : Asm->getObjFileLowering().getDwarfRangesSection());
3184eb11fae6SDimitry Andric }
3185eb11fae6SDimitry Andric 
emitDebugRangesDWO()3186d8e91e46SDimitry Andric void DwarfDebug::emitDebugRangesDWO() {
3187706b4fc4SDimitry Andric   emitDebugRangesImpl(InfoHolder,
3188d8e91e46SDimitry Andric                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
3189009b1c42SEd Schouten }
3190009b1c42SEd Schouten 
3191b60736ecSDimitry Andric /// Emit the header of a DWARF 5 macro section, or the GNU extension for
3192b60736ecSDimitry Andric /// DWARF 4.
emitMacroHeader(AsmPrinter * Asm,const DwarfDebug & DD,const DwarfCompileUnit & CU,uint16_t DwarfVersion)3193cfca06d7SDimitry Andric static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3194b60736ecSDimitry Andric                             const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
3195cfca06d7SDimitry Andric   enum HeaderFlagMask {
3196cfca06d7SDimitry Andric #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
3197cfca06d7SDimitry Andric #include "llvm/BinaryFormat/Dwarf.def"
3198cfca06d7SDimitry Andric   };
3199cfca06d7SDimitry Andric   Asm->OutStreamer->AddComment("Macro information version");
3200b60736ecSDimitry Andric   Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3201b60736ecSDimitry Andric   // We emit the line offset flag unconditionally here, since line offset should
3202b60736ecSDimitry Andric   // be mostly present.
3203b60736ecSDimitry Andric   if (Asm->isDwarf64()) {
3204b60736ecSDimitry Andric     Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3205b60736ecSDimitry Andric     Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3206b60736ecSDimitry Andric   } else {
3207cfca06d7SDimitry Andric     Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3208b60736ecSDimitry Andric     Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3209b60736ecSDimitry Andric   }
3210cfca06d7SDimitry Andric   Asm->OutStreamer->AddComment("debug_line_offset");
3211b60736ecSDimitry Andric   if (DD.useSplitDwarf())
3212b60736ecSDimitry Andric     Asm->emitDwarfLengthOrOffset(0);
3213b60736ecSDimitry Andric   else
3214b60736ecSDimitry Andric     Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
3215cfca06d7SDimitry Andric }
3216cfca06d7SDimitry Andric 
handleMacroNodes(DIMacroNodeArray Nodes,DwarfCompileUnit & U)321701095a5dSDimitry Andric void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3218050e163aSDimitry Andric   for (auto *MN : Nodes) {
3219050e163aSDimitry Andric     if (auto *M = dyn_cast<DIMacro>(MN))
322001095a5dSDimitry Andric       emitMacro(*M);
3221050e163aSDimitry Andric     else if (auto *F = dyn_cast<DIMacroFile>(MN))
322201095a5dSDimitry Andric       emitMacroFile(*F, U);
3223050e163aSDimitry Andric     else
3224050e163aSDimitry Andric       llvm_unreachable("Unexpected DI type!");
3225050e163aSDimitry Andric   }
3226050e163aSDimitry Andric }
3227050e163aSDimitry Andric 
emitMacro(DIMacro & M)322801095a5dSDimitry Andric void DwarfDebug::emitMacro(DIMacro &M) {
3229050e163aSDimitry Andric   StringRef Name = M.getName();
3230050e163aSDimitry Andric   StringRef Value = M.getValue();
3231cfca06d7SDimitry Andric 
3232b60736ecSDimitry Andric   // There should be one space between the macro name and the macro value in
3233b60736ecSDimitry Andric   // define entries. In undef entries, only the macro name is emitted.
3234b60736ecSDimitry Andric   std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3235b60736ecSDimitry Andric 
3236b60736ecSDimitry Andric   if (UseDebugMacroSection) {
3237b60736ecSDimitry Andric     if (getDwarfVersion() >= 5) {
3238cfca06d7SDimitry Andric       unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3239cfca06d7SDimitry Andric                           ? dwarf::DW_MACRO_define_strx
3240cfca06d7SDimitry Andric                           : dwarf::DW_MACRO_undef_strx;
3241cfca06d7SDimitry Andric       Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
3242cfca06d7SDimitry Andric       Asm->emitULEB128(Type);
3243cfca06d7SDimitry Andric       Asm->OutStreamer->AddComment("Line Number");
3244cfca06d7SDimitry Andric       Asm->emitULEB128(M.getLine());
3245cfca06d7SDimitry Andric       Asm->OutStreamer->AddComment("Macro String");
3246b60736ecSDimitry Andric       Asm->emitULEB128(
3247b60736ecSDimitry Andric           InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3248b60736ecSDimitry Andric     } else {
3249b60736ecSDimitry Andric       unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3250b60736ecSDimitry Andric                           ? dwarf::DW_MACRO_GNU_define_indirect
3251b60736ecSDimitry Andric                           : dwarf::DW_MACRO_GNU_undef_indirect;
3252b60736ecSDimitry Andric       Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
3253b60736ecSDimitry Andric       Asm->emitULEB128(Type);
3254b60736ecSDimitry Andric       Asm->OutStreamer->AddComment("Line Number");
3255b60736ecSDimitry Andric       Asm->emitULEB128(M.getLine());
3256b60736ecSDimitry Andric       Asm->OutStreamer->AddComment("Macro String");
3257b60736ecSDimitry Andric       Asm->emitDwarfSymbolReference(
3258b60736ecSDimitry Andric           InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3259b60736ecSDimitry Andric     }
3260cfca06d7SDimitry Andric   } else {
3261cfca06d7SDimitry Andric     Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
3262cfca06d7SDimitry Andric     Asm->emitULEB128(M.getMacinfoType());
3263cfca06d7SDimitry Andric     Asm->OutStreamer->AddComment("Line Number");
3264cfca06d7SDimitry Andric     Asm->emitULEB128(M.getLine());
3265cfca06d7SDimitry Andric     Asm->OutStreamer->AddComment("Macro String");
3266b60736ecSDimitry Andric     Asm->OutStreamer->emitBytes(Str);
3267eb11fae6SDimitry Andric     Asm->emitInt8('\0');
3268050e163aSDimitry Andric   }
3269cfca06d7SDimitry Andric }
3270cfca06d7SDimitry Andric 
emitMacroFileImpl(DIMacroFile & MF,DwarfCompileUnit & U,unsigned StartFile,unsigned EndFile,StringRef (* MacroFormToString)(unsigned Form))3271cfca06d7SDimitry Andric void DwarfDebug::emitMacroFileImpl(
3272b60736ecSDimitry Andric     DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3273cfca06d7SDimitry Andric     StringRef (*MacroFormToString)(unsigned Form)) {
3274cfca06d7SDimitry Andric 
3275cfca06d7SDimitry Andric   Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3276cfca06d7SDimitry Andric   Asm->emitULEB128(StartFile);
3277cfca06d7SDimitry Andric   Asm->OutStreamer->AddComment("Line Number");
3278b60736ecSDimitry Andric   Asm->emitULEB128(MF.getLine());
3279cfca06d7SDimitry Andric   Asm->OutStreamer->AddComment("File Number");
3280b60736ecSDimitry Andric   DIFile &F = *MF.getFile();
3281b60736ecSDimitry Andric   if (useSplitDwarf())
3282b60736ecSDimitry Andric     Asm->emitULEB128(getDwoLineTable(U)->getFile(
3283b60736ecSDimitry Andric         F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3284b60736ecSDimitry Andric         Asm->OutContext.getDwarfVersion(), F.getSource()));
3285b60736ecSDimitry Andric   else
3286b60736ecSDimitry Andric     Asm->emitULEB128(U.getOrCreateSourceID(&F));
3287b60736ecSDimitry Andric   handleMacroNodes(MF.getElements(), U);
3288cfca06d7SDimitry Andric   Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
3289cfca06d7SDimitry Andric   Asm->emitULEB128(EndFile);
3290cfca06d7SDimitry Andric }
3291050e163aSDimitry Andric 
emitMacroFile(DIMacroFile & F,DwarfCompileUnit & U)329201095a5dSDimitry Andric void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3293cfca06d7SDimitry Andric   // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3294cfca06d7SDimitry Andric   // so for readibility/uniformity, We are explicitly emitting those.
3295050e163aSDimitry Andric   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3296b60736ecSDimitry Andric   if (UseDebugMacroSection)
3297b60736ecSDimitry Andric     emitMacroFileImpl(
3298b60736ecSDimitry Andric         F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3299b60736ecSDimitry Andric         (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
3300cfca06d7SDimitry Andric   else
3301cfca06d7SDimitry Andric     emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
3302cfca06d7SDimitry Andric                       dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
3303050e163aSDimitry Andric }
3304050e163aSDimitry Andric 
emitDebugMacinfoImpl(MCSection * Section)3305706b4fc4SDimitry Andric void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3306050e163aSDimitry Andric   for (const auto &P : CUMap) {
3307050e163aSDimitry Andric     auto &TheCU = *P.second;
3308050e163aSDimitry Andric     auto *SkCU = TheCU.getSkeleton();
3309050e163aSDimitry Andric     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3310050e163aSDimitry Andric     auto *CUNode = cast<DICompileUnit>(P.first);
3311eb11fae6SDimitry Andric     DIMacroNodeArray Macros = CUNode->getMacros();
3312706b4fc4SDimitry Andric     if (Macros.empty())
3313706b4fc4SDimitry Andric       continue;
3314145449b1SDimitry Andric     Asm->OutStreamer->switchSection(Section);
3315cfca06d7SDimitry Andric     Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3316b60736ecSDimitry Andric     if (UseDebugMacroSection)
3317b60736ecSDimitry Andric       emitMacroHeader(Asm, *this, U, getDwarfVersion());
3318eb11fae6SDimitry Andric     handleMacroNodes(Macros, U);
3319050e163aSDimitry Andric     Asm->OutStreamer->AddComment("End Of Macro List Mark");
3320eb11fae6SDimitry Andric     Asm->emitInt8(0);
3321050e163aSDimitry Andric   }
3322706b4fc4SDimitry Andric }
3323706b4fc4SDimitry Andric 
3324cfca06d7SDimitry Andric /// Emit macros into a debug macinfo/macro section.
emitDebugMacinfo()3325706b4fc4SDimitry Andric void DwarfDebug::emitDebugMacinfo() {
3326cfca06d7SDimitry Andric   auto &ObjLower = Asm->getObjFileLowering();
3327b60736ecSDimitry Andric   emitDebugMacinfoImpl(UseDebugMacroSection
3328cfca06d7SDimitry Andric                            ? ObjLower.getDwarfMacroSection()
3329cfca06d7SDimitry Andric                            : ObjLower.getDwarfMacinfoSection());
3330706b4fc4SDimitry Andric }
3331706b4fc4SDimitry Andric 
emitDebugMacinfoDWO()3332706b4fc4SDimitry Andric void DwarfDebug::emitDebugMacinfoDWO() {
3333cfca06d7SDimitry Andric   auto &ObjLower = Asm->getObjFileLowering();
3334b60736ecSDimitry Andric   emitDebugMacinfoImpl(UseDebugMacroSection
3335cfca06d7SDimitry Andric                            ? ObjLower.getDwarfMacroDWOSection()
3336cfca06d7SDimitry Andric                            : ObjLower.getDwarfMacinfoDWOSection());
3337706b4fc4SDimitry Andric }
3338050e163aSDimitry Andric 
33394a16efa3SDimitry Andric // DWARF5 Experimental Separate Dwarf emitters.
33404a16efa3SDimitry Andric 
initSkeletonUnit(const DwarfUnit & U,DIE & Die,std::unique_ptr<DwarfCompileUnit> NewU)33415ca98fd9SDimitry Andric void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
334201095a5dSDimitry Andric                                   std::unique_ptr<DwarfCompileUnit> NewU) {
33434a16efa3SDimitry Andric 
33444a16efa3SDimitry Andric   if (!CompilationDir.empty())
334567c32a98SDimitry Andric     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
33465ca98fd9SDimitry Andric   addGnuPubAttributes(*NewU, Die);
3347f8af5cf6SDimitry Andric 
33485ca98fd9SDimitry Andric   SkeletonHolder.addUnit(std::move(NewU));
3349f8af5cf6SDimitry Andric }
3350f8af5cf6SDimitry Andric 
constructSkeletonCU(const DwarfCompileUnit & CU)33515ca98fd9SDimitry Andric DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3352f8af5cf6SDimitry Andric 
33531d5ae102SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3354706b4fc4SDimitry Andric       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3355706b4fc4SDimitry Andric       UnitKind::Skeleton);
33565ca98fd9SDimitry Andric   DwarfCompileUnit &NewCU = *OwnedUnit;
3357b915e9e0SDimitry Andric   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
33585ca98fd9SDimitry Andric 
33595a5ac124SDimitry Andric   NewCU.initStmtList();
33605ca98fd9SDimitry Andric 
3361eb11fae6SDimitry Andric   if (useSegmentedStringOffsetsTable())
3362eb11fae6SDimitry Andric     NewCU.addStringOffsetsStart();
3363eb11fae6SDimitry Andric 
33645ca98fd9SDimitry Andric   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
33654a16efa3SDimitry Andric 
33664a16efa3SDimitry Andric   return NewCU;
33674a16efa3SDimitry Andric }
33684a16efa3SDimitry Andric 
33694a16efa3SDimitry Andric // Emit the .debug_info.dwo section for separated dwarf. This contains the
33704a16efa3SDimitry Andric // compile units that would normally be in debug_info.
emitDebugInfoDWO()33714a16efa3SDimitry Andric void DwarfDebug::emitDebugInfoDWO() {
33724a16efa3SDimitry Andric   assert(useSplitDwarf() && "No split dwarf debug info?");
33735a5ac124SDimitry Andric   // Don't emit relocations into the dwo file.
33745a5ac124SDimitry Andric   InfoHolder.emitUnits(/* UseOffsets */ true);
33754a16efa3SDimitry Andric }
33764a16efa3SDimitry Andric 
33774a16efa3SDimitry Andric // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
33784a16efa3SDimitry Andric // abbreviations for the .debug_info.dwo section.
emitDebugAbbrevDWO()33794a16efa3SDimitry Andric void DwarfDebug::emitDebugAbbrevDWO() {
33804a16efa3SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
33815ca98fd9SDimitry Andric   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
33825ca98fd9SDimitry Andric }
33835ca98fd9SDimitry Andric 
emitDebugLineDWO()33845ca98fd9SDimitry Andric void DwarfDebug::emitDebugLineDWO() {
33855ca98fd9SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
3386eb11fae6SDimitry Andric   SplitTypeUnitFileTable.Emit(
3387eb11fae6SDimitry Andric       *Asm->OutStreamer, MCDwarfLineTableParams(),
33885ca98fd9SDimitry Andric       Asm->getObjFileLowering().getDwarfLineDWOSection());
3389eb11fae6SDimitry Andric }
3390eb11fae6SDimitry Andric 
emitStringOffsetsTableHeaderDWO()3391eb11fae6SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3392eb11fae6SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
3393eb11fae6SDimitry Andric   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
3394eb11fae6SDimitry Andric       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
3395eb11fae6SDimitry Andric       InfoHolder.getStringOffsetsStartSym());
33964a16efa3SDimitry Andric }
33974a16efa3SDimitry Andric 
33984a16efa3SDimitry Andric // Emit the .debug_str.dwo section for separated dwarf. This contains the
33994a16efa3SDimitry Andric // string section and is identical in format to traditional .debug_str
34004a16efa3SDimitry Andric // sections.
emitDebugStrDWO()34014a16efa3SDimitry Andric void DwarfDebug::emitDebugStrDWO() {
3402eb11fae6SDimitry Andric   if (useSegmentedStringOffsetsTable())
3403eb11fae6SDimitry Andric     emitStringOffsetsTableHeaderDWO();
34044a16efa3SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
34055a5ac124SDimitry Andric   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
34064a16efa3SDimitry Andric   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3407eb11fae6SDimitry Andric                          OffSec, /* UseRelativeOffsets = */ false);
34084a16efa3SDimitry Andric }
34095ca98fd9SDimitry Andric 
3410d8e91e46SDimitry Andric // Emit address pool.
emitDebugAddr()3411b7eb8e35SDimitry Andric void DwarfDebug::emitDebugAddr() {
3412b7eb8e35SDimitry Andric   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
3413b7eb8e35SDimitry Andric }
3414b7eb8e35SDimitry Andric 
getDwoLineTable(const DwarfCompileUnit & CU)34155ca98fd9SDimitry Andric MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
34165ca98fd9SDimitry Andric   if (!useSplitDwarf())
34175ca98fd9SDimitry Andric     return nullptr;
3418eb11fae6SDimitry Andric   const DICompileUnit *DIUnit = CU.getCUNode();
3419eb11fae6SDimitry Andric   SplitTypeUnitFileTable.maybeSetRootFile(
3420eb11fae6SDimitry Andric       DIUnit->getDirectory(), DIUnit->getFilename(),
3421b60736ecSDimitry Andric       getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
34225ca98fd9SDimitry Andric   return &SplitTypeUnitFileTable;
34235ca98fd9SDimitry Andric }
34245ca98fd9SDimitry Andric 
makeTypeSignature(StringRef Identifier)3425dd58ef01SDimitry Andric uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
34265ca98fd9SDimitry Andric   MD5 Hash;
34275ca98fd9SDimitry Andric   Hash.update(Identifier);
34285ca98fd9SDimitry Andric   // ... take the least significant 8 bytes and return those. Our MD5
342971d5a254SDimitry Andric   // implementation always returns its results in little endian, so we actually
343071d5a254SDimitry Andric   // need the "high" word.
34315ca98fd9SDimitry Andric   MD5::MD5Result Result;
34325ca98fd9SDimitry Andric   Hash.final(Result);
343371d5a254SDimitry Andric   return Result.high();
34345ca98fd9SDimitry Andric }
34355ca98fd9SDimitry Andric 
addDwarfTypeUnitType(DwarfCompileUnit & CU,StringRef Identifier,DIE & RefDie,const DICompositeType * CTy)34365ca98fd9SDimitry Andric void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
34375ca98fd9SDimitry Andric                                       StringRef Identifier, DIE &RefDie,
34385a5ac124SDimitry Andric                                       const DICompositeType *CTy) {
34395ca98fd9SDimitry Andric   // Fast path if we're building some type units and one has already used the
34405ca98fd9SDimitry Andric   // address pool we know we're going to throw away all this work anyway, so
34415ca98fd9SDimitry Andric   // don't bother building dependent types.
3442ecbca9f5SDimitry Andric   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
34435ca98fd9SDimitry Andric     return;
34445ca98fd9SDimitry Andric 
344501095a5dSDimitry Andric   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
344601095a5dSDimitry Andric   if (!Ins.second) {
344701095a5dSDimitry Andric     CU.addDIETypeSignature(RefDie, Ins.first->second);
34485ca98fd9SDimitry Andric     return;
34495ca98fd9SDimitry Andric   }
34505ca98fd9SDimitry Andric 
34514df029ccSDimitry Andric   setCurrentDWARF5AccelTable(DWARF5AccelTableKind::TU);
34525ca98fd9SDimitry Andric   bool TopLevelType = TypeUnitsUnderConstruction.empty();
34535ca98fd9SDimitry Andric   AddrPool.resetUsedFlag();
34545ca98fd9SDimitry Andric 
3455b1c73532SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
3456b1c73532SDimitry Andric       CU, Asm, this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(CU));
34575ca98fd9SDimitry Andric   DwarfTypeUnit &NewTU = *OwnedUnit;
34585ca98fd9SDimitry Andric   DIE &UnitDie = NewTU.getUnitDie();
3459b915e9e0SDimitry Andric   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
34605ca98fd9SDimitry Andric 
34615ca98fd9SDimitry Andric   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
34625ca98fd9SDimitry Andric                 CU.getLanguage());
34635ca98fd9SDimitry Andric 
34645ca98fd9SDimitry Andric   uint64_t Signature = makeTypeSignature(Identifier);
34655ca98fd9SDimitry Andric   NewTU.setTypeSignature(Signature);
346601095a5dSDimitry Andric   Ins.first->second = Signature;
34675ca98fd9SDimitry Andric 
3468d8e91e46SDimitry Andric   if (useSplitDwarf()) {
3469312c0ed1SDimitry Andric     // Although multiple type units can have the same signature, they are not
3470312c0ed1SDimitry Andric     // guranteed to be bit identical. When LLDB uses .debug_names it needs to
3471312c0ed1SDimitry Andric     // know from which CU a type unit came from. These two attrbutes help it to
3472312c0ed1SDimitry Andric     // figure that out.
3473312c0ed1SDimitry Andric     if (getDwarfVersion() >= 5) {
3474312c0ed1SDimitry Andric       if (!CompilationDir.empty())
3475312c0ed1SDimitry Andric         NewTU.addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
3476312c0ed1SDimitry Andric       NewTU.addString(UnitDie, dwarf::DW_AT_dwo_name,
3477312c0ed1SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
3478312c0ed1SDimitry Andric     }
3479d8e91e46SDimitry Andric     MCSection *Section =
3480d8e91e46SDimitry Andric         getDwarfVersion() <= 4
3481d8e91e46SDimitry Andric             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
3482d8e91e46SDimitry Andric             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
3483d8e91e46SDimitry Andric     NewTU.setSection(Section);
3484d8e91e46SDimitry Andric   } else {
3485d8e91e46SDimitry Andric     MCSection *Section =
3486d8e91e46SDimitry Andric         getDwarfVersion() <= 4
3487d8e91e46SDimitry Andric             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
3488d8e91e46SDimitry Andric             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
3489d8e91e46SDimitry Andric     NewTU.setSection(Section);
3490eb11fae6SDimitry Andric     // Non-split type units reuse the compile unit's line table.
3491eb11fae6SDimitry Andric     CU.applyStmtList(UnitDie);
349267c32a98SDimitry Andric   }
34935ca98fd9SDimitry Andric 
3494eb11fae6SDimitry Andric   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3495eb11fae6SDimitry Andric   // units.
3496eb11fae6SDimitry Andric   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3497eb11fae6SDimitry Andric     NewTU.addStringOffsetsStart();
3498eb11fae6SDimitry Andric 
34995ca98fd9SDimitry Andric   NewTU.setType(NewTU.createTypeDIE(CTy));
35005ca98fd9SDimitry Andric 
35015ca98fd9SDimitry Andric   if (TopLevelType) {
35025ca98fd9SDimitry Andric     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
35035ca98fd9SDimitry Andric     TypeUnitsUnderConstruction.clear();
35045ca98fd9SDimitry Andric 
35055ca98fd9SDimitry Andric     // Types referencing entries in the address table cannot be placed in type
35065ca98fd9SDimitry Andric     // units.
3507ecbca9f5SDimitry Andric     if (AddrPool.hasBeenUsed()) {
3508b1c73532SDimitry Andric       AccelTypeUnitsDebugNames.clear();
35095ca98fd9SDimitry Andric       // Remove all the types built while building this type.
35105ca98fd9SDimitry Andric       // This is pessimistic as some of these types might not be dependent on
35115ca98fd9SDimitry Andric       // the type that used an address.
35125ca98fd9SDimitry Andric       for (const auto &TU : TypeUnitsToAdd)
351301095a5dSDimitry Andric         TypeSignatures.erase(TU.second);
35145ca98fd9SDimitry Andric 
35155ca98fd9SDimitry Andric       // Construct this type in the CU directly.
35165ca98fd9SDimitry Andric       // This is inefficient because all the dependent types will be rebuilt
35175ca98fd9SDimitry Andric       // from scratch, including building them in type units, discovering that
35185ca98fd9SDimitry Andric       // they depend on addresses, throwing them out and rebuilding them.
3519b1c73532SDimitry Andric       setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);
35205a5ac124SDimitry Andric       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
35215ca98fd9SDimitry Andric       return;
35225ca98fd9SDimitry Andric     }
35235ca98fd9SDimitry Andric 
35245ca98fd9SDimitry Andric     // If the type wasn't dependent on fission addresses, finish adding the type
35255ca98fd9SDimitry Andric     // and all its dependent types.
352601095a5dSDimitry Andric     for (auto &TU : TypeUnitsToAdd) {
352701095a5dSDimitry Andric       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
352801095a5dSDimitry Andric       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3529b1c73532SDimitry Andric       if (getDwarfVersion() >= 5 &&
3530b1c73532SDimitry Andric           getAccelTableKind() == AccelTableKind::Dwarf) {
3531b1c73532SDimitry Andric         if (useSplitDwarf())
3532b1c73532SDimitry Andric           AccelDebugNames.addTypeUnitSignature(*TU.first);
3533b1c73532SDimitry Andric         else
3534b1c73532SDimitry Andric           AccelDebugNames.addTypeUnitSymbol(*TU.first);
35355ca98fd9SDimitry Andric       }
353601095a5dSDimitry Andric     }
3537b1c73532SDimitry Andric     AccelTypeUnitsDebugNames.convertDieToOffset();
3538b1c73532SDimitry Andric     AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);
3539b1c73532SDimitry Andric     AccelTypeUnitsDebugNames.clear();
35404df029ccSDimitry Andric     setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);
3541b1c73532SDimitry Andric   }
354201095a5dSDimitry Andric   CU.addDIETypeSignature(RefDie, Signature);
35435ca98fd9SDimitry Andric }
35445ca98fd9SDimitry Andric 
3545eb11fae6SDimitry Andric // Add the Name along with its companion DIE to the appropriate accelerator
3546eb11fae6SDimitry Andric // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3547eb11fae6SDimitry Andric // AccelTableKind::Apple, we use the table we got as an argument). If
3548eb11fae6SDimitry Andric // accelerator tables are disabled, this function does nothing.
3549eb11fae6SDimitry Andric template <typename DataT>
addAccelNameImpl(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,AccelTable<DataT> & AppleAccel,StringRef Name,const DIE & Die)3550b1c73532SDimitry Andric void DwarfDebug::addAccelNameImpl(
3551b1c73532SDimitry Andric     const DwarfUnit &Unit,
3552b1c73532SDimitry Andric     const DICompileUnit::DebugNameTableKind NameTableKind,
3553b1c73532SDimitry Andric     AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {
3554ac9a064cSDimitry Andric   if (getAccelTableKind() == AccelTableKind::None ||
3555ac9a064cSDimitry Andric       Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())
35565ca98fd9SDimitry Andric     return;
3557eb11fae6SDimitry Andric 
3558d8e91e46SDimitry Andric   if (getAccelTableKind() != AccelTableKind::Apple &&
3559b1c73532SDimitry Andric       NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&
3560b1c73532SDimitry Andric       NameTableKind != DICompileUnit::DebugNameTableKind::Default)
3561d8e91e46SDimitry Andric     return;
3562d8e91e46SDimitry Andric 
3563eb11fae6SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3564d8e91e46SDimitry Andric   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3565eb11fae6SDimitry Andric 
3566eb11fae6SDimitry Andric   switch (getAccelTableKind()) {
3567eb11fae6SDimitry Andric   case AccelTableKind::Apple:
3568eb11fae6SDimitry Andric     AppleAccel.addName(Ref, Die);
3569eb11fae6SDimitry Andric     break;
3570b1c73532SDimitry Andric   case AccelTableKind::Dwarf: {
3571b1c73532SDimitry Andric     DWARF5AccelTable &Current = getCurrentDWARF5AccelTable();
35724df029ccSDimitry Andric     assert(((&Current == &AccelTypeUnitsDebugNames) ||
35734df029ccSDimitry Andric             ((&Current == &AccelDebugNames) &&
35744df029ccSDimitry Andric              (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
35754df029ccSDimitry Andric                "Kind is CU but TU is being processed.");
35764df029ccSDimitry Andric     assert(((&Current == &AccelDebugNames) ||
35774df029ccSDimitry Andric             ((&Current == &AccelTypeUnitsDebugNames) &&
35784df029ccSDimitry Andric              (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
35794df029ccSDimitry Andric                "Kind is TU but CU is being processed.");
3580b1c73532SDimitry Andric     // The type unit can be discarded, so need to add references to final
3581b1c73532SDimitry Andric     // acceleration table once we know it's complete and we emit it.
3582ac9a064cSDimitry Andric     Current.addName(Ref, Die, Unit.getUniqueID(),
3583ac9a064cSDimitry Andric                     Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
3584eb11fae6SDimitry Andric     break;
3585b1c73532SDimitry Andric   }
3586eb11fae6SDimitry Andric   case AccelTableKind::Default:
3587eb11fae6SDimitry Andric     llvm_unreachable("Default should have already been resolved.");
3588eb11fae6SDimitry Andric   case AccelTableKind::None:
3589eb11fae6SDimitry Andric     llvm_unreachable("None handled above");
3590eb11fae6SDimitry Andric   }
3591eb11fae6SDimitry Andric }
3592eb11fae6SDimitry Andric 
addAccelName(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die)3593b1c73532SDimitry Andric void DwarfDebug::addAccelName(
3594b1c73532SDimitry Andric     const DwarfUnit &Unit,
3595b1c73532SDimitry Andric     const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
3596d8e91e46SDimitry Andric     const DIE &Die) {
3597b1c73532SDimitry Andric   addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);
35985ca98fd9SDimitry Andric }
35995ca98fd9SDimitry Andric 
addAccelObjC(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die)3600b1c73532SDimitry Andric void DwarfDebug::addAccelObjC(
3601b1c73532SDimitry Andric     const DwarfUnit &Unit,
3602b1c73532SDimitry Andric     const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
3603d8e91e46SDimitry Andric     const DIE &Die) {
3604eb11fae6SDimitry Andric   // ObjC names go only into the Apple accelerator tables.
3605eb11fae6SDimitry Andric   if (getAccelTableKind() == AccelTableKind::Apple)
3606b1c73532SDimitry Andric     addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);
36075ca98fd9SDimitry Andric }
36085ca98fd9SDimitry Andric 
addAccelNamespace(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die)3609b1c73532SDimitry Andric void DwarfDebug::addAccelNamespace(
3610b1c73532SDimitry Andric     const DwarfUnit &Unit,
3611b1c73532SDimitry Andric     const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
3612d8e91e46SDimitry Andric     const DIE &Die) {
3613b1c73532SDimitry Andric   addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);
36145ca98fd9SDimitry Andric }
36155ca98fd9SDimitry Andric 
addAccelType(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die,char Flags)3616b1c73532SDimitry Andric void DwarfDebug::addAccelType(
3617b1c73532SDimitry Andric     const DwarfUnit &Unit,
3618b1c73532SDimitry Andric     const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
3619d8e91e46SDimitry Andric     const DIE &Die, char Flags) {
3620b1c73532SDimitry Andric   addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);
36215ca98fd9SDimitry Andric }
3622b915e9e0SDimitry Andric 
getDwarfVersion() const3623b915e9e0SDimitry Andric uint16_t DwarfDebug::getDwarfVersion() const {
3624b915e9e0SDimitry Andric   return Asm->OutStreamer->getContext().getDwarfVersion();
3625b915e9e0SDimitry Andric }
3626d8e91e46SDimitry Andric 
getDwarfSectionOffsetForm() const3627b60736ecSDimitry Andric dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
3628b60736ecSDimitry Andric   if (Asm->getDwarfVersion() >= 4)
3629b60736ecSDimitry Andric     return dwarf::Form::DW_FORM_sec_offset;
3630b60736ecSDimitry Andric   assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
3631b60736ecSDimitry Andric          "DWARF64 is not defined prior DWARFv3");
3632b60736ecSDimitry Andric   return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3633b60736ecSDimitry Andric                           : dwarf::Form::DW_FORM_data4;
3634b60736ecSDimitry Andric }
3635b60736ecSDimitry Andric 
getSectionLabel(const MCSection * S)3636d8e91e46SDimitry Andric const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
36377fa27ce4SDimitry Andric   return SectionLabels.lookup(S);
3638d8e91e46SDimitry Andric }
36397fa27ce4SDimitry Andric 
insertSectionLabel(const MCSymbol * S)3640cfca06d7SDimitry Andric void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
3641cfca06d7SDimitry Andric   if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
3642cfca06d7SDimitry Andric     if (useSplitDwarf() || getDwarfVersion() >= 5)
3643cfca06d7SDimitry Andric       AddrPool.getIndex(S);
3644cfca06d7SDimitry Andric }
3645b60736ecSDimitry Andric 
3646e3b55780SDimitry Andric std::optional<MD5::MD5Result>
getMD5AsBytes(const DIFile * File) const3647e3b55780SDimitry Andric DwarfDebug::getMD5AsBytes(const DIFile *File) const {
3648b60736ecSDimitry Andric   assert(File);
3649b60736ecSDimitry Andric   if (getDwarfVersion() < 5)
3650e3b55780SDimitry Andric     return std::nullopt;
3651e3b55780SDimitry Andric   std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3652b60736ecSDimitry Andric   if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3653e3b55780SDimitry Andric     return std::nullopt;
3654b60736ecSDimitry Andric 
3655b60736ecSDimitry Andric   // Convert the string checksum to an MD5Result for the streamer.
3656b60736ecSDimitry Andric   // The verifier validates the checksum so we assume it's okay.
3657b60736ecSDimitry Andric   // An MD5 checksum is 16 bytes.
3658b60736ecSDimitry Andric   std::string ChecksumString = fromHex(Checksum->Value);
3659b60736ecSDimitry Andric   MD5::MD5Result CKMem;
3660145449b1SDimitry Andric   std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3661b60736ecSDimitry Andric   return CKMem;
3662b60736ecSDimitry Andric }
36637fa27ce4SDimitry Andric 
alwaysUseRanges(const DwarfCompileUnit & CU) const36647fa27ce4SDimitry Andric bool DwarfDebug::alwaysUseRanges(const DwarfCompileUnit &CU) const {
36657fa27ce4SDimitry Andric   if (MinimizeAddr == MinimizeAddrInV5::Ranges)
36667fa27ce4SDimitry Andric     return true;
36677fa27ce4SDimitry Andric   if (MinimizeAddr != MinimizeAddrInV5::Default)
36687fa27ce4SDimitry Andric     return false;
36697fa27ce4SDimitry Andric   if (useSplitDwarf())
36707fa27ce4SDimitry Andric     return true;
36717fa27ce4SDimitry Andric   return false;
36727fa27ce4SDimitry Andric }
3673