10b57cec5SDimitry Andric //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains support for writing dwarf debug info into asm files.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "DwarfDebug.h"
140b57cec5SDimitry Andric #include "ByteStreamer.h"
150b57cec5SDimitry Andric #include "DIEHash.h"
160b57cec5SDimitry Andric #include "DwarfCompileUnit.h"
170b57cec5SDimitry Andric #include "DwarfExpression.h"
180b57cec5SDimitry Andric #include "DwarfUnit.h"
190b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
208bcb0991SDimitry Andric #include "llvm/ADT/Statistic.h"
2106c3fb27SDimitry Andric #include "llvm/ADT/StringExtras.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/DIE.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
318bcb0991SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
340b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
3581ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
360b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
370b57cec5SDimitry Andric #include "llvm/IR/Function.h"
380b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
390b57cec5SDimitry Andric #include "llvm/IR/Module.h"
400b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
410b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
420b57cec5SDimitry Andric #include "llvm/MC/MCSection.h"
430b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
440b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
450b57cec5SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
460b57cec5SDimitry Andric #include "llvm/MC/MachineLocation.h"
470b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
480b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
490b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
500b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
510b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
520b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
530b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
540b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
550b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
5606c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
570b57cec5SDimitry Andric #include <algorithm>
580b57cec5SDimitry Andric #include <cstddef>
590b57cec5SDimitry Andric #include <iterator>
60bdd1243dSDimitry Andric #include <optional>
610b57cec5SDimitry Andric #include <string>
620b57cec5SDimitry Andric
630b57cec5SDimitry Andric using namespace llvm;
640b57cec5SDimitry Andric
650b57cec5SDimitry Andric #define DEBUG_TYPE "dwarfdebug"
660b57cec5SDimitry Andric
678bcb0991SDimitry Andric STATISTIC(NumCSParams, "Number of dbg call site params created");
688bcb0991SDimitry Andric
690b57cec5SDimitry Andric static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
700b57cec5SDimitry Andric "use-dwarf-ranges-base-address-specifier", cl::Hidden,
710b57cec5SDimitry Andric cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
720b57cec5SDimitry Andric
730b57cec5SDimitry Andric static cl::opt<bool> GenerateARangeSection("generate-arange-section",
740b57cec5SDimitry Andric cl::Hidden,
750b57cec5SDimitry Andric cl::desc("Generate dwarf aranges"),
760b57cec5SDimitry Andric cl::init(false));
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric static cl::opt<bool>
790b57cec5SDimitry Andric GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
800b57cec5SDimitry Andric cl::desc("Generate DWARF4 type units."),
810b57cec5SDimitry Andric cl::init(false));
820b57cec5SDimitry Andric
830b57cec5SDimitry Andric static cl::opt<bool> SplitDwarfCrossCuReferences(
840b57cec5SDimitry Andric "split-dwarf-cross-cu-references", cl::Hidden,
850b57cec5SDimitry Andric cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
860b57cec5SDimitry Andric
870b57cec5SDimitry Andric enum DefaultOnOff { Default, Enable, Disable };
880b57cec5SDimitry Andric
890b57cec5SDimitry Andric static cl::opt<DefaultOnOff> UnknownLocations(
900b57cec5SDimitry Andric "use-unknown-locations", cl::Hidden,
910b57cec5SDimitry Andric cl::desc("Make an absence of debug location information explicit."),
920b57cec5SDimitry Andric cl::values(clEnumVal(Default, "At top of block or after label"),
930b57cec5SDimitry Andric clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
940b57cec5SDimitry Andric cl::init(Default));
950b57cec5SDimitry Andric
960b57cec5SDimitry Andric static cl::opt<AccelTableKind> AccelTables(
970b57cec5SDimitry Andric "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
980b57cec5SDimitry Andric cl::values(clEnumValN(AccelTableKind::Default, "Default",
990b57cec5SDimitry Andric "Default for platform"),
1000b57cec5SDimitry Andric clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
1010b57cec5SDimitry Andric clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
1020b57cec5SDimitry Andric clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
1030b57cec5SDimitry Andric cl::init(AccelTableKind::Default));
1040b57cec5SDimitry Andric
1050b57cec5SDimitry Andric static cl::opt<DefaultOnOff>
1060b57cec5SDimitry Andric DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
1070b57cec5SDimitry Andric cl::desc("Use inlined strings rather than string section."),
1080b57cec5SDimitry Andric cl::values(clEnumVal(Default, "Default for platform"),
1090b57cec5SDimitry Andric clEnumVal(Enable, "Enabled"),
1100b57cec5SDimitry Andric clEnumVal(Disable, "Disabled")),
1110b57cec5SDimitry Andric cl::init(Default));
1120b57cec5SDimitry Andric
1130b57cec5SDimitry Andric static cl::opt<bool>
1140b57cec5SDimitry Andric NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
1150b57cec5SDimitry Andric cl::desc("Disable emission .debug_ranges section."),
1160b57cec5SDimitry Andric cl::init(false));
1170b57cec5SDimitry Andric
1180b57cec5SDimitry Andric static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
1190b57cec5SDimitry Andric "dwarf-sections-as-references", cl::Hidden,
1200b57cec5SDimitry Andric cl::desc("Use sections+offset as references rather than labels."),
1210b57cec5SDimitry Andric cl::values(clEnumVal(Default, "Default for platform"),
1220b57cec5SDimitry Andric clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
1230b57cec5SDimitry Andric cl::init(Default));
1240b57cec5SDimitry Andric
125e8d8bef9SDimitry Andric static cl::opt<bool>
126e8d8bef9SDimitry Andric UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
127e8d8bef9SDimitry Andric cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
128e8d8bef9SDimitry Andric cl::init(false));
129e8d8bef9SDimitry Andric
130e8d8bef9SDimitry Andric static cl::opt<DefaultOnOff> DwarfOpConvert(
131e8d8bef9SDimitry Andric "dwarf-op-convert", cl::Hidden,
132e8d8bef9SDimitry Andric cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
133e8d8bef9SDimitry Andric cl::values(clEnumVal(Default, "Default for platform"),
134e8d8bef9SDimitry Andric clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
135e8d8bef9SDimitry Andric cl::init(Default));
136e8d8bef9SDimitry Andric
1370b57cec5SDimitry Andric enum LinkageNameOption {
1380b57cec5SDimitry Andric DefaultLinkageNames,
1390b57cec5SDimitry Andric AllLinkageNames,
1400b57cec5SDimitry Andric AbstractLinkageNames
1410b57cec5SDimitry Andric };
1420b57cec5SDimitry Andric
1430b57cec5SDimitry Andric static cl::opt<LinkageNameOption>
1440b57cec5SDimitry Andric DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
1450b57cec5SDimitry Andric cl::desc("Which DWARF linkage-name attributes to emit."),
1460b57cec5SDimitry Andric cl::values(clEnumValN(DefaultLinkageNames, "Default",
1470b57cec5SDimitry Andric "Default for platform"),
1480b57cec5SDimitry Andric clEnumValN(AllLinkageNames, "All", "All"),
1490b57cec5SDimitry Andric clEnumValN(AbstractLinkageNames, "Abstract",
1500b57cec5SDimitry Andric "Abstract subprograms")),
1510b57cec5SDimitry Andric cl::init(DefaultLinkageNames));
1520b57cec5SDimitry Andric
153e8d8bef9SDimitry Andric static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
154e8d8bef9SDimitry Andric "minimize-addr-in-v5", cl::Hidden,
155e8d8bef9SDimitry Andric cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
156e8d8bef9SDimitry Andric "address pool entry sharing to reduce relocations/object size"),
157e8d8bef9SDimitry Andric cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",
158e8d8bef9SDimitry Andric "Default address minimization strategy"),
159e8d8bef9SDimitry Andric clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",
160e8d8bef9SDimitry Andric "Use rnglists for contiguous ranges if that allows "
161e8d8bef9SDimitry Andric "using a pre-existing base address"),
162fe6060f1SDimitry Andric clEnumValN(DwarfDebug::MinimizeAddrInV5::Expressions,
163fe6060f1SDimitry Andric "Expressions",
164fe6060f1SDimitry Andric "Use exprloc addrx+offset expressions for any "
165fe6060f1SDimitry Andric "address with a prior base address"),
166fe6060f1SDimitry Andric clEnumValN(DwarfDebug::MinimizeAddrInV5::Form, "Form",
167fe6060f1SDimitry Andric "Use addrx+offset extension form for any address "
168fe6060f1SDimitry Andric "with a prior base address"),
169e8d8bef9SDimitry Andric clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",
170e8d8bef9SDimitry Andric "Stuff")),
171e8d8bef9SDimitry Andric cl::init(DwarfDebug::MinimizeAddrInV5::Default));
1725ffd83dbSDimitry Andric
1730b57cec5SDimitry Andric static constexpr unsigned ULEB128PadSize = 4;
1740b57cec5SDimitry Andric
emitOp(uint8_t Op,const char * Comment)1750b57cec5SDimitry Andric void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
176e8d8bef9SDimitry Andric getActiveStreamer().emitInt8(
1770b57cec5SDimitry Andric Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
1780b57cec5SDimitry Andric : dwarf::OperationEncodingString(Op));
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric
emitSigned(int64_t Value)1810b57cec5SDimitry Andric void DebugLocDwarfExpression::emitSigned(int64_t Value) {
1825ffd83dbSDimitry Andric getActiveStreamer().emitSLEB128(Value, Twine(Value));
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric
emitUnsigned(uint64_t Value)1850b57cec5SDimitry Andric void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
1865ffd83dbSDimitry Andric getActiveStreamer().emitULEB128(Value, Twine(Value));
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric
emitData1(uint8_t Value)1890b57cec5SDimitry Andric void DebugLocDwarfExpression::emitData1(uint8_t Value) {
190e8d8bef9SDimitry Andric getActiveStreamer().emitInt8(Value, Twine(Value));
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric
emitBaseTypeRef(uint64_t Idx)1930b57cec5SDimitry Andric void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
1940b57cec5SDimitry Andric assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
1955ffd83dbSDimitry Andric getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric
isFrameRegister(const TargetRegisterInfo & TRI,llvm::Register MachineReg)1980b57cec5SDimitry Andric bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
199e8d8bef9SDimitry Andric llvm::Register MachineReg) {
2000b57cec5SDimitry Andric // This information is not available while emitting .debug_loc entries.
2010b57cec5SDimitry Andric return false;
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric
enableTemporaryBuffer()2048bcb0991SDimitry Andric void DebugLocDwarfExpression::enableTemporaryBuffer() {
2058bcb0991SDimitry Andric assert(!IsBuffering && "Already buffering?");
2068bcb0991SDimitry Andric if (!TmpBuf)
2078bcb0991SDimitry Andric TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
2088bcb0991SDimitry Andric IsBuffering = true;
2098bcb0991SDimitry Andric }
2108bcb0991SDimitry Andric
disableTemporaryBuffer()2118bcb0991SDimitry Andric void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
2128bcb0991SDimitry Andric
getTemporaryBufferSize()2138bcb0991SDimitry Andric unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
2148bcb0991SDimitry Andric return TmpBuf ? TmpBuf->Bytes.size() : 0;
2158bcb0991SDimitry Andric }
2168bcb0991SDimitry Andric
commitTemporaryBuffer()2178bcb0991SDimitry Andric void DebugLocDwarfExpression::commitTemporaryBuffer() {
2188bcb0991SDimitry Andric if (!TmpBuf)
2198bcb0991SDimitry Andric return;
2208bcb0991SDimitry Andric for (auto Byte : enumerate(TmpBuf->Bytes)) {
2218bcb0991SDimitry Andric const char *Comment = (Byte.index() < TmpBuf->Comments.size())
2228bcb0991SDimitry Andric ? TmpBuf->Comments[Byte.index()].c_str()
2238bcb0991SDimitry Andric : "";
224e8d8bef9SDimitry Andric OutBS.emitInt8(Byte.value(), Comment);
2258bcb0991SDimitry Andric }
2268bcb0991SDimitry Andric TmpBuf->Bytes.clear();
2278bcb0991SDimitry Andric TmpBuf->Comments.clear();
2280b57cec5SDimitry Andric }
2290b57cec5SDimitry Andric
getType() const2300b57cec5SDimitry Andric const DIType *DbgVariable::getType() const {
2318bcb0991SDimitry Andric return getVariable()->getType();
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric
2340b57cec5SDimitry Andric /// Get .debug_loc entry for the instruction range starting at MI.
getDebugLocValue(const MachineInstr * MI)2350b57cec5SDimitry Andric static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
2360b57cec5SDimitry Andric const DIExpression *Expr = MI->getDebugExpression();
2375f757f3fSDimitry Andric auto SingleLocExprOpt = DIExpression::convertToNonVariadicExpression(Expr);
2385f757f3fSDimitry Andric const bool IsVariadic = !SingleLocExprOpt;
2395f757f3fSDimitry Andric // If we have a variadic debug value instruction that is equivalent to a
2405f757f3fSDimitry Andric // non-variadic instruction, then convert it to non-variadic form here.
2415f757f3fSDimitry Andric if (!IsVariadic && !MI->isNonListDebugValue()) {
2425f757f3fSDimitry Andric assert(MI->getNumDebugOperands() == 1 &&
2435f757f3fSDimitry Andric "Mismatched DIExpression and debug operands for debug instruction.");
2445f757f3fSDimitry Andric Expr = *SingleLocExprOpt;
2455f757f3fSDimitry Andric }
246fe6060f1SDimitry Andric assert(MI->getNumOperands() >= 3);
247fe6060f1SDimitry Andric SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
248fe6060f1SDimitry Andric for (const MachineOperand &Op : MI->debug_operands()) {
249fe6060f1SDimitry Andric if (Op.isReg()) {
250fe6060f1SDimitry Andric MachineLocation MLoc(Op.getReg(),
251fe6060f1SDimitry Andric MI->isNonListDebugValue() && MI->isDebugOffsetImm());
252fe6060f1SDimitry Andric DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
253fe6060f1SDimitry Andric } else if (Op.isTargetIndex()) {
254fe6060f1SDimitry Andric DbgValueLocEntries.push_back(
255fe6060f1SDimitry Andric DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
256fe6060f1SDimitry Andric } else if (Op.isImm())
257fe6060f1SDimitry Andric DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
258fe6060f1SDimitry Andric else if (Op.isFPImm())
259fe6060f1SDimitry Andric DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
260fe6060f1SDimitry Andric else if (Op.isCImm())
261fe6060f1SDimitry Andric DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
262fe6060f1SDimitry Andric else
263fe6060f1SDimitry Andric llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
2640b57cec5SDimitry Andric }
265fe6060f1SDimitry Andric return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric
getFragmentOffsetInBits(const DIExpression & Expr)2685f757f3fSDimitry Andric static uint64_t getFragmentOffsetInBits(const DIExpression &Expr) {
2695f757f3fSDimitry Andric std::optional<DIExpression::FragmentInfo> Fragment = Expr.getFragmentInfo();
2705f757f3fSDimitry Andric return Fragment ? Fragment->OffsetInBits : 0;
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric
operator <(const FrameIndexExpr & LHS,const FrameIndexExpr & RHS)2735f757f3fSDimitry Andric bool llvm::operator<(const FrameIndexExpr &LHS, const FrameIndexExpr &RHS) {
2745f757f3fSDimitry Andric return getFragmentOffsetInBits(*LHS.Expr) <
2755f757f3fSDimitry Andric getFragmentOffsetInBits(*RHS.Expr);
2765f757f3fSDimitry Andric }
2770b57cec5SDimitry Andric
operator <(const EntryValueInfo & LHS,const EntryValueInfo & RHS)2785f757f3fSDimitry Andric bool llvm::operator<(const EntryValueInfo &LHS, const EntryValueInfo &RHS) {
2795f757f3fSDimitry Andric return getFragmentOffsetInBits(LHS.Expr) < getFragmentOffsetInBits(RHS.Expr);
2805f757f3fSDimitry Andric }
2810b57cec5SDimitry Andric
Single(DbgValueLoc ValueLoc)2825f757f3fSDimitry Andric Loc::Single::Single(DbgValueLoc ValueLoc)
2835f757f3fSDimitry Andric : ValueLoc(std::make_unique<DbgValueLoc>(ValueLoc)),
2845f757f3fSDimitry Andric Expr(ValueLoc.getExpression()) {
2855f757f3fSDimitry Andric if (!Expr->getNumElements())
2865f757f3fSDimitry Andric Expr = nullptr;
2875f757f3fSDimitry Andric }
2885f757f3fSDimitry Andric
Single(const MachineInstr * DbgValue)2895f757f3fSDimitry Andric Loc::Single::Single(const MachineInstr *DbgValue)
2905f757f3fSDimitry Andric : Single(getDebugLocValue(DbgValue)) {}
2915f757f3fSDimitry Andric
getFrameIndexExprs() const2925f757f3fSDimitry Andric const std::set<FrameIndexExpr> &Loc::MMI::getFrameIndexExprs() const {
2930b57cec5SDimitry Andric return FrameIndexExprs;
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric
addFrameIndexExpr(const DIExpression * Expr,int FI)2965f757f3fSDimitry Andric void Loc::MMI::addFrameIndexExpr(const DIExpression *Expr, int FI) {
2975f757f3fSDimitry Andric FrameIndexExprs.insert({FI, Expr});
2980b57cec5SDimitry Andric assert((FrameIndexExprs.size() == 1 ||
2990b57cec5SDimitry Andric llvm::all_of(FrameIndexExprs,
3005f757f3fSDimitry Andric [](const FrameIndexExpr &FIE) {
3010b57cec5SDimitry Andric return FIE.Expr && FIE.Expr->isFragment();
3020b57cec5SDimitry Andric })) &&
3030b57cec5SDimitry Andric "conflicting locations for variable");
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric
computeAccelTableKind(unsigned DwarfVersion,bool GenerateTypeUnits,DebuggerKind Tuning,const Triple & TT)3060b57cec5SDimitry Andric static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
3070b57cec5SDimitry Andric bool GenerateTypeUnits,
3080b57cec5SDimitry Andric DebuggerKind Tuning,
3090b57cec5SDimitry Andric const Triple &TT) {
3100b57cec5SDimitry Andric // Honor an explicit request.
3110b57cec5SDimitry Andric if (AccelTables != AccelTableKind::Default)
3120b57cec5SDimitry Andric return AccelTables;
3130b57cec5SDimitry Andric
3145f757f3fSDimitry Andric // Generating DWARF5 acceleration table.
3155f757f3fSDimitry Andric // Currently Split dwarf and non ELF format is not supported.
3165f757f3fSDimitry Andric if (GenerateTypeUnits && (DwarfVersion < 5 || !TT.isOSBinFormatELF()))
3170b57cec5SDimitry Andric return AccelTableKind::None;
3180b57cec5SDimitry Andric
3190b57cec5SDimitry Andric // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
3200b57cec5SDimitry Andric // always implies debug_names. For lower standard versions we use apple
3210b57cec5SDimitry Andric // accelerator tables on apple platforms and debug_names elsewhere.
3220b57cec5SDimitry Andric if (DwarfVersion >= 5)
3230b57cec5SDimitry Andric return AccelTableKind::Dwarf;
3240b57cec5SDimitry Andric if (Tuning == DebuggerKind::LLDB)
3250b57cec5SDimitry Andric return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
3260b57cec5SDimitry Andric : AccelTableKind::Dwarf;
3270b57cec5SDimitry Andric return AccelTableKind::None;
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric
DwarfDebug(AsmPrinter * A)330e8d8bef9SDimitry Andric DwarfDebug::DwarfDebug(AsmPrinter *A)
3310b57cec5SDimitry Andric : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
3320b57cec5SDimitry Andric InfoHolder(A, "info_string", DIEValueAllocator),
3330b57cec5SDimitry Andric SkeletonHolder(A, "skel_string", DIEValueAllocator),
3340b57cec5SDimitry Andric IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
3350b57cec5SDimitry Andric const Triple &TT = Asm->TM.getTargetTriple();
3360b57cec5SDimitry Andric
3370b57cec5SDimitry Andric // Make sure we know our "debugger tuning". The target option takes
3380b57cec5SDimitry Andric // precedence; fall back to triple-based defaults.
3390b57cec5SDimitry Andric if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
3400b57cec5SDimitry Andric DebuggerTuning = Asm->TM.Options.DebuggerTuning;
3410b57cec5SDimitry Andric else if (IsDarwin)
3420b57cec5SDimitry Andric DebuggerTuning = DebuggerKind::LLDB;
34381ad6265SDimitry Andric else if (TT.isPS())
3440b57cec5SDimitry Andric DebuggerTuning = DebuggerKind::SCE;
345fe6060f1SDimitry Andric else if (TT.isOSAIX())
346fe6060f1SDimitry Andric DebuggerTuning = DebuggerKind::DBX;
3470b57cec5SDimitry Andric else
3480b57cec5SDimitry Andric DebuggerTuning = DebuggerKind::GDB;
3490b57cec5SDimitry Andric
3500b57cec5SDimitry Andric if (DwarfInlinedStrings == Default)
351fe6060f1SDimitry Andric UseInlineStrings = TT.isNVPTX() || tuneForDBX();
3520b57cec5SDimitry Andric else
3530b57cec5SDimitry Andric UseInlineStrings = DwarfInlinedStrings == Enable;
3540b57cec5SDimitry Andric
3550b57cec5SDimitry Andric UseLocSection = !TT.isNVPTX();
3560b57cec5SDimitry Andric
3570b57cec5SDimitry Andric HasAppleExtensionAttributes = tuneForLLDB();
3580b57cec5SDimitry Andric
3590b57cec5SDimitry Andric // Handle split DWARF.
3600b57cec5SDimitry Andric HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
3610b57cec5SDimitry Andric
3620b57cec5SDimitry Andric // SCE defaults to linkage names only for abstract subprograms.
3630b57cec5SDimitry Andric if (DwarfLinkageNames == DefaultLinkageNames)
3640b57cec5SDimitry Andric UseAllLinkageNames = !tuneForSCE();
3650b57cec5SDimitry Andric else
3660b57cec5SDimitry Andric UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
3670b57cec5SDimitry Andric
3680b57cec5SDimitry Andric unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
3690b57cec5SDimitry Andric unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
3700b57cec5SDimitry Andric : MMI->getModule()->getDwarfVersion();
3710b57cec5SDimitry Andric // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
3720b57cec5SDimitry Andric DwarfVersion =
3730b57cec5SDimitry Andric TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
3740b57cec5SDimitry Andric
375fe6060f1SDimitry Andric bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
376fe6060f1SDimitry Andric TT.isArch64Bit(); // DWARF64 requires 64-bit relocations.
377fe6060f1SDimitry Andric
378fe6060f1SDimitry Andric // Support DWARF64
379fe6060f1SDimitry Andric // 1: For ELF when requested.
380fe6060f1SDimitry Andric // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
381fe6060f1SDimitry Andric // according to the DWARF64 format for 64-bit assembly, so we must use
382fe6060f1SDimitry Andric // DWARF64 in the compiler too for 64-bit mode.
383fe6060f1SDimitry Andric Dwarf64 &=
384fe6060f1SDimitry Andric ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
385fe6060f1SDimitry Andric TT.isOSBinFormatELF()) ||
386fe6060f1SDimitry Andric TT.isOSBinFormatXCOFF();
387fe6060f1SDimitry Andric
388fe6060f1SDimitry Andric if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
389fe6060f1SDimitry Andric report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
390e8d8bef9SDimitry Andric
3910b57cec5SDimitry Andric UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
3920b57cec5SDimitry Andric
3930b57cec5SDimitry Andric // Use sections as references. Force for NVPTX.
3940b57cec5SDimitry Andric if (DwarfSectionsAsReferences == Default)
3950b57cec5SDimitry Andric UseSectionsAsReferences = TT.isNVPTX();
3960b57cec5SDimitry Andric else
3970b57cec5SDimitry Andric UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
3980b57cec5SDimitry Andric
3990b57cec5SDimitry Andric // Don't generate type units for unsupported object file formats.
400e8d8bef9SDimitry Andric GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
401e8d8bef9SDimitry Andric A->TM.getTargetTriple().isOSBinFormatWasm()) &&
402e8d8bef9SDimitry Andric GenerateDwarfTypeUnits;
4030b57cec5SDimitry Andric
4040b57cec5SDimitry Andric TheAccelTableKind = computeAccelTableKind(
4050b57cec5SDimitry Andric DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
4060b57cec5SDimitry Andric
4070b57cec5SDimitry Andric // Work around a GDB bug. GDB doesn't support the standard opcode;
4080b57cec5SDimitry Andric // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
4090b57cec5SDimitry Andric // is defined as of DWARF 3.
4100b57cec5SDimitry Andric // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
4110b57cec5SDimitry Andric // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
4120b57cec5SDimitry Andric UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
4130b57cec5SDimitry Andric
414bdd1243dSDimitry Andric UseDWARF2Bitfields = DwarfVersion < 4;
4150b57cec5SDimitry Andric
4160b57cec5SDimitry Andric // The DWARF v5 string offsets table has - possibly shared - contributions
4170b57cec5SDimitry Andric // from each compile and type unit each preceded by a header. The string
4180b57cec5SDimitry Andric // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
4190b57cec5SDimitry Andric // a monolithic string offsets table without any header.
4200b57cec5SDimitry Andric UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
4210b57cec5SDimitry Andric
4225ffd83dbSDimitry Andric // Emit call-site-param debug info for GDB and LLDB, if the target supports
4235ffd83dbSDimitry Andric // the debug entry values feature. It can also be enabled explicitly.
424e8d8bef9SDimitry Andric EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
425e8d8bef9SDimitry Andric
426e8d8bef9SDimitry Andric // It is unclear if the GCC .debug_macro extension is well-specified
427e8d8bef9SDimitry Andric // for split DWARF. For now, do not allow LLVM to emit it.
428e8d8bef9SDimitry Andric UseDebugMacroSection =
429e8d8bef9SDimitry Andric DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
430e8d8bef9SDimitry Andric if (DwarfOpConvert == Default)
431e8d8bef9SDimitry Andric EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
432e8d8bef9SDimitry Andric else
433e8d8bef9SDimitry Andric EnableOpConvert = (DwarfOpConvert == Enable);
434e8d8bef9SDimitry Andric
435e8d8bef9SDimitry Andric // Split DWARF would benefit object size significantly by trading reductions
436e8d8bef9SDimitry Andric // in address pool usage for slightly increased range list encodings.
43706c3fb27SDimitry Andric if (DwarfVersion >= 5)
438e8d8bef9SDimitry Andric MinimizeAddr = MinimizeAddrInV5Option;
4395ffd83dbSDimitry Andric
4400b57cec5SDimitry Andric Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
441e8d8bef9SDimitry Andric Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
442e8d8bef9SDimitry Andric : dwarf::DWARF32);
4430b57cec5SDimitry Andric }
4440b57cec5SDimitry Andric
4450b57cec5SDimitry Andric // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
4460b57cec5SDimitry Andric DwarfDebug::~DwarfDebug() = default;
4470b57cec5SDimitry Andric
isObjCClass(StringRef Name)4480b57cec5SDimitry Andric static bool isObjCClass(StringRef Name) {
4495f757f3fSDimitry Andric return Name.starts_with("+") || Name.starts_with("-");
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric
hasObjCCategory(StringRef Name)4520b57cec5SDimitry Andric static bool hasObjCCategory(StringRef Name) {
4530b57cec5SDimitry Andric if (!isObjCClass(Name))
4540b57cec5SDimitry Andric return false;
4550b57cec5SDimitry Andric
456349cc55cSDimitry Andric return Name.contains(") ");
4570b57cec5SDimitry Andric }
4580b57cec5SDimitry Andric
getObjCClassCategory(StringRef In,StringRef & Class,StringRef & Category)4590b57cec5SDimitry Andric static void getObjCClassCategory(StringRef In, StringRef &Class,
4600b57cec5SDimitry Andric StringRef &Category) {
4610b57cec5SDimitry Andric if (!hasObjCCategory(In)) {
4620b57cec5SDimitry Andric Class = In.slice(In.find('[') + 1, In.find(' '));
4630b57cec5SDimitry Andric Category = "";
4640b57cec5SDimitry Andric return;
4650b57cec5SDimitry Andric }
4660b57cec5SDimitry Andric
4670b57cec5SDimitry Andric Class = In.slice(In.find('[') + 1, In.find('('));
4680b57cec5SDimitry Andric Category = In.slice(In.find('[') + 1, In.find(' '));
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric
getObjCMethodName(StringRef In)4710b57cec5SDimitry Andric static StringRef getObjCMethodName(StringRef In) {
4720b57cec5SDimitry Andric return In.slice(In.find(' ') + 1, In.find(']'));
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric // Add the various names to the Dwarf accelerator table names.
addSubprogramNames(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,const DISubprogram * SP,DIE & Die)4765f757f3fSDimitry Andric void DwarfDebug::addSubprogramNames(
4775f757f3fSDimitry Andric const DwarfUnit &Unit,
4785f757f3fSDimitry Andric const DICompileUnit::DebugNameTableKind NameTableKind,
4790b57cec5SDimitry Andric const DISubprogram *SP, DIE &Die) {
4800b57cec5SDimitry Andric if (getAccelTableKind() != AccelTableKind::Apple &&
4815f757f3fSDimitry Andric NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&
4825f757f3fSDimitry Andric NameTableKind == DICompileUnit::DebugNameTableKind::None)
4830b57cec5SDimitry Andric return;
4840b57cec5SDimitry Andric
4850b57cec5SDimitry Andric if (!SP->isDefinition())
4860b57cec5SDimitry Andric return;
4870b57cec5SDimitry Andric
4880b57cec5SDimitry Andric if (SP->getName() != "")
4895f757f3fSDimitry Andric addAccelName(Unit, NameTableKind, SP->getName(), Die);
4900b57cec5SDimitry Andric
4910b57cec5SDimitry Andric // If the linkage name is different than the name, go ahead and output that as
4920b57cec5SDimitry Andric // well into the name table. Only do that if we are going to actually emit
4930b57cec5SDimitry Andric // that name.
4940b57cec5SDimitry Andric if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
49506c3fb27SDimitry Andric (useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(SP)))
4965f757f3fSDimitry Andric addAccelName(Unit, NameTableKind, SP->getLinkageName(), Die);
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric // If this is an Objective-C selector name add it to the ObjC accelerator
4990b57cec5SDimitry Andric // too.
5000b57cec5SDimitry Andric if (isObjCClass(SP->getName())) {
5010b57cec5SDimitry Andric StringRef Class, Category;
5020b57cec5SDimitry Andric getObjCClassCategory(SP->getName(), Class, Category);
5035f757f3fSDimitry Andric addAccelObjC(Unit, NameTableKind, Class, Die);
5040b57cec5SDimitry Andric if (Category != "")
5055f757f3fSDimitry Andric addAccelObjC(Unit, NameTableKind, Category, Die);
5060b57cec5SDimitry Andric // Also add the base method name to the name table.
5075f757f3fSDimitry Andric addAccelName(Unit, NameTableKind, getObjCMethodName(SP->getName()), Die);
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric }
5100b57cec5SDimitry Andric
5110b57cec5SDimitry Andric /// Check whether we should create a DIE for the given Scope, return true
5120b57cec5SDimitry Andric /// if we don't create a DIE (the corresponding DIE is null).
isLexicalScopeDIENull(LexicalScope * Scope)5130b57cec5SDimitry Andric bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
5140b57cec5SDimitry Andric if (Scope->isAbstractScope())
5150b57cec5SDimitry Andric return false;
5160b57cec5SDimitry Andric
5170b57cec5SDimitry Andric // We don't create a DIE if there is no Range.
5180b57cec5SDimitry Andric const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
5190b57cec5SDimitry Andric if (Ranges.empty())
5200b57cec5SDimitry Andric return true;
5210b57cec5SDimitry Andric
5220b57cec5SDimitry Andric if (Ranges.size() > 1)
5230b57cec5SDimitry Andric return false;
5240b57cec5SDimitry Andric
5250b57cec5SDimitry Andric // We don't create a DIE if we have a single Range and the end label
5260b57cec5SDimitry Andric // is null.
5270b57cec5SDimitry Andric return !getLabelAfterInsn(Ranges.front().second);
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric
forBothCUs(DwarfCompileUnit & CU,Func F)5300b57cec5SDimitry Andric template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
5310b57cec5SDimitry Andric F(CU);
5320b57cec5SDimitry Andric if (auto *SkelCU = CU.getSkeleton())
5330b57cec5SDimitry Andric if (CU.getCUNode()->getSplitDebugInlining())
5340b57cec5SDimitry Andric F(*SkelCU);
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric
shareAcrossDWOCUs() const5370b57cec5SDimitry Andric bool DwarfDebug::shareAcrossDWOCUs() const {
5380b57cec5SDimitry Andric return SplitDwarfCrossCuReferences;
5390b57cec5SDimitry Andric }
5400b57cec5SDimitry Andric
constructAbstractSubprogramScopeDIE(DwarfCompileUnit & SrcCU,LexicalScope * Scope)5410b57cec5SDimitry Andric void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
5420b57cec5SDimitry Andric LexicalScope *Scope) {
5430b57cec5SDimitry Andric assert(Scope && Scope->getScopeNode());
5440b57cec5SDimitry Andric assert(Scope->isAbstractScope());
5450b57cec5SDimitry Andric assert(!Scope->getInlinedAt());
5460b57cec5SDimitry Andric
5470b57cec5SDimitry Andric auto *SP = cast<DISubprogram>(Scope->getScopeNode());
5480b57cec5SDimitry Andric
5490b57cec5SDimitry Andric // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
5500b57cec5SDimitry Andric // was inlined from another compile unit.
5510b57cec5SDimitry Andric if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
5520b57cec5SDimitry Andric // Avoid building the original CU if it won't be used
5530b57cec5SDimitry Andric SrcCU.constructAbstractSubprogramScopeDIE(Scope);
5540b57cec5SDimitry Andric else {
5550b57cec5SDimitry Andric auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
5560b57cec5SDimitry Andric if (auto *SkelCU = CU.getSkeleton()) {
5570b57cec5SDimitry Andric (shareAcrossDWOCUs() ? CU : SrcCU)
5580b57cec5SDimitry Andric .constructAbstractSubprogramScopeDIE(Scope);
5590b57cec5SDimitry Andric if (CU.getCUNode()->getSplitDebugInlining())
5600b57cec5SDimitry Andric SkelCU->constructAbstractSubprogramScopeDIE(Scope);
5610b57cec5SDimitry Andric } else
5620b57cec5SDimitry Andric CU.constructAbstractSubprogramScopeDIE(Scope);
5630b57cec5SDimitry Andric }
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric
5665ffd83dbSDimitry Andric /// Represents a parameter whose call site value can be described by applying a
5675ffd83dbSDimitry Andric /// debug expression to a register in the forwarded register worklist.
5685ffd83dbSDimitry Andric struct FwdRegParamInfo {
5695ffd83dbSDimitry Andric /// The described parameter register.
5705ffd83dbSDimitry Andric unsigned ParamReg;
5715ffd83dbSDimitry Andric
5725ffd83dbSDimitry Andric /// Debug expression that has been built up when walking through the
5735ffd83dbSDimitry Andric /// instruction chain that produces the parameter's value.
5745ffd83dbSDimitry Andric const DIExpression *Expr;
5755ffd83dbSDimitry Andric };
5765ffd83dbSDimitry Andric
5775ffd83dbSDimitry Andric /// Register worklist for finding call site values.
5785ffd83dbSDimitry Andric using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
579bdd1243dSDimitry Andric /// Container for the set of registers known to be clobbered on the path to a
580bdd1243dSDimitry Andric /// call site.
581bdd1243dSDimitry Andric using ClobberedRegSet = SmallSet<Register, 16>;
5825ffd83dbSDimitry Andric
5835ffd83dbSDimitry Andric /// Append the expression \p Addition to \p Original and return the result.
combineDIExpressions(const DIExpression * Original,const DIExpression * Addition)5845ffd83dbSDimitry Andric static const DIExpression *combineDIExpressions(const DIExpression *Original,
5855ffd83dbSDimitry Andric const DIExpression *Addition) {
5865ffd83dbSDimitry Andric std::vector<uint64_t> Elts = Addition->getElements().vec();
5875ffd83dbSDimitry Andric // Avoid multiple DW_OP_stack_values.
5885ffd83dbSDimitry Andric if (Original->isImplicit() && Addition->isImplicit())
5895f757f3fSDimitry Andric llvm::erase(Elts, dwarf::DW_OP_stack_value);
5905ffd83dbSDimitry Andric const DIExpression *CombinedExpr =
5915ffd83dbSDimitry Andric (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
5925ffd83dbSDimitry Andric return CombinedExpr;
5935ffd83dbSDimitry Andric }
5945ffd83dbSDimitry Andric
5955ffd83dbSDimitry Andric /// Emit call site parameter entries that are described by the given value and
5965ffd83dbSDimitry Andric /// debug expression.
5975ffd83dbSDimitry Andric template <typename ValT>
finishCallSiteParams(ValT Val,const DIExpression * Expr,ArrayRef<FwdRegParamInfo> DescribedParams,ParamSet & Params)5985ffd83dbSDimitry Andric static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
5995ffd83dbSDimitry Andric ArrayRef<FwdRegParamInfo> DescribedParams,
6005ffd83dbSDimitry Andric ParamSet &Params) {
6015ffd83dbSDimitry Andric for (auto Param : DescribedParams) {
6025ffd83dbSDimitry Andric bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
6035ffd83dbSDimitry Andric
6045ffd83dbSDimitry Andric // TODO: Entry value operations can currently not be combined with any
6055ffd83dbSDimitry Andric // other expressions, so we can't emit call site entries in those cases.
6065ffd83dbSDimitry Andric if (ShouldCombineExpressions && Expr->isEntryValue())
6075ffd83dbSDimitry Andric continue;
6085ffd83dbSDimitry Andric
6095ffd83dbSDimitry Andric // If a parameter's call site value is produced by a chain of
6105ffd83dbSDimitry Andric // instructions we may have already created an expression for the
6115ffd83dbSDimitry Andric // parameter when walking through the instructions. Append that to the
6125ffd83dbSDimitry Andric // base expression.
6135ffd83dbSDimitry Andric const DIExpression *CombinedExpr =
6145ffd83dbSDimitry Andric ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
6155ffd83dbSDimitry Andric : Expr;
6165ffd83dbSDimitry Andric assert((!CombinedExpr || CombinedExpr->isValid()) &&
6175ffd83dbSDimitry Andric "Combined debug expression is invalid");
6185ffd83dbSDimitry Andric
619fe6060f1SDimitry Andric DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
6205ffd83dbSDimitry Andric DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
6215ffd83dbSDimitry Andric Params.push_back(CSParm);
6225ffd83dbSDimitry Andric ++NumCSParams;
6235ffd83dbSDimitry Andric }
6245ffd83dbSDimitry Andric }
6255ffd83dbSDimitry Andric
6265ffd83dbSDimitry Andric /// Add \p Reg to the worklist, if it's not already present, and mark that the
6275ffd83dbSDimitry Andric /// given parameter registers' values can (potentially) be described using
6285ffd83dbSDimitry Andric /// that register and an debug expression.
addToFwdRegWorklist(FwdRegWorklist & Worklist,unsigned Reg,const DIExpression * Expr,ArrayRef<FwdRegParamInfo> ParamsToAdd)6295ffd83dbSDimitry Andric static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
6305ffd83dbSDimitry Andric const DIExpression *Expr,
6315ffd83dbSDimitry Andric ArrayRef<FwdRegParamInfo> ParamsToAdd) {
6325ffd83dbSDimitry Andric auto I = Worklist.insert({Reg, {}});
6335ffd83dbSDimitry Andric auto &ParamsForFwdReg = I.first->second;
6345ffd83dbSDimitry Andric for (auto Param : ParamsToAdd) {
6355ffd83dbSDimitry Andric assert(none_of(ParamsForFwdReg,
6365ffd83dbSDimitry Andric [Param](const FwdRegParamInfo &D) {
6375ffd83dbSDimitry Andric return D.ParamReg == Param.ParamReg;
6385ffd83dbSDimitry Andric }) &&
6395ffd83dbSDimitry Andric "Same parameter described twice by forwarding reg");
6405ffd83dbSDimitry Andric
6415ffd83dbSDimitry Andric // If a parameter's call site value is produced by a chain of
6425ffd83dbSDimitry Andric // instructions we may have already created an expression for the
6435ffd83dbSDimitry Andric // parameter when walking through the instructions. Append that to the
6445ffd83dbSDimitry Andric // new expression.
6455ffd83dbSDimitry Andric const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
6465ffd83dbSDimitry Andric ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
6475ffd83dbSDimitry Andric }
6485ffd83dbSDimitry Andric }
6495ffd83dbSDimitry Andric
6505ffd83dbSDimitry Andric /// Interpret values loaded into registers by \p CurMI.
interpretValues(const MachineInstr * CurMI,FwdRegWorklist & ForwardedRegWorklist,ParamSet & Params,ClobberedRegSet & ClobberedRegUnits)6515ffd83dbSDimitry Andric static void interpretValues(const MachineInstr *CurMI,
6525ffd83dbSDimitry Andric FwdRegWorklist &ForwardedRegWorklist,
653bdd1243dSDimitry Andric ParamSet &Params,
654bdd1243dSDimitry Andric ClobberedRegSet &ClobberedRegUnits) {
6555ffd83dbSDimitry Andric
6565ffd83dbSDimitry Andric const MachineFunction *MF = CurMI->getMF();
6575ffd83dbSDimitry Andric const DIExpression *EmptyExpr =
6585ffd83dbSDimitry Andric DIExpression::get(MF->getFunction().getContext(), {});
6595ffd83dbSDimitry Andric const auto &TRI = *MF->getSubtarget().getRegisterInfo();
6605ffd83dbSDimitry Andric const auto &TII = *MF->getSubtarget().getInstrInfo();
6615ffd83dbSDimitry Andric const auto &TLI = *MF->getSubtarget().getTargetLowering();
6625ffd83dbSDimitry Andric
6635ffd83dbSDimitry Andric // If an instruction defines more than one item in the worklist, we may run
6645ffd83dbSDimitry Andric // into situations where a worklist register's value is (potentially)
6655ffd83dbSDimitry Andric // described by the previous value of another register that is also defined
6665ffd83dbSDimitry Andric // by that instruction.
6675ffd83dbSDimitry Andric //
6685ffd83dbSDimitry Andric // This can for example occur in cases like this:
6695ffd83dbSDimitry Andric //
6705ffd83dbSDimitry Andric // $r1 = mov 123
6715ffd83dbSDimitry Andric // $r0, $r1 = mvrr $r1, 456
6725ffd83dbSDimitry Andric // call @foo, $r0, $r1
6735ffd83dbSDimitry Andric //
6745ffd83dbSDimitry Andric // When describing $r1's value for the mvrr instruction, we need to make sure
6755ffd83dbSDimitry Andric // that we don't finalize an entry value for $r0, as that is dependent on the
6765ffd83dbSDimitry Andric // previous value of $r1 (123 rather than 456).
6775ffd83dbSDimitry Andric //
6785ffd83dbSDimitry Andric // In order to not have to distinguish between those cases when finalizing
6795ffd83dbSDimitry Andric // entry values, we simply postpone adding new parameter registers to the
6805ffd83dbSDimitry Andric // worklist, by first keeping them in this temporary container until the
6815ffd83dbSDimitry Andric // instruction has been handled.
6825ffd83dbSDimitry Andric FwdRegWorklist TmpWorklistItems;
6835ffd83dbSDimitry Andric
6845ffd83dbSDimitry Andric // If the MI is an instruction defining one or more parameters' forwarding
6855ffd83dbSDimitry Andric // registers, add those defines.
686bdd1243dSDimitry Andric ClobberedRegSet NewClobberedRegUnits;
6875ffd83dbSDimitry Andric auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
6885ffd83dbSDimitry Andric SmallSetVector<unsigned, 4> &Defs) {
6895ffd83dbSDimitry Andric if (MI.isDebugInstr())
6905ffd83dbSDimitry Andric return;
6915ffd83dbSDimitry Andric
69206c3fb27SDimitry Andric for (const MachineOperand &MO : MI.all_defs()) {
69306c3fb27SDimitry Andric if (MO.getReg().isPhysical()) {
694fe6060f1SDimitry Andric for (auto &FwdReg : ForwardedRegWorklist)
6955ffd83dbSDimitry Andric if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
6965ffd83dbSDimitry Andric Defs.insert(FwdReg.first);
69706c3fb27SDimitry Andric for (MCRegUnit Unit : TRI.regunits(MO.getReg()))
69806c3fb27SDimitry Andric NewClobberedRegUnits.insert(Unit);
6995ffd83dbSDimitry Andric }
7005ffd83dbSDimitry Andric }
7015ffd83dbSDimitry Andric };
7025ffd83dbSDimitry Andric
7035ffd83dbSDimitry Andric // Set of worklist registers that are defined by this instruction.
7045ffd83dbSDimitry Andric SmallSetVector<unsigned, 4> FwdRegDefs;
7055ffd83dbSDimitry Andric
7065ffd83dbSDimitry Andric getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
707bdd1243dSDimitry Andric if (FwdRegDefs.empty()) {
708bdd1243dSDimitry Andric // Any definitions by this instruction will clobber earlier reg movements.
709bdd1243dSDimitry Andric ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
710bdd1243dSDimitry Andric NewClobberedRegUnits.end());
7115ffd83dbSDimitry Andric return;
712bdd1243dSDimitry Andric }
713bdd1243dSDimitry Andric
714bdd1243dSDimitry Andric // It's possible that we find a copy from a non-volatile register to the param
715bdd1243dSDimitry Andric // register, which is clobbered in the meantime. Test for clobbered reg unit
716bdd1243dSDimitry Andric // overlaps before completing.
717bdd1243dSDimitry Andric auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
718bdd1243dSDimitry Andric for (auto &RegUnit : ClobberedRegUnits)
719bdd1243dSDimitry Andric if (TRI.hasRegUnit(Reg, RegUnit))
720bdd1243dSDimitry Andric return true;
721bdd1243dSDimitry Andric return false;
722bdd1243dSDimitry Andric };
7235ffd83dbSDimitry Andric
7245ffd83dbSDimitry Andric for (auto ParamFwdReg : FwdRegDefs) {
7255ffd83dbSDimitry Andric if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
7265ffd83dbSDimitry Andric if (ParamValue->first.isImm()) {
7275ffd83dbSDimitry Andric int64_t Val = ParamValue->first.getImm();
7285ffd83dbSDimitry Andric finishCallSiteParams(Val, ParamValue->second,
7295ffd83dbSDimitry Andric ForwardedRegWorklist[ParamFwdReg], Params);
7305ffd83dbSDimitry Andric } else if (ParamValue->first.isReg()) {
7315ffd83dbSDimitry Andric Register RegLoc = ParamValue->first.getReg();
732e8d8bef9SDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore();
7335ffd83dbSDimitry Andric Register FP = TRI.getFrameRegister(*MF);
7345ffd83dbSDimitry Andric bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
735bdd1243dSDimitry Andric if (!IsRegClobberedInMeantime(RegLoc) &&
736bdd1243dSDimitry Andric (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
737e8d8bef9SDimitry Andric MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
7385ffd83dbSDimitry Andric finishCallSiteParams(MLoc, ParamValue->second,
7395ffd83dbSDimitry Andric ForwardedRegWorklist[ParamFwdReg], Params);
7405ffd83dbSDimitry Andric } else {
7415ffd83dbSDimitry Andric // ParamFwdReg was described by the non-callee saved register
7425ffd83dbSDimitry Andric // RegLoc. Mark that the call site values for the parameters are
7435ffd83dbSDimitry Andric // dependent on that register instead of ParamFwdReg. Since RegLoc
7445ffd83dbSDimitry Andric // may be a register that will be handled in this iteration, we
7455ffd83dbSDimitry Andric // postpone adding the items to the worklist, and instead keep them
7465ffd83dbSDimitry Andric // in a temporary container.
7475ffd83dbSDimitry Andric addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
7485ffd83dbSDimitry Andric ForwardedRegWorklist[ParamFwdReg]);
7495ffd83dbSDimitry Andric }
7505ffd83dbSDimitry Andric }
7515ffd83dbSDimitry Andric }
7525ffd83dbSDimitry Andric }
7535ffd83dbSDimitry Andric
7545ffd83dbSDimitry Andric // Remove all registers that this instruction defines from the worklist.
7555ffd83dbSDimitry Andric for (auto ParamFwdReg : FwdRegDefs)
7565ffd83dbSDimitry Andric ForwardedRegWorklist.erase(ParamFwdReg);
7575ffd83dbSDimitry Andric
758bdd1243dSDimitry Andric // Any definitions by this instruction will clobber earlier reg movements.
759bdd1243dSDimitry Andric ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
760bdd1243dSDimitry Andric NewClobberedRegUnits.end());
761bdd1243dSDimitry Andric
7625ffd83dbSDimitry Andric // Now that we are done handling this instruction, add items from the
7635ffd83dbSDimitry Andric // temporary worklist to the real one.
764fe6060f1SDimitry Andric for (auto &New : TmpWorklistItems)
7655ffd83dbSDimitry Andric addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
7665ffd83dbSDimitry Andric TmpWorklistItems.clear();
7675ffd83dbSDimitry Andric }
7685ffd83dbSDimitry Andric
interpretNextInstr(const MachineInstr * CurMI,FwdRegWorklist & ForwardedRegWorklist,ParamSet & Params,ClobberedRegSet & ClobberedRegUnits)7695ffd83dbSDimitry Andric static bool interpretNextInstr(const MachineInstr *CurMI,
7705ffd83dbSDimitry Andric FwdRegWorklist &ForwardedRegWorklist,
771bdd1243dSDimitry Andric ParamSet &Params,
772bdd1243dSDimitry Andric ClobberedRegSet &ClobberedRegUnits) {
7735ffd83dbSDimitry Andric // Skip bundle headers.
7745ffd83dbSDimitry Andric if (CurMI->isBundle())
7755ffd83dbSDimitry Andric return true;
7765ffd83dbSDimitry Andric
7775ffd83dbSDimitry Andric // If the next instruction is a call we can not interpret parameter's
7785ffd83dbSDimitry Andric // forwarding registers or we finished the interpretation of all
7795ffd83dbSDimitry Andric // parameters.
7805ffd83dbSDimitry Andric if (CurMI->isCall())
7815ffd83dbSDimitry Andric return false;
7825ffd83dbSDimitry Andric
7835ffd83dbSDimitry Andric if (ForwardedRegWorklist.empty())
7845ffd83dbSDimitry Andric return false;
7855ffd83dbSDimitry Andric
7865ffd83dbSDimitry Andric // Avoid NOP description.
7875ffd83dbSDimitry Andric if (CurMI->getNumOperands() == 0)
7885ffd83dbSDimitry Andric return true;
7895ffd83dbSDimitry Andric
790bdd1243dSDimitry Andric interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
7915ffd83dbSDimitry Andric
7925ffd83dbSDimitry Andric return true;
7935ffd83dbSDimitry Andric }
7945ffd83dbSDimitry Andric
7958bcb0991SDimitry Andric /// Try to interpret values loaded into registers that forward parameters
7968bcb0991SDimitry Andric /// for \p CallMI. Store parameters with interpreted value into \p Params.
collectCallSiteParameters(const MachineInstr * CallMI,ParamSet & Params)7978bcb0991SDimitry Andric static void collectCallSiteParameters(const MachineInstr *CallMI,
7988bcb0991SDimitry Andric ParamSet &Params) {
7995ffd83dbSDimitry Andric const MachineFunction *MF = CallMI->getMF();
800fe6060f1SDimitry Andric const auto &CalleesMap = MF->getCallSitesInfo();
801*0fca6ea1SDimitry Andric auto CSInfo = CalleesMap.find(CallMI);
8028bcb0991SDimitry Andric
8038bcb0991SDimitry Andric // There is no information for the call instruction.
804*0fca6ea1SDimitry Andric if (CSInfo == CalleesMap.end())
8058bcb0991SDimitry Andric return;
8068bcb0991SDimitry Andric
8075ffd83dbSDimitry Andric const MachineBasicBlock *MBB = CallMI->getParent();
8088bcb0991SDimitry Andric
8098bcb0991SDimitry Andric // Skip the call instruction.
8108bcb0991SDimitry Andric auto I = std::next(CallMI->getReverseIterator());
8118bcb0991SDimitry Andric
8125ffd83dbSDimitry Andric FwdRegWorklist ForwardedRegWorklist;
8135ffd83dbSDimitry Andric
8145ffd83dbSDimitry Andric const DIExpression *EmptyExpr =
8155ffd83dbSDimitry Andric DIExpression::get(MF->getFunction().getContext(), {});
8165ffd83dbSDimitry Andric
8178bcb0991SDimitry Andric // Add all the forwarding registers into the ForwardedRegWorklist.
818*0fca6ea1SDimitry Andric for (const auto &ArgReg : CSInfo->second.ArgRegPairs) {
8195ffd83dbSDimitry Andric bool InsertedReg =
8205ffd83dbSDimitry Andric ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
8215ffd83dbSDimitry Andric .second;
8228bcb0991SDimitry Andric assert(InsertedReg && "Single register used to forward two arguments?");
8238bcb0991SDimitry Andric (void)InsertedReg;
8248bcb0991SDimitry Andric }
8258bcb0991SDimitry Andric
826e8d8bef9SDimitry Andric // Do not emit CSInfo for undef forwarding registers.
827fcaf7f86SDimitry Andric for (const auto &MO : CallMI->uses())
828e8d8bef9SDimitry Andric if (MO.isReg() && MO.isUndef())
829e8d8bef9SDimitry Andric ForwardedRegWorklist.erase(MO.getReg());
830e8d8bef9SDimitry Andric
8318bcb0991SDimitry Andric // We erase, from the ForwardedRegWorklist, those forwarding registers for
8328bcb0991SDimitry Andric // which we successfully describe a loaded value (by using
8338bcb0991SDimitry Andric // the describeLoadedValue()). For those remaining arguments in the working
8348bcb0991SDimitry Andric // list, for which we do not describe a loaded value by
8358bcb0991SDimitry Andric // the describeLoadedValue(), we try to generate an entry value expression
8365ffd83dbSDimitry Andric // for their call site value description, if the call is within the entry MBB.
8378bcb0991SDimitry Andric // TODO: Handle situations when call site parameter value can be described
8385ffd83dbSDimitry Andric // as the entry value within basic blocks other than the first one.
8398bcb0991SDimitry Andric bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
8408bcb0991SDimitry Andric
8415ffd83dbSDimitry Andric // Search for a loading value in forwarding registers inside call delay slot.
842bdd1243dSDimitry Andric ClobberedRegSet ClobberedRegUnits;
8435ffd83dbSDimitry Andric if (CallMI->hasDelaySlot()) {
8445ffd83dbSDimitry Andric auto Suc = std::next(CallMI->getIterator());
8455ffd83dbSDimitry Andric // Only one-instruction delay slot is supported.
8465ffd83dbSDimitry Andric auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
8475ffd83dbSDimitry Andric (void)BundleEnd;
8485ffd83dbSDimitry Andric assert(std::next(Suc) == BundleEnd &&
8495ffd83dbSDimitry Andric "More than one instruction in call delay slot");
8505ffd83dbSDimitry Andric // Try to interpret value loaded by instruction.
851bdd1243dSDimitry Andric if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
8528bcb0991SDimitry Andric return;
8538bcb0991SDimitry Andric }
8548bcb0991SDimitry Andric
855480093f4SDimitry Andric // Search for a loading value in forwarding registers.
8568bcb0991SDimitry Andric for (; I != MBB->rend(); ++I) {
8575ffd83dbSDimitry Andric // Try to interpret values loaded by instruction.
858bdd1243dSDimitry Andric if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
8598bcb0991SDimitry Andric return;
8608bcb0991SDimitry Andric }
8618bcb0991SDimitry Andric
8628bcb0991SDimitry Andric // Emit the call site parameter's value as an entry value.
8638bcb0991SDimitry Andric if (ShouldTryEmitEntryVals) {
8648bcb0991SDimitry Andric // Create an expression where the register's entry value is used.
8658bcb0991SDimitry Andric DIExpression *EntryExpr = DIExpression::get(
8668bcb0991SDimitry Andric MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
867fe6060f1SDimitry Andric for (auto &RegEntry : ForwardedRegWorklist) {
8685ffd83dbSDimitry Andric MachineLocation MLoc(RegEntry.first);
8695ffd83dbSDimitry Andric finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
8708bcb0991SDimitry Andric }
8718bcb0991SDimitry Andric }
8728bcb0991SDimitry Andric }
8738bcb0991SDimitry Andric
constructCallSiteEntryDIEs(const DISubprogram & SP,DwarfCompileUnit & CU,DIE & ScopeDIE,const MachineFunction & MF)8740b57cec5SDimitry Andric void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
8750b57cec5SDimitry Andric DwarfCompileUnit &CU, DIE &ScopeDIE,
8760b57cec5SDimitry Andric const MachineFunction &MF) {
8770b57cec5SDimitry Andric // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
8780b57cec5SDimitry Andric // the subprogram is required to have one.
8790b57cec5SDimitry Andric if (!SP.areAllCallsDescribed() || !SP.isDefinition())
8800b57cec5SDimitry Andric return;
8810b57cec5SDimitry Andric
8820b57cec5SDimitry Andric // Use DW_AT_call_all_calls to express that call site entries are present
8830b57cec5SDimitry Andric // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
8840b57cec5SDimitry Andric // because one of its requirements is not met: call site entries for
8850b57cec5SDimitry Andric // optimized-out calls are elided.
8868bcb0991SDimitry Andric CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
8870b57cec5SDimitry Andric
8880b57cec5SDimitry Andric const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8890b57cec5SDimitry Andric assert(TII && "TargetInstrInfo not found: cannot label tail calls");
8905ffd83dbSDimitry Andric
8915ffd83dbSDimitry Andric // Delay slot support check.
8925ffd83dbSDimitry Andric auto delaySlotSupported = [&](const MachineInstr &MI) {
8935ffd83dbSDimitry Andric if (!MI.isBundledWithSucc())
8945ffd83dbSDimitry Andric return false;
8955ffd83dbSDimitry Andric auto Suc = std::next(MI.getIterator());
8965ffd83dbSDimitry Andric auto CallInstrBundle = getBundleStart(MI.getIterator());
8975ffd83dbSDimitry Andric (void)CallInstrBundle;
8985ffd83dbSDimitry Andric auto DelaySlotBundle = getBundleStart(Suc);
8995ffd83dbSDimitry Andric (void)DelaySlotBundle;
9005ffd83dbSDimitry Andric // Ensure that label after call is following delay slot instruction.
9015ffd83dbSDimitry Andric // Ex. CALL_INSTRUCTION {
9025ffd83dbSDimitry Andric // DELAY_SLOT_INSTRUCTION }
9035ffd83dbSDimitry Andric // LABEL_AFTER_CALL
9045ffd83dbSDimitry Andric assert(getLabelAfterInsn(&*CallInstrBundle) ==
9055ffd83dbSDimitry Andric getLabelAfterInsn(&*DelaySlotBundle) &&
9065ffd83dbSDimitry Andric "Call and its successor instruction don't have same label after.");
9075ffd83dbSDimitry Andric return true;
9085ffd83dbSDimitry Andric };
9090b57cec5SDimitry Andric
9100b57cec5SDimitry Andric // Emit call site entries for each call or tail call in the function.
9110b57cec5SDimitry Andric for (const MachineBasicBlock &MBB : MF) {
9120b57cec5SDimitry Andric for (const MachineInstr &MI : MBB.instrs()) {
913480093f4SDimitry Andric // Bundles with call in them will pass the isCall() test below but do not
914480093f4SDimitry Andric // have callee operand information so skip them here. Iterator will
915480093f4SDimitry Andric // eventually reach the call MI.
916480093f4SDimitry Andric if (MI.isBundle())
917480093f4SDimitry Andric continue;
918480093f4SDimitry Andric
9190b57cec5SDimitry Andric // Skip instructions which aren't calls. Both calls and tail-calling jump
9200b57cec5SDimitry Andric // instructions (e.g TAILJMPd64) are classified correctly here.
9215ffd83dbSDimitry Andric if (!MI.isCandidateForCallSiteEntry())
9220b57cec5SDimitry Andric continue;
9230b57cec5SDimitry Andric
9245ffd83dbSDimitry Andric // Skip instructions marked as frame setup, as they are not interesting to
9255ffd83dbSDimitry Andric // the user.
9265ffd83dbSDimitry Andric if (MI.getFlag(MachineInstr::FrameSetup))
9275ffd83dbSDimitry Andric continue;
9285ffd83dbSDimitry Andric
9295ffd83dbSDimitry Andric // Check if delay slot support is enabled.
9305ffd83dbSDimitry Andric if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
9310b57cec5SDimitry Andric return;
9320b57cec5SDimitry Andric
9330b57cec5SDimitry Andric // If this is a direct call, find the callee's subprogram.
9348bcb0991SDimitry Andric // In the case of an indirect call find the register that holds
9358bcb0991SDimitry Andric // the callee.
936fe6060f1SDimitry Andric const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
937fe6060f1SDimitry Andric if (!CalleeOp.isGlobal() &&
938bdd1243dSDimitry Andric (!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))
9390b57cec5SDimitry Andric continue;
9400b57cec5SDimitry Andric
9418bcb0991SDimitry Andric unsigned CallReg = 0;
94269ade1e0SDimitry Andric const DISubprogram *CalleeSP = nullptr;
9438bcb0991SDimitry Andric const Function *CalleeDecl = nullptr;
9448bcb0991SDimitry Andric if (CalleeOp.isReg()) {
9458bcb0991SDimitry Andric CallReg = CalleeOp.getReg();
9468bcb0991SDimitry Andric if (!CallReg)
9478bcb0991SDimitry Andric continue;
9488bcb0991SDimitry Andric } else {
9498bcb0991SDimitry Andric CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
9508bcb0991SDimitry Andric if (!CalleeDecl || !CalleeDecl->getSubprogram())
9518bcb0991SDimitry Andric continue;
95269ade1e0SDimitry Andric CalleeSP = CalleeDecl->getSubprogram();
9538bcb0991SDimitry Andric }
9548bcb0991SDimitry Andric
9550b57cec5SDimitry Andric // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
9560b57cec5SDimitry Andric
9570b57cec5SDimitry Andric bool IsTail = TII->isTailCall(MI);
9580b57cec5SDimitry Andric
959480093f4SDimitry Andric // If MI is in a bundle, the label was created after the bundle since
960480093f4SDimitry Andric // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
961480093f4SDimitry Andric // to search for that label below.
962480093f4SDimitry Andric const MachineInstr *TopLevelCallMI =
963480093f4SDimitry Andric MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
964480093f4SDimitry Andric
9655ffd83dbSDimitry Andric // For non-tail calls, the return PC is needed to disambiguate paths in
9665ffd83dbSDimitry Andric // the call graph which could lead to some target function. For tail
9675ffd83dbSDimitry Andric // calls, no return PC information is needed, unless tuning for GDB in
9685ffd83dbSDimitry Andric // DWARF4 mode in which case we fake a return PC for compatibility.
9698bcb0991SDimitry Andric const MCSymbol *PCAddr =
9705ffd83dbSDimitry Andric (!IsTail || CU.useGNUAnalogForDwarf5Feature())
971480093f4SDimitry Andric ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
9728bcb0991SDimitry Andric : nullptr;
9738bcb0991SDimitry Andric
9745ffd83dbSDimitry Andric // For tail calls, it's necessary to record the address of the branch
9755ffd83dbSDimitry Andric // instruction so that the debugger can show where the tail call occurred.
9765ffd83dbSDimitry Andric const MCSymbol *CallAddr =
9775ffd83dbSDimitry Andric IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
9785ffd83dbSDimitry Andric
9795ffd83dbSDimitry Andric assert((IsTail || PCAddr) && "Non-tail call without return PC");
9808bcb0991SDimitry Andric
9810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
9828bcb0991SDimitry Andric << (CalleeDecl ? CalleeDecl->getName()
9838bcb0991SDimitry Andric : StringRef(MF.getSubtarget()
9848bcb0991SDimitry Andric .getRegisterInfo()
9858bcb0991SDimitry Andric ->getName(CallReg)))
9868bcb0991SDimitry Andric << (IsTail ? " [IsTail]" : "") << "\n");
9878bcb0991SDimitry Andric
9885ffd83dbSDimitry Andric DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
98969ade1e0SDimitry Andric ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
9908bcb0991SDimitry Andric
9915ffd83dbSDimitry Andric // Optionally emit call-site-param debug info.
9925ffd83dbSDimitry Andric if (emitDebugEntryValues()) {
9938bcb0991SDimitry Andric ParamSet Params;
9948bcb0991SDimitry Andric // Try to interpret values of call site parameters.
9958bcb0991SDimitry Andric collectCallSiteParameters(&MI, Params);
9968bcb0991SDimitry Andric CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
9978bcb0991SDimitry Andric }
9980b57cec5SDimitry Andric }
9990b57cec5SDimitry Andric }
10000b57cec5SDimitry Andric }
10010b57cec5SDimitry Andric
addGnuPubAttributes(DwarfCompileUnit & U,DIE & D) const10020b57cec5SDimitry Andric void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
10030b57cec5SDimitry Andric if (!U.hasDwarfPubSections())
10040b57cec5SDimitry Andric return;
10050b57cec5SDimitry Andric
10060b57cec5SDimitry Andric U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric
finishUnitAttributes(const DICompileUnit * DIUnit,DwarfCompileUnit & NewCU)10090b57cec5SDimitry Andric void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
10100b57cec5SDimitry Andric DwarfCompileUnit &NewCU) {
10110b57cec5SDimitry Andric DIE &Die = NewCU.getUnitDie();
10120b57cec5SDimitry Andric StringRef FN = DIUnit->getFilename();
10130b57cec5SDimitry Andric
10140b57cec5SDimitry Andric StringRef Producer = DIUnit->getProducer();
10150b57cec5SDimitry Andric StringRef Flags = DIUnit->getFlags();
10160b57cec5SDimitry Andric if (!Flags.empty() && !useAppleExtensionAttributes()) {
10170b57cec5SDimitry Andric std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
10180b57cec5SDimitry Andric NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
10190b57cec5SDimitry Andric } else
10200b57cec5SDimitry Andric NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
10210b57cec5SDimitry Andric
10220b57cec5SDimitry Andric NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
10230b57cec5SDimitry Andric DIUnit->getSourceLanguage());
10240b57cec5SDimitry Andric NewCU.addString(Die, dwarf::DW_AT_name, FN);
10255ffd83dbSDimitry Andric StringRef SysRoot = DIUnit->getSysRoot();
10265ffd83dbSDimitry Andric if (!SysRoot.empty())
10275ffd83dbSDimitry Andric NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
10285ffd83dbSDimitry Andric StringRef SDK = DIUnit->getSDK();
10295ffd83dbSDimitry Andric if (!SDK.empty())
10305ffd83dbSDimitry Andric NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
10310b57cec5SDimitry Andric
103206c3fb27SDimitry Andric if (!useSplitDwarf()) {
10330b57cec5SDimitry Andric // Add DW_str_offsets_base to the unit DIE, except for split units.
103406c3fb27SDimitry Andric if (useSegmentedStringOffsetsTable())
10350b57cec5SDimitry Andric NewCU.addStringOffsetsStart();
10360b57cec5SDimitry Andric
10370b57cec5SDimitry Andric NewCU.initStmtList();
10380b57cec5SDimitry Andric
10390b57cec5SDimitry Andric // If we're using split dwarf the compilation dir is going to be in the
10400b57cec5SDimitry Andric // skeleton CU and so we don't need to duplicate it here.
10410b57cec5SDimitry Andric if (!CompilationDir.empty())
10420b57cec5SDimitry Andric NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
10430b57cec5SDimitry Andric addGnuPubAttributes(NewCU, Die);
10440b57cec5SDimitry Andric }
10450b57cec5SDimitry Andric
10460b57cec5SDimitry Andric if (useAppleExtensionAttributes()) {
10470b57cec5SDimitry Andric if (DIUnit->isOptimized())
10480b57cec5SDimitry Andric NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
10490b57cec5SDimitry Andric
10500b57cec5SDimitry Andric StringRef Flags = DIUnit->getFlags();
10510b57cec5SDimitry Andric if (!Flags.empty())
10520b57cec5SDimitry Andric NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
10530b57cec5SDimitry Andric
10540b57cec5SDimitry Andric if (unsigned RVer = DIUnit->getRuntimeVersion())
10550b57cec5SDimitry Andric NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
10560b57cec5SDimitry Andric dwarf::DW_FORM_data1, RVer);
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric
10590b57cec5SDimitry Andric if (DIUnit->getDWOId()) {
10600b57cec5SDimitry Andric // This CU is either a clang module DWO or a skeleton CU.
10610b57cec5SDimitry Andric NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
10620b57cec5SDimitry Andric DIUnit->getDWOId());
1063480093f4SDimitry Andric if (!DIUnit->getSplitDebugFilename().empty()) {
10640b57cec5SDimitry Andric // This is a prefabricated skeleton CU.
1065480093f4SDimitry Andric dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1066480093f4SDimitry Andric ? dwarf::DW_AT_dwo_name
1067480093f4SDimitry Andric : dwarf::DW_AT_GNU_dwo_name;
1068480093f4SDimitry Andric NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1069480093f4SDimitry Andric }
10700b57cec5SDimitry Andric }
10710b57cec5SDimitry Andric }
10720b57cec5SDimitry Andric // Create new DwarfCompileUnit for the given metadata node with tag
10730b57cec5SDimitry Andric // DW_TAG_compile_unit.
10740b57cec5SDimitry Andric DwarfCompileUnit &
getOrCreateDwarfCompileUnit(const DICompileUnit * DIUnit)10750b57cec5SDimitry Andric DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
10760b57cec5SDimitry Andric if (auto *CU = CUMap.lookup(DIUnit))
10770b57cec5SDimitry Andric return *CU;
10780b57cec5SDimitry Andric
107906c3fb27SDimitry Andric if (useSplitDwarf() &&
108006c3fb27SDimitry Andric !shareAcrossDWOCUs() &&
108106c3fb27SDimitry Andric (!DIUnit->getSplitDebugInlining() ||
108206c3fb27SDimitry Andric DIUnit->getEmissionKind() == DICompileUnit::FullDebug) &&
108306c3fb27SDimitry Andric !CUMap.empty()) {
108406c3fb27SDimitry Andric return *CUMap.begin()->second;
108506c3fb27SDimitry Andric }
10860b57cec5SDimitry Andric CompilationDir = DIUnit->getDirectory();
10870b57cec5SDimitry Andric
10888bcb0991SDimitry Andric auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
10890b57cec5SDimitry Andric InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
10900b57cec5SDimitry Andric DwarfCompileUnit &NewCU = *OwnedUnit;
10910b57cec5SDimitry Andric InfoHolder.addUnit(std::move(OwnedUnit));
10920b57cec5SDimitry Andric
10930b57cec5SDimitry Andric // LTO with assembly output shares a single line table amongst multiple CUs.
10940b57cec5SDimitry Andric // To avoid the compilation directory being ambiguous, let the line table
10950b57cec5SDimitry Andric // explicitly describe the directory of all files, never relying on the
10960b57cec5SDimitry Andric // compilation directory.
10970b57cec5SDimitry Andric if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
10980b57cec5SDimitry Andric Asm->OutStreamer->emitDwarfFile0Directive(
1099e8d8bef9SDimitry Andric CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1100e8d8bef9SDimitry Andric DIUnit->getSource(), NewCU.getUniqueID());
11010b57cec5SDimitry Andric
11020b57cec5SDimitry Andric if (useSplitDwarf()) {
11030b57cec5SDimitry Andric NewCU.setSkeleton(constructSkeletonCU(NewCU));
11040b57cec5SDimitry Andric NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
11050b57cec5SDimitry Andric } else {
11060b57cec5SDimitry Andric finishUnitAttributes(DIUnit, NewCU);
11070b57cec5SDimitry Andric NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
11080b57cec5SDimitry Andric }
11090b57cec5SDimitry Andric
11100b57cec5SDimitry Andric CUMap.insert({DIUnit, &NewCU});
11110b57cec5SDimitry Andric CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
11120b57cec5SDimitry Andric return NewCU;
11130b57cec5SDimitry Andric }
11140b57cec5SDimitry Andric
11150b57cec5SDimitry Andric /// Sort and unique GVEs by comparing their fragment offset.
11160b57cec5SDimitry Andric static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> & GVEs)11170b57cec5SDimitry Andric sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
11180b57cec5SDimitry Andric llvm::sort(
11190b57cec5SDimitry Andric GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
11200b57cec5SDimitry Andric // Sort order: first null exprs, then exprs without fragment
11210b57cec5SDimitry Andric // info, then sort by fragment offset in bits.
11220b57cec5SDimitry Andric // FIXME: Come up with a more comprehensive comparator so
11230b57cec5SDimitry Andric // the sorting isn't non-deterministic, and so the following
11240b57cec5SDimitry Andric // std::unique call works correctly.
11250b57cec5SDimitry Andric if (!A.Expr || !B.Expr)
11260b57cec5SDimitry Andric return !!B.Expr;
11270b57cec5SDimitry Andric auto FragmentA = A.Expr->getFragmentInfo();
11280b57cec5SDimitry Andric auto FragmentB = B.Expr->getFragmentInfo();
11290b57cec5SDimitry Andric if (!FragmentA || !FragmentB)
11300b57cec5SDimitry Andric return !!FragmentB;
11310b57cec5SDimitry Andric return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
11320b57cec5SDimitry Andric });
1133*0fca6ea1SDimitry Andric GVEs.erase(llvm::unique(GVEs,
11340b57cec5SDimitry Andric [](DwarfCompileUnit::GlobalExpr A,
11350b57cec5SDimitry Andric DwarfCompileUnit::GlobalExpr B) {
11360b57cec5SDimitry Andric return A.Expr == B.Expr;
11370b57cec5SDimitry Andric }),
11380b57cec5SDimitry Andric GVEs.end());
11390b57cec5SDimitry Andric return GVEs;
11400b57cec5SDimitry Andric }
11410b57cec5SDimitry Andric
11420b57cec5SDimitry Andric // Emit all Dwarf sections that should come prior to the content. Create
11430b57cec5SDimitry Andric // global DIEs and emit initial debug info sections. This is invoked by
11440b57cec5SDimitry Andric // the target AsmPrinter.
beginModule(Module * M)1145e8d8bef9SDimitry Andric void DwarfDebug::beginModule(Module *M) {
1146e8d8bef9SDimitry Andric DebugHandlerBase::beginModule(M);
11470b57cec5SDimitry Andric
1148e8d8bef9SDimitry Andric if (!Asm || !MMI->hasDebugInfo())
1149e8d8bef9SDimitry Andric return;
11500b57cec5SDimitry Andric
11510b57cec5SDimitry Andric unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
11520b57cec5SDimitry Andric M->debug_compile_units_end());
1153e8d8bef9SDimitry Andric assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1154e8d8bef9SDimitry Andric assert(MMI->hasDebugInfo() &&
1155e8d8bef9SDimitry Andric "DebugInfoAvailabilty unexpectedly not initialized");
11560b57cec5SDimitry Andric SingleCU = NumDebugCUs == 1;
11570b57cec5SDimitry Andric DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
11580b57cec5SDimitry Andric GVMap;
11590b57cec5SDimitry Andric for (const GlobalVariable &Global : M->globals()) {
11600b57cec5SDimitry Andric SmallVector<DIGlobalVariableExpression *, 1> GVs;
11610b57cec5SDimitry Andric Global.getDebugInfo(GVs);
11620b57cec5SDimitry Andric for (auto *GVE : GVs)
11630b57cec5SDimitry Andric GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
11640b57cec5SDimitry Andric }
11650b57cec5SDimitry Andric
11660b57cec5SDimitry Andric // Create the symbol that designates the start of the unit's contribution
11670b57cec5SDimitry Andric // to the string offsets table. In a split DWARF scenario, only the skeleton
11680b57cec5SDimitry Andric // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
11690b57cec5SDimitry Andric if (useSegmentedStringOffsetsTable())
11700b57cec5SDimitry Andric (useSplitDwarf() ? SkeletonHolder : InfoHolder)
11710b57cec5SDimitry Andric .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
11720b57cec5SDimitry Andric
11730b57cec5SDimitry Andric
11740b57cec5SDimitry Andric // Create the symbols that designates the start of the DWARF v5 range list
11750b57cec5SDimitry Andric // and locations list tables. They are located past the table headers.
11760b57cec5SDimitry Andric if (getDwarfVersion() >= 5) {
11770b57cec5SDimitry Andric DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
11780b57cec5SDimitry Andric Holder.setRnglistsTableBaseSym(
11790b57cec5SDimitry Andric Asm->createTempSymbol("rnglists_table_base"));
11800b57cec5SDimitry Andric
11810b57cec5SDimitry Andric if (useSplitDwarf())
11820b57cec5SDimitry Andric InfoHolder.setRnglistsTableBaseSym(
11830b57cec5SDimitry Andric Asm->createTempSymbol("rnglists_dwo_table_base"));
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric
11860b57cec5SDimitry Andric // Create the symbol that points to the first entry following the debug
11870b57cec5SDimitry Andric // address table (.debug_addr) header.
11880b57cec5SDimitry Andric AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1189480093f4SDimitry Andric DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
11900b57cec5SDimitry Andric
11910b57cec5SDimitry Andric for (DICompileUnit *CUNode : M->debug_compile_units()) {
119206c3fb27SDimitry Andric if (CUNode->getImportedEntities().empty() &&
119306c3fb27SDimitry Andric CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
11940b57cec5SDimitry Andric CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
11950b57cec5SDimitry Andric continue;
11960b57cec5SDimitry Andric
11970b57cec5SDimitry Andric DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
11980b57cec5SDimitry Andric
11990b57cec5SDimitry Andric // Global Variables.
12000b57cec5SDimitry Andric for (auto *GVE : CUNode->getGlobalVariables()) {
12010b57cec5SDimitry Andric // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
12020b57cec5SDimitry Andric // already know about the variable and it isn't adding a constant
12030b57cec5SDimitry Andric // expression.
12040b57cec5SDimitry Andric auto &GVMapEntry = GVMap[GVE->getVariable()];
12050b57cec5SDimitry Andric auto *Expr = GVE->getExpression();
12060b57cec5SDimitry Andric if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
12070b57cec5SDimitry Andric GVMapEntry.push_back({nullptr, Expr});
12080b57cec5SDimitry Andric }
1209fe6060f1SDimitry Andric
12100b57cec5SDimitry Andric DenseSet<DIGlobalVariable *> Processed;
12110b57cec5SDimitry Andric for (auto *GVE : CUNode->getGlobalVariables()) {
12120b57cec5SDimitry Andric DIGlobalVariable *GV = GVE->getVariable();
12130b57cec5SDimitry Andric if (Processed.insert(GV).second)
12140b57cec5SDimitry Andric CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric
12170eae32dcSDimitry Andric for (auto *Ty : CUNode->getEnumTypes())
12180b57cec5SDimitry Andric CU.getOrCreateTypeDIE(cast<DIType>(Ty));
12190eae32dcSDimitry Andric
12200b57cec5SDimitry Andric for (auto *Ty : CUNode->getRetainedTypes()) {
12210b57cec5SDimitry Andric // The retained types array by design contains pointers to
12220b57cec5SDimitry Andric // MDNodes rather than DIRefs. Unique them here.
12230b57cec5SDimitry Andric if (DIType *RT = dyn_cast<DIType>(Ty))
12240b57cec5SDimitry Andric // There is no point in force-emitting a forward declaration.
12250b57cec5SDimitry Andric CU.getOrCreateTypeDIE(RT);
12260b57cec5SDimitry Andric }
12270b57cec5SDimitry Andric }
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric
finishEntityDefinitions()12300b57cec5SDimitry Andric void DwarfDebug::finishEntityDefinitions() {
12310b57cec5SDimitry Andric for (const auto &Entity : ConcreteEntities) {
12320b57cec5SDimitry Andric DIE *Die = Entity->getDIE();
12330b57cec5SDimitry Andric assert(Die);
12340b57cec5SDimitry Andric // FIXME: Consider the time-space tradeoff of just storing the unit pointer
12350b57cec5SDimitry Andric // in the ConcreteEntities list, rather than looking it up again here.
12360b57cec5SDimitry Andric // DIE::getUnit isn't simple - it walks parent pointers, etc.
12370b57cec5SDimitry Andric DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
12380b57cec5SDimitry Andric assert(Unit);
12390b57cec5SDimitry Andric Unit->finishEntityDefinition(Entity.get());
12400b57cec5SDimitry Andric }
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric
finishSubprogramDefinitions()12430b57cec5SDimitry Andric void DwarfDebug::finishSubprogramDefinitions() {
12440b57cec5SDimitry Andric for (const DISubprogram *SP : ProcessedSPNodes) {
12450b57cec5SDimitry Andric assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
12460b57cec5SDimitry Andric forBothCUs(
12470b57cec5SDimitry Andric getOrCreateDwarfCompileUnit(SP->getUnit()),
12480b57cec5SDimitry Andric [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
12490b57cec5SDimitry Andric }
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric
finalizeModuleInfo()12520b57cec5SDimitry Andric void DwarfDebug::finalizeModuleInfo() {
12530b57cec5SDimitry Andric const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
12540b57cec5SDimitry Andric
12550b57cec5SDimitry Andric finishSubprogramDefinitions();
12560b57cec5SDimitry Andric
12570b57cec5SDimitry Andric finishEntityDefinitions();
12580b57cec5SDimitry Andric
12590b57cec5SDimitry Andric // Include the DWO file name in the hash if there's more than one CU.
12600b57cec5SDimitry Andric // This handles ThinLTO's situation where imported CUs may very easily be
12610b57cec5SDimitry Andric // duplicate with the same CU partially imported into another ThinLTO unit.
12620b57cec5SDimitry Andric StringRef DWOName;
12630b57cec5SDimitry Andric if (CUMap.size() > 1)
12640b57cec5SDimitry Andric DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
12650b57cec5SDimitry Andric
126606c3fb27SDimitry Andric bool HasEmittedSplitCU = false;
126706c3fb27SDimitry Andric
12680b57cec5SDimitry Andric // Handle anything that needs to be done on a per-unit basis after
12690b57cec5SDimitry Andric // all other generation.
12700b57cec5SDimitry Andric for (const auto &P : CUMap) {
12710b57cec5SDimitry Andric auto &TheCU = *P.second;
12720b57cec5SDimitry Andric if (TheCU.getCUNode()->isDebugDirectivesOnly())
12730b57cec5SDimitry Andric continue;
12740b57cec5SDimitry Andric // Emit DW_AT_containing_type attribute to connect types with their
12750b57cec5SDimitry Andric // vtable holding type.
12760b57cec5SDimitry Andric TheCU.constructContainingTypeDIEs();
12770b57cec5SDimitry Andric
12780b57cec5SDimitry Andric // Add CU specific attributes if we need to add any.
12790b57cec5SDimitry Andric // If we're splitting the dwarf out now that we've got the entire
12800b57cec5SDimitry Andric // CU then add the dwo id to it.
12810b57cec5SDimitry Andric auto *SkCU = TheCU.getSkeleton();
1282480093f4SDimitry Andric
1283480093f4SDimitry Andric bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1284480093f4SDimitry Andric
1285480093f4SDimitry Andric if (HasSplitUnit) {
128606c3fb27SDimitry Andric (void)HasEmittedSplitCU;
128706c3fb27SDimitry Andric assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
128806c3fb27SDimitry Andric "Multiple CUs emitted into a single dwo file");
128906c3fb27SDimitry Andric HasEmittedSplitCU = true;
1290480093f4SDimitry Andric dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1291480093f4SDimitry Andric ? dwarf::DW_AT_dwo_name
1292480093f4SDimitry Andric : dwarf::DW_AT_GNU_dwo_name;
12930b57cec5SDimitry Andric finishUnitAttributes(TheCU.getCUNode(), TheCU);
1294480093f4SDimitry Andric TheCU.addString(TheCU.getUnitDie(), attrDWOName,
12950b57cec5SDimitry Andric Asm->TM.Options.MCOptions.SplitDwarfFile);
1296480093f4SDimitry Andric SkCU->addString(SkCU->getUnitDie(), attrDWOName,
12970b57cec5SDimitry Andric Asm->TM.Options.MCOptions.SplitDwarfFile);
12980b57cec5SDimitry Andric // Emit a unique identifier for this CU.
12990b57cec5SDimitry Andric uint64_t ID =
1300e8d8bef9SDimitry Andric DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
13010b57cec5SDimitry Andric if (getDwarfVersion() >= 5) {
13020b57cec5SDimitry Andric TheCU.setDWOId(ID);
13030b57cec5SDimitry Andric SkCU->setDWOId(ID);
13040b57cec5SDimitry Andric } else {
13050b57cec5SDimitry Andric TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
13060b57cec5SDimitry Andric dwarf::DW_FORM_data8, ID);
13070b57cec5SDimitry Andric SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
13080b57cec5SDimitry Andric dwarf::DW_FORM_data8, ID);
13090b57cec5SDimitry Andric }
13100b57cec5SDimitry Andric
13110b57cec5SDimitry Andric if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
13120b57cec5SDimitry Andric const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
13130b57cec5SDimitry Andric SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
13140b57cec5SDimitry Andric Sym, Sym);
13150b57cec5SDimitry Andric }
13160b57cec5SDimitry Andric } else if (SkCU) {
13170b57cec5SDimitry Andric finishUnitAttributes(SkCU->getCUNode(), *SkCU);
13180b57cec5SDimitry Andric }
13190b57cec5SDimitry Andric
13200b57cec5SDimitry Andric // If we have code split among multiple sections or non-contiguous
13210b57cec5SDimitry Andric // ranges of code then emit a DW_AT_ranges attribute on the unit that will
13220b57cec5SDimitry Andric // remain in the .o file, otherwise add a DW_AT_low_pc.
13230b57cec5SDimitry Andric // FIXME: We should use ranges allow reordering of code ala
13240b57cec5SDimitry Andric // .subsections_via_symbols in mach-o. This would mean turning on
13250b57cec5SDimitry Andric // ranges for all subprogram DIEs for mach-o.
13260b57cec5SDimitry Andric DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
13270b57cec5SDimitry Andric
13280b57cec5SDimitry Andric if (unsigned NumRanges = TheCU.getRanges().size()) {
13290b57cec5SDimitry Andric if (NumRanges > 1 && useRangesSection())
13300b57cec5SDimitry Andric // A DW_AT_low_pc attribute may also be specified in combination with
13310b57cec5SDimitry Andric // DW_AT_ranges to specify the default base address for use in
13320b57cec5SDimitry Andric // location lists (see Section 2.6.2) and range lists (see Section
13330b57cec5SDimitry Andric // 2.17.3).
13340b57cec5SDimitry Andric U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
13350b57cec5SDimitry Andric else
13368bcb0991SDimitry Andric U.setBaseAddress(TheCU.getRanges().front().Begin);
13370b57cec5SDimitry Andric U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
13380b57cec5SDimitry Andric }
13390b57cec5SDimitry Andric
13400b57cec5SDimitry Andric // We don't keep track of which addresses are used in which CU so this
13410b57cec5SDimitry Andric // is a bit pessimistic under LTO.
13425ffd83dbSDimitry Andric if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
13430b57cec5SDimitry Andric U.addAddrTableBase();
13440b57cec5SDimitry Andric
13450b57cec5SDimitry Andric if (getDwarfVersion() >= 5) {
13460b57cec5SDimitry Andric if (U.hasRangeLists())
13470b57cec5SDimitry Andric U.addRnglistsBase();
13480b57cec5SDimitry Andric
134906c3fb27SDimitry Andric if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
13508bcb0991SDimitry Andric U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
13518bcb0991SDimitry Andric DebugLocs.getSym(),
13528bcb0991SDimitry Andric TLOF.getDwarfLoclistsSection()->getBeginSymbol());
13538bcb0991SDimitry Andric }
13540b57cec5SDimitry Andric }
13550b57cec5SDimitry Andric
13560b57cec5SDimitry Andric auto *CUNode = cast<DICompileUnit>(P.first);
13575ffd83dbSDimitry Andric // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
13585ffd83dbSDimitry Andric // attribute.
1359480093f4SDimitry Andric if (CUNode->getMacros()) {
1360e8d8bef9SDimitry Andric if (UseDebugMacroSection) {
1361480093f4SDimitry Andric if (useSplitDwarf())
13625ffd83dbSDimitry Andric TheCU.addSectionDelta(
13635ffd83dbSDimitry Andric TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
13645ffd83dbSDimitry Andric TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
1365e8d8bef9SDimitry Andric else {
1366e8d8bef9SDimitry Andric dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1367e8d8bef9SDimitry Andric ? dwarf::DW_AT_macros
1368e8d8bef9SDimitry Andric : dwarf::DW_AT_GNU_macros;
1369e8d8bef9SDimitry Andric U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
13705ffd83dbSDimitry Andric TLOF.getDwarfMacroSection()->getBeginSymbol());
1371e8d8bef9SDimitry Andric }
13725ffd83dbSDimitry Andric } else {
13735ffd83dbSDimitry Andric if (useSplitDwarf())
13745ffd83dbSDimitry Andric TheCU.addSectionDelta(
13755ffd83dbSDimitry Andric TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1376480093f4SDimitry Andric U.getMacroLabelBegin(),
1377480093f4SDimitry Andric TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1378480093f4SDimitry Andric else
13790b57cec5SDimitry Andric U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
13800b57cec5SDimitry Andric U.getMacroLabelBegin(),
13810b57cec5SDimitry Andric TLOF.getDwarfMacinfoSection()->getBeginSymbol());
13820b57cec5SDimitry Andric }
1383480093f4SDimitry Andric }
13845ffd83dbSDimitry Andric }
13850b57cec5SDimitry Andric
13860b57cec5SDimitry Andric // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
13870b57cec5SDimitry Andric for (auto *CUNode : MMI->getModule()->debug_compile_units())
13880b57cec5SDimitry Andric if (CUNode->getDWOId())
13890b57cec5SDimitry Andric getOrCreateDwarfCompileUnit(CUNode);
13900b57cec5SDimitry Andric
13910b57cec5SDimitry Andric // Compute DIE offsets and sizes.
13920b57cec5SDimitry Andric InfoHolder.computeSizeAndOffsets();
13930b57cec5SDimitry Andric if (useSplitDwarf())
13940b57cec5SDimitry Andric SkeletonHolder.computeSizeAndOffsets();
13955f757f3fSDimitry Andric
13965f757f3fSDimitry Andric // Now that offsets are computed, can replace DIEs in debug_names Entry with
13975f757f3fSDimitry Andric // an actual offset.
13985f757f3fSDimitry Andric AccelDebugNames.convertDieToOffset();
13990b57cec5SDimitry Andric }
14000b57cec5SDimitry Andric
14010b57cec5SDimitry Andric // Emit all Dwarf sections that should come after the content.
endModule()14020b57cec5SDimitry Andric void DwarfDebug::endModule() {
1403349cc55cSDimitry Andric // Terminate the pending line table.
1404349cc55cSDimitry Andric if (PrevCU)
1405349cc55cSDimitry Andric terminateLineTable(PrevCU);
1406349cc55cSDimitry Andric PrevCU = nullptr;
14070b57cec5SDimitry Andric assert(CurFn == nullptr);
14080b57cec5SDimitry Andric assert(CurMI == nullptr);
14090b57cec5SDimitry Andric
14100b57cec5SDimitry Andric for (const auto &P : CUMap) {
141106c3fb27SDimitry Andric const auto *CUNode = cast<DICompileUnit>(P.first);
141206c3fb27SDimitry Andric DwarfCompileUnit *CU = &*P.second;
141306c3fb27SDimitry Andric
141406c3fb27SDimitry Andric // Emit imported entities.
141506c3fb27SDimitry Andric for (auto *IE : CUNode->getImportedEntities()) {
141606c3fb27SDimitry Andric assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
141706c3fb27SDimitry Andric "Unexpected function-local entity in 'imports' CU field.");
141806c3fb27SDimitry Andric CU->getOrCreateImportedEntityDIE(IE);
141906c3fb27SDimitry Andric }
142006c3fb27SDimitry Andric for (const auto *D : CU->getDeferredLocalDecls()) {
142106c3fb27SDimitry Andric if (auto *IE = dyn_cast<DIImportedEntity>(D))
142206c3fb27SDimitry Andric CU->getOrCreateImportedEntityDIE(IE);
142306c3fb27SDimitry Andric else
142406c3fb27SDimitry Andric llvm_unreachable("Unexpected local retained node!");
142506c3fb27SDimitry Andric }
142606c3fb27SDimitry Andric
142706c3fb27SDimitry Andric // Emit base types.
142806c3fb27SDimitry Andric CU->createBaseTypeDIEs();
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric
14310b57cec5SDimitry Andric // If we aren't actually generating debug info (check beginModule -
1432e8d8bef9SDimitry Andric // conditionalized on the presence of the llvm.dbg.cu metadata node)
1433e8d8bef9SDimitry Andric if (!Asm || !MMI->hasDebugInfo())
14340b57cec5SDimitry Andric return;
14350b57cec5SDimitry Andric
14360b57cec5SDimitry Andric // Finalize the debug info for the module.
14370b57cec5SDimitry Andric finalizeModuleInfo();
14380b57cec5SDimitry Andric
14390b57cec5SDimitry Andric if (useSplitDwarf())
1440480093f4SDimitry Andric // Emit debug_loc.dwo/debug_loclists.dwo section.
14410b57cec5SDimitry Andric emitDebugLocDWO();
14420b57cec5SDimitry Andric else
1443480093f4SDimitry Andric // Emit debug_loc/debug_loclists section.
14440b57cec5SDimitry Andric emitDebugLoc();
14450b57cec5SDimitry Andric
14460b57cec5SDimitry Andric // Corresponding abbreviations into a abbrev section.
14470b57cec5SDimitry Andric emitAbbreviations();
14480b57cec5SDimitry Andric
14490b57cec5SDimitry Andric // Emit all the DIEs into a debug info section.
14500b57cec5SDimitry Andric emitDebugInfo();
14510b57cec5SDimitry Andric
14520b57cec5SDimitry Andric // Emit info into a debug aranges section.
14530b57cec5SDimitry Andric if (GenerateARangeSection)
14540b57cec5SDimitry Andric emitDebugARanges();
14550b57cec5SDimitry Andric
14560b57cec5SDimitry Andric // Emit info into a debug ranges section.
14570b57cec5SDimitry Andric emitDebugRanges();
14580b57cec5SDimitry Andric
1459480093f4SDimitry Andric if (useSplitDwarf())
1460480093f4SDimitry Andric // Emit info into a debug macinfo.dwo section.
1461480093f4SDimitry Andric emitDebugMacinfoDWO();
1462480093f4SDimitry Andric else
14635ffd83dbSDimitry Andric // Emit info into a debug macinfo/macro section.
14640b57cec5SDimitry Andric emitDebugMacinfo();
14650b57cec5SDimitry Andric
14665ffd83dbSDimitry Andric emitDebugStr();
14675ffd83dbSDimitry Andric
14680b57cec5SDimitry Andric if (useSplitDwarf()) {
14690b57cec5SDimitry Andric emitDebugStrDWO();
14700b57cec5SDimitry Andric emitDebugInfoDWO();
14710b57cec5SDimitry Andric emitDebugAbbrevDWO();
14720b57cec5SDimitry Andric emitDebugLineDWO();
14730b57cec5SDimitry Andric emitDebugRangesDWO();
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric
14760b57cec5SDimitry Andric emitDebugAddr();
14770b57cec5SDimitry Andric
14780b57cec5SDimitry Andric // Emit info into the dwarf accelerator table sections.
14790b57cec5SDimitry Andric switch (getAccelTableKind()) {
14800b57cec5SDimitry Andric case AccelTableKind::Apple:
14810b57cec5SDimitry Andric emitAccelNames();
14820b57cec5SDimitry Andric emitAccelObjC();
14830b57cec5SDimitry Andric emitAccelNamespaces();
14840b57cec5SDimitry Andric emitAccelTypes();
14850b57cec5SDimitry Andric break;
14860b57cec5SDimitry Andric case AccelTableKind::Dwarf:
14870b57cec5SDimitry Andric emitAccelDebugNames();
14880b57cec5SDimitry Andric break;
14890b57cec5SDimitry Andric case AccelTableKind::None:
14900b57cec5SDimitry Andric break;
14910b57cec5SDimitry Andric case AccelTableKind::Default:
14920b57cec5SDimitry Andric llvm_unreachable("Default should have already been resolved.");
14930b57cec5SDimitry Andric }
14940b57cec5SDimitry Andric
14950b57cec5SDimitry Andric // Emit the pubnames and pubtypes sections if requested.
14960b57cec5SDimitry Andric emitDebugPubSections();
14970b57cec5SDimitry Andric
14980b57cec5SDimitry Andric // clean up.
14990b57cec5SDimitry Andric // FIXME: AbstractVariables.clear();
15000b57cec5SDimitry Andric }
15010b57cec5SDimitry Andric
ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit & CU,const DINode * Node,const MDNode * ScopeNode)15020b57cec5SDimitry Andric void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
15030b57cec5SDimitry Andric const DINode *Node, const MDNode *ScopeNode) {
15040b57cec5SDimitry Andric if (CU.getExistingAbstractEntity(Node))
15050b57cec5SDimitry Andric return;
15060b57cec5SDimitry Andric
15070b57cec5SDimitry Andric if (LexicalScope *Scope =
15080b57cec5SDimitry Andric LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
15090b57cec5SDimitry Andric CU.createAbstractEntity(Node, Scope);
15100b57cec5SDimitry Andric }
15110b57cec5SDimitry Andric
getRetainedNodeScope(const MDNode * N)151206c3fb27SDimitry Andric static const DILocalScope *getRetainedNodeScope(const MDNode *N) {
151306c3fb27SDimitry Andric const DIScope *S;
151406c3fb27SDimitry Andric if (const auto *LV = dyn_cast<DILocalVariable>(N))
151506c3fb27SDimitry Andric S = LV->getScope();
151606c3fb27SDimitry Andric else if (const auto *L = dyn_cast<DILabel>(N))
151706c3fb27SDimitry Andric S = L->getScope();
151806c3fb27SDimitry Andric else if (const auto *IE = dyn_cast<DIImportedEntity>(N))
151906c3fb27SDimitry Andric S = IE->getScope();
152006c3fb27SDimitry Andric else
152106c3fb27SDimitry Andric llvm_unreachable("Unexpected retained node!");
152206c3fb27SDimitry Andric
152306c3fb27SDimitry Andric // Ensure the scope is not a DILexicalBlockFile.
152406c3fb27SDimitry Andric return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();
152506c3fb27SDimitry Andric }
152606c3fb27SDimitry Andric
15270b57cec5SDimitry Andric // Collect variable information from side table maintained by MF.
collectVariableInfoFromMFTable(DwarfCompileUnit & TheCU,DenseSet<InlinedEntity> & Processed)15280b57cec5SDimitry Andric void DwarfDebug::collectVariableInfoFromMFTable(
15290b57cec5SDimitry Andric DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
15300b57cec5SDimitry Andric SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
15315ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
15320b57cec5SDimitry Andric for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
15330b57cec5SDimitry Andric if (!VI.Var)
15340b57cec5SDimitry Andric continue;
15350b57cec5SDimitry Andric assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
15360b57cec5SDimitry Andric "Expected inlined-at fields to agree");
15370b57cec5SDimitry Andric
15380b57cec5SDimitry Andric InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
15390b57cec5SDimitry Andric Processed.insert(Var);
15400b57cec5SDimitry Andric LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
15410b57cec5SDimitry Andric
15420b57cec5SDimitry Andric // If variable scope is not found then skip this variable.
15435ffd83dbSDimitry Andric if (!Scope) {
15445ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
15455ffd83dbSDimitry Andric << ", no variable scope found\n");
15460b57cec5SDimitry Andric continue;
15475ffd83dbSDimitry Andric }
15480b57cec5SDimitry Andric
15490b57cec5SDimitry Andric ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
15505f757f3fSDimitry Andric
15515f757f3fSDimitry Andric // If we have already seen information for this variable, add to what we
15525f757f3fSDimitry Andric // already know.
15535f757f3fSDimitry Andric if (DbgVariable *PreviousLoc = MFVars.lookup(Var)) {
15545f757f3fSDimitry Andric auto *PreviousMMI = std::get_if<Loc::MMI>(PreviousLoc);
15555f757f3fSDimitry Andric auto *PreviousEntryValue = std::get_if<Loc::EntryValue>(PreviousLoc);
15565f757f3fSDimitry Andric // Previous and new locations are both stack slots (MMI).
15575f757f3fSDimitry Andric if (PreviousMMI && VI.inStackSlot())
15585f757f3fSDimitry Andric PreviousMMI->addFrameIndexExpr(VI.Expr, VI.getStackSlot());
15595f757f3fSDimitry Andric // Previous and new locations are both entry values.
15605f757f3fSDimitry Andric else if (PreviousEntryValue && VI.inEntryValueRegister())
15615f757f3fSDimitry Andric PreviousEntryValue->addExpr(VI.getEntryValueRegister(), *VI.Expr);
15625f757f3fSDimitry Andric else {
15635f757f3fSDimitry Andric // Locations differ, this should (rarely) happen in optimized async
15645f757f3fSDimitry Andric // coroutines.
15655f757f3fSDimitry Andric // Prefer whichever location has an EntryValue.
15665f757f3fSDimitry Andric if (PreviousLoc->holds<Loc::MMI>())
15675f757f3fSDimitry Andric PreviousLoc->emplace<Loc::EntryValue>(VI.getEntryValueRegister(),
15685f757f3fSDimitry Andric *VI.Expr);
15695f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
15705f757f3fSDimitry Andric << ", conflicting fragment location types\n");
15715f757f3fSDimitry Andric }
15725f757f3fSDimitry Andric continue;
15735f757f3fSDimitry Andric }
15745f757f3fSDimitry Andric
15758bcb0991SDimitry Andric auto RegVar = std::make_unique<DbgVariable>(
15760b57cec5SDimitry Andric cast<DILocalVariable>(Var.first), Var.second);
157706c3fb27SDimitry Andric if (VI.inStackSlot())
15785f757f3fSDimitry Andric RegVar->emplace<Loc::MMI>(VI.Expr, VI.getStackSlot());
15795f757f3fSDimitry Andric else
15805f757f3fSDimitry Andric RegVar->emplace<Loc::EntryValue>(VI.getEntryValueRegister(), *VI.Expr);
15815ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
15825ffd83dbSDimitry Andric << "\n");
15835f757f3fSDimitry Andric InfoHolder.addScopeVariable(Scope, RegVar.get());
15840b57cec5SDimitry Andric MFVars.insert({Var, RegVar.get()});
15850b57cec5SDimitry Andric ConcreteEntities.push_back(std::move(RegVar));
15860b57cec5SDimitry Andric }
15870b57cec5SDimitry Andric }
15880b57cec5SDimitry Andric
15890b57cec5SDimitry Andric /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
15900b57cec5SDimitry Andric /// enclosing lexical scope. The check ensures there are no other instructions
15910b57cec5SDimitry Andric /// in the same lexical scope preceding the DBG_VALUE and that its range is
15920b57cec5SDimitry Andric /// either open or otherwise rolls off the end of the scope.
validThroughout(LexicalScopes & LScopes,const MachineInstr * DbgValue,const MachineInstr * RangeEnd,const InstructionOrdering & Ordering)15930b57cec5SDimitry Andric static bool validThroughout(LexicalScopes &LScopes,
15940b57cec5SDimitry Andric const MachineInstr *DbgValue,
1595e8d8bef9SDimitry Andric const MachineInstr *RangeEnd,
1596e8d8bef9SDimitry Andric const InstructionOrdering &Ordering) {
15970b57cec5SDimitry Andric assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
15980b57cec5SDimitry Andric auto MBB = DbgValue->getParent();
15990b57cec5SDimitry Andric auto DL = DbgValue->getDebugLoc();
16000b57cec5SDimitry Andric auto *LScope = LScopes.findLexicalScope(DL);
16010b57cec5SDimitry Andric // Scope doesn't exist; this is a dead DBG_VALUE.
16020b57cec5SDimitry Andric if (!LScope)
16030b57cec5SDimitry Andric return false;
16040b57cec5SDimitry Andric auto &LSRange = LScope->getRanges();
16050b57cec5SDimitry Andric if (LSRange.size() == 0)
16060b57cec5SDimitry Andric return false;
16070b57cec5SDimitry Andric
16080b57cec5SDimitry Andric const MachineInstr *LScopeBegin = LSRange.front().first;
1609e8d8bef9SDimitry Andric // If the scope starts before the DBG_VALUE then we may have a negative
1610e8d8bef9SDimitry Andric // result. Otherwise the location is live coming into the scope and we
1611e8d8bef9SDimitry Andric // can skip the following checks.
1612e8d8bef9SDimitry Andric if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1613e8d8bef9SDimitry Andric // Exit if the lexical scope begins outside of the current block.
16140b57cec5SDimitry Andric if (LScopeBegin->getParent() != MBB)
16150b57cec5SDimitry Andric return false;
16165ffd83dbSDimitry Andric
16170b57cec5SDimitry Andric MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
16180b57cec5SDimitry Andric for (++Pred; Pred != MBB->rend(); ++Pred) {
16190b57cec5SDimitry Andric if (Pred->getFlag(MachineInstr::FrameSetup))
16200b57cec5SDimitry Andric break;
16210b57cec5SDimitry Andric auto PredDL = Pred->getDebugLoc();
16220b57cec5SDimitry Andric if (!PredDL || Pred->isMetaInstruction())
16230b57cec5SDimitry Andric continue;
16240b57cec5SDimitry Andric // Check whether the instruction preceding the DBG_VALUE is in the same
16250b57cec5SDimitry Andric // (sub)scope as the DBG_VALUE.
16260b57cec5SDimitry Andric if (DL->getScope() == PredDL->getScope())
16270b57cec5SDimitry Andric return false;
16280b57cec5SDimitry Andric auto *PredScope = LScopes.findLexicalScope(PredDL);
16290b57cec5SDimitry Andric if (!PredScope || LScope->dominates(PredScope))
16300b57cec5SDimitry Andric return false;
16310b57cec5SDimitry Andric }
1632e8d8bef9SDimitry Andric }
16330b57cec5SDimitry Andric
16340b57cec5SDimitry Andric // If the range of the DBG_VALUE is open-ended, report success.
16350b57cec5SDimitry Andric if (!RangeEnd)
16360b57cec5SDimitry Andric return true;
16370b57cec5SDimitry Andric
16380b57cec5SDimitry Andric // Single, constant DBG_VALUEs in the prologue are promoted to be live
16390b57cec5SDimitry Andric // throughout the function. This is a hack, presumably for DWARF v2 and not
16400b57cec5SDimitry Andric // necessarily correct. It would be much better to use a dbg.declare instead
16410b57cec5SDimitry Andric // if we know the constant is live throughout the scope.
1642fe6060f1SDimitry Andric if (MBB->pred_empty() &&
1643fe6060f1SDimitry Andric all_of(DbgValue->debug_operands(),
1644fe6060f1SDimitry Andric [](const MachineOperand &Op) { return Op.isImm(); }))
16450b57cec5SDimitry Andric return true;
16460b57cec5SDimitry Andric
1647e8d8bef9SDimitry Andric // Test if the location terminates before the end of the scope.
1648e8d8bef9SDimitry Andric const MachineInstr *LScopeEnd = LSRange.back().second;
1649e8d8bef9SDimitry Andric if (Ordering.isBefore(RangeEnd, LScopeEnd))
16500b57cec5SDimitry Andric return false;
16515ffd83dbSDimitry Andric
16525ffd83dbSDimitry Andric // There's a single location which starts at the scope start, and ends at or
16535ffd83dbSDimitry Andric // after the scope end.
16545ffd83dbSDimitry Andric return true;
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric
16570b57cec5SDimitry Andric /// Build the location list for all DBG_VALUEs in the function that
16580b57cec5SDimitry Andric /// describe the same variable. The resulting DebugLocEntries will have
16590b57cec5SDimitry Andric /// strict monotonically increasing begin addresses and will never
16600b57cec5SDimitry Andric /// overlap. If the resulting list has only one entry that is valid
16610b57cec5SDimitry Andric /// throughout variable's scope return true.
16620b57cec5SDimitry Andric //
16630b57cec5SDimitry Andric // See the definition of DbgValueHistoryMap::Entry for an explanation of the
16640b57cec5SDimitry Andric // different kinds of history map entries. One thing to be aware of is that if
16650b57cec5SDimitry Andric // a debug value is ended by another entry (rather than being valid until the
16660b57cec5SDimitry Andric // end of the function), that entry's instruction may or may not be included in
16670b57cec5SDimitry Andric // the range, depending on if the entry is a clobbering entry (it has an
16680b57cec5SDimitry Andric // instruction that clobbers one or more preceding locations), or if it is an
16690b57cec5SDimitry Andric // (overlapping) debug value entry. This distinction can be seen in the example
16700b57cec5SDimitry Andric // below. The first debug value is ended by the clobbering entry 2, and the
16710b57cec5SDimitry Andric // second and third debug values are ended by the overlapping debug value entry
16720b57cec5SDimitry Andric // 4.
16730b57cec5SDimitry Andric //
16740b57cec5SDimitry Andric // Input:
16750b57cec5SDimitry Andric //
16760b57cec5SDimitry Andric // History map entries [type, end index, mi]
16770b57cec5SDimitry Andric //
16780b57cec5SDimitry Andric // 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
16790b57cec5SDimitry Andric // 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
16800b57cec5SDimitry Andric // 2 | | [Clobber, $reg0 = [...], -, -]
16810b57cec5SDimitry Andric // 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
16820b57cec5SDimitry Andric // 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
16830b57cec5SDimitry Andric //
16840b57cec5SDimitry Andric // Output [start, end) [Value...]:
16850b57cec5SDimitry Andric //
16860b57cec5SDimitry Andric // [0-1) [(reg0, fragment 0, 32)]
16870b57cec5SDimitry Andric // [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
16880b57cec5SDimitry Andric // [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
16890b57cec5SDimitry Andric // [4-) [(@g, fragment 0, 96)]
buildLocationList(SmallVectorImpl<DebugLocEntry> & DebugLoc,const DbgValueHistoryMap::Entries & Entries)1690e8d8bef9SDimitry Andric bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1691e8d8bef9SDimitry Andric const DbgValueHistoryMap::Entries &Entries) {
16920b57cec5SDimitry Andric using OpenRange =
16930b57cec5SDimitry Andric std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
16940b57cec5SDimitry Andric SmallVector<OpenRange, 4> OpenRanges;
16950b57cec5SDimitry Andric bool isSafeForSingleLocation = true;
16960b57cec5SDimitry Andric const MachineInstr *StartDebugMI = nullptr;
16970b57cec5SDimitry Andric const MachineInstr *EndMI = nullptr;
16980b57cec5SDimitry Andric
16990b57cec5SDimitry Andric for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
17000b57cec5SDimitry Andric const MachineInstr *Instr = EI->getInstr();
17010b57cec5SDimitry Andric
17020b57cec5SDimitry Andric // Remove all values that are no longer live.
17030b57cec5SDimitry Andric size_t Index = std::distance(EB, EI);
1704e8d8bef9SDimitry Andric erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
17050b57cec5SDimitry Andric
17060b57cec5SDimitry Andric // If we are dealing with a clobbering entry, this iteration will result in
17070b57cec5SDimitry Andric // a location list entry starting after the clobbering instruction.
17080b57cec5SDimitry Andric const MCSymbol *StartLabel =
17090b57cec5SDimitry Andric EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
17100b57cec5SDimitry Andric assert(StartLabel &&
17110b57cec5SDimitry Andric "Forgot label before/after instruction starting a range!");
17120b57cec5SDimitry Andric
17130b57cec5SDimitry Andric const MCSymbol *EndLabel;
17140b57cec5SDimitry Andric if (std::next(EI) == Entries.end()) {
17155ffd83dbSDimitry Andric const MachineBasicBlock &EndMBB = Asm->MF->back();
1716*0fca6ea1SDimitry Andric EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionID()].EndLabel;
17170b57cec5SDimitry Andric if (EI->isClobber())
17180b57cec5SDimitry Andric EndMI = EI->getInstr();
17190b57cec5SDimitry Andric }
17200b57cec5SDimitry Andric else if (std::next(EI)->isClobber())
17210b57cec5SDimitry Andric EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
17220b57cec5SDimitry Andric else
17230b57cec5SDimitry Andric EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
17240b57cec5SDimitry Andric assert(EndLabel && "Forgot label after instruction ending a range!");
17250b57cec5SDimitry Andric
17260b57cec5SDimitry Andric if (EI->isDbgValue())
17270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
17280b57cec5SDimitry Andric
17290b57cec5SDimitry Andric // If this history map entry has a debug value, add that to the list of
17300b57cec5SDimitry Andric // open ranges and check if its location is valid for a single value
17310b57cec5SDimitry Andric // location.
17320b57cec5SDimitry Andric if (EI->isDbgValue()) {
17330b57cec5SDimitry Andric // Do not add undef debug values, as they are redundant information in
17340b57cec5SDimitry Andric // the location list entries. An undef debug results in an empty location
17350b57cec5SDimitry Andric // description. If there are any non-undef fragments then padding pieces
17360b57cec5SDimitry Andric // with empty location descriptions will automatically be inserted, and if
17370b57cec5SDimitry Andric // all fragments are undef then the whole location list entry is
17380b57cec5SDimitry Andric // redundant.
17390b57cec5SDimitry Andric if (!Instr->isUndefDebugValue()) {
17400b57cec5SDimitry Andric auto Value = getDebugLocValue(Instr);
17410b57cec5SDimitry Andric OpenRanges.emplace_back(EI->getEndIndex(), Value);
17420b57cec5SDimitry Andric
17430b57cec5SDimitry Andric // TODO: Add support for single value fragment locations.
17440b57cec5SDimitry Andric if (Instr->getDebugExpression()->isFragment())
17450b57cec5SDimitry Andric isSafeForSingleLocation = false;
17460b57cec5SDimitry Andric
17470b57cec5SDimitry Andric if (!StartDebugMI)
17480b57cec5SDimitry Andric StartDebugMI = Instr;
17490b57cec5SDimitry Andric } else {
17500b57cec5SDimitry Andric isSafeForSingleLocation = false;
17510b57cec5SDimitry Andric }
17520b57cec5SDimitry Andric }
17530b57cec5SDimitry Andric
17540b57cec5SDimitry Andric // Location list entries with empty location descriptions are redundant
17550b57cec5SDimitry Andric // information in DWARF, so do not emit those.
17560b57cec5SDimitry Andric if (OpenRanges.empty())
17570b57cec5SDimitry Andric continue;
17580b57cec5SDimitry Andric
17590b57cec5SDimitry Andric // Omit entries with empty ranges as they do not have any effect in DWARF.
17600b57cec5SDimitry Andric if (StartLabel == EndLabel) {
17610b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
17620b57cec5SDimitry Andric continue;
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric
17650b57cec5SDimitry Andric SmallVector<DbgValueLoc, 4> Values;
17660b57cec5SDimitry Andric for (auto &R : OpenRanges)
17670b57cec5SDimitry Andric Values.push_back(R.second);
1768fe6060f1SDimitry Andric
1769fe6060f1SDimitry Andric // With Basic block sections, it is posssible that the StartLabel and the
1770fe6060f1SDimitry Andric // Instr are not in the same section. This happens when the StartLabel is
1771fe6060f1SDimitry Andric // the function begin label and the dbg value appears in a basic block
1772fe6060f1SDimitry Andric // that is not the entry. In this case, the range needs to be split to
1773fe6060f1SDimitry Andric // span each individual section in the range from StartLabel to EndLabel.
1774fe6060f1SDimitry Andric if (Asm->MF->hasBBSections() && StartLabel == Asm->getFunctionBegin() &&
1775fe6060f1SDimitry Andric !Instr->getParent()->sameSection(&Asm->MF->front())) {
1776fe6060f1SDimitry Andric const MCSymbol *BeginSectionLabel = StartLabel;
1777fe6060f1SDimitry Andric
1778fe6060f1SDimitry Andric for (const MachineBasicBlock &MBB : *Asm->MF) {
1779fe6060f1SDimitry Andric if (MBB.isBeginSection() && &MBB != &Asm->MF->front())
1780fe6060f1SDimitry Andric BeginSectionLabel = MBB.getSymbol();
1781fe6060f1SDimitry Andric
1782fe6060f1SDimitry Andric if (MBB.sameSection(Instr->getParent())) {
1783fe6060f1SDimitry Andric DebugLoc.emplace_back(BeginSectionLabel, EndLabel, Values);
1784fe6060f1SDimitry Andric break;
1785fe6060f1SDimitry Andric }
1786fe6060f1SDimitry Andric if (MBB.isEndSection())
1787fe6060f1SDimitry Andric DebugLoc.emplace_back(BeginSectionLabel, MBB.getEndSymbol(), Values);
1788fe6060f1SDimitry Andric }
1789fe6060f1SDimitry Andric } else {
17900b57cec5SDimitry Andric DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1791fe6060f1SDimitry Andric }
17920b57cec5SDimitry Andric
17930b57cec5SDimitry Andric // Attempt to coalesce the ranges of two otherwise identical
17940b57cec5SDimitry Andric // DebugLocEntries.
17950b57cec5SDimitry Andric auto CurEntry = DebugLoc.rbegin();
17960b57cec5SDimitry Andric LLVM_DEBUG({
17970b57cec5SDimitry Andric dbgs() << CurEntry->getValues().size() << " Values:\n";
17980b57cec5SDimitry Andric for (auto &Value : CurEntry->getValues())
17990b57cec5SDimitry Andric Value.dump();
18000b57cec5SDimitry Andric dbgs() << "-----\n";
18010b57cec5SDimitry Andric });
18020b57cec5SDimitry Andric
18030b57cec5SDimitry Andric auto PrevEntry = std::next(CurEntry);
18040b57cec5SDimitry Andric if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
18050b57cec5SDimitry Andric DebugLoc.pop_back();
18060b57cec5SDimitry Andric }
18070b57cec5SDimitry Andric
1808fe6060f1SDimitry Andric if (!isSafeForSingleLocation ||
1809fe6060f1SDimitry Andric !validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering()))
1810fe6060f1SDimitry Andric return false;
1811fe6060f1SDimitry Andric
1812fe6060f1SDimitry Andric if (DebugLoc.size() == 1)
1813fe6060f1SDimitry Andric return true;
1814fe6060f1SDimitry Andric
1815fe6060f1SDimitry Andric if (!Asm->MF->hasBBSections())
1816fe6060f1SDimitry Andric return false;
1817fe6060f1SDimitry Andric
1818fe6060f1SDimitry Andric // Check here to see if loclist can be merged into a single range. If not,
1819fe6060f1SDimitry Andric // we must keep the split loclists per section. This does exactly what
1820fe6060f1SDimitry Andric // MergeRanges does without sections. We don't actually merge the ranges
1821fe6060f1SDimitry Andric // as the split ranges must be kept intact if this cannot be collapsed
1822fe6060f1SDimitry Andric // into a single range.
1823fe6060f1SDimitry Andric const MachineBasicBlock *RangeMBB = nullptr;
1824fe6060f1SDimitry Andric if (DebugLoc[0].getBeginSym() == Asm->getFunctionBegin())
1825fe6060f1SDimitry Andric RangeMBB = &Asm->MF->front();
1826fe6060f1SDimitry Andric else
1827fe6060f1SDimitry Andric RangeMBB = Entries.begin()->getInstr()->getParent();
1828fe6060f1SDimitry Andric auto *CurEntry = DebugLoc.begin();
1829fe6060f1SDimitry Andric auto *NextEntry = std::next(CurEntry);
1830fe6060f1SDimitry Andric while (NextEntry != DebugLoc.end()) {
1831fe6060f1SDimitry Andric // Get the last machine basic block of this section.
1832fe6060f1SDimitry Andric while (!RangeMBB->isEndSection())
1833fe6060f1SDimitry Andric RangeMBB = RangeMBB->getNextNode();
1834fe6060f1SDimitry Andric if (!RangeMBB->getNextNode())
1835fe6060f1SDimitry Andric return false;
1836fe6060f1SDimitry Andric // CurEntry should end the current section and NextEntry should start
1837fe6060f1SDimitry Andric // the next section and the Values must match for these two ranges to be
1838fe6060f1SDimitry Andric // merged.
1839fe6060f1SDimitry Andric if (CurEntry->getEndSym() != RangeMBB->getEndSymbol() ||
1840fe6060f1SDimitry Andric NextEntry->getBeginSym() != RangeMBB->getNextNode()->getSymbol() ||
1841fe6060f1SDimitry Andric CurEntry->getValues() != NextEntry->getValues())
1842fe6060f1SDimitry Andric return false;
1843fe6060f1SDimitry Andric RangeMBB = RangeMBB->getNextNode();
1844fe6060f1SDimitry Andric CurEntry = NextEntry;
1845fe6060f1SDimitry Andric NextEntry = std::next(CurEntry);
1846fe6060f1SDimitry Andric }
1847fe6060f1SDimitry Andric return true;
18480b57cec5SDimitry Andric }
18490b57cec5SDimitry Andric
createConcreteEntity(DwarfCompileUnit & TheCU,LexicalScope & Scope,const DINode * Node,const DILocation * Location,const MCSymbol * Sym)18500b57cec5SDimitry Andric DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
18510b57cec5SDimitry Andric LexicalScope &Scope,
18520b57cec5SDimitry Andric const DINode *Node,
18530b57cec5SDimitry Andric const DILocation *Location,
18540b57cec5SDimitry Andric const MCSymbol *Sym) {
18550b57cec5SDimitry Andric ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
18560b57cec5SDimitry Andric if (isa<const DILocalVariable>(Node)) {
18570b57cec5SDimitry Andric ConcreteEntities.push_back(
18588bcb0991SDimitry Andric std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
18590b57cec5SDimitry Andric Location));
18600b57cec5SDimitry Andric InfoHolder.addScopeVariable(&Scope,
18610b57cec5SDimitry Andric cast<DbgVariable>(ConcreteEntities.back().get()));
18620b57cec5SDimitry Andric } else if (isa<const DILabel>(Node)) {
18630b57cec5SDimitry Andric ConcreteEntities.push_back(
18648bcb0991SDimitry Andric std::make_unique<DbgLabel>(cast<const DILabel>(Node),
18650b57cec5SDimitry Andric Location, Sym));
18660b57cec5SDimitry Andric InfoHolder.addScopeLabel(&Scope,
18670b57cec5SDimitry Andric cast<DbgLabel>(ConcreteEntities.back().get()));
18680b57cec5SDimitry Andric }
18690b57cec5SDimitry Andric return ConcreteEntities.back().get();
18700b57cec5SDimitry Andric }
18710b57cec5SDimitry Andric
18720b57cec5SDimitry Andric // Find variables for each lexical scope.
collectEntityInfo(DwarfCompileUnit & TheCU,const DISubprogram * SP,DenseSet<InlinedEntity> & Processed)18730b57cec5SDimitry Andric void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
18740b57cec5SDimitry Andric const DISubprogram *SP,
18750b57cec5SDimitry Andric DenseSet<InlinedEntity> &Processed) {
18760b57cec5SDimitry Andric // Grab the variable info that was squirreled away in the MMI side-table.
18770b57cec5SDimitry Andric collectVariableInfoFromMFTable(TheCU, Processed);
18780b57cec5SDimitry Andric
18790b57cec5SDimitry Andric for (const auto &I : DbgValues) {
18800b57cec5SDimitry Andric InlinedEntity IV = I.first;
18810b57cec5SDimitry Andric if (Processed.count(IV))
18820b57cec5SDimitry Andric continue;
18830b57cec5SDimitry Andric
18840b57cec5SDimitry Andric // Instruction ranges, specifying where IV is accessible.
18850b57cec5SDimitry Andric const auto &HistoryMapEntries = I.second;
1886fe6060f1SDimitry Andric
1887fe6060f1SDimitry Andric // Try to find any non-empty variable location. Do not create a concrete
1888fe6060f1SDimitry Andric // entity if there are no locations.
1889fe6060f1SDimitry Andric if (!DbgValues.hasNonEmptyLocation(HistoryMapEntries))
18900b57cec5SDimitry Andric continue;
18910b57cec5SDimitry Andric
18920b57cec5SDimitry Andric LexicalScope *Scope = nullptr;
18930b57cec5SDimitry Andric const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
18940b57cec5SDimitry Andric if (const DILocation *IA = IV.second)
18950b57cec5SDimitry Andric Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
18960b57cec5SDimitry Andric else
18970b57cec5SDimitry Andric Scope = LScopes.findLexicalScope(LocalVar->getScope());
18980b57cec5SDimitry Andric // If variable scope is not found then skip this variable.
18990b57cec5SDimitry Andric if (!Scope)
19000b57cec5SDimitry Andric continue;
19010b57cec5SDimitry Andric
19020b57cec5SDimitry Andric Processed.insert(IV);
19030b57cec5SDimitry Andric DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
19040b57cec5SDimitry Andric *Scope, LocalVar, IV.second));
19050b57cec5SDimitry Andric
19060b57cec5SDimitry Andric const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
19070b57cec5SDimitry Andric assert(MInsn->isDebugValue() && "History must begin with debug value");
19080b57cec5SDimitry Andric
19090b57cec5SDimitry Andric // Check if there is a single DBG_VALUE, valid throughout the var's scope.
19100b57cec5SDimitry Andric // If the history map contains a single debug value, there may be an
19110b57cec5SDimitry Andric // additional entry which clobbers the debug value.
19120b57cec5SDimitry Andric size_t HistSize = HistoryMapEntries.size();
19130b57cec5SDimitry Andric bool SingleValueWithClobber =
19140b57cec5SDimitry Andric HistSize == 2 && HistoryMapEntries[1].isClobber();
19150b57cec5SDimitry Andric if (HistSize == 1 || SingleValueWithClobber) {
19160b57cec5SDimitry Andric const auto *End =
19170b57cec5SDimitry Andric SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1918e8d8bef9SDimitry Andric if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
19195f757f3fSDimitry Andric RegVar->emplace<Loc::Single>(MInsn);
19200b57cec5SDimitry Andric continue;
19210b57cec5SDimitry Andric }
19220b57cec5SDimitry Andric }
19230b57cec5SDimitry Andric
19240b57cec5SDimitry Andric // Do not emit location lists if .debug_loc secton is disabled.
19250b57cec5SDimitry Andric if (!useLocSection())
19260b57cec5SDimitry Andric continue;
19270b57cec5SDimitry Andric
19280b57cec5SDimitry Andric // Handle multiple DBG_VALUE instructions describing one variable.
19295f757f3fSDimitry Andric DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar);
19300b57cec5SDimitry Andric
19310b57cec5SDimitry Andric // Build the location list for this variable.
19320b57cec5SDimitry Andric SmallVector<DebugLocEntry, 8> Entries;
1933e8d8bef9SDimitry Andric bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
19340b57cec5SDimitry Andric
19350b57cec5SDimitry Andric // Check whether buildLocationList managed to merge all locations to one
19360b57cec5SDimitry Andric // that is valid throughout the variable's scope. If so, produce single
19370b57cec5SDimitry Andric // value location.
19380b57cec5SDimitry Andric if (isValidSingleLocation) {
19395f757f3fSDimitry Andric RegVar->emplace<Loc::Single>(Entries[0].getValues()[0]);
19400b57cec5SDimitry Andric continue;
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric
19430b57cec5SDimitry Andric // If the variable has a DIBasicType, extract it. Basic types cannot have
19440b57cec5SDimitry Andric // unique identifiers, so don't bother resolving the type with the
19450b57cec5SDimitry Andric // identifier map.
19460b57cec5SDimitry Andric const DIBasicType *BT = dyn_cast<DIBasicType>(
19470b57cec5SDimitry Andric static_cast<const Metadata *>(LocalVar->getType()));
19480b57cec5SDimitry Andric
19490b57cec5SDimitry Andric // Finalize the entry by lowering it into a DWARF bytestream.
19500b57cec5SDimitry Andric for (auto &Entry : Entries)
19510b57cec5SDimitry Andric Entry.finalize(*Asm, List, BT, TheCU);
19520b57cec5SDimitry Andric }
19530b57cec5SDimitry Andric
19540b57cec5SDimitry Andric // For each InlinedEntity collected from DBG_LABEL instructions, convert to
19550b57cec5SDimitry Andric // DWARF-related DbgLabel.
19560b57cec5SDimitry Andric for (const auto &I : DbgLabels) {
19570b57cec5SDimitry Andric InlinedEntity IL = I.first;
19580b57cec5SDimitry Andric const MachineInstr *MI = I.second;
19590b57cec5SDimitry Andric if (MI == nullptr)
19600b57cec5SDimitry Andric continue;
19610b57cec5SDimitry Andric
19620b57cec5SDimitry Andric LexicalScope *Scope = nullptr;
19630b57cec5SDimitry Andric const DILabel *Label = cast<DILabel>(IL.first);
19648bcb0991SDimitry Andric // The scope could have an extra lexical block file.
19658bcb0991SDimitry Andric const DILocalScope *LocalScope =
19668bcb0991SDimitry Andric Label->getScope()->getNonLexicalBlockFileScope();
19670b57cec5SDimitry Andric // Get inlined DILocation if it is inlined label.
19680b57cec5SDimitry Andric if (const DILocation *IA = IL.second)
19698bcb0991SDimitry Andric Scope = LScopes.findInlinedScope(LocalScope, IA);
19700b57cec5SDimitry Andric else
19718bcb0991SDimitry Andric Scope = LScopes.findLexicalScope(LocalScope);
19720b57cec5SDimitry Andric // If label scope is not found then skip this label.
19730b57cec5SDimitry Andric if (!Scope)
19740b57cec5SDimitry Andric continue;
19750b57cec5SDimitry Andric
19760b57cec5SDimitry Andric Processed.insert(IL);
19770b57cec5SDimitry Andric /// At this point, the temporary label is created.
19780b57cec5SDimitry Andric /// Save the temporary label to DbgLabel entity to get the
19790b57cec5SDimitry Andric /// actually address when generating Dwarf DIE.
19800b57cec5SDimitry Andric MCSymbol *Sym = getLabelBeforeInsn(MI);
19810b57cec5SDimitry Andric createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
19820b57cec5SDimitry Andric }
19830b57cec5SDimitry Andric
198406c3fb27SDimitry Andric // Collect info for retained nodes.
19850b57cec5SDimitry Andric for (const DINode *DN : SP->getRetainedNodes()) {
198606c3fb27SDimitry Andric const auto *LS = getRetainedNodeScope(DN);
198706c3fb27SDimitry Andric if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
19880b57cec5SDimitry Andric if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
19890b57cec5SDimitry Andric continue;
199006c3fb27SDimitry Andric LexicalScope *LexS = LScopes.findLexicalScope(LS);
199106c3fb27SDimitry Andric if (LexS)
199206c3fb27SDimitry Andric createConcreteEntity(TheCU, *LexS, DN, nullptr);
199306c3fb27SDimitry Andric } else {
199406c3fb27SDimitry Andric LocalDeclsPerLS[LS].insert(DN);
19950b57cec5SDimitry Andric }
19960b57cec5SDimitry Andric }
19970b57cec5SDimitry Andric }
19980b57cec5SDimitry Andric
19990b57cec5SDimitry Andric // Process beginning of an instruction.
beginInstruction(const MachineInstr * MI)20000b57cec5SDimitry Andric void DwarfDebug::beginInstruction(const MachineInstr *MI) {
20015ffd83dbSDimitry Andric const MachineFunction &MF = *MI->getMF();
20025ffd83dbSDimitry Andric const auto *SP = MF.getFunction().getSubprogram();
20035ffd83dbSDimitry Andric bool NoDebug =
20045ffd83dbSDimitry Andric !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
20055ffd83dbSDimitry Andric
20065ffd83dbSDimitry Andric // Delay slot support check.
20075ffd83dbSDimitry Andric auto delaySlotSupported = [](const MachineInstr &MI) {
20085ffd83dbSDimitry Andric if (!MI.isBundledWithSucc())
20095ffd83dbSDimitry Andric return false;
20105ffd83dbSDimitry Andric auto Suc = std::next(MI.getIterator());
20115ffd83dbSDimitry Andric (void)Suc;
20125ffd83dbSDimitry Andric // Ensure that delay slot instruction is successor of the call instruction.
20135ffd83dbSDimitry Andric // Ex. CALL_INSTRUCTION {
20145ffd83dbSDimitry Andric // DELAY_SLOT_INSTRUCTION }
20155ffd83dbSDimitry Andric assert(Suc->isBundledWithPred() &&
20165ffd83dbSDimitry Andric "Call bundle instructions are out of order");
20175ffd83dbSDimitry Andric return true;
20185ffd83dbSDimitry Andric };
20195ffd83dbSDimitry Andric
20205ffd83dbSDimitry Andric // When describing calls, we need a label for the call instruction.
20215ffd83dbSDimitry Andric if (!NoDebug && SP->areAllCallsDescribed() &&
20225ffd83dbSDimitry Andric MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
20235ffd83dbSDimitry Andric (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
20245ffd83dbSDimitry Andric const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
20255ffd83dbSDimitry Andric bool IsTail = TII->isTailCall(*MI);
20265ffd83dbSDimitry Andric // For tail calls, we need the address of the branch instruction for
20275ffd83dbSDimitry Andric // DW_AT_call_pc.
20285ffd83dbSDimitry Andric if (IsTail)
20295ffd83dbSDimitry Andric requestLabelBeforeInsn(MI);
20305ffd83dbSDimitry Andric // For non-tail calls, we need the return address for the call for
20315ffd83dbSDimitry Andric // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
20325ffd83dbSDimitry Andric // tail calls as well.
20335ffd83dbSDimitry Andric requestLabelAfterInsn(MI);
20345ffd83dbSDimitry Andric }
20355ffd83dbSDimitry Andric
20360b57cec5SDimitry Andric DebugHandlerBase::beginInstruction(MI);
2037e8d8bef9SDimitry Andric if (!CurMI)
2038e8d8bef9SDimitry Andric return;
20390b57cec5SDimitry Andric
20405ffd83dbSDimitry Andric if (NoDebug)
20410b57cec5SDimitry Andric return;
20420b57cec5SDimitry Andric
20430b57cec5SDimitry Andric // Check if source location changes, but ignore DBG_VALUE and CFI locations.
20440b57cec5SDimitry Andric // If the instruction is part of the function frame setup code, do not emit
20450b57cec5SDimitry Andric // any line record, as there is no correspondence with any user code.
20460b57cec5SDimitry Andric if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
20470b57cec5SDimitry Andric return;
20480b57cec5SDimitry Andric const DebugLoc &DL = MI->getDebugLoc();
2049bdd1243dSDimitry Andric unsigned Flags = 0;
2050bdd1243dSDimitry Andric
2051bdd1243dSDimitry Andric if (MI->getFlag(MachineInstr::FrameDestroy) && DL) {
2052bdd1243dSDimitry Andric const MachineBasicBlock *MBB = MI->getParent();
2053bdd1243dSDimitry Andric if (MBB && (MBB != EpilogBeginBlock)) {
2054bdd1243dSDimitry Andric // First time FrameDestroy has been seen in this basic block
2055bdd1243dSDimitry Andric EpilogBeginBlock = MBB;
2056bdd1243dSDimitry Andric Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2057bdd1243dSDimitry Andric }
2058bdd1243dSDimitry Andric }
2059bdd1243dSDimitry Andric
20600b57cec5SDimitry Andric // When we emit a line-0 record, we don't update PrevInstLoc; so look at
20610b57cec5SDimitry Andric // the last line number actually emitted, to see if it was line 0.
20620b57cec5SDimitry Andric unsigned LastAsmLine =
20630b57cec5SDimitry Andric Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
20640b57cec5SDimitry Andric
206506c3fb27SDimitry Andric bool PrevInstInSameSection =
206606c3fb27SDimitry Andric (!PrevInstBB ||
2067*0fca6ea1SDimitry Andric PrevInstBB->getSectionID() == MI->getParent()->getSectionID());
206806c3fb27SDimitry Andric if (DL == PrevInstLoc && PrevInstInSameSection) {
20690b57cec5SDimitry Andric // If we have an ongoing unspecified location, nothing to do here.
20700b57cec5SDimitry Andric if (!DL)
20710b57cec5SDimitry Andric return;
20720b57cec5SDimitry Andric // We have an explicit location, same as the previous location.
20730b57cec5SDimitry Andric // But we might be coming back to it after a line 0 record.
2074bdd1243dSDimitry Andric if ((LastAsmLine == 0 && DL.getLine() != 0) || Flags) {
20750b57cec5SDimitry Andric // Reinstate the source location but not marked as a statement.
20760b57cec5SDimitry Andric const MDNode *Scope = DL.getScope();
2077bdd1243dSDimitry Andric recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
20780b57cec5SDimitry Andric }
20790b57cec5SDimitry Andric return;
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric
20820b57cec5SDimitry Andric if (!DL) {
20830b57cec5SDimitry Andric // We have an unspecified location, which might want to be line 0.
20840b57cec5SDimitry Andric // If we have already emitted a line-0 record, don't repeat it.
20850b57cec5SDimitry Andric if (LastAsmLine == 0)
20860b57cec5SDimitry Andric return;
20870b57cec5SDimitry Andric // If user said Don't Do That, don't do that.
20880b57cec5SDimitry Andric if (UnknownLocations == Disable)
20890b57cec5SDimitry Andric return;
20900b57cec5SDimitry Andric // See if we have a reason to emit a line-0 record now.
20910b57cec5SDimitry Andric // Reasons to emit a line-0 record include:
20920b57cec5SDimitry Andric // - User asked for it (UnknownLocations).
20930b57cec5SDimitry Andric // - Instruction has a label, so it's referenced from somewhere else,
20940b57cec5SDimitry Andric // possibly debug information; we want it to have a source location.
20950b57cec5SDimitry Andric // - Instruction is at the top of a block; we don't want to inherit the
20960b57cec5SDimitry Andric // location from the physically previous (maybe unrelated) block.
20970b57cec5SDimitry Andric if (UnknownLocations == Enable || PrevLabel ||
20980b57cec5SDimitry Andric (PrevInstBB && PrevInstBB != MI->getParent())) {
20990b57cec5SDimitry Andric // Preserve the file and column numbers, if we can, to save space in
21000b57cec5SDimitry Andric // the encoded line table.
21010b57cec5SDimitry Andric // Do not update PrevInstLoc, it remembers the last non-0 line.
21020b57cec5SDimitry Andric const MDNode *Scope = nullptr;
21030b57cec5SDimitry Andric unsigned Column = 0;
21040b57cec5SDimitry Andric if (PrevInstLoc) {
21050b57cec5SDimitry Andric Scope = PrevInstLoc.getScope();
21060b57cec5SDimitry Andric Column = PrevInstLoc.getCol();
21070b57cec5SDimitry Andric }
21080b57cec5SDimitry Andric recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
21090b57cec5SDimitry Andric }
21100b57cec5SDimitry Andric return;
21110b57cec5SDimitry Andric }
21120b57cec5SDimitry Andric
21130b57cec5SDimitry Andric // We have an explicit location, different from the previous location.
21140b57cec5SDimitry Andric // Don't repeat a line-0 record, but otherwise emit the new location.
21150b57cec5SDimitry Andric // (The new location might be an explicit line 0, which we do emit.)
21160b57cec5SDimitry Andric if (DL.getLine() == 0 && LastAsmLine == 0)
21170b57cec5SDimitry Andric return;
21180b57cec5SDimitry Andric if (DL == PrologEndLoc) {
21190b57cec5SDimitry Andric Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
21200b57cec5SDimitry Andric PrologEndLoc = DebugLoc();
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric // If the line changed, we call that a new statement; unless we went to
21230b57cec5SDimitry Andric // line 0 and came back, in which case it is not a new statement.
21240b57cec5SDimitry Andric unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
21250b57cec5SDimitry Andric if (DL.getLine() && DL.getLine() != OldLine)
21260b57cec5SDimitry Andric Flags |= DWARF2_FLAG_IS_STMT;
21270b57cec5SDimitry Andric
21280b57cec5SDimitry Andric const MDNode *Scope = DL.getScope();
21290b57cec5SDimitry Andric recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
21300b57cec5SDimitry Andric
21310b57cec5SDimitry Andric // If we're not at line 0, remember this location.
21320b57cec5SDimitry Andric if (DL.getLine())
21330b57cec5SDimitry Andric PrevInstLoc = DL;
21340b57cec5SDimitry Andric }
21350b57cec5SDimitry Andric
findPrologueEndLoc(const MachineFunction * MF)213606c3fb27SDimitry Andric static std::pair<DebugLoc, bool> findPrologueEndLoc(const MachineFunction *MF) {
21370b57cec5SDimitry Andric // First known non-DBG_VALUE and non-frame setup location marks
21380b57cec5SDimitry Andric // the beginning of the function body.
2139349cc55cSDimitry Andric DebugLoc LineZeroLoc;
214006c3fb27SDimitry Andric const Function &F = MF->getFunction();
214106c3fb27SDimitry Andric
214206c3fb27SDimitry Andric // Some instructions may be inserted into prologue after this function. Must
214306c3fb27SDimitry Andric // keep prologue for these cases.
214406c3fb27SDimitry Andric bool IsEmptyPrologue =
214506c3fb27SDimitry Andric !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2146349cc55cSDimitry Andric for (const auto &MBB : *MF) {
2147349cc55cSDimitry Andric for (const auto &MI : MBB) {
214806c3fb27SDimitry Andric if (!MI.isMetaInstruction()) {
214906c3fb27SDimitry Andric if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {
215006c3fb27SDimitry Andric // Scan forward to try to find a non-zero line number. The
215106c3fb27SDimitry Andric // prologue_end marks the first breakpoint in the function after the
215206c3fb27SDimitry Andric // frame setup, and a compiler-generated line 0 location is not a
215306c3fb27SDimitry Andric // meaningful breakpoint. If none is found, return the first
215406c3fb27SDimitry Andric // location after the frame setup.
2155349cc55cSDimitry Andric if (MI.getDebugLoc().getLine())
215606c3fb27SDimitry Andric return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);
215706c3fb27SDimitry Andric
2158349cc55cSDimitry Andric LineZeroLoc = MI.getDebugLoc();
2159349cc55cSDimitry Andric }
216006c3fb27SDimitry Andric IsEmptyPrologue = false;
2161349cc55cSDimitry Andric }
2162349cc55cSDimitry Andric }
216306c3fb27SDimitry Andric }
216406c3fb27SDimitry Andric return std::make_pair(LineZeroLoc, IsEmptyPrologue);
21650b57cec5SDimitry Andric }
21660b57cec5SDimitry Andric
21670b57cec5SDimitry Andric /// Register a source line with debug info. Returns the unique label that was
21680b57cec5SDimitry 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)21690b57cec5SDimitry Andric static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
21700b57cec5SDimitry Andric const MDNode *S, unsigned Flags, unsigned CUID,
21710b57cec5SDimitry Andric uint16_t DwarfVersion,
21720b57cec5SDimitry Andric ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
21730b57cec5SDimitry Andric StringRef Fn;
21740b57cec5SDimitry Andric unsigned FileNo = 1;
21750b57cec5SDimitry Andric unsigned Discriminator = 0;
21760b57cec5SDimitry Andric if (auto *Scope = cast_or_null<DIScope>(S)) {
21770b57cec5SDimitry Andric Fn = Scope->getFilename();
21780b57cec5SDimitry Andric if (Line != 0 && DwarfVersion >= 4)
21790b57cec5SDimitry Andric if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
21800b57cec5SDimitry Andric Discriminator = LBF->getDiscriminator();
21810b57cec5SDimitry Andric
21820b57cec5SDimitry Andric FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
21830b57cec5SDimitry Andric .getOrCreateSourceID(Scope->getFile());
21840b57cec5SDimitry Andric }
21855ffd83dbSDimitry Andric Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
21860b57cec5SDimitry Andric Discriminator, Fn);
21870b57cec5SDimitry Andric }
21880b57cec5SDimitry Andric
emitInitialLocDirective(const MachineFunction & MF,unsigned CUID)21890b57cec5SDimitry Andric DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
21900b57cec5SDimitry Andric unsigned CUID) {
219106c3fb27SDimitry Andric std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);
219206c3fb27SDimitry Andric DebugLoc PrologEndLoc = PrologEnd.first;
219306c3fb27SDimitry Andric bool IsEmptyPrologue = PrologEnd.second;
219406c3fb27SDimitry Andric
21950b57cec5SDimitry Andric // Get beginning of function.
219606c3fb27SDimitry Andric if (PrologEndLoc) {
219706c3fb27SDimitry Andric // If the prolog is empty, no need to generate scope line for the proc.
219806c3fb27SDimitry Andric if (IsEmptyPrologue)
219906c3fb27SDimitry Andric return PrologEndLoc;
220006c3fb27SDimitry Andric
22010b57cec5SDimitry Andric // Ensure the compile unit is created if the function is called before
22020b57cec5SDimitry Andric // beginFunction().
22030b57cec5SDimitry Andric (void)getOrCreateDwarfCompileUnit(
22040b57cec5SDimitry Andric MF.getFunction().getSubprogram()->getUnit());
22050b57cec5SDimitry Andric // We'd like to list the prologue as "not statements" but GDB behaves
22060b57cec5SDimitry Andric // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
22070b57cec5SDimitry Andric const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
22080b57cec5SDimitry Andric ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
22090b57cec5SDimitry Andric CUID, getDwarfVersion(), getUnits());
22100b57cec5SDimitry Andric return PrologEndLoc;
22110b57cec5SDimitry Andric }
22120b57cec5SDimitry Andric return DebugLoc();
22130b57cec5SDimitry Andric }
22140b57cec5SDimitry Andric
22150b57cec5SDimitry Andric // Gather pre-function debug information. Assumes being called immediately
22160b57cec5SDimitry Andric // after the function entry point has been emitted.
beginFunctionImpl(const MachineFunction * MF)22170b57cec5SDimitry Andric void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
22180b57cec5SDimitry Andric CurFn = MF;
22190b57cec5SDimitry Andric
22200b57cec5SDimitry Andric auto *SP = MF->getFunction().getSubprogram();
22210b57cec5SDimitry Andric assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
22220b57cec5SDimitry Andric if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
22230b57cec5SDimitry Andric return;
22240b57cec5SDimitry Andric
22250b57cec5SDimitry Andric DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
22260b57cec5SDimitry Andric
2227349cc55cSDimitry Andric Asm->OutStreamer->getContext().setDwarfCompileUnitID(
2228349cc55cSDimitry Andric getDwarfCompileUnitIDForLineTable(CU));
22290b57cec5SDimitry Andric
22300b57cec5SDimitry Andric // Record beginning of function.
22310b57cec5SDimitry Andric PrologEndLoc = emitInitialLocDirective(
22320b57cec5SDimitry Andric *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
22330b57cec5SDimitry Andric }
22340b57cec5SDimitry Andric
2235349cc55cSDimitry Andric unsigned
getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit & CU)2236349cc55cSDimitry Andric DwarfDebug::getDwarfCompileUnitIDForLineTable(const DwarfCompileUnit &CU) {
2237349cc55cSDimitry Andric // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2238349cc55cSDimitry Andric // belongs to so that we add to the correct per-cu line table in the
2239349cc55cSDimitry Andric // non-asm case.
2240349cc55cSDimitry Andric if (Asm->OutStreamer->hasRawTextSupport())
2241349cc55cSDimitry Andric // Use a single line table if we are generating assembly.
2242349cc55cSDimitry Andric return 0;
2243349cc55cSDimitry Andric else
2244349cc55cSDimitry Andric return CU.getUniqueID();
2245349cc55cSDimitry Andric }
2246349cc55cSDimitry Andric
terminateLineTable(const DwarfCompileUnit * CU)2247349cc55cSDimitry Andric void DwarfDebug::terminateLineTable(const DwarfCompileUnit *CU) {
2248349cc55cSDimitry Andric const auto &CURanges = CU->getRanges();
2249349cc55cSDimitry Andric auto &LineTable = Asm->OutStreamer->getContext().getMCDwarfLineTable(
2250349cc55cSDimitry Andric getDwarfCompileUnitIDForLineTable(*CU));
2251349cc55cSDimitry Andric // Add the last range label for the given CU.
2252349cc55cSDimitry Andric LineTable.getMCLineSections().addEndEntry(
2253349cc55cSDimitry Andric const_cast<MCSymbol *>(CURanges.back().End));
2254349cc55cSDimitry Andric }
2255349cc55cSDimitry Andric
skippedNonDebugFunction()22560b57cec5SDimitry Andric void DwarfDebug::skippedNonDebugFunction() {
22570b57cec5SDimitry Andric // If we don't have a subprogram for this function then there will be a hole
22580b57cec5SDimitry Andric // in the range information. Keep note of this by setting the previously used
22590b57cec5SDimitry Andric // section to nullptr.
2260349cc55cSDimitry Andric // Terminate the pending line table.
2261349cc55cSDimitry Andric if (PrevCU)
2262349cc55cSDimitry Andric terminateLineTable(PrevCU);
22630b57cec5SDimitry Andric PrevCU = nullptr;
22640b57cec5SDimitry Andric CurFn = nullptr;
22650b57cec5SDimitry Andric }
22660b57cec5SDimitry Andric
22670b57cec5SDimitry Andric // Gather and emit post-function debug information.
endFunctionImpl(const MachineFunction * MF)22680b57cec5SDimitry Andric void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
22690b57cec5SDimitry Andric const DISubprogram *SP = MF->getFunction().getSubprogram();
22700b57cec5SDimitry Andric
22710b57cec5SDimitry Andric assert(CurFn == MF &&
22720b57cec5SDimitry Andric "endFunction should be called with the same function as beginFunction");
22730b57cec5SDimitry Andric
22740b57cec5SDimitry Andric // Set DwarfDwarfCompileUnitID in MCContext to default value.
22750b57cec5SDimitry Andric Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
22760b57cec5SDimitry Andric
22770b57cec5SDimitry Andric LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
22780b57cec5SDimitry Andric assert(!FnScope || SP == FnScope->getScopeNode());
227906c3fb27SDimitry Andric DwarfCompileUnit &TheCU = getOrCreateDwarfCompileUnit(SP->getUnit());
22800b57cec5SDimitry Andric if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
22810b57cec5SDimitry Andric PrevLabel = nullptr;
22820b57cec5SDimitry Andric CurFn = nullptr;
22830b57cec5SDimitry Andric return;
22840b57cec5SDimitry Andric }
22850b57cec5SDimitry Andric
22860b57cec5SDimitry Andric DenseSet<InlinedEntity> Processed;
22870b57cec5SDimitry Andric collectEntityInfo(TheCU, SP, Processed);
22880b57cec5SDimitry Andric
22890b57cec5SDimitry Andric // Add the range of this function to the list of ranges for the CU.
22905ffd83dbSDimitry Andric // With basic block sections, add ranges for all basic block sections.
22915ffd83dbSDimitry Andric for (const auto &R : Asm->MBBSectionRanges)
22925ffd83dbSDimitry Andric TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
22930b57cec5SDimitry Andric
22940b57cec5SDimitry Andric // Under -gmlt, skip building the subprogram if there are no inlined
22950b57cec5SDimitry Andric // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
22960b57cec5SDimitry Andric // is still needed as we need its source location.
22970b57cec5SDimitry Andric if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
22980b57cec5SDimitry Andric TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
22990b57cec5SDimitry Andric LScopes.getAbstractScopesList().empty() && !IsDarwin) {
230006c3fb27SDimitry Andric for (const auto &R : Asm->MBBSectionRanges)
230106c3fb27SDimitry Andric addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
230206c3fb27SDimitry Andric
23030b57cec5SDimitry Andric assert(InfoHolder.getScopeVariables().empty());
23040b57cec5SDimitry Andric PrevLabel = nullptr;
23050b57cec5SDimitry Andric CurFn = nullptr;
23060b57cec5SDimitry Andric return;
23070b57cec5SDimitry Andric }
23080b57cec5SDimitry Andric
23090b57cec5SDimitry Andric #ifndef NDEBUG
231006c3fb27SDimitry Andric size_t NumAbstractSubprograms = LScopes.getAbstractScopesList().size();
23110b57cec5SDimitry Andric #endif
23120b57cec5SDimitry Andric for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2313fcaf7f86SDimitry Andric const auto *SP = cast<DISubprogram>(AScope->getScopeNode());
23140b57cec5SDimitry Andric for (const DINode *DN : SP->getRetainedNodes()) {
231506c3fb27SDimitry Andric const auto *LS = getRetainedNodeScope(DN);
231606c3fb27SDimitry Andric // Ensure LexicalScope is created for the scope of this node.
231706c3fb27SDimitry Andric auto *LexS = LScopes.getOrCreateAbstractScope(LS);
231806c3fb27SDimitry Andric assert(LexS && "Expected the LexicalScope to be created.");
231906c3fb27SDimitry Andric if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
23200b57cec5SDimitry Andric // Collect info for variables/labels that were optimized out.
232106c3fb27SDimitry Andric if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||
232206c3fb27SDimitry Andric TheCU.getExistingAbstractEntity(DN))
232306c3fb27SDimitry Andric continue;
232406c3fb27SDimitry Andric TheCU.createAbstractEntity(DN, LexS);
232506c3fb27SDimitry Andric } else {
232606c3fb27SDimitry Andric // Remember the node if this is a local declarations.
232706c3fb27SDimitry Andric LocalDeclsPerLS[LS].insert(DN);
232806c3fb27SDimitry Andric }
232906c3fb27SDimitry Andric assert(
233006c3fb27SDimitry Andric LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
233106c3fb27SDimitry Andric "getOrCreateAbstractScope() inserted an abstract subprogram scope");
23320b57cec5SDimitry Andric }
23330b57cec5SDimitry Andric constructAbstractSubprogramScopeDIE(TheCU, AScope);
23340b57cec5SDimitry Andric }
23350b57cec5SDimitry Andric
23360b57cec5SDimitry Andric ProcessedSPNodes.insert(SP);
23370b57cec5SDimitry Andric DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
23380b57cec5SDimitry Andric if (auto *SkelCU = TheCU.getSkeleton())
23390b57cec5SDimitry Andric if (!LScopes.getAbstractScopesList().empty() &&
23400b57cec5SDimitry Andric TheCU.getCUNode()->getSplitDebugInlining())
23410b57cec5SDimitry Andric SkelCU->constructSubprogramScopeDIE(SP, FnScope);
23420b57cec5SDimitry Andric
23430b57cec5SDimitry Andric // Construct call site entries.
23440b57cec5SDimitry Andric constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
23450b57cec5SDimitry Andric
23460b57cec5SDimitry Andric // Clear debug info
23470b57cec5SDimitry Andric // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
23480b57cec5SDimitry Andric // DbgVariables except those that are also in AbstractVariables (since they
23490b57cec5SDimitry Andric // can be used cross-function)
23500b57cec5SDimitry Andric InfoHolder.getScopeVariables().clear();
23510b57cec5SDimitry Andric InfoHolder.getScopeLabels().clear();
235206c3fb27SDimitry Andric LocalDeclsPerLS.clear();
23530b57cec5SDimitry Andric PrevLabel = nullptr;
23540b57cec5SDimitry Andric CurFn = nullptr;
23550b57cec5SDimitry Andric }
23560b57cec5SDimitry Andric
23570b57cec5SDimitry Andric // Register a source line with debug info. Returns the unique label that was
23580b57cec5SDimitry Andric // emitted and which provides correspondence to the source line list.
recordSourceLine(unsigned Line,unsigned Col,const MDNode * S,unsigned Flags)23590b57cec5SDimitry Andric void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
23600b57cec5SDimitry Andric unsigned Flags) {
23610b57cec5SDimitry Andric ::recordSourceLine(*Asm, Line, Col, S, Flags,
23620b57cec5SDimitry Andric Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
23630b57cec5SDimitry Andric getDwarfVersion(), getUnits());
23640b57cec5SDimitry Andric }
23650b57cec5SDimitry Andric
23660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23670b57cec5SDimitry Andric // Emit Methods
23680b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23690b57cec5SDimitry Andric
23700b57cec5SDimitry Andric // Emit the debug info section.
emitDebugInfo()23710b57cec5SDimitry Andric void DwarfDebug::emitDebugInfo() {
23720b57cec5SDimitry Andric DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
23730b57cec5SDimitry Andric Holder.emitUnits(/* UseOffsets */ false);
23740b57cec5SDimitry Andric }
23750b57cec5SDimitry Andric
23760b57cec5SDimitry Andric // Emit the abbreviation section.
emitAbbreviations()23770b57cec5SDimitry Andric void DwarfDebug::emitAbbreviations() {
23780b57cec5SDimitry Andric DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
23790b57cec5SDimitry Andric
23800b57cec5SDimitry Andric Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric
emitStringOffsetsTableHeader()23830b57cec5SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeader() {
23840b57cec5SDimitry Andric DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
23850b57cec5SDimitry Andric Holder.getStringPool().emitStringOffsetsTableHeader(
23860b57cec5SDimitry Andric *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
23870b57cec5SDimitry Andric Holder.getStringOffsetsStartSym());
23880b57cec5SDimitry Andric }
23890b57cec5SDimitry Andric
23900b57cec5SDimitry Andric template <typename AccelTableT>
emitAccel(AccelTableT & Accel,MCSection * Section,StringRef TableName)23910b57cec5SDimitry Andric void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
23920b57cec5SDimitry Andric StringRef TableName) {
239381ad6265SDimitry Andric Asm->OutStreamer->switchSection(Section);
23940b57cec5SDimitry Andric
23950b57cec5SDimitry Andric // Emit the full data.
23960b57cec5SDimitry Andric emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
23970b57cec5SDimitry Andric }
23980b57cec5SDimitry Andric
emitAccelDebugNames()23990b57cec5SDimitry Andric void DwarfDebug::emitAccelDebugNames() {
24000b57cec5SDimitry Andric // Don't emit anything if we have no compilation units to index.
24010b57cec5SDimitry Andric if (getUnits().empty())
24020b57cec5SDimitry Andric return;
24030b57cec5SDimitry Andric
24040b57cec5SDimitry Andric emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
24050b57cec5SDimitry Andric }
24060b57cec5SDimitry Andric
24070b57cec5SDimitry Andric // Emit visible names into a hashed accelerator table section.
emitAccelNames()24080b57cec5SDimitry Andric void DwarfDebug::emitAccelNames() {
24090b57cec5SDimitry Andric emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
24100b57cec5SDimitry Andric "Names");
24110b57cec5SDimitry Andric }
24120b57cec5SDimitry Andric
24130b57cec5SDimitry Andric // Emit objective C classes and categories into a hashed accelerator table
24140b57cec5SDimitry Andric // section.
emitAccelObjC()24150b57cec5SDimitry Andric void DwarfDebug::emitAccelObjC() {
24160b57cec5SDimitry Andric emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
24170b57cec5SDimitry Andric "ObjC");
24180b57cec5SDimitry Andric }
24190b57cec5SDimitry Andric
24200b57cec5SDimitry Andric // Emit namespace dies into a hashed accelerator table.
emitAccelNamespaces()24210b57cec5SDimitry Andric void DwarfDebug::emitAccelNamespaces() {
24220b57cec5SDimitry Andric emitAccel(AccelNamespace,
24230b57cec5SDimitry Andric Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
24240b57cec5SDimitry Andric "namespac");
24250b57cec5SDimitry Andric }
24260b57cec5SDimitry Andric
24270b57cec5SDimitry Andric // Emit type dies into a hashed accelerator table.
emitAccelTypes()24280b57cec5SDimitry Andric void DwarfDebug::emitAccelTypes() {
24290b57cec5SDimitry Andric emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
24300b57cec5SDimitry Andric "types");
24310b57cec5SDimitry Andric }
24320b57cec5SDimitry Andric
24330b57cec5SDimitry Andric // Public name handling.
24340b57cec5SDimitry Andric // The format for the various pubnames:
24350b57cec5SDimitry Andric //
24360b57cec5SDimitry Andric // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
24370b57cec5SDimitry Andric // for the DIE that is named.
24380b57cec5SDimitry Andric //
24390b57cec5SDimitry Andric // gnu pubnames - offset/index value/name tuples where the offset is the offset
24400b57cec5SDimitry Andric // into the CU and the index value is computed according to the type of value
24410b57cec5SDimitry Andric // for the DIE that is named.
24420b57cec5SDimitry Andric //
24430b57cec5SDimitry Andric // For type units the offset is the offset of the skeleton DIE. For split dwarf
24440b57cec5SDimitry Andric // it's the offset within the debug_info/debug_types dwo section, however, the
24450b57cec5SDimitry Andric // reference in the pubname header doesn't change.
24460b57cec5SDimitry Andric
24470b57cec5SDimitry Andric /// computeIndexValue - Compute the gdb index value for the DIE and CU.
computeIndexValue(DwarfUnit * CU,const DIE * Die)24480b57cec5SDimitry Andric static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
24490b57cec5SDimitry Andric const DIE *Die) {
24500b57cec5SDimitry Andric // Entities that ended up only in a Type Unit reference the CU instead (since
24510b57cec5SDimitry Andric // the pub entry has offsets within the CU there's no real offset that can be
24520b57cec5SDimitry Andric // provided anyway). As it happens all such entities (namespaces and types,
24530b57cec5SDimitry Andric // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
24540b57cec5SDimitry Andric // not to be true it would be necessary to persist this information from the
24550b57cec5SDimitry Andric // point at which the entry is added to the index data structure - since by
24560b57cec5SDimitry Andric // the time the index is built from that, the original type/namespace DIE in a
24570b57cec5SDimitry Andric // type unit has already been destroyed so it can't be queried for properties
24580b57cec5SDimitry Andric // like tag, etc.
24590b57cec5SDimitry Andric if (Die->getTag() == dwarf::DW_TAG_compile_unit)
24600b57cec5SDimitry Andric return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
24610b57cec5SDimitry Andric dwarf::GIEL_EXTERNAL);
24620b57cec5SDimitry Andric dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
24630b57cec5SDimitry Andric
24640b57cec5SDimitry Andric // We could have a specification DIE that has our most of our knowledge,
24650b57cec5SDimitry Andric // look for that now.
24660b57cec5SDimitry Andric if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
24670b57cec5SDimitry Andric DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
24680b57cec5SDimitry Andric if (SpecDIE.findAttribute(dwarf::DW_AT_external))
24690b57cec5SDimitry Andric Linkage = dwarf::GIEL_EXTERNAL;
24700b57cec5SDimitry Andric } else if (Die->findAttribute(dwarf::DW_AT_external))
24710b57cec5SDimitry Andric Linkage = dwarf::GIEL_EXTERNAL;
24720b57cec5SDimitry Andric
24730b57cec5SDimitry Andric switch (Die->getTag()) {
24740b57cec5SDimitry Andric case dwarf::DW_TAG_class_type:
24750b57cec5SDimitry Andric case dwarf::DW_TAG_structure_type:
24760b57cec5SDimitry Andric case dwarf::DW_TAG_union_type:
24770b57cec5SDimitry Andric case dwarf::DW_TAG_enumeration_type:
24780b57cec5SDimitry Andric return dwarf::PubIndexEntryDescriptor(
24798bcb0991SDimitry Andric dwarf::GIEK_TYPE,
24808bcb0991SDimitry Andric dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
24818bcb0991SDimitry Andric ? dwarf::GIEL_EXTERNAL
24828bcb0991SDimitry Andric : dwarf::GIEL_STATIC);
24830b57cec5SDimitry Andric case dwarf::DW_TAG_typedef:
24840b57cec5SDimitry Andric case dwarf::DW_TAG_base_type:
24850b57cec5SDimitry Andric case dwarf::DW_TAG_subrange_type:
2486*0fca6ea1SDimitry Andric case dwarf::DW_TAG_template_alias:
24870b57cec5SDimitry Andric return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
24880b57cec5SDimitry Andric case dwarf::DW_TAG_namespace:
24890b57cec5SDimitry Andric return dwarf::GIEK_TYPE;
24900b57cec5SDimitry Andric case dwarf::DW_TAG_subprogram:
24910b57cec5SDimitry Andric return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
24920b57cec5SDimitry Andric case dwarf::DW_TAG_variable:
24930b57cec5SDimitry Andric return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
24940b57cec5SDimitry Andric case dwarf::DW_TAG_enumerator:
24950b57cec5SDimitry Andric return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
24960b57cec5SDimitry Andric dwarf::GIEL_STATIC);
24970b57cec5SDimitry Andric default:
24980b57cec5SDimitry Andric return dwarf::GIEK_NONE;
24990b57cec5SDimitry Andric }
25000b57cec5SDimitry Andric }
25010b57cec5SDimitry Andric
25020b57cec5SDimitry Andric /// emitDebugPubSections - Emit visible names and types into debug pubnames and
25030b57cec5SDimitry Andric /// pubtypes sections.
emitDebugPubSections()25040b57cec5SDimitry Andric void DwarfDebug::emitDebugPubSections() {
25050b57cec5SDimitry Andric for (const auto &NU : CUMap) {
25060b57cec5SDimitry Andric DwarfCompileUnit *TheU = NU.second;
25070b57cec5SDimitry Andric if (!TheU->hasDwarfPubSections())
25080b57cec5SDimitry Andric continue;
25090b57cec5SDimitry Andric
25100b57cec5SDimitry Andric bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
25110b57cec5SDimitry Andric DICompileUnit::DebugNameTableKind::GNU;
25120b57cec5SDimitry Andric
251381ad6265SDimitry Andric Asm->OutStreamer->switchSection(
25140b57cec5SDimitry Andric GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
25150b57cec5SDimitry Andric : Asm->getObjFileLowering().getDwarfPubNamesSection());
25160b57cec5SDimitry Andric emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
25170b57cec5SDimitry Andric
251881ad6265SDimitry Andric Asm->OutStreamer->switchSection(
25190b57cec5SDimitry Andric GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
25200b57cec5SDimitry Andric : Asm->getObjFileLowering().getDwarfPubTypesSection());
25210b57cec5SDimitry Andric emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
25220b57cec5SDimitry Andric }
25230b57cec5SDimitry Andric }
25240b57cec5SDimitry Andric
emitSectionReference(const DwarfCompileUnit & CU)25250b57cec5SDimitry Andric void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
25260b57cec5SDimitry Andric if (useSectionsAsReferences())
25275ffd83dbSDimitry Andric Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
25280b57cec5SDimitry Andric CU.getDebugSectionOffset());
25290b57cec5SDimitry Andric else
25300b57cec5SDimitry Andric Asm->emitDwarfSymbolReference(CU.getLabelBegin());
25310b57cec5SDimitry Andric }
25320b57cec5SDimitry Andric
emitDebugPubSection(bool GnuStyle,StringRef Name,DwarfCompileUnit * TheU,const StringMap<const DIE * > & Globals)25330b57cec5SDimitry Andric void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
25340b57cec5SDimitry Andric DwarfCompileUnit *TheU,
25350b57cec5SDimitry Andric const StringMap<const DIE *> &Globals) {
25360b57cec5SDimitry Andric if (auto *Skeleton = TheU->getSkeleton())
25370b57cec5SDimitry Andric TheU = Skeleton;
25380b57cec5SDimitry Andric
25390b57cec5SDimitry Andric // Emit the header.
2540fe6060f1SDimitry Andric MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
2541fe6060f1SDimitry Andric "pub" + Name, "Length of Public " + Name + " Info");
25420b57cec5SDimitry Andric
25430b57cec5SDimitry Andric Asm->OutStreamer->AddComment("DWARF Version");
25440b57cec5SDimitry Andric Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
25450b57cec5SDimitry Andric
25460b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
25470b57cec5SDimitry Andric emitSectionReference(*TheU);
25480b57cec5SDimitry Andric
25490b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Compilation Unit Length");
2550e8d8bef9SDimitry Andric Asm->emitDwarfLengthOrOffset(TheU->getLength());
25510b57cec5SDimitry Andric
25520b57cec5SDimitry Andric // Emit the pubnames for this compilation unit.
255306c3fb27SDimitry Andric SmallVector<std::pair<StringRef, const DIE *>, 0> Vec;
255406c3fb27SDimitry Andric for (const auto &GI : Globals)
255506c3fb27SDimitry Andric Vec.emplace_back(GI.first(), GI.second);
255606c3fb27SDimitry Andric llvm::sort(Vec, [](auto &A, auto &B) {
255706c3fb27SDimitry Andric return A.second->getOffset() < B.second->getOffset();
255806c3fb27SDimitry Andric });
255906c3fb27SDimitry Andric for (const auto &[Name, Entity] : Vec) {
25600b57cec5SDimitry Andric Asm->OutStreamer->AddComment("DIE offset");
2561e8d8bef9SDimitry Andric Asm->emitDwarfLengthOrOffset(Entity->getOffset());
25620b57cec5SDimitry Andric
25630b57cec5SDimitry Andric if (GnuStyle) {
25640b57cec5SDimitry Andric dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
25650b57cec5SDimitry Andric Asm->OutStreamer->AddComment(
25660b57cec5SDimitry Andric Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
25670b57cec5SDimitry Andric ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
25680b57cec5SDimitry Andric Asm->emitInt8(Desc.toBits());
25690b57cec5SDimitry Andric }
25700b57cec5SDimitry Andric
25710b57cec5SDimitry Andric Asm->OutStreamer->AddComment("External Name");
257206c3fb27SDimitry Andric Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));
25730b57cec5SDimitry Andric }
25740b57cec5SDimitry Andric
25750b57cec5SDimitry Andric Asm->OutStreamer->AddComment("End Mark");
2576e8d8bef9SDimitry Andric Asm->emitDwarfLengthOrOffset(0);
25775ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(EndLabel);
25780b57cec5SDimitry Andric }
25790b57cec5SDimitry Andric
25800b57cec5SDimitry Andric /// Emit null-terminated strings into a debug str section.
emitDebugStr()25810b57cec5SDimitry Andric void DwarfDebug::emitDebugStr() {
25820b57cec5SDimitry Andric MCSection *StringOffsetsSection = nullptr;
25830b57cec5SDimitry Andric if (useSegmentedStringOffsetsTable()) {
25840b57cec5SDimitry Andric emitStringOffsetsTableHeader();
25850b57cec5SDimitry Andric StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
25860b57cec5SDimitry Andric }
25870b57cec5SDimitry Andric DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
25880b57cec5SDimitry Andric Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
25890b57cec5SDimitry Andric StringOffsetsSection, /* UseRelativeOffsets = */ true);
25900b57cec5SDimitry Andric }
25910b57cec5SDimitry Andric
emitDebugLocEntry(ByteStreamer & Streamer,const DebugLocStream::Entry & Entry,const DwarfCompileUnit * CU)25920b57cec5SDimitry Andric void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
25930b57cec5SDimitry Andric const DebugLocStream::Entry &Entry,
25940b57cec5SDimitry Andric const DwarfCompileUnit *CU) {
25950b57cec5SDimitry Andric auto &&Comments = DebugLocs.getComments(Entry);
25960b57cec5SDimitry Andric auto Comment = Comments.begin();
25970b57cec5SDimitry Andric auto End = Comments.end();
25980b57cec5SDimitry Andric
25990b57cec5SDimitry Andric // The expressions are inserted into a byte stream rather early (see
26000b57cec5SDimitry Andric // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
26010b57cec5SDimitry Andric // need to reference a base_type DIE the offset of that DIE is not yet known.
26020b57cec5SDimitry Andric // To deal with this we instead insert a placeholder early and then extract
26030b57cec5SDimitry Andric // it here and replace it with the real reference.
26040b57cec5SDimitry Andric unsigned PtrSize = Asm->MAI->getCodePointerSize();
26050b57cec5SDimitry Andric DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
26060b57cec5SDimitry Andric DebugLocs.getBytes(Entry).size()),
26070b57cec5SDimitry Andric Asm->getDataLayout().isLittleEndian(), PtrSize);
26085ffd83dbSDimitry Andric DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
26090b57cec5SDimitry Andric
26100b57cec5SDimitry Andric using Encoding = DWARFExpression::Operation::Encoding;
26118bcb0991SDimitry Andric uint64_t Offset = 0;
2612fcaf7f86SDimitry Andric for (const auto &Op : Expr) {
26130b57cec5SDimitry Andric assert(Op.getCode() != dwarf::DW_OP_const_type &&
26140b57cec5SDimitry Andric "3 operand ops not yet supported");
261506c3fb27SDimitry Andric assert(!Op.getSubCode() && "SubOps not yet supported");
2616e8d8bef9SDimitry Andric Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
26170b57cec5SDimitry Andric Offset++;
261806c3fb27SDimitry Andric for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
26190b57cec5SDimitry Andric if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
262004eeddc0SDimitry Andric unsigned Length =
262104eeddc0SDimitry Andric Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
26220b57cec5SDimitry Andric // Make sure comments stay aligned.
262304eeddc0SDimitry Andric for (unsigned J = 0; J < Length; ++J)
26240b57cec5SDimitry Andric if (Comment != End)
26250b57cec5SDimitry Andric Comment++;
26260b57cec5SDimitry Andric } else {
26278bcb0991SDimitry Andric for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2628e8d8bef9SDimitry Andric Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
26290b57cec5SDimitry Andric }
26300b57cec5SDimitry Andric Offset = Op.getOperandEndOffset(I);
26310b57cec5SDimitry Andric }
26320b57cec5SDimitry Andric assert(Offset == Op.getEndOffset());
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric }
26350b57cec5SDimitry Andric
emitDebugLocValue(const AsmPrinter & AP,const DIBasicType * BT,const DbgValueLoc & Value,DwarfExpression & DwarfExpr)26360b57cec5SDimitry Andric void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
26370b57cec5SDimitry Andric const DbgValueLoc &Value,
26380b57cec5SDimitry Andric DwarfExpression &DwarfExpr) {
26390b57cec5SDimitry Andric auto *DIExpr = Value.getExpression();
26400b57cec5SDimitry Andric DIExpressionCursor ExprCursor(DIExpr);
26410b57cec5SDimitry Andric DwarfExpr.addFragmentOffset(DIExpr);
2642fe6060f1SDimitry Andric
26435f757f3fSDimitry Andric // If the DIExpr is an Entry Value, we want to follow the same code path
2644fe6060f1SDimitry Andric // regardless of whether the DBG_VALUE is variadic or not.
2645fe6060f1SDimitry Andric if (DIExpr && DIExpr->isEntryValue()) {
2646fe6060f1SDimitry Andric // Entry values can only be a single register with no additional DIExpr,
2647fe6060f1SDimitry Andric // so just add it directly.
2648fe6060f1SDimitry Andric assert(Value.getLocEntries().size() == 1);
2649fe6060f1SDimitry Andric assert(Value.getLocEntries()[0].isLocation());
2650fe6060f1SDimitry Andric MachineLocation Location = Value.getLocEntries()[0].getLoc();
2651fe6060f1SDimitry Andric DwarfExpr.setLocation(Location, DIExpr);
2652fe6060f1SDimitry Andric
2653fe6060f1SDimitry Andric DwarfExpr.beginEntryValueExpression(ExprCursor);
2654fe6060f1SDimitry Andric
2655fe6060f1SDimitry Andric const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2656fe6060f1SDimitry Andric if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
2657fe6060f1SDimitry Andric return;
2658fe6060f1SDimitry Andric return DwarfExpr.addExpression(std::move(ExprCursor));
2659fe6060f1SDimitry Andric }
2660fe6060f1SDimitry Andric
26610b57cec5SDimitry Andric // Regular entry.
2662fe6060f1SDimitry Andric auto EmitValueLocEntry = [&DwarfExpr, &BT,
2663fe6060f1SDimitry Andric &AP](const DbgValueLocEntry &Entry,
2664fe6060f1SDimitry Andric DIExpressionCursor &Cursor) -> bool {
2665fe6060f1SDimitry Andric if (Entry.isInt()) {
26660b57cec5SDimitry Andric if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
26670b57cec5SDimitry Andric BT->getEncoding() == dwarf::DW_ATE_signed_char))
2668fe6060f1SDimitry Andric DwarfExpr.addSignedConstant(Entry.getInt());
26690b57cec5SDimitry Andric else
2670fe6060f1SDimitry Andric DwarfExpr.addUnsignedConstant(Entry.getInt());
2671fe6060f1SDimitry Andric } else if (Entry.isLocation()) {
2672fe6060f1SDimitry Andric MachineLocation Location = Entry.getLoc();
2673fe6060f1SDimitry Andric if (Location.isIndirect())
2674fe6060f1SDimitry Andric DwarfExpr.setMemoryLocationKind();
26750b57cec5SDimitry Andric
26760b57cec5SDimitry Andric const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
26770b57cec5SDimitry Andric if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2678fe6060f1SDimitry Andric return false;
2679fe6060f1SDimitry Andric } else if (Entry.isTargetIndexLocation()) {
2680fe6060f1SDimitry Andric TargetIndexLocation Loc = Entry.getTargetIndexLocation();
2681fe6060f1SDimitry Andric // TODO TargetIndexLocation is a target-independent. Currently only the
2682fe6060f1SDimitry Andric // WebAssembly-specific encoding is supported.
2683e8d8bef9SDimitry Andric assert(AP.TM.getTargetTriple().isWasm());
26845ffd83dbSDimitry Andric DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2685fe6060f1SDimitry Andric } else if (Entry.isConstantFP()) {
2686e8d8bef9SDimitry Andric if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2687fe6060f1SDimitry Andric !Cursor) {
2688fe6060f1SDimitry Andric DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2689fe6060f1SDimitry Andric } else if (Entry.getConstantFP()
2690fe6060f1SDimitry Andric ->getValueAPF()
2691fe6060f1SDimitry Andric .bitcastToAPInt()
2692fe6060f1SDimitry Andric .getBitWidth() <= 64 /*bits*/) {
2693fe6060f1SDimitry Andric DwarfExpr.addUnsignedConstant(
2694fe6060f1SDimitry Andric Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2695fe6060f1SDimitry Andric } else {
2696fe6060f1SDimitry Andric LLVM_DEBUG(
2697fe6060f1SDimitry Andric dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
2698fe6060f1SDimitry Andric << Entry.getConstantFP()
2699fe6060f1SDimitry Andric ->getValueAPF()
2700fe6060f1SDimitry Andric .bitcastToAPInt()
2701fe6060f1SDimitry Andric .getBitWidth()
2702fe6060f1SDimitry Andric << " bits\n");
2703fe6060f1SDimitry Andric return false;
2704fe6060f1SDimitry Andric }
2705fe6060f1SDimitry Andric }
2706fe6060f1SDimitry Andric return true;
2707fe6060f1SDimitry Andric };
2708fe6060f1SDimitry Andric
2709fe6060f1SDimitry Andric if (!Value.isVariadic()) {
2710fe6060f1SDimitry Andric if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
2711fe6060f1SDimitry Andric return;
2712fe6060f1SDimitry Andric DwarfExpr.addExpression(std::move(ExprCursor));
2713e8d8bef9SDimitry Andric return;
2714e8d8bef9SDimitry Andric }
2715fe6060f1SDimitry Andric
2716fe6060f1SDimitry Andric // If any of the location entries are registers with the value 0, then the
2717fe6060f1SDimitry Andric // location is undefined.
2718fe6060f1SDimitry Andric if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
2719fe6060f1SDimitry Andric return Entry.isLocation() && !Entry.getLoc().getReg();
2720fe6060f1SDimitry Andric }))
2721fe6060f1SDimitry Andric return;
2722fe6060f1SDimitry Andric
2723fe6060f1SDimitry Andric DwarfExpr.addExpression(
2724fe6060f1SDimitry Andric std::move(ExprCursor),
2725fe6060f1SDimitry Andric [EmitValueLocEntry, &Value](unsigned Idx,
2726fe6060f1SDimitry Andric DIExpressionCursor &Cursor) -> bool {
2727fe6060f1SDimitry Andric return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
2728fe6060f1SDimitry Andric });
27290b57cec5SDimitry Andric }
27300b57cec5SDimitry Andric
finalize(const AsmPrinter & AP,DebugLocStream::ListBuilder & List,const DIBasicType * BT,DwarfCompileUnit & TheCU)27310b57cec5SDimitry Andric void DebugLocEntry::finalize(const AsmPrinter &AP,
27320b57cec5SDimitry Andric DebugLocStream::ListBuilder &List,
27330b57cec5SDimitry Andric const DIBasicType *BT,
27340b57cec5SDimitry Andric DwarfCompileUnit &TheCU) {
27350b57cec5SDimitry Andric assert(!Values.empty() &&
27360b57cec5SDimitry Andric "location list entries without values are redundant");
27370b57cec5SDimitry Andric assert(Begin != End && "unexpected location list entry with empty range");
27380b57cec5SDimitry Andric DebugLocStream::EntryBuilder Entry(List, Begin, End);
27390b57cec5SDimitry Andric BufferByteStreamer Streamer = Entry.getStreamer();
27400b57cec5SDimitry Andric DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
27410b57cec5SDimitry Andric const DbgValueLoc &Value = Values[0];
27420b57cec5SDimitry Andric if (Value.isFragment()) {
27430b57cec5SDimitry Andric // Emit all fragments that belong to the same variable and range.
27440b57cec5SDimitry Andric assert(llvm::all_of(Values, [](DbgValueLoc P) {
27450b57cec5SDimitry Andric return P.isFragment();
27460b57cec5SDimitry Andric }) && "all values are expected to be fragments");
27475ffd83dbSDimitry Andric assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
27480b57cec5SDimitry Andric
2749e8d8bef9SDimitry Andric for (const auto &Fragment : Values)
27500b57cec5SDimitry Andric DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
27510b57cec5SDimitry Andric
27520b57cec5SDimitry Andric } else {
27530b57cec5SDimitry Andric assert(Values.size() == 1 && "only fragments may have >1 value");
27540b57cec5SDimitry Andric DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
27550b57cec5SDimitry Andric }
27560b57cec5SDimitry Andric DwarfExpr.finalize();
2757480093f4SDimitry Andric if (DwarfExpr.TagOffset)
2758480093f4SDimitry Andric List.setTagOffset(*DwarfExpr.TagOffset);
27590b57cec5SDimitry Andric }
27600b57cec5SDimitry Andric
emitDebugLocEntryLocation(const DebugLocStream::Entry & Entry,const DwarfCompileUnit * CU)27610b57cec5SDimitry Andric void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
27620b57cec5SDimitry Andric const DwarfCompileUnit *CU) {
27630b57cec5SDimitry Andric // Emit the size.
27640b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Loc expr size");
27650b57cec5SDimitry Andric if (getDwarfVersion() >= 5)
27665ffd83dbSDimitry Andric Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
27670b57cec5SDimitry Andric else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
27680b57cec5SDimitry Andric Asm->emitInt16(DebugLocs.getBytes(Entry).size());
27690b57cec5SDimitry Andric else {
27700b57cec5SDimitry Andric // The entry is too big to fit into 16 bit, drop it as there is nothing we
27710b57cec5SDimitry Andric // can do.
27720b57cec5SDimitry Andric Asm->emitInt16(0);
27730b57cec5SDimitry Andric return;
27740b57cec5SDimitry Andric }
27750b57cec5SDimitry Andric // Emit the entry.
27760b57cec5SDimitry Andric APByteStreamer Streamer(*Asm);
27770b57cec5SDimitry Andric emitDebugLocEntry(Streamer, Entry, CU);
27780b57cec5SDimitry Andric }
27790b57cec5SDimitry Andric
27800b57cec5SDimitry Andric // Emit the header of a DWARF 5 range list table list table. Returns the symbol
27810b57cec5SDimitry Andric // that designates the end of the table for the caller to emit when the table is
27820b57cec5SDimitry Andric // complete.
emitRnglistsTableHeader(AsmPrinter * Asm,const DwarfFile & Holder)27830b57cec5SDimitry Andric static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
27840b57cec5SDimitry Andric const DwarfFile &Holder) {
27855ffd83dbSDimitry Andric MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
27860b57cec5SDimitry Andric
27870b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Offset entry count");
27880b57cec5SDimitry Andric Asm->emitInt32(Holder.getRangeLists().size());
27895ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
27900b57cec5SDimitry Andric
27910b57cec5SDimitry Andric for (const RangeSpanList &List : Holder.getRangeLists())
2792e8d8bef9SDimitry Andric Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2793e8d8bef9SDimitry Andric Asm->getDwarfOffsetByteSize());
27940b57cec5SDimitry Andric
27950b57cec5SDimitry Andric return TableEnd;
27960b57cec5SDimitry Andric }
27970b57cec5SDimitry Andric
27980b57cec5SDimitry Andric // Emit the header of a DWARF 5 locations list table. Returns the symbol that
27990b57cec5SDimitry Andric // designates the end of the table for the caller to emit when the table is
28000b57cec5SDimitry Andric // complete.
emitLoclistsTableHeader(AsmPrinter * Asm,const DwarfDebug & DD)28010b57cec5SDimitry Andric static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
28028bcb0991SDimitry Andric const DwarfDebug &DD) {
28035ffd83dbSDimitry Andric MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
28048bcb0991SDimitry Andric
28058bcb0991SDimitry Andric const auto &DebugLocs = DD.getDebugLocs();
28060b57cec5SDimitry Andric
28070b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Offset entry count");
2808480093f4SDimitry Andric Asm->emitInt32(DebugLocs.getLists().size());
28095ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(DebugLocs.getSym());
28100b57cec5SDimitry Andric
2811480093f4SDimitry Andric for (const auto &List : DebugLocs.getLists())
2812e8d8bef9SDimitry Andric Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2813e8d8bef9SDimitry Andric Asm->getDwarfOffsetByteSize());
2814480093f4SDimitry Andric
28150b57cec5SDimitry Andric return TableEnd;
28160b57cec5SDimitry Andric }
28170b57cec5SDimitry Andric
28188bcb0991SDimitry 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)28198bcb0991SDimitry Andric static void emitRangeList(
28208bcb0991SDimitry Andric DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
28218bcb0991SDimitry Andric const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
28228bcb0991SDimitry Andric unsigned StartxLength, unsigned EndOfList,
28238bcb0991SDimitry Andric StringRef (*StringifyEnum)(unsigned),
28248bcb0991SDimitry Andric bool ShouldUseBaseAddress,
28258bcb0991SDimitry Andric PayloadEmitter EmitPayload) {
28268bcb0991SDimitry Andric
28278bcb0991SDimitry Andric auto Size = Asm->MAI->getCodePointerSize();
28288bcb0991SDimitry Andric bool UseDwarf5 = DD.getDwarfVersion() >= 5;
28298bcb0991SDimitry Andric
28308bcb0991SDimitry Andric // Emit our symbol so we can find the beginning of the range.
28315ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(Sym);
28328bcb0991SDimitry Andric
28338bcb0991SDimitry Andric // Gather all the ranges that apply to the same section so they can share
28348bcb0991SDimitry Andric // a base address entry.
28358bcb0991SDimitry Andric MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
28368bcb0991SDimitry Andric
28378bcb0991SDimitry Andric for (const auto &Range : R)
28388bcb0991SDimitry Andric SectionRanges[&Range.Begin->getSection()].push_back(&Range);
28398bcb0991SDimitry Andric
28408bcb0991SDimitry Andric const MCSymbol *CUBase = CU.getBaseAddress();
28418bcb0991SDimitry Andric bool BaseIsSet = false;
28428bcb0991SDimitry Andric for (const auto &P : SectionRanges) {
28438bcb0991SDimitry Andric auto *Base = CUBase;
28448bcb0991SDimitry Andric if (!Base && ShouldUseBaseAddress) {
28458bcb0991SDimitry Andric const MCSymbol *Begin = P.second.front()->Begin;
28468bcb0991SDimitry Andric const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
28478bcb0991SDimitry Andric if (!UseDwarf5) {
28488bcb0991SDimitry Andric Base = NewBase;
28498bcb0991SDimitry Andric BaseIsSet = true;
28505ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(-1, Size);
28518bcb0991SDimitry Andric Asm->OutStreamer->AddComment(" base address");
28525ffd83dbSDimitry Andric Asm->OutStreamer->emitSymbolValue(Base, Size);
28538bcb0991SDimitry Andric } else if (NewBase != Begin || P.second.size() > 1) {
28548bcb0991SDimitry Andric // Only use a base address if
28558bcb0991SDimitry Andric // * the existing pool address doesn't match (NewBase != Begin)
28568bcb0991SDimitry Andric // * or, there's more than one entry to share the base address
28578bcb0991SDimitry Andric Base = NewBase;
28588bcb0991SDimitry Andric BaseIsSet = true;
28598bcb0991SDimitry Andric Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
28608bcb0991SDimitry Andric Asm->emitInt8(BaseAddressx);
28618bcb0991SDimitry Andric Asm->OutStreamer->AddComment(" base address index");
28625ffd83dbSDimitry Andric Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
28638bcb0991SDimitry Andric }
28648bcb0991SDimitry Andric } else if (BaseIsSet && !UseDwarf5) {
28658bcb0991SDimitry Andric BaseIsSet = false;
28668bcb0991SDimitry Andric assert(!Base);
28675ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(-1, Size);
28685ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(0, Size);
28698bcb0991SDimitry Andric }
28708bcb0991SDimitry Andric
28718bcb0991SDimitry Andric for (const auto *RS : P.second) {
28728bcb0991SDimitry Andric const MCSymbol *Begin = RS->Begin;
28738bcb0991SDimitry Andric const MCSymbol *End = RS->End;
28748bcb0991SDimitry Andric assert(Begin && "Range without a begin symbol?");
28758bcb0991SDimitry Andric assert(End && "Range without an end symbol?");
28768bcb0991SDimitry Andric if (Base) {
28778bcb0991SDimitry Andric if (UseDwarf5) {
28788bcb0991SDimitry Andric // Emit offset_pair when we have a base.
28798bcb0991SDimitry Andric Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
28808bcb0991SDimitry Andric Asm->emitInt8(OffsetPair);
28818bcb0991SDimitry Andric Asm->OutStreamer->AddComment(" starting offset");
28825ffd83dbSDimitry Andric Asm->emitLabelDifferenceAsULEB128(Begin, Base);
28838bcb0991SDimitry Andric Asm->OutStreamer->AddComment(" ending offset");
28845ffd83dbSDimitry Andric Asm->emitLabelDifferenceAsULEB128(End, Base);
28858bcb0991SDimitry Andric } else {
28865ffd83dbSDimitry Andric Asm->emitLabelDifference(Begin, Base, Size);
28875ffd83dbSDimitry Andric Asm->emitLabelDifference(End, Base, Size);
28888bcb0991SDimitry Andric }
28898bcb0991SDimitry Andric } else if (UseDwarf5) {
28908bcb0991SDimitry Andric Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
28918bcb0991SDimitry Andric Asm->emitInt8(StartxLength);
28928bcb0991SDimitry Andric Asm->OutStreamer->AddComment(" start index");
28935ffd83dbSDimitry Andric Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
28948bcb0991SDimitry Andric Asm->OutStreamer->AddComment(" length");
28955ffd83dbSDimitry Andric Asm->emitLabelDifferenceAsULEB128(End, Begin);
28968bcb0991SDimitry Andric } else {
28975ffd83dbSDimitry Andric Asm->OutStreamer->emitSymbolValue(Begin, Size);
28985ffd83dbSDimitry Andric Asm->OutStreamer->emitSymbolValue(End, Size);
28998bcb0991SDimitry Andric }
29008bcb0991SDimitry Andric EmitPayload(*RS);
29018bcb0991SDimitry Andric }
29028bcb0991SDimitry Andric }
29038bcb0991SDimitry Andric
29048bcb0991SDimitry Andric if (UseDwarf5) {
29058bcb0991SDimitry Andric Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
29068bcb0991SDimitry Andric Asm->emitInt8(EndOfList);
29078bcb0991SDimitry Andric } else {
29088bcb0991SDimitry Andric // Terminate the list with two 0 values.
29095ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(0, Size);
29105ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(0, Size);
29118bcb0991SDimitry Andric }
29128bcb0991SDimitry Andric }
29138bcb0991SDimitry Andric
2914480093f4SDimitry Andric // Handles emission of both debug_loclist / debug_loclist.dwo
emitLocList(DwarfDebug & DD,AsmPrinter * Asm,const DebugLocStream::List & List)29158bcb0991SDimitry Andric static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2916480093f4SDimitry Andric emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2917480093f4SDimitry Andric *List.CU, dwarf::DW_LLE_base_addressx,
2918480093f4SDimitry Andric dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2919480093f4SDimitry Andric dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
29208bcb0991SDimitry Andric /* ShouldUseBaseAddress */ true,
29218bcb0991SDimitry Andric [&](const DebugLocStream::Entry &E) {
29228bcb0991SDimitry Andric DD.emitDebugLocEntryLocation(E, List.CU);
29238bcb0991SDimitry Andric });
29248bcb0991SDimitry Andric }
29258bcb0991SDimitry Andric
emitDebugLocImpl(MCSection * Sec)2926480093f4SDimitry Andric void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
29270b57cec5SDimitry Andric if (DebugLocs.getLists().empty())
29280b57cec5SDimitry Andric return;
29290b57cec5SDimitry Andric
293081ad6265SDimitry Andric Asm->OutStreamer->switchSection(Sec);
2931480093f4SDimitry Andric
29320b57cec5SDimitry Andric MCSymbol *TableEnd = nullptr;
2933480093f4SDimitry Andric if (getDwarfVersion() >= 5)
29348bcb0991SDimitry Andric TableEnd = emitLoclistsTableHeader(Asm, *this);
29350b57cec5SDimitry Andric
29368bcb0991SDimitry Andric for (const auto &List : DebugLocs.getLists())
29378bcb0991SDimitry Andric emitLocList(*this, Asm, List);
29380b57cec5SDimitry Andric
29390b57cec5SDimitry Andric if (TableEnd)
29405ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(TableEnd);
29410b57cec5SDimitry Andric }
29420b57cec5SDimitry Andric
2943480093f4SDimitry Andric // Emit locations into the .debug_loc/.debug_loclists section.
emitDebugLoc()2944480093f4SDimitry Andric void DwarfDebug::emitDebugLoc() {
2945480093f4SDimitry Andric emitDebugLocImpl(
2946480093f4SDimitry Andric getDwarfVersion() >= 5
2947480093f4SDimitry Andric ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2948480093f4SDimitry Andric : Asm->getObjFileLowering().getDwarfLocSection());
2949480093f4SDimitry Andric }
2950480093f4SDimitry Andric
2951480093f4SDimitry Andric // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
emitDebugLocDWO()29520b57cec5SDimitry Andric void DwarfDebug::emitDebugLocDWO() {
2953480093f4SDimitry Andric if (getDwarfVersion() >= 5) {
2954480093f4SDimitry Andric emitDebugLocImpl(
2955480093f4SDimitry Andric Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2956480093f4SDimitry Andric
2957480093f4SDimitry Andric return;
2958480093f4SDimitry Andric }
2959480093f4SDimitry Andric
29600b57cec5SDimitry Andric for (const auto &List : DebugLocs.getLists()) {
296181ad6265SDimitry Andric Asm->OutStreamer->switchSection(
29620b57cec5SDimitry Andric Asm->getObjFileLowering().getDwarfLocDWOSection());
29635ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(List.Label);
2964480093f4SDimitry Andric
29650b57cec5SDimitry Andric for (const auto &Entry : DebugLocs.getEntries(List)) {
29660b57cec5SDimitry Andric // GDB only supports startx_length in pre-standard split-DWARF.
29670b57cec5SDimitry Andric // (in v5 standard loclists, it currently* /only/ supports base_address +
29680b57cec5SDimitry Andric // offset_pair, so the implementations can't really share much since they
29690b57cec5SDimitry Andric // need to use different representations)
29700b57cec5SDimitry Andric // * as of October 2018, at least
29715ffd83dbSDimitry Andric //
29725ffd83dbSDimitry Andric // In v5 (see emitLocList), this uses SectionLabels to reuse existing
29735ffd83dbSDimitry Andric // addresses in the address pool to minimize object size/relocations.
29740b57cec5SDimitry Andric Asm->emitInt8(dwarf::DW_LLE_startx_length);
29758bcb0991SDimitry Andric unsigned idx = AddrPool.getIndex(Entry.Begin);
29765ffd83dbSDimitry Andric Asm->emitULEB128(idx);
2977480093f4SDimitry Andric // Also the pre-standard encoding is slightly different, emitting this as
2978480093f4SDimitry Andric // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
29795ffd83dbSDimitry Andric Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
29800b57cec5SDimitry Andric emitDebugLocEntryLocation(Entry, List.CU);
29810b57cec5SDimitry Andric }
29820b57cec5SDimitry Andric Asm->emitInt8(dwarf::DW_LLE_end_of_list);
29830b57cec5SDimitry Andric }
29840b57cec5SDimitry Andric }
29850b57cec5SDimitry Andric
29860b57cec5SDimitry Andric struct ArangeSpan {
29870b57cec5SDimitry Andric const MCSymbol *Start, *End;
29880b57cec5SDimitry Andric };
29890b57cec5SDimitry Andric
29900b57cec5SDimitry Andric // Emit a debug aranges section, containing a CU lookup for any
29910b57cec5SDimitry Andric // address we can tie back to a CU.
emitDebugARanges()29920b57cec5SDimitry Andric void DwarfDebug::emitDebugARanges() {
2993*0fca6ea1SDimitry Andric if (ArangeLabels.empty())
2994*0fca6ea1SDimitry Andric return;
2995*0fca6ea1SDimitry Andric
29960b57cec5SDimitry Andric // Provides a unique id per text section.
29970b57cec5SDimitry Andric MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
29980b57cec5SDimitry Andric
29990b57cec5SDimitry Andric // Filter labels by section.
30000b57cec5SDimitry Andric for (const SymbolCU &SCU : ArangeLabels) {
30010b57cec5SDimitry Andric if (SCU.Sym->isInSection()) {
30020b57cec5SDimitry Andric // Make a note of this symbol and it's section.
30030b57cec5SDimitry Andric MCSection *Section = &SCU.Sym->getSection();
30040b57cec5SDimitry Andric SectionMap[Section].push_back(SCU);
30050b57cec5SDimitry Andric } else {
30060b57cec5SDimitry Andric // Some symbols (e.g. common/bss on mach-o) can have no section but still
30070b57cec5SDimitry Andric // appear in the output. This sucks as we rely on sections to build
30080b57cec5SDimitry Andric // arange spans. We can do it without, but it's icky.
30090b57cec5SDimitry Andric SectionMap[nullptr].push_back(SCU);
30100b57cec5SDimitry Andric }
30110b57cec5SDimitry Andric }
30120b57cec5SDimitry Andric
30130b57cec5SDimitry Andric DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
30140b57cec5SDimitry Andric
30150b57cec5SDimitry Andric for (auto &I : SectionMap) {
30160b57cec5SDimitry Andric MCSection *Section = I.first;
30170b57cec5SDimitry Andric SmallVector<SymbolCU, 8> &List = I.second;
3018*0fca6ea1SDimitry Andric assert(!List.empty());
30190b57cec5SDimitry Andric
30200b57cec5SDimitry Andric // If we have no section (e.g. common), just write out
30210b57cec5SDimitry Andric // individual spans for each symbol.
30220b57cec5SDimitry Andric if (!Section) {
30230b57cec5SDimitry Andric for (const SymbolCU &Cur : List) {
30240b57cec5SDimitry Andric ArangeSpan Span;
30250b57cec5SDimitry Andric Span.Start = Cur.Sym;
30260b57cec5SDimitry Andric Span.End = nullptr;
30270b57cec5SDimitry Andric assert(Cur.CU);
30280b57cec5SDimitry Andric Spans[Cur.CU].push_back(Span);
30290b57cec5SDimitry Andric }
30300b57cec5SDimitry Andric continue;
30310b57cec5SDimitry Andric }
30320b57cec5SDimitry Andric
30330b57cec5SDimitry Andric // Insert a final terminator.
30340b57cec5SDimitry Andric List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
30350b57cec5SDimitry Andric
30360b57cec5SDimitry Andric // Build spans between each label.
30370b57cec5SDimitry Andric const MCSymbol *StartSym = List[0].Sym;
30380b57cec5SDimitry Andric for (size_t n = 1, e = List.size(); n < e; n++) {
30390b57cec5SDimitry Andric const SymbolCU &Prev = List[n - 1];
30400b57cec5SDimitry Andric const SymbolCU &Cur = List[n];
30410b57cec5SDimitry Andric
30420b57cec5SDimitry Andric // Try and build the longest span we can within the same CU.
30430b57cec5SDimitry Andric if (Cur.CU != Prev.CU) {
30440b57cec5SDimitry Andric ArangeSpan Span;
30450b57cec5SDimitry Andric Span.Start = StartSym;
30460b57cec5SDimitry Andric Span.End = Cur.Sym;
30470b57cec5SDimitry Andric assert(Prev.CU);
30480b57cec5SDimitry Andric Spans[Prev.CU].push_back(Span);
30490b57cec5SDimitry Andric StartSym = Cur.Sym;
30500b57cec5SDimitry Andric }
30510b57cec5SDimitry Andric }
30520b57cec5SDimitry Andric }
30530b57cec5SDimitry Andric
30540b57cec5SDimitry Andric // Start the dwarf aranges section.
305581ad6265SDimitry Andric Asm->OutStreamer->switchSection(
30560b57cec5SDimitry Andric Asm->getObjFileLowering().getDwarfARangesSection());
30570b57cec5SDimitry Andric
30580b57cec5SDimitry Andric unsigned PtrSize = Asm->MAI->getCodePointerSize();
30590b57cec5SDimitry Andric
30600b57cec5SDimitry Andric // Build a list of CUs used.
30610b57cec5SDimitry Andric std::vector<DwarfCompileUnit *> CUs;
30620b57cec5SDimitry Andric for (const auto &it : Spans) {
30630b57cec5SDimitry Andric DwarfCompileUnit *CU = it.first;
30640b57cec5SDimitry Andric CUs.push_back(CU);
30650b57cec5SDimitry Andric }
30660b57cec5SDimitry Andric
30670b57cec5SDimitry Andric // Sort the CU list (again, to ensure consistent output order).
30680b57cec5SDimitry Andric llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
30690b57cec5SDimitry Andric return A->getUniqueID() < B->getUniqueID();
30700b57cec5SDimitry Andric });
30710b57cec5SDimitry Andric
30720b57cec5SDimitry Andric // Emit an arange table for each CU we used.
30730b57cec5SDimitry Andric for (DwarfCompileUnit *CU : CUs) {
30740b57cec5SDimitry Andric std::vector<ArangeSpan> &List = Spans[CU];
30750b57cec5SDimitry Andric
30760b57cec5SDimitry Andric // Describe the skeleton CU's offset and length, not the dwo file's.
30770b57cec5SDimitry Andric if (auto *Skel = CU->getSkeleton())
30780b57cec5SDimitry Andric CU = Skel;
30790b57cec5SDimitry Andric
30800b57cec5SDimitry Andric // Emit size of content not including length itself.
30810b57cec5SDimitry Andric unsigned ContentSize =
30820b57cec5SDimitry Andric sizeof(int16_t) + // DWARF ARange version number
3083e8d8bef9SDimitry Andric Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3084e8d8bef9SDimitry Andric // section
30850b57cec5SDimitry Andric sizeof(int8_t) + // Pointer Size (in bytes)
30860b57cec5SDimitry Andric sizeof(int8_t); // Segment Size (in bytes)
30870b57cec5SDimitry Andric
30880b57cec5SDimitry Andric unsigned TupleSize = PtrSize * 2;
30890b57cec5SDimitry Andric
30900b57cec5SDimitry Andric // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3091e8d8bef9SDimitry Andric unsigned Padding = offsetToAlignment(
3092e8d8bef9SDimitry Andric Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
30930b57cec5SDimitry Andric
30940b57cec5SDimitry Andric ContentSize += Padding;
30950b57cec5SDimitry Andric ContentSize += (List.size() + 1) * TupleSize;
30960b57cec5SDimitry Andric
30970b57cec5SDimitry Andric // For each compile unit, write the list of spans it covers.
3098e8d8bef9SDimitry Andric Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
30990b57cec5SDimitry Andric Asm->OutStreamer->AddComment("DWARF Arange version number");
31000b57cec5SDimitry Andric Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
31010b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
31020b57cec5SDimitry Andric emitSectionReference(*CU);
31030b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Address Size (in bytes)");
31040b57cec5SDimitry Andric Asm->emitInt8(PtrSize);
31050b57cec5SDimitry Andric Asm->OutStreamer->AddComment("Segment Size (in bytes)");
31060b57cec5SDimitry Andric Asm->emitInt8(0);
31070b57cec5SDimitry Andric
31080b57cec5SDimitry Andric Asm->OutStreamer->emitFill(Padding, 0xff);
31090b57cec5SDimitry Andric
31100b57cec5SDimitry Andric for (const ArangeSpan &Span : List) {
31115ffd83dbSDimitry Andric Asm->emitLabelReference(Span.Start, PtrSize);
31120b57cec5SDimitry Andric
311381ad6265SDimitry Andric // Calculate the size as being from the span start to its end.
311481ad6265SDimitry Andric //
311581ad6265SDimitry Andric // If the size is zero, then round it up to one byte. The DWARF
311681ad6265SDimitry Andric // specification requires that entries in this table have nonzero
311781ad6265SDimitry Andric // lengths.
311881ad6265SDimitry Andric auto SizeRef = SymSize.find(Span.Start);
311981ad6265SDimitry Andric if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
31205ffd83dbSDimitry Andric Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
31210b57cec5SDimitry Andric } else {
31220b57cec5SDimitry Andric // For symbols without an end marker (e.g. common), we
31230b57cec5SDimitry Andric // write a single arange entry containing just that one symbol.
312481ad6265SDimitry Andric uint64_t Size;
312581ad6265SDimitry Andric if (SizeRef == SymSize.end() || SizeRef->second == 0)
31260b57cec5SDimitry Andric Size = 1;
312781ad6265SDimitry Andric else
312881ad6265SDimitry Andric Size = SizeRef->second;
31290b57cec5SDimitry Andric
31305ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(Size, PtrSize);
31310b57cec5SDimitry Andric }
31320b57cec5SDimitry Andric }
31330b57cec5SDimitry Andric
31340b57cec5SDimitry Andric Asm->OutStreamer->AddComment("ARange terminator");
31355ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(0, PtrSize);
31365ffd83dbSDimitry Andric Asm->OutStreamer->emitIntValue(0, PtrSize);
31370b57cec5SDimitry Andric }
31380b57cec5SDimitry Andric }
31390b57cec5SDimitry Andric
31400b57cec5SDimitry Andric /// Emit a single range list. We handle both DWARF v5 and earlier.
emitRangeList(DwarfDebug & DD,AsmPrinter * Asm,const RangeSpanList & List)31410b57cec5SDimitry Andric static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
31420b57cec5SDimitry Andric const RangeSpanList &List) {
3143480093f4SDimitry Andric emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
31448bcb0991SDimitry Andric dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
31458bcb0991SDimitry Andric dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
31468bcb0991SDimitry Andric llvm::dwarf::RangeListEncodingString,
3147480093f4SDimitry Andric List.CU->getCUNode()->getRangesBaseAddress() ||
31488bcb0991SDimitry Andric DD.getDwarfVersion() >= 5,
31498bcb0991SDimitry Andric [](auto) {});
31500b57cec5SDimitry Andric }
31510b57cec5SDimitry Andric
emitDebugRangesImpl(const DwarfFile & Holder,MCSection * Section)3152480093f4SDimitry Andric void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3153480093f4SDimitry Andric if (Holder.getRangeLists().empty())
3154480093f4SDimitry Andric return;
3155480093f4SDimitry Andric
3156480093f4SDimitry Andric assert(useRangesSection());
3157480093f4SDimitry Andric assert(!CUMap.empty());
3158480093f4SDimitry Andric assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3159480093f4SDimitry Andric return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3160480093f4SDimitry Andric }));
3161480093f4SDimitry Andric
316281ad6265SDimitry Andric Asm->OutStreamer->switchSection(Section);
3163480093f4SDimitry Andric
3164480093f4SDimitry Andric MCSymbol *TableEnd = nullptr;
3165480093f4SDimitry Andric if (getDwarfVersion() >= 5)
3166480093f4SDimitry Andric TableEnd = emitRnglistsTableHeader(Asm, Holder);
3167480093f4SDimitry Andric
31680b57cec5SDimitry Andric for (const RangeSpanList &List : Holder.getRangeLists())
3169480093f4SDimitry Andric emitRangeList(*this, Asm, List);
31700b57cec5SDimitry Andric
31710b57cec5SDimitry Andric if (TableEnd)
31725ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(TableEnd);
31730b57cec5SDimitry Andric }
31740b57cec5SDimitry Andric
31750b57cec5SDimitry Andric /// Emit address ranges into the .debug_ranges section or into the DWARF v5
31760b57cec5SDimitry Andric /// .debug_rnglists section.
emitDebugRanges()31770b57cec5SDimitry Andric void DwarfDebug::emitDebugRanges() {
31780b57cec5SDimitry Andric const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
31790b57cec5SDimitry Andric
3180480093f4SDimitry Andric emitDebugRangesImpl(Holder,
3181480093f4SDimitry Andric getDwarfVersion() >= 5
3182480093f4SDimitry Andric ? Asm->getObjFileLowering().getDwarfRnglistsSection()
3183480093f4SDimitry Andric : Asm->getObjFileLowering().getDwarfRangesSection());
31840b57cec5SDimitry Andric }
31850b57cec5SDimitry Andric
emitDebugRangesDWO()31860b57cec5SDimitry Andric void DwarfDebug::emitDebugRangesDWO() {
3187480093f4SDimitry Andric emitDebugRangesImpl(InfoHolder,
31880b57cec5SDimitry Andric Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
31890b57cec5SDimitry Andric }
31900b57cec5SDimitry Andric
3191e8d8bef9SDimitry Andric /// Emit the header of a DWARF 5 macro section, or the GNU extension for
3192e8d8bef9SDimitry Andric /// DWARF 4.
emitMacroHeader(AsmPrinter * Asm,const DwarfDebug & DD,const DwarfCompileUnit & CU,uint16_t DwarfVersion)31935ffd83dbSDimitry Andric static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3194e8d8bef9SDimitry Andric const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
31955ffd83dbSDimitry Andric enum HeaderFlagMask {
31965ffd83dbSDimitry Andric #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
31975ffd83dbSDimitry Andric #include "llvm/BinaryFormat/Dwarf.def"
31985ffd83dbSDimitry Andric };
31995ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Macro information version");
3200e8d8bef9SDimitry Andric Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3201e8d8bef9SDimitry Andric // We emit the line offset flag unconditionally here, since line offset should
3202e8d8bef9SDimitry Andric // be mostly present.
3203e8d8bef9SDimitry Andric if (Asm->isDwarf64()) {
3204e8d8bef9SDimitry Andric Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3205e8d8bef9SDimitry Andric Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3206e8d8bef9SDimitry Andric } else {
32075ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3208e8d8bef9SDimitry Andric Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3209e8d8bef9SDimitry Andric }
32105ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("debug_line_offset");
3211e8d8bef9SDimitry Andric if (DD.useSplitDwarf())
3212e8d8bef9SDimitry Andric Asm->emitDwarfLengthOrOffset(0);
3213e8d8bef9SDimitry Andric else
3214e8d8bef9SDimitry Andric Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
32155ffd83dbSDimitry Andric }
32165ffd83dbSDimitry Andric
handleMacroNodes(DIMacroNodeArray Nodes,DwarfCompileUnit & U)32170b57cec5SDimitry Andric void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
32180b57cec5SDimitry Andric for (auto *MN : Nodes) {
32190b57cec5SDimitry Andric if (auto *M = dyn_cast<DIMacro>(MN))
32200b57cec5SDimitry Andric emitMacro(*M);
32210b57cec5SDimitry Andric else if (auto *F = dyn_cast<DIMacroFile>(MN))
32220b57cec5SDimitry Andric emitMacroFile(*F, U);
32230b57cec5SDimitry Andric else
32240b57cec5SDimitry Andric llvm_unreachable("Unexpected DI type!");
32250b57cec5SDimitry Andric }
32260b57cec5SDimitry Andric }
32270b57cec5SDimitry Andric
emitMacro(DIMacro & M)32280b57cec5SDimitry Andric void DwarfDebug::emitMacro(DIMacro &M) {
32290b57cec5SDimitry Andric StringRef Name = M.getName();
32300b57cec5SDimitry Andric StringRef Value = M.getValue();
32315ffd83dbSDimitry Andric
3232e8d8bef9SDimitry Andric // There should be one space between the macro name and the macro value in
3233e8d8bef9SDimitry Andric // define entries. In undef entries, only the macro name is emitted.
3234e8d8bef9SDimitry Andric std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3235e8d8bef9SDimitry Andric
3236e8d8bef9SDimitry Andric if (UseDebugMacroSection) {
3237e8d8bef9SDimitry Andric if (getDwarfVersion() >= 5) {
32385ffd83dbSDimitry Andric unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
32395ffd83dbSDimitry Andric ? dwarf::DW_MACRO_define_strx
32405ffd83dbSDimitry Andric : dwarf::DW_MACRO_undef_strx;
32415ffd83dbSDimitry Andric Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
32425ffd83dbSDimitry Andric Asm->emitULEB128(Type);
32435ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Line Number");
32445ffd83dbSDimitry Andric Asm->emitULEB128(M.getLine());
32455ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Macro String");
3246e8d8bef9SDimitry Andric Asm->emitULEB128(
3247e8d8bef9SDimitry Andric InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3248e8d8bef9SDimitry Andric } else {
3249e8d8bef9SDimitry Andric unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3250e8d8bef9SDimitry Andric ? dwarf::DW_MACRO_GNU_define_indirect
3251e8d8bef9SDimitry Andric : dwarf::DW_MACRO_GNU_undef_indirect;
3252e8d8bef9SDimitry Andric Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
3253e8d8bef9SDimitry Andric Asm->emitULEB128(Type);
3254e8d8bef9SDimitry Andric Asm->OutStreamer->AddComment("Line Number");
3255e8d8bef9SDimitry Andric Asm->emitULEB128(M.getLine());
3256e8d8bef9SDimitry Andric Asm->OutStreamer->AddComment("Macro String");
3257e8d8bef9SDimitry Andric Asm->emitDwarfSymbolReference(
3258e8d8bef9SDimitry Andric InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3259e8d8bef9SDimitry Andric }
32605ffd83dbSDimitry Andric } else {
32615ffd83dbSDimitry Andric Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
32625ffd83dbSDimitry Andric Asm->emitULEB128(M.getMacinfoType());
32635ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Line Number");
32645ffd83dbSDimitry Andric Asm->emitULEB128(M.getLine());
32655ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Macro String");
3266e8d8bef9SDimitry Andric Asm->OutStreamer->emitBytes(Str);
32670b57cec5SDimitry Andric Asm->emitInt8('\0');
32680b57cec5SDimitry Andric }
32695ffd83dbSDimitry Andric }
32705ffd83dbSDimitry Andric
emitMacroFileImpl(DIMacroFile & MF,DwarfCompileUnit & U,unsigned StartFile,unsigned EndFile,StringRef (* MacroFormToString)(unsigned Form))32715ffd83dbSDimitry Andric void DwarfDebug::emitMacroFileImpl(
3272e8d8bef9SDimitry Andric DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
32735ffd83dbSDimitry Andric StringRef (*MacroFormToString)(unsigned Form)) {
32745ffd83dbSDimitry Andric
32755ffd83dbSDimitry Andric Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
32765ffd83dbSDimitry Andric Asm->emitULEB128(StartFile);
32775ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("Line Number");
3278e8d8bef9SDimitry Andric Asm->emitULEB128(MF.getLine());
32795ffd83dbSDimitry Andric Asm->OutStreamer->AddComment("File Number");
3280e8d8bef9SDimitry Andric DIFile &F = *MF.getFile();
3281e8d8bef9SDimitry Andric if (useSplitDwarf())
3282e8d8bef9SDimitry Andric Asm->emitULEB128(getDwoLineTable(U)->getFile(
3283e8d8bef9SDimitry Andric F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3284e8d8bef9SDimitry Andric Asm->OutContext.getDwarfVersion(), F.getSource()));
3285e8d8bef9SDimitry Andric else
3286e8d8bef9SDimitry Andric Asm->emitULEB128(U.getOrCreateSourceID(&F));
3287e8d8bef9SDimitry Andric handleMacroNodes(MF.getElements(), U);
32885ffd83dbSDimitry Andric Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
32895ffd83dbSDimitry Andric Asm->emitULEB128(EndFile);
32905ffd83dbSDimitry Andric }
32910b57cec5SDimitry Andric
emitMacroFile(DIMacroFile & F,DwarfCompileUnit & U)32920b57cec5SDimitry Andric void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
32935ffd83dbSDimitry Andric // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
32945ffd83dbSDimitry Andric // so for readibility/uniformity, We are explicitly emitting those.
32950b57cec5SDimitry Andric assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3296e8d8bef9SDimitry Andric if (UseDebugMacroSection)
3297e8d8bef9SDimitry Andric emitMacroFileImpl(
3298e8d8bef9SDimitry Andric F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3299e8d8bef9SDimitry Andric (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
33005ffd83dbSDimitry Andric else
33015ffd83dbSDimitry Andric emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
33025ffd83dbSDimitry Andric dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
33030b57cec5SDimitry Andric }
33040b57cec5SDimitry Andric
emitDebugMacinfoImpl(MCSection * Section)3305480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
33060b57cec5SDimitry Andric for (const auto &P : CUMap) {
33070b57cec5SDimitry Andric auto &TheCU = *P.second;
33080b57cec5SDimitry Andric auto *SkCU = TheCU.getSkeleton();
33090b57cec5SDimitry Andric DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
33100b57cec5SDimitry Andric auto *CUNode = cast<DICompileUnit>(P.first);
33110b57cec5SDimitry Andric DIMacroNodeArray Macros = CUNode->getMacros();
3312480093f4SDimitry Andric if (Macros.empty())
3313480093f4SDimitry Andric continue;
331481ad6265SDimitry Andric Asm->OutStreamer->switchSection(Section);
33155ffd83dbSDimitry Andric Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3316e8d8bef9SDimitry Andric if (UseDebugMacroSection)
3317e8d8bef9SDimitry Andric emitMacroHeader(Asm, *this, U, getDwarfVersion());
33180b57cec5SDimitry Andric handleMacroNodes(Macros, U);
33190b57cec5SDimitry Andric Asm->OutStreamer->AddComment("End Of Macro List Mark");
33200b57cec5SDimitry Andric Asm->emitInt8(0);
33210b57cec5SDimitry Andric }
3322480093f4SDimitry Andric }
3323480093f4SDimitry Andric
33245ffd83dbSDimitry Andric /// Emit macros into a debug macinfo/macro section.
emitDebugMacinfo()3325480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfo() {
33265ffd83dbSDimitry Andric auto &ObjLower = Asm->getObjFileLowering();
3327e8d8bef9SDimitry Andric emitDebugMacinfoImpl(UseDebugMacroSection
33285ffd83dbSDimitry Andric ? ObjLower.getDwarfMacroSection()
33295ffd83dbSDimitry Andric : ObjLower.getDwarfMacinfoSection());
3330480093f4SDimitry Andric }
3331480093f4SDimitry Andric
emitDebugMacinfoDWO()3332480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfoDWO() {
33335ffd83dbSDimitry Andric auto &ObjLower = Asm->getObjFileLowering();
3334e8d8bef9SDimitry Andric emitDebugMacinfoImpl(UseDebugMacroSection
33355ffd83dbSDimitry Andric ? ObjLower.getDwarfMacroDWOSection()
33365ffd83dbSDimitry Andric : ObjLower.getDwarfMacinfoDWOSection());
3337480093f4SDimitry Andric }
33380b57cec5SDimitry Andric
33390b57cec5SDimitry Andric // DWARF5 Experimental Separate Dwarf emitters.
33400b57cec5SDimitry Andric
initSkeletonUnit(const DwarfUnit & U,DIE & Die,std::unique_ptr<DwarfCompileUnit> NewU)33410b57cec5SDimitry Andric void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
33420b57cec5SDimitry Andric std::unique_ptr<DwarfCompileUnit> NewU) {
33430b57cec5SDimitry Andric
33440b57cec5SDimitry Andric if (!CompilationDir.empty())
33450b57cec5SDimitry Andric NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
33460b57cec5SDimitry Andric addGnuPubAttributes(*NewU, Die);
33470b57cec5SDimitry Andric
33480b57cec5SDimitry Andric SkeletonHolder.addUnit(std::move(NewU));
33490b57cec5SDimitry Andric }
33500b57cec5SDimitry Andric
constructSkeletonCU(const DwarfCompileUnit & CU)33510b57cec5SDimitry Andric DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
33520b57cec5SDimitry Andric
33538bcb0991SDimitry Andric auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3354480093f4SDimitry Andric CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3355480093f4SDimitry Andric UnitKind::Skeleton);
33560b57cec5SDimitry Andric DwarfCompileUnit &NewCU = *OwnedUnit;
33570b57cec5SDimitry Andric NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
33580b57cec5SDimitry Andric
33590b57cec5SDimitry Andric NewCU.initStmtList();
33600b57cec5SDimitry Andric
33610b57cec5SDimitry Andric if (useSegmentedStringOffsetsTable())
33620b57cec5SDimitry Andric NewCU.addStringOffsetsStart();
33630b57cec5SDimitry Andric
33640b57cec5SDimitry Andric initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
33650b57cec5SDimitry Andric
33660b57cec5SDimitry Andric return NewCU;
33670b57cec5SDimitry Andric }
33680b57cec5SDimitry Andric
33690b57cec5SDimitry Andric // Emit the .debug_info.dwo section for separated dwarf. This contains the
33700b57cec5SDimitry Andric // compile units that would normally be in debug_info.
emitDebugInfoDWO()33710b57cec5SDimitry Andric void DwarfDebug::emitDebugInfoDWO() {
33720b57cec5SDimitry Andric assert(useSplitDwarf() && "No split dwarf debug info?");
33730b57cec5SDimitry Andric // Don't emit relocations into the dwo file.
33740b57cec5SDimitry Andric InfoHolder.emitUnits(/* UseOffsets */ true);
33750b57cec5SDimitry Andric }
33760b57cec5SDimitry Andric
33770b57cec5SDimitry Andric // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
33780b57cec5SDimitry Andric // abbreviations for the .debug_info.dwo section.
emitDebugAbbrevDWO()33790b57cec5SDimitry Andric void DwarfDebug::emitDebugAbbrevDWO() {
33800b57cec5SDimitry Andric assert(useSplitDwarf() && "No split dwarf?");
33810b57cec5SDimitry Andric InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
33820b57cec5SDimitry Andric }
33830b57cec5SDimitry Andric
emitDebugLineDWO()33840b57cec5SDimitry Andric void DwarfDebug::emitDebugLineDWO() {
33850b57cec5SDimitry Andric assert(useSplitDwarf() && "No split dwarf?");
33860b57cec5SDimitry Andric SplitTypeUnitFileTable.Emit(
33870b57cec5SDimitry Andric *Asm->OutStreamer, MCDwarfLineTableParams(),
33880b57cec5SDimitry Andric Asm->getObjFileLowering().getDwarfLineDWOSection());
33890b57cec5SDimitry Andric }
33900b57cec5SDimitry Andric
emitStringOffsetsTableHeaderDWO()33910b57cec5SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
33920b57cec5SDimitry Andric assert(useSplitDwarf() && "No split dwarf?");
33930b57cec5SDimitry Andric InfoHolder.getStringPool().emitStringOffsetsTableHeader(
33940b57cec5SDimitry Andric *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
33950b57cec5SDimitry Andric InfoHolder.getStringOffsetsStartSym());
33960b57cec5SDimitry Andric }
33970b57cec5SDimitry Andric
33980b57cec5SDimitry Andric // Emit the .debug_str.dwo section for separated dwarf. This contains the
33990b57cec5SDimitry Andric // string section and is identical in format to traditional .debug_str
34000b57cec5SDimitry Andric // sections.
emitDebugStrDWO()34010b57cec5SDimitry Andric void DwarfDebug::emitDebugStrDWO() {
34020b57cec5SDimitry Andric if (useSegmentedStringOffsetsTable())
34030b57cec5SDimitry Andric emitStringOffsetsTableHeaderDWO();
34040b57cec5SDimitry Andric assert(useSplitDwarf() && "No split dwarf?");
34050b57cec5SDimitry Andric MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
34060b57cec5SDimitry Andric InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
34070b57cec5SDimitry Andric OffSec, /* UseRelativeOffsets = */ false);
34080b57cec5SDimitry Andric }
34090b57cec5SDimitry Andric
34100b57cec5SDimitry Andric // Emit address pool.
emitDebugAddr()34110b57cec5SDimitry Andric void DwarfDebug::emitDebugAddr() {
34120b57cec5SDimitry Andric AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
34130b57cec5SDimitry Andric }
34140b57cec5SDimitry Andric
getDwoLineTable(const DwarfCompileUnit & CU)34150b57cec5SDimitry Andric MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
34160b57cec5SDimitry Andric if (!useSplitDwarf())
34170b57cec5SDimitry Andric return nullptr;
34180b57cec5SDimitry Andric const DICompileUnit *DIUnit = CU.getCUNode();
34190b57cec5SDimitry Andric SplitTypeUnitFileTable.maybeSetRootFile(
34200b57cec5SDimitry Andric DIUnit->getDirectory(), DIUnit->getFilename(),
3421e8d8bef9SDimitry Andric getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
34220b57cec5SDimitry Andric return &SplitTypeUnitFileTable;
34230b57cec5SDimitry Andric }
34240b57cec5SDimitry Andric
makeTypeSignature(StringRef Identifier)34250b57cec5SDimitry Andric uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
34260b57cec5SDimitry Andric MD5 Hash;
34270b57cec5SDimitry Andric Hash.update(Identifier);
34280b57cec5SDimitry Andric // ... take the least significant 8 bytes and return those. Our MD5
34290b57cec5SDimitry Andric // implementation always returns its results in little endian, so we actually
34300b57cec5SDimitry Andric // need the "high" word.
34310b57cec5SDimitry Andric MD5::MD5Result Result;
34320b57cec5SDimitry Andric Hash.final(Result);
34330b57cec5SDimitry Andric return Result.high();
34340b57cec5SDimitry Andric }
34350b57cec5SDimitry Andric
addDwarfTypeUnitType(DwarfCompileUnit & CU,StringRef Identifier,DIE & RefDie,const DICompositeType * CTy)34360b57cec5SDimitry Andric void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
34370b57cec5SDimitry Andric StringRef Identifier, DIE &RefDie,
34380b57cec5SDimitry Andric const DICompositeType *CTy) {
34390b57cec5SDimitry Andric // Fast path if we're building some type units and one has already used the
34400b57cec5SDimitry Andric // address pool we know we're going to throw away all this work anyway, so
34410b57cec5SDimitry Andric // don't bother building dependent types.
34421fd87a68SDimitry Andric if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
34430b57cec5SDimitry Andric return;
34440b57cec5SDimitry Andric
34450b57cec5SDimitry Andric auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
34460b57cec5SDimitry Andric if (!Ins.second) {
34470b57cec5SDimitry Andric CU.addDIETypeSignature(RefDie, Ins.first->second);
34480b57cec5SDimitry Andric return;
34490b57cec5SDimitry Andric }
34500b57cec5SDimitry Andric
34517a6dacacSDimitry Andric setCurrentDWARF5AccelTable(DWARF5AccelTableKind::TU);
34520b57cec5SDimitry Andric bool TopLevelType = TypeUnitsUnderConstruction.empty();
34530b57cec5SDimitry Andric AddrPool.resetUsedFlag();
34540b57cec5SDimitry Andric
34555f757f3fSDimitry Andric auto OwnedUnit = std::make_unique<DwarfTypeUnit>(
34565f757f3fSDimitry Andric CU, Asm, this, &InfoHolder, NumTypeUnitsCreated++, getDwoLineTable(CU));
34570b57cec5SDimitry Andric DwarfTypeUnit &NewTU = *OwnedUnit;
34580b57cec5SDimitry Andric DIE &UnitDie = NewTU.getUnitDie();
34590b57cec5SDimitry Andric TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
34600b57cec5SDimitry Andric
34610b57cec5SDimitry Andric NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
34620b57cec5SDimitry Andric CU.getLanguage());
34630b57cec5SDimitry Andric
34640b57cec5SDimitry Andric uint64_t Signature = makeTypeSignature(Identifier);
34650b57cec5SDimitry Andric NewTU.setTypeSignature(Signature);
34660b57cec5SDimitry Andric Ins.first->second = Signature;
34670b57cec5SDimitry Andric
34680b57cec5SDimitry Andric if (useSplitDwarf()) {
34695f757f3fSDimitry Andric // Although multiple type units can have the same signature, they are not
34705f757f3fSDimitry Andric // guranteed to be bit identical. When LLDB uses .debug_names it needs to
34715f757f3fSDimitry Andric // know from which CU a type unit came from. These two attrbutes help it to
34725f757f3fSDimitry Andric // figure that out.
34735f757f3fSDimitry Andric if (getDwarfVersion() >= 5) {
34745f757f3fSDimitry Andric if (!CompilationDir.empty())
34755f757f3fSDimitry Andric NewTU.addString(UnitDie, dwarf::DW_AT_comp_dir, CompilationDir);
34765f757f3fSDimitry Andric NewTU.addString(UnitDie, dwarf::DW_AT_dwo_name,
34775f757f3fSDimitry Andric Asm->TM.Options.MCOptions.SplitDwarfFile);
34785f757f3fSDimitry Andric }
34790b57cec5SDimitry Andric MCSection *Section =
34800b57cec5SDimitry Andric getDwarfVersion() <= 4
34810b57cec5SDimitry Andric ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
34820b57cec5SDimitry Andric : Asm->getObjFileLowering().getDwarfInfoDWOSection();
34830b57cec5SDimitry Andric NewTU.setSection(Section);
34840b57cec5SDimitry Andric } else {
34850b57cec5SDimitry Andric MCSection *Section =
34860b57cec5SDimitry Andric getDwarfVersion() <= 4
34870b57cec5SDimitry Andric ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
34880b57cec5SDimitry Andric : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
34890b57cec5SDimitry Andric NewTU.setSection(Section);
34900b57cec5SDimitry Andric // Non-split type units reuse the compile unit's line table.
34910b57cec5SDimitry Andric CU.applyStmtList(UnitDie);
34920b57cec5SDimitry Andric }
34930b57cec5SDimitry Andric
34940b57cec5SDimitry Andric // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
34950b57cec5SDimitry Andric // units.
34960b57cec5SDimitry Andric if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
34970b57cec5SDimitry Andric NewTU.addStringOffsetsStart();
34980b57cec5SDimitry Andric
34990b57cec5SDimitry Andric NewTU.setType(NewTU.createTypeDIE(CTy));
35000b57cec5SDimitry Andric
35010b57cec5SDimitry Andric if (TopLevelType) {
35020b57cec5SDimitry Andric auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
35030b57cec5SDimitry Andric TypeUnitsUnderConstruction.clear();
35040b57cec5SDimitry Andric
35050b57cec5SDimitry Andric // Types referencing entries in the address table cannot be placed in type
35060b57cec5SDimitry Andric // units.
35071fd87a68SDimitry Andric if (AddrPool.hasBeenUsed()) {
35085f757f3fSDimitry Andric AccelTypeUnitsDebugNames.clear();
35090b57cec5SDimitry Andric // Remove all the types built while building this type.
35100b57cec5SDimitry Andric // This is pessimistic as some of these types might not be dependent on
35110b57cec5SDimitry Andric // the type that used an address.
35120b57cec5SDimitry Andric for (const auto &TU : TypeUnitsToAdd)
35130b57cec5SDimitry Andric TypeSignatures.erase(TU.second);
35140b57cec5SDimitry Andric
35150b57cec5SDimitry Andric // Construct this type in the CU directly.
35160b57cec5SDimitry Andric // This is inefficient because all the dependent types will be rebuilt
35170b57cec5SDimitry Andric // from scratch, including building them in type units, discovering that
35180b57cec5SDimitry Andric // they depend on addresses, throwing them out and rebuilding them.
35195f757f3fSDimitry Andric setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);
35200b57cec5SDimitry Andric CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
35210b57cec5SDimitry Andric return;
35220b57cec5SDimitry Andric }
35230b57cec5SDimitry Andric
35240b57cec5SDimitry Andric // If the type wasn't dependent on fission addresses, finish adding the type
35250b57cec5SDimitry Andric // and all its dependent types.
35260b57cec5SDimitry Andric for (auto &TU : TypeUnitsToAdd) {
35270b57cec5SDimitry Andric InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
35280b57cec5SDimitry Andric InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
35295f757f3fSDimitry Andric if (getDwarfVersion() >= 5 &&
35305f757f3fSDimitry Andric getAccelTableKind() == AccelTableKind::Dwarf) {
35315f757f3fSDimitry Andric if (useSplitDwarf())
35325f757f3fSDimitry Andric AccelDebugNames.addTypeUnitSignature(*TU.first);
35335f757f3fSDimitry Andric else
35345f757f3fSDimitry Andric AccelDebugNames.addTypeUnitSymbol(*TU.first);
35350b57cec5SDimitry Andric }
35360b57cec5SDimitry Andric }
35375f757f3fSDimitry Andric AccelTypeUnitsDebugNames.convertDieToOffset();
35385f757f3fSDimitry Andric AccelDebugNames.addTypeEntries(AccelTypeUnitsDebugNames);
35395f757f3fSDimitry Andric AccelTypeUnitsDebugNames.clear();
35407a6dacacSDimitry Andric setCurrentDWARF5AccelTable(DWARF5AccelTableKind::CU);
35415f757f3fSDimitry Andric }
35420b57cec5SDimitry Andric CU.addDIETypeSignature(RefDie, Signature);
35430b57cec5SDimitry Andric }
35440b57cec5SDimitry Andric
35450b57cec5SDimitry Andric // Add the Name along with its companion DIE to the appropriate accelerator
35460b57cec5SDimitry Andric // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
35470b57cec5SDimitry Andric // AccelTableKind::Apple, we use the table we got as an argument). If
35480b57cec5SDimitry Andric // accelerator tables are disabled, this function does nothing.
35490b57cec5SDimitry Andric template <typename DataT>
addAccelNameImpl(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,AccelTable<DataT> & AppleAccel,StringRef Name,const DIE & Die)35505f757f3fSDimitry Andric void DwarfDebug::addAccelNameImpl(
35515f757f3fSDimitry Andric const DwarfUnit &Unit,
35525f757f3fSDimitry Andric const DICompileUnit::DebugNameTableKind NameTableKind,
35535f757f3fSDimitry Andric AccelTable<DataT> &AppleAccel, StringRef Name, const DIE &Die) {
3554*0fca6ea1SDimitry Andric if (getAccelTableKind() == AccelTableKind::None ||
3555*0fca6ea1SDimitry Andric Unit.getUnitDie().getTag() == dwarf::DW_TAG_skeleton_unit || Name.empty())
35560b57cec5SDimitry Andric return;
35570b57cec5SDimitry Andric
35580b57cec5SDimitry Andric if (getAccelTableKind() != AccelTableKind::Apple &&
35595f757f3fSDimitry Andric NameTableKind != DICompileUnit::DebugNameTableKind::Apple &&
35605f757f3fSDimitry Andric NameTableKind != DICompileUnit::DebugNameTableKind::Default)
35610b57cec5SDimitry Andric return;
35620b57cec5SDimitry Andric
35630b57cec5SDimitry Andric DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
35640b57cec5SDimitry Andric DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
35650b57cec5SDimitry Andric
35660b57cec5SDimitry Andric switch (getAccelTableKind()) {
35670b57cec5SDimitry Andric case AccelTableKind::Apple:
35680b57cec5SDimitry Andric AppleAccel.addName(Ref, Die);
35690b57cec5SDimitry Andric break;
35705f757f3fSDimitry Andric case AccelTableKind::Dwarf: {
35715f757f3fSDimitry Andric DWARF5AccelTable &Current = getCurrentDWARF5AccelTable();
35727a6dacacSDimitry Andric assert(((&Current == &AccelTypeUnitsDebugNames) ||
35737a6dacacSDimitry Andric ((&Current == &AccelDebugNames) &&
35747a6dacacSDimitry Andric (Unit.getUnitDie().getTag() != dwarf::DW_TAG_type_unit))) &&
35757a6dacacSDimitry Andric "Kind is CU but TU is being processed.");
35767a6dacacSDimitry Andric assert(((&Current == &AccelDebugNames) ||
35777a6dacacSDimitry Andric ((&Current == &AccelTypeUnitsDebugNames) &&
35787a6dacacSDimitry Andric (Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit))) &&
35797a6dacacSDimitry Andric "Kind is TU but CU is being processed.");
35805f757f3fSDimitry Andric // The type unit can be discarded, so need to add references to final
35815f757f3fSDimitry Andric // acceleration table once we know it's complete and we emit it.
3582*0fca6ea1SDimitry Andric Current.addName(Ref, Die, Unit.getUniqueID(),
3583*0fca6ea1SDimitry Andric Unit.getUnitDie().getTag() == dwarf::DW_TAG_type_unit);
35840b57cec5SDimitry Andric break;
35855f757f3fSDimitry Andric }
35860b57cec5SDimitry Andric case AccelTableKind::Default:
35870b57cec5SDimitry Andric llvm_unreachable("Default should have already been resolved.");
35880b57cec5SDimitry Andric case AccelTableKind::None:
35890b57cec5SDimitry Andric llvm_unreachable("None handled above");
35900b57cec5SDimitry Andric }
35910b57cec5SDimitry Andric }
35920b57cec5SDimitry Andric
addAccelName(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die)35935f757f3fSDimitry Andric void DwarfDebug::addAccelName(
35945f757f3fSDimitry Andric const DwarfUnit &Unit,
35955f757f3fSDimitry Andric const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
35960b57cec5SDimitry Andric const DIE &Die) {
35975f757f3fSDimitry Andric addAccelNameImpl(Unit, NameTableKind, AccelNames, Name, Die);
35980b57cec5SDimitry Andric }
35990b57cec5SDimitry Andric
addAccelObjC(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die)36005f757f3fSDimitry Andric void DwarfDebug::addAccelObjC(
36015f757f3fSDimitry Andric const DwarfUnit &Unit,
36025f757f3fSDimitry Andric const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
36030b57cec5SDimitry Andric const DIE &Die) {
36040b57cec5SDimitry Andric // ObjC names go only into the Apple accelerator tables.
36050b57cec5SDimitry Andric if (getAccelTableKind() == AccelTableKind::Apple)
36065f757f3fSDimitry Andric addAccelNameImpl(Unit, NameTableKind, AccelObjC, Name, Die);
36070b57cec5SDimitry Andric }
36080b57cec5SDimitry Andric
addAccelNamespace(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die)36095f757f3fSDimitry Andric void DwarfDebug::addAccelNamespace(
36105f757f3fSDimitry Andric const DwarfUnit &Unit,
36115f757f3fSDimitry Andric const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
36120b57cec5SDimitry Andric const DIE &Die) {
36135f757f3fSDimitry Andric addAccelNameImpl(Unit, NameTableKind, AccelNamespace, Name, Die);
36140b57cec5SDimitry Andric }
36150b57cec5SDimitry Andric
addAccelType(const DwarfUnit & Unit,const DICompileUnit::DebugNameTableKind NameTableKind,StringRef Name,const DIE & Die,char Flags)36165f757f3fSDimitry Andric void DwarfDebug::addAccelType(
36175f757f3fSDimitry Andric const DwarfUnit &Unit,
36185f757f3fSDimitry Andric const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name,
36190b57cec5SDimitry Andric const DIE &Die, char Flags) {
36205f757f3fSDimitry Andric addAccelNameImpl(Unit, NameTableKind, AccelTypes, Name, Die);
36210b57cec5SDimitry Andric }
36220b57cec5SDimitry Andric
getDwarfVersion() const36230b57cec5SDimitry Andric uint16_t DwarfDebug::getDwarfVersion() const {
36240b57cec5SDimitry Andric return Asm->OutStreamer->getContext().getDwarfVersion();
36250b57cec5SDimitry Andric }
36260b57cec5SDimitry Andric
getDwarfSectionOffsetForm() const3627e8d8bef9SDimitry Andric dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
3628e8d8bef9SDimitry Andric if (Asm->getDwarfVersion() >= 4)
3629e8d8bef9SDimitry Andric return dwarf::Form::DW_FORM_sec_offset;
3630e8d8bef9SDimitry Andric assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
3631e8d8bef9SDimitry Andric "DWARF64 is not defined prior DWARFv3");
3632e8d8bef9SDimitry Andric return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3633e8d8bef9SDimitry Andric : dwarf::Form::DW_FORM_data4;
3634e8d8bef9SDimitry Andric }
3635e8d8bef9SDimitry Andric
getSectionLabel(const MCSection * S)36360b57cec5SDimitry Andric const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
363706c3fb27SDimitry Andric return SectionLabels.lookup(S);
36380b57cec5SDimitry Andric }
363906c3fb27SDimitry Andric
insertSectionLabel(const MCSymbol * S)36405ffd83dbSDimitry Andric void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
36415ffd83dbSDimitry Andric if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
36425ffd83dbSDimitry Andric if (useSplitDwarf() || getDwarfVersion() >= 5)
36435ffd83dbSDimitry Andric AddrPool.getIndex(S);
36445ffd83dbSDimitry Andric }
3645e8d8bef9SDimitry Andric
3646bdd1243dSDimitry Andric std::optional<MD5::MD5Result>
getMD5AsBytes(const DIFile * File) const3647bdd1243dSDimitry Andric DwarfDebug::getMD5AsBytes(const DIFile *File) const {
3648e8d8bef9SDimitry Andric assert(File);
3649e8d8bef9SDimitry Andric if (getDwarfVersion() < 5)
3650bdd1243dSDimitry Andric return std::nullopt;
3651bdd1243dSDimitry Andric std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3652e8d8bef9SDimitry Andric if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3653bdd1243dSDimitry Andric return std::nullopt;
3654e8d8bef9SDimitry Andric
3655e8d8bef9SDimitry Andric // Convert the string checksum to an MD5Result for the streamer.
3656e8d8bef9SDimitry Andric // The verifier validates the checksum so we assume it's okay.
3657e8d8bef9SDimitry Andric // An MD5 checksum is 16 bytes.
3658e8d8bef9SDimitry Andric std::string ChecksumString = fromHex(Checksum->Value);
3659e8d8bef9SDimitry Andric MD5::MD5Result CKMem;
366081ad6265SDimitry Andric std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3661e8d8bef9SDimitry Andric return CKMem;
3662e8d8bef9SDimitry Andric }
366306c3fb27SDimitry Andric
alwaysUseRanges(const DwarfCompileUnit & CU) const366406c3fb27SDimitry Andric bool DwarfDebug::alwaysUseRanges(const DwarfCompileUnit &CU) const {
366506c3fb27SDimitry Andric if (MinimizeAddr == MinimizeAddrInV5::Ranges)
366606c3fb27SDimitry Andric return true;
366706c3fb27SDimitry Andric if (MinimizeAddr != MinimizeAddrInV5::Default)
366806c3fb27SDimitry Andric return false;
366906c3fb27SDimitry Andric if (useSplitDwarf())
367006c3fb27SDimitry Andric return true;
367106c3fb27SDimitry Andric return false;
367206c3fb27SDimitry Andric }
3673