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"
21*fe013be4SDimitry 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"
56*fe013be4SDimitry 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 
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 
1810b57cec5SDimitry Andric void DebugLocDwarfExpression::emitSigned(int64_t Value) {
1825ffd83dbSDimitry Andric   getActiveStreamer().emitSLEB128(Value, Twine(Value));
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
1865ffd83dbSDimitry Andric   getActiveStreamer().emitULEB128(Value, Twine(Value));
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric void DebugLocDwarfExpression::emitData1(uint8_t Value) {
190e8d8bef9SDimitry Andric   getActiveStreamer().emitInt8(Value, Twine(Value));
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
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 
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 
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 
2118bcb0991SDimitry Andric void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
2128bcb0991SDimitry Andric 
2138bcb0991SDimitry Andric unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
2148bcb0991SDimitry Andric   return TmpBuf ? TmpBuf->Bytes.size() : 0;
2158bcb0991SDimitry Andric }
2168bcb0991SDimitry Andric 
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 
2300b57cec5SDimitry 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.
2350b57cec5SDimitry Andric static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
2360b57cec5SDimitry Andric   const DIExpression *Expr = MI->getDebugExpression();
237fe6060f1SDimitry Andric   const bool IsVariadic = MI->isDebugValueList();
238fe6060f1SDimitry Andric   assert(MI->getNumOperands() >= 3);
239fe6060f1SDimitry Andric   SmallVector<DbgValueLocEntry, 4> DbgValueLocEntries;
240fe6060f1SDimitry Andric   for (const MachineOperand &Op : MI->debug_operands()) {
241fe6060f1SDimitry Andric     if (Op.isReg()) {
242fe6060f1SDimitry Andric       MachineLocation MLoc(Op.getReg(),
243fe6060f1SDimitry Andric                            MI->isNonListDebugValue() && MI->isDebugOffsetImm());
244fe6060f1SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(MLoc));
245fe6060f1SDimitry Andric     } else if (Op.isTargetIndex()) {
246fe6060f1SDimitry Andric       DbgValueLocEntries.push_back(
247fe6060f1SDimitry Andric           DbgValueLocEntry(TargetIndexLocation(Op.getIndex(), Op.getOffset())));
248fe6060f1SDimitry Andric     } else if (Op.isImm())
249fe6060f1SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getImm()));
250fe6060f1SDimitry Andric     else if (Op.isFPImm())
251fe6060f1SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getFPImm()));
252fe6060f1SDimitry Andric     else if (Op.isCImm())
253fe6060f1SDimitry Andric       DbgValueLocEntries.push_back(DbgValueLocEntry(Op.getCImm()));
254fe6060f1SDimitry Andric     else
255fe6060f1SDimitry Andric       llvm_unreachable("Unexpected debug operand in DBG_VALUE* instruction!");
2560b57cec5SDimitry Andric   }
257fe6060f1SDimitry Andric   return DbgValueLoc(Expr, DbgValueLocEntries, IsVariadic);
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
2610b57cec5SDimitry Andric   assert(FrameIndexExprs.empty() && "Already initialized?");
2620b57cec5SDimitry Andric   assert(!ValueLoc.get() && "Already initialized?");
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
2650b57cec5SDimitry Andric   assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
2660b57cec5SDimitry Andric          "Wrong inlined-at");
2670b57cec5SDimitry Andric 
2688bcb0991SDimitry Andric   ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
2690b57cec5SDimitry Andric   if (auto *E = DbgValue->getDebugExpression())
2700b57cec5SDimitry Andric     if (E->getNumElements())
2710b57cec5SDimitry Andric       FrameIndexExprs.push_back({0, E});
2720b57cec5SDimitry Andric }
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
2750b57cec5SDimitry Andric   if (FrameIndexExprs.size() == 1)
2760b57cec5SDimitry Andric     return FrameIndexExprs;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   assert(llvm::all_of(FrameIndexExprs,
2790b57cec5SDimitry Andric                       [](const FrameIndexExpr &A) {
2800b57cec5SDimitry Andric                         return A.Expr->isFragment();
2810b57cec5SDimitry Andric                       }) &&
2820b57cec5SDimitry Andric          "multiple FI expressions without DW_OP_LLVM_fragment");
2830b57cec5SDimitry Andric   llvm::sort(FrameIndexExprs,
2840b57cec5SDimitry Andric              [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
2850b57cec5SDimitry Andric                return A.Expr->getFragmentInfo()->OffsetInBits <
2860b57cec5SDimitry Andric                       B.Expr->getFragmentInfo()->OffsetInBits;
2870b57cec5SDimitry Andric              });
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   return FrameIndexExprs;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric void DbgVariable::addMMIEntry(const DbgVariable &V) {
2930b57cec5SDimitry Andric   assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
2940b57cec5SDimitry Andric   assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
2950b57cec5SDimitry Andric   assert(V.getVariable() == getVariable() && "conflicting variable");
2960b57cec5SDimitry Andric   assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
2990b57cec5SDimitry Andric   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   // FIXME: This logic should not be necessary anymore, as we now have proper
3020b57cec5SDimitry Andric   // deduplication. However, without it, we currently run into the assertion
3030b57cec5SDimitry Andric   // below, which means that we are likely dealing with broken input, i.e. two
3040b57cec5SDimitry Andric   // non-fragment entries for the same variable at different frame indices.
3050b57cec5SDimitry Andric   if (FrameIndexExprs.size()) {
3060b57cec5SDimitry Andric     auto *Expr = FrameIndexExprs.back().Expr;
3070b57cec5SDimitry Andric     if (!Expr || !Expr->isFragment())
3080b57cec5SDimitry Andric       return;
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   for (const auto &FIE : V.FrameIndexExprs)
3120b57cec5SDimitry Andric     // Ignore duplicate entries.
3130b57cec5SDimitry Andric     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
3140b57cec5SDimitry Andric           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
3150b57cec5SDimitry Andric         }))
3160b57cec5SDimitry Andric       FrameIndexExprs.push_back(FIE);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   assert((FrameIndexExprs.size() == 1 ||
3190b57cec5SDimitry Andric           llvm::all_of(FrameIndexExprs,
3200b57cec5SDimitry Andric                        [](FrameIndexExpr &FIE) {
3210b57cec5SDimitry Andric                          return FIE.Expr && FIE.Expr->isFragment();
3220b57cec5SDimitry Andric                        })) &&
3230b57cec5SDimitry Andric          "conflicting locations for variable");
3240b57cec5SDimitry Andric }
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
3270b57cec5SDimitry Andric                                             bool GenerateTypeUnits,
3280b57cec5SDimitry Andric                                             DebuggerKind Tuning,
3290b57cec5SDimitry Andric                                             const Triple &TT) {
3300b57cec5SDimitry Andric   // Honor an explicit request.
3310b57cec5SDimitry Andric   if (AccelTables != AccelTableKind::Default)
3320b57cec5SDimitry Andric     return AccelTables;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   // Accelerator tables with type units are currently not supported.
3350b57cec5SDimitry Andric   if (GenerateTypeUnits)
3360b57cec5SDimitry Andric     return AccelTableKind::None;
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
3390b57cec5SDimitry Andric   // always implies debug_names. For lower standard versions we use apple
3400b57cec5SDimitry Andric   // accelerator tables on apple platforms and debug_names elsewhere.
3410b57cec5SDimitry Andric   if (DwarfVersion >= 5)
3420b57cec5SDimitry Andric     return AccelTableKind::Dwarf;
3430b57cec5SDimitry Andric   if (Tuning == DebuggerKind::LLDB)
3440b57cec5SDimitry Andric     return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
3450b57cec5SDimitry Andric                                    : AccelTableKind::Dwarf;
3460b57cec5SDimitry Andric   return AccelTableKind::None;
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
349e8d8bef9SDimitry Andric DwarfDebug::DwarfDebug(AsmPrinter *A)
3500b57cec5SDimitry Andric     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
3510b57cec5SDimitry Andric       InfoHolder(A, "info_string", DIEValueAllocator),
3520b57cec5SDimitry Andric       SkeletonHolder(A, "skel_string", DIEValueAllocator),
3530b57cec5SDimitry Andric       IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
3540b57cec5SDimitry Andric   const Triple &TT = Asm->TM.getTargetTriple();
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   // Make sure we know our "debugger tuning".  The target option takes
3570b57cec5SDimitry Andric   // precedence; fall back to triple-based defaults.
3580b57cec5SDimitry Andric   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
3590b57cec5SDimitry Andric     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
3600b57cec5SDimitry Andric   else if (IsDarwin)
3610b57cec5SDimitry Andric     DebuggerTuning = DebuggerKind::LLDB;
36281ad6265SDimitry Andric   else if (TT.isPS())
3630b57cec5SDimitry Andric     DebuggerTuning = DebuggerKind::SCE;
364fe6060f1SDimitry Andric   else if (TT.isOSAIX())
365fe6060f1SDimitry Andric     DebuggerTuning = DebuggerKind::DBX;
3660b57cec5SDimitry Andric   else
3670b57cec5SDimitry Andric     DebuggerTuning = DebuggerKind::GDB;
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   if (DwarfInlinedStrings == Default)
370fe6060f1SDimitry Andric     UseInlineStrings = TT.isNVPTX() || tuneForDBX();
3710b57cec5SDimitry Andric   else
3720b57cec5SDimitry Andric     UseInlineStrings = DwarfInlinedStrings == Enable;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   UseLocSection = !TT.isNVPTX();
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   HasAppleExtensionAttributes = tuneForLLDB();
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   // Handle split DWARF.
3790b57cec5SDimitry Andric   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   // SCE defaults to linkage names only for abstract subprograms.
3820b57cec5SDimitry Andric   if (DwarfLinkageNames == DefaultLinkageNames)
3830b57cec5SDimitry Andric     UseAllLinkageNames = !tuneForSCE();
3840b57cec5SDimitry Andric   else
3850b57cec5SDimitry Andric     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
3880b57cec5SDimitry Andric   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
3890b57cec5SDimitry Andric                                     : MMI->getModule()->getDwarfVersion();
3900b57cec5SDimitry Andric   // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
3910b57cec5SDimitry Andric   DwarfVersion =
3920b57cec5SDimitry Andric       TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
3930b57cec5SDimitry Andric 
394fe6060f1SDimitry Andric   bool Dwarf64 = DwarfVersion >= 3 && // DWARF64 was introduced in DWARFv3.
395fe6060f1SDimitry Andric                  TT.isArch64Bit();    // DWARF64 requires 64-bit relocations.
396fe6060f1SDimitry Andric 
397fe6060f1SDimitry Andric   // Support DWARF64
398fe6060f1SDimitry Andric   // 1: For ELF when requested.
399fe6060f1SDimitry Andric   // 2: For XCOFF64: the AIX assembler will fill in debug section lengths
400fe6060f1SDimitry Andric   //    according to the DWARF64 format for 64-bit assembly, so we must use
401fe6060f1SDimitry Andric   //    DWARF64 in the compiler too for 64-bit mode.
402fe6060f1SDimitry Andric   Dwarf64 &=
403fe6060f1SDimitry Andric       ((Asm->TM.Options.MCOptions.Dwarf64 || MMI->getModule()->isDwarf64()) &&
404fe6060f1SDimitry Andric        TT.isOSBinFormatELF()) ||
405fe6060f1SDimitry Andric       TT.isOSBinFormatXCOFF();
406fe6060f1SDimitry Andric 
407fe6060f1SDimitry Andric   if (!Dwarf64 && TT.isArch64Bit() && TT.isOSBinFormatXCOFF())
408fe6060f1SDimitry Andric     report_fatal_error("XCOFF requires DWARF64 for 64-bit mode!");
409e8d8bef9SDimitry Andric 
4100b57cec5SDimitry Andric   UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   // Use sections as references. Force for NVPTX.
4130b57cec5SDimitry Andric   if (DwarfSectionsAsReferences == Default)
4140b57cec5SDimitry Andric     UseSectionsAsReferences = TT.isNVPTX();
4150b57cec5SDimitry Andric   else
4160b57cec5SDimitry Andric     UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   // Don't generate type units for unsupported object file formats.
419e8d8bef9SDimitry Andric   GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
420e8d8bef9SDimitry Andric                        A->TM.getTargetTriple().isOSBinFormatWasm()) &&
421e8d8bef9SDimitry Andric                       GenerateDwarfTypeUnits;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   TheAccelTableKind = computeAccelTableKind(
4240b57cec5SDimitry Andric       DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // Work around a GDB bug. GDB doesn't support the standard opcode;
4270b57cec5SDimitry Andric   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
4280b57cec5SDimitry Andric   // is defined as of DWARF 3.
4290b57cec5SDimitry Andric   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
4300b57cec5SDimitry Andric   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
4310b57cec5SDimitry Andric   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
4320b57cec5SDimitry Andric 
433bdd1243dSDimitry Andric   UseDWARF2Bitfields = DwarfVersion < 4;
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   // The DWARF v5 string offsets table has - possibly shared - contributions
4360b57cec5SDimitry Andric   // from each compile and type unit each preceded by a header. The string
4370b57cec5SDimitry Andric   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
4380b57cec5SDimitry Andric   // a monolithic string offsets table without any header.
4390b57cec5SDimitry Andric   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
4400b57cec5SDimitry Andric 
4415ffd83dbSDimitry Andric   // Emit call-site-param debug info for GDB and LLDB, if the target supports
4425ffd83dbSDimitry Andric   // the debug entry values feature. It can also be enabled explicitly.
443e8d8bef9SDimitry Andric   EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
444e8d8bef9SDimitry Andric 
445e8d8bef9SDimitry Andric   // It is unclear if the GCC .debug_macro extension is well-specified
446e8d8bef9SDimitry Andric   // for split DWARF. For now, do not allow LLVM to emit it.
447e8d8bef9SDimitry Andric   UseDebugMacroSection =
448e8d8bef9SDimitry Andric       DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
449e8d8bef9SDimitry Andric   if (DwarfOpConvert == Default)
450e8d8bef9SDimitry Andric     EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
451e8d8bef9SDimitry Andric   else
452e8d8bef9SDimitry Andric     EnableOpConvert = (DwarfOpConvert == Enable);
453e8d8bef9SDimitry Andric 
454e8d8bef9SDimitry Andric   // Split DWARF would benefit object size significantly by trading reductions
455e8d8bef9SDimitry Andric   // in address pool usage for slightly increased range list encodings.
456*fe013be4SDimitry Andric   if (DwarfVersion >= 5)
457e8d8bef9SDimitry Andric     MinimizeAddr = MinimizeAddrInV5Option;
4585ffd83dbSDimitry Andric 
4590b57cec5SDimitry Andric   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
460e8d8bef9SDimitry Andric   Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
461e8d8bef9SDimitry Andric                                                         : dwarf::DWARF32);
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
4650b57cec5SDimitry Andric DwarfDebug::~DwarfDebug() = default;
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric static bool isObjCClass(StringRef Name) {
4680b57cec5SDimitry Andric   return Name.startswith("+") || Name.startswith("-");
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric static bool hasObjCCategory(StringRef Name) {
4720b57cec5SDimitry Andric   if (!isObjCClass(Name))
4730b57cec5SDimitry Andric     return false;
4740b57cec5SDimitry Andric 
475349cc55cSDimitry Andric   return Name.contains(") ");
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric static void getObjCClassCategory(StringRef In, StringRef &Class,
4790b57cec5SDimitry Andric                                  StringRef &Category) {
4800b57cec5SDimitry Andric   if (!hasObjCCategory(In)) {
4810b57cec5SDimitry Andric     Class = In.slice(In.find('[') + 1, In.find(' '));
4820b57cec5SDimitry Andric     Category = "";
4830b57cec5SDimitry Andric     return;
4840b57cec5SDimitry Andric   }
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   Class = In.slice(In.find('[') + 1, In.find('('));
4870b57cec5SDimitry Andric   Category = In.slice(In.find('[') + 1, In.find(' '));
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric static StringRef getObjCMethodName(StringRef In) {
4910b57cec5SDimitry Andric   return In.slice(In.find(' ') + 1, In.find(']'));
4920b57cec5SDimitry Andric }
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric // Add the various names to the Dwarf accelerator table names.
4950b57cec5SDimitry Andric void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
4960b57cec5SDimitry Andric                                     const DISubprogram *SP, DIE &Die) {
4970b57cec5SDimitry Andric   if (getAccelTableKind() != AccelTableKind::Apple &&
498*fe013be4SDimitry Andric       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Apple &&
4990b57cec5SDimitry Andric       CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
5000b57cec5SDimitry Andric     return;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   if (!SP->isDefinition())
5030b57cec5SDimitry Andric     return;
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   if (SP->getName() != "")
5060b57cec5SDimitry Andric     addAccelName(CU, SP->getName(), Die);
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // If the linkage name is different than the name, go ahead and output that as
5090b57cec5SDimitry Andric   // well into the name table. Only do that if we are going to actually emit
5100b57cec5SDimitry Andric   // that name.
5110b57cec5SDimitry Andric   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
512*fe013be4SDimitry Andric       (useAllLinkageNames() || InfoHolder.getAbstractScopeDIEs().lookup(SP)))
5130b57cec5SDimitry Andric     addAccelName(CU, SP->getLinkageName(), Die);
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   // If this is an Objective-C selector name add it to the ObjC accelerator
5160b57cec5SDimitry Andric   // too.
5170b57cec5SDimitry Andric   if (isObjCClass(SP->getName())) {
5180b57cec5SDimitry Andric     StringRef Class, Category;
5190b57cec5SDimitry Andric     getObjCClassCategory(SP->getName(), Class, Category);
5200b57cec5SDimitry Andric     addAccelObjC(CU, Class, Die);
5210b57cec5SDimitry Andric     if (Category != "")
5220b57cec5SDimitry Andric       addAccelObjC(CU, Category, Die);
5230b57cec5SDimitry Andric     // Also add the base method name to the name table.
5240b57cec5SDimitry Andric     addAccelName(CU, getObjCMethodName(SP->getName()), Die);
5250b57cec5SDimitry Andric   }
5260b57cec5SDimitry Andric }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric /// Check whether we should create a DIE for the given Scope, return true
5290b57cec5SDimitry Andric /// if we don't create a DIE (the corresponding DIE is null).
5300b57cec5SDimitry Andric bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
5310b57cec5SDimitry Andric   if (Scope->isAbstractScope())
5320b57cec5SDimitry Andric     return false;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // We don't create a DIE if there is no Range.
5350b57cec5SDimitry Andric   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
5360b57cec5SDimitry Andric   if (Ranges.empty())
5370b57cec5SDimitry Andric     return true;
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   if (Ranges.size() > 1)
5400b57cec5SDimitry Andric     return false;
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   // We don't create a DIE if we have a single Range and the end label
5430b57cec5SDimitry Andric   // is null.
5440b57cec5SDimitry Andric   return !getLabelAfterInsn(Ranges.front().second);
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
5480b57cec5SDimitry Andric   F(CU);
5490b57cec5SDimitry Andric   if (auto *SkelCU = CU.getSkeleton())
5500b57cec5SDimitry Andric     if (CU.getCUNode()->getSplitDebugInlining())
5510b57cec5SDimitry Andric       F(*SkelCU);
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric bool DwarfDebug::shareAcrossDWOCUs() const {
5550b57cec5SDimitry Andric   return SplitDwarfCrossCuReferences;
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
5590b57cec5SDimitry Andric                                                      LexicalScope *Scope) {
5600b57cec5SDimitry Andric   assert(Scope && Scope->getScopeNode());
5610b57cec5SDimitry Andric   assert(Scope->isAbstractScope());
5620b57cec5SDimitry Andric   assert(!Scope->getInlinedAt());
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
5670b57cec5SDimitry Andric   // was inlined from another compile unit.
5680b57cec5SDimitry Andric   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
5690b57cec5SDimitry Andric     // Avoid building the original CU if it won't be used
5700b57cec5SDimitry Andric     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
5710b57cec5SDimitry Andric   else {
5720b57cec5SDimitry Andric     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
5730b57cec5SDimitry Andric     if (auto *SkelCU = CU.getSkeleton()) {
5740b57cec5SDimitry Andric       (shareAcrossDWOCUs() ? CU : SrcCU)
5750b57cec5SDimitry Andric           .constructAbstractSubprogramScopeDIE(Scope);
5760b57cec5SDimitry Andric       if (CU.getCUNode()->getSplitDebugInlining())
5770b57cec5SDimitry Andric         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
5780b57cec5SDimitry Andric     } else
5790b57cec5SDimitry Andric       CU.constructAbstractSubprogramScopeDIE(Scope);
5800b57cec5SDimitry Andric   }
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
5835ffd83dbSDimitry Andric /// Represents a parameter whose call site value can be described by applying a
5845ffd83dbSDimitry Andric /// debug expression to a register in the forwarded register worklist.
5855ffd83dbSDimitry Andric struct FwdRegParamInfo {
5865ffd83dbSDimitry Andric   /// The described parameter register.
5875ffd83dbSDimitry Andric   unsigned ParamReg;
5885ffd83dbSDimitry Andric 
5895ffd83dbSDimitry Andric   /// Debug expression that has been built up when walking through the
5905ffd83dbSDimitry Andric   /// instruction chain that produces the parameter's value.
5915ffd83dbSDimitry Andric   const DIExpression *Expr;
5925ffd83dbSDimitry Andric };
5935ffd83dbSDimitry Andric 
5945ffd83dbSDimitry Andric /// Register worklist for finding call site values.
5955ffd83dbSDimitry Andric using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
596bdd1243dSDimitry Andric /// Container for the set of registers known to be clobbered on the path to a
597bdd1243dSDimitry Andric /// call site.
598bdd1243dSDimitry Andric using ClobberedRegSet = SmallSet<Register, 16>;
5995ffd83dbSDimitry Andric 
6005ffd83dbSDimitry Andric /// Append the expression \p Addition to \p Original and return the result.
6015ffd83dbSDimitry Andric static const DIExpression *combineDIExpressions(const DIExpression *Original,
6025ffd83dbSDimitry Andric                                                 const DIExpression *Addition) {
6035ffd83dbSDimitry Andric   std::vector<uint64_t> Elts = Addition->getElements().vec();
6045ffd83dbSDimitry Andric   // Avoid multiple DW_OP_stack_values.
6055ffd83dbSDimitry Andric   if (Original->isImplicit() && Addition->isImplicit())
606e8d8bef9SDimitry Andric     erase_value(Elts, dwarf::DW_OP_stack_value);
6075ffd83dbSDimitry Andric   const DIExpression *CombinedExpr =
6085ffd83dbSDimitry Andric       (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
6095ffd83dbSDimitry Andric   return CombinedExpr;
6105ffd83dbSDimitry Andric }
6115ffd83dbSDimitry Andric 
6125ffd83dbSDimitry Andric /// Emit call site parameter entries that are described by the given value and
6135ffd83dbSDimitry Andric /// debug expression.
6145ffd83dbSDimitry Andric template <typename ValT>
6155ffd83dbSDimitry Andric static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
6165ffd83dbSDimitry Andric                                  ArrayRef<FwdRegParamInfo> DescribedParams,
6175ffd83dbSDimitry Andric                                  ParamSet &Params) {
6185ffd83dbSDimitry Andric   for (auto Param : DescribedParams) {
6195ffd83dbSDimitry Andric     bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
6205ffd83dbSDimitry Andric 
6215ffd83dbSDimitry Andric     // TODO: Entry value operations can currently not be combined with any
6225ffd83dbSDimitry Andric     // other expressions, so we can't emit call site entries in those cases.
6235ffd83dbSDimitry Andric     if (ShouldCombineExpressions && Expr->isEntryValue())
6245ffd83dbSDimitry Andric       continue;
6255ffd83dbSDimitry Andric 
6265ffd83dbSDimitry Andric     // If a parameter's call site value is produced by a chain of
6275ffd83dbSDimitry Andric     // instructions we may have already created an expression for the
6285ffd83dbSDimitry Andric     // parameter when walking through the instructions. Append that to the
6295ffd83dbSDimitry Andric     // base expression.
6305ffd83dbSDimitry Andric     const DIExpression *CombinedExpr =
6315ffd83dbSDimitry Andric         ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
6325ffd83dbSDimitry Andric                                  : Expr;
6335ffd83dbSDimitry Andric     assert((!CombinedExpr || CombinedExpr->isValid()) &&
6345ffd83dbSDimitry Andric            "Combined debug expression is invalid");
6355ffd83dbSDimitry Andric 
636fe6060f1SDimitry Andric     DbgValueLoc DbgLocVal(CombinedExpr, DbgValueLocEntry(Val));
6375ffd83dbSDimitry Andric     DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
6385ffd83dbSDimitry Andric     Params.push_back(CSParm);
6395ffd83dbSDimitry Andric     ++NumCSParams;
6405ffd83dbSDimitry Andric   }
6415ffd83dbSDimitry Andric }
6425ffd83dbSDimitry Andric 
6435ffd83dbSDimitry Andric /// Add \p Reg to the worklist, if it's not already present, and mark that the
6445ffd83dbSDimitry Andric /// given parameter registers' values can (potentially) be described using
6455ffd83dbSDimitry Andric /// that register and an debug expression.
6465ffd83dbSDimitry Andric static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
6475ffd83dbSDimitry Andric                                 const DIExpression *Expr,
6485ffd83dbSDimitry Andric                                 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
6495ffd83dbSDimitry Andric   auto I = Worklist.insert({Reg, {}});
6505ffd83dbSDimitry Andric   auto &ParamsForFwdReg = I.first->second;
6515ffd83dbSDimitry Andric   for (auto Param : ParamsToAdd) {
6525ffd83dbSDimitry Andric     assert(none_of(ParamsForFwdReg,
6535ffd83dbSDimitry Andric                    [Param](const FwdRegParamInfo &D) {
6545ffd83dbSDimitry Andric                      return D.ParamReg == Param.ParamReg;
6555ffd83dbSDimitry Andric                    }) &&
6565ffd83dbSDimitry Andric            "Same parameter described twice by forwarding reg");
6575ffd83dbSDimitry Andric 
6585ffd83dbSDimitry Andric     // If a parameter's call site value is produced by a chain of
6595ffd83dbSDimitry Andric     // instructions we may have already created an expression for the
6605ffd83dbSDimitry Andric     // parameter when walking through the instructions. Append that to the
6615ffd83dbSDimitry Andric     // new expression.
6625ffd83dbSDimitry Andric     const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
6635ffd83dbSDimitry Andric     ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
6645ffd83dbSDimitry Andric   }
6655ffd83dbSDimitry Andric }
6665ffd83dbSDimitry Andric 
6675ffd83dbSDimitry Andric /// Interpret values loaded into registers by \p CurMI.
6685ffd83dbSDimitry Andric static void interpretValues(const MachineInstr *CurMI,
6695ffd83dbSDimitry Andric                             FwdRegWorklist &ForwardedRegWorklist,
670bdd1243dSDimitry Andric                             ParamSet &Params,
671bdd1243dSDimitry Andric                             ClobberedRegSet &ClobberedRegUnits) {
6725ffd83dbSDimitry Andric 
6735ffd83dbSDimitry Andric   const MachineFunction *MF = CurMI->getMF();
6745ffd83dbSDimitry Andric   const DIExpression *EmptyExpr =
6755ffd83dbSDimitry Andric       DIExpression::get(MF->getFunction().getContext(), {});
6765ffd83dbSDimitry Andric   const auto &TRI = *MF->getSubtarget().getRegisterInfo();
6775ffd83dbSDimitry Andric   const auto &TII = *MF->getSubtarget().getInstrInfo();
6785ffd83dbSDimitry Andric   const auto &TLI = *MF->getSubtarget().getTargetLowering();
6795ffd83dbSDimitry Andric 
6805ffd83dbSDimitry Andric   // If an instruction defines more than one item in the worklist, we may run
6815ffd83dbSDimitry Andric   // into situations where a worklist register's value is (potentially)
6825ffd83dbSDimitry Andric   // described by the previous value of another register that is also defined
6835ffd83dbSDimitry Andric   // by that instruction.
6845ffd83dbSDimitry Andric   //
6855ffd83dbSDimitry Andric   // This can for example occur in cases like this:
6865ffd83dbSDimitry Andric   //
6875ffd83dbSDimitry Andric   //   $r1 = mov 123
6885ffd83dbSDimitry Andric   //   $r0, $r1 = mvrr $r1, 456
6895ffd83dbSDimitry Andric   //   call @foo, $r0, $r1
6905ffd83dbSDimitry Andric   //
6915ffd83dbSDimitry Andric   // When describing $r1's value for the mvrr instruction, we need to make sure
6925ffd83dbSDimitry Andric   // that we don't finalize an entry value for $r0, as that is dependent on the
6935ffd83dbSDimitry Andric   // previous value of $r1 (123 rather than 456).
6945ffd83dbSDimitry Andric   //
6955ffd83dbSDimitry Andric   // In order to not have to distinguish between those cases when finalizing
6965ffd83dbSDimitry Andric   // entry values, we simply postpone adding new parameter registers to the
6975ffd83dbSDimitry Andric   // worklist, by first keeping them in this temporary container until the
6985ffd83dbSDimitry Andric   // instruction has been handled.
6995ffd83dbSDimitry Andric   FwdRegWorklist TmpWorklistItems;
7005ffd83dbSDimitry Andric 
7015ffd83dbSDimitry Andric   // If the MI is an instruction defining one or more parameters' forwarding
7025ffd83dbSDimitry Andric   // registers, add those defines.
703bdd1243dSDimitry Andric   ClobberedRegSet NewClobberedRegUnits;
7045ffd83dbSDimitry Andric   auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
7055ffd83dbSDimitry Andric                                           SmallSetVector<unsigned, 4> &Defs) {
7065ffd83dbSDimitry Andric     if (MI.isDebugInstr())
7075ffd83dbSDimitry Andric       return;
7085ffd83dbSDimitry Andric 
709*fe013be4SDimitry Andric     for (const MachineOperand &MO : MI.all_defs()) {
710*fe013be4SDimitry Andric       if (MO.getReg().isPhysical()) {
711fe6060f1SDimitry Andric         for (auto &FwdReg : ForwardedRegWorklist)
7125ffd83dbSDimitry Andric           if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
7135ffd83dbSDimitry Andric             Defs.insert(FwdReg.first);
714*fe013be4SDimitry Andric         for (MCRegUnit Unit : TRI.regunits(MO.getReg()))
715*fe013be4SDimitry Andric           NewClobberedRegUnits.insert(Unit);
7165ffd83dbSDimitry Andric       }
7175ffd83dbSDimitry Andric     }
7185ffd83dbSDimitry Andric   };
7195ffd83dbSDimitry Andric 
7205ffd83dbSDimitry Andric   // Set of worklist registers that are defined by this instruction.
7215ffd83dbSDimitry Andric   SmallSetVector<unsigned, 4> FwdRegDefs;
7225ffd83dbSDimitry Andric 
7235ffd83dbSDimitry Andric   getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
724bdd1243dSDimitry Andric   if (FwdRegDefs.empty()) {
725bdd1243dSDimitry Andric     // Any definitions by this instruction will clobber earlier reg movements.
726bdd1243dSDimitry Andric     ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
727bdd1243dSDimitry Andric                              NewClobberedRegUnits.end());
7285ffd83dbSDimitry Andric     return;
729bdd1243dSDimitry Andric   }
730bdd1243dSDimitry Andric 
731bdd1243dSDimitry Andric   // It's possible that we find a copy from a non-volatile register to the param
732bdd1243dSDimitry Andric   // register, which is clobbered in the meantime. Test for clobbered reg unit
733bdd1243dSDimitry Andric   // overlaps before completing.
734bdd1243dSDimitry Andric   auto IsRegClobberedInMeantime = [&](Register Reg) -> bool {
735bdd1243dSDimitry Andric     for (auto &RegUnit : ClobberedRegUnits)
736bdd1243dSDimitry Andric       if (TRI.hasRegUnit(Reg, RegUnit))
737bdd1243dSDimitry Andric         return true;
738bdd1243dSDimitry Andric     return false;
739bdd1243dSDimitry Andric   };
7405ffd83dbSDimitry Andric 
7415ffd83dbSDimitry Andric   for (auto ParamFwdReg : FwdRegDefs) {
7425ffd83dbSDimitry Andric     if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
7435ffd83dbSDimitry Andric       if (ParamValue->first.isImm()) {
7445ffd83dbSDimitry Andric         int64_t Val = ParamValue->first.getImm();
7455ffd83dbSDimitry Andric         finishCallSiteParams(Val, ParamValue->second,
7465ffd83dbSDimitry Andric                              ForwardedRegWorklist[ParamFwdReg], Params);
7475ffd83dbSDimitry Andric       } else if (ParamValue->first.isReg()) {
7485ffd83dbSDimitry Andric         Register RegLoc = ParamValue->first.getReg();
749e8d8bef9SDimitry Andric         Register SP = TLI.getStackPointerRegisterToSaveRestore();
7505ffd83dbSDimitry Andric         Register FP = TRI.getFrameRegister(*MF);
7515ffd83dbSDimitry Andric         bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
752bdd1243dSDimitry Andric         if (!IsRegClobberedInMeantime(RegLoc) &&
753bdd1243dSDimitry Andric             (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP)) {
754e8d8bef9SDimitry Andric           MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
7555ffd83dbSDimitry Andric           finishCallSiteParams(MLoc, ParamValue->second,
7565ffd83dbSDimitry Andric                                ForwardedRegWorklist[ParamFwdReg], Params);
7575ffd83dbSDimitry Andric         } else {
7585ffd83dbSDimitry Andric           // ParamFwdReg was described by the non-callee saved register
7595ffd83dbSDimitry Andric           // RegLoc. Mark that the call site values for the parameters are
7605ffd83dbSDimitry Andric           // dependent on that register instead of ParamFwdReg. Since RegLoc
7615ffd83dbSDimitry Andric           // may be a register that will be handled in this iteration, we
7625ffd83dbSDimitry Andric           // postpone adding the items to the worklist, and instead keep them
7635ffd83dbSDimitry Andric           // in a temporary container.
7645ffd83dbSDimitry Andric           addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
7655ffd83dbSDimitry Andric                               ForwardedRegWorklist[ParamFwdReg]);
7665ffd83dbSDimitry Andric         }
7675ffd83dbSDimitry Andric       }
7685ffd83dbSDimitry Andric     }
7695ffd83dbSDimitry Andric   }
7705ffd83dbSDimitry Andric 
7715ffd83dbSDimitry Andric   // Remove all registers that this instruction defines from the worklist.
7725ffd83dbSDimitry Andric   for (auto ParamFwdReg : FwdRegDefs)
7735ffd83dbSDimitry Andric     ForwardedRegWorklist.erase(ParamFwdReg);
7745ffd83dbSDimitry Andric 
775bdd1243dSDimitry Andric   // Any definitions by this instruction will clobber earlier reg movements.
776bdd1243dSDimitry Andric   ClobberedRegUnits.insert(NewClobberedRegUnits.begin(),
777bdd1243dSDimitry Andric                            NewClobberedRegUnits.end());
778bdd1243dSDimitry Andric 
7795ffd83dbSDimitry Andric   // Now that we are done handling this instruction, add items from the
7805ffd83dbSDimitry Andric   // temporary worklist to the real one.
781fe6060f1SDimitry Andric   for (auto &New : TmpWorklistItems)
7825ffd83dbSDimitry Andric     addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
7835ffd83dbSDimitry Andric   TmpWorklistItems.clear();
7845ffd83dbSDimitry Andric }
7855ffd83dbSDimitry Andric 
7865ffd83dbSDimitry Andric static bool interpretNextInstr(const MachineInstr *CurMI,
7875ffd83dbSDimitry Andric                                FwdRegWorklist &ForwardedRegWorklist,
788bdd1243dSDimitry Andric                                ParamSet &Params,
789bdd1243dSDimitry Andric                                ClobberedRegSet &ClobberedRegUnits) {
7905ffd83dbSDimitry Andric   // Skip bundle headers.
7915ffd83dbSDimitry Andric   if (CurMI->isBundle())
7925ffd83dbSDimitry Andric     return true;
7935ffd83dbSDimitry Andric 
7945ffd83dbSDimitry Andric   // If the next instruction is a call we can not interpret parameter's
7955ffd83dbSDimitry Andric   // forwarding registers or we finished the interpretation of all
7965ffd83dbSDimitry Andric   // parameters.
7975ffd83dbSDimitry Andric   if (CurMI->isCall())
7985ffd83dbSDimitry Andric     return false;
7995ffd83dbSDimitry Andric 
8005ffd83dbSDimitry Andric   if (ForwardedRegWorklist.empty())
8015ffd83dbSDimitry Andric     return false;
8025ffd83dbSDimitry Andric 
8035ffd83dbSDimitry Andric   // Avoid NOP description.
8045ffd83dbSDimitry Andric   if (CurMI->getNumOperands() == 0)
8055ffd83dbSDimitry Andric     return true;
8065ffd83dbSDimitry Andric 
807bdd1243dSDimitry Andric   interpretValues(CurMI, ForwardedRegWorklist, Params, ClobberedRegUnits);
8085ffd83dbSDimitry Andric 
8095ffd83dbSDimitry Andric   return true;
8105ffd83dbSDimitry Andric }
8115ffd83dbSDimitry Andric 
8128bcb0991SDimitry Andric /// Try to interpret values loaded into registers that forward parameters
8138bcb0991SDimitry Andric /// for \p CallMI. Store parameters with interpreted value into \p Params.
8148bcb0991SDimitry Andric static void collectCallSiteParameters(const MachineInstr *CallMI,
8158bcb0991SDimitry Andric                                       ParamSet &Params) {
8165ffd83dbSDimitry Andric   const MachineFunction *MF = CallMI->getMF();
817fe6060f1SDimitry Andric   const auto &CalleesMap = MF->getCallSitesInfo();
8188bcb0991SDimitry Andric   auto CallFwdRegsInfo = CalleesMap.find(CallMI);
8198bcb0991SDimitry Andric 
8208bcb0991SDimitry Andric   // There is no information for the call instruction.
8218bcb0991SDimitry Andric   if (CallFwdRegsInfo == CalleesMap.end())
8228bcb0991SDimitry Andric     return;
8238bcb0991SDimitry Andric 
8245ffd83dbSDimitry Andric   const MachineBasicBlock *MBB = CallMI->getParent();
8258bcb0991SDimitry Andric 
8268bcb0991SDimitry Andric   // Skip the call instruction.
8278bcb0991SDimitry Andric   auto I = std::next(CallMI->getReverseIterator());
8288bcb0991SDimitry Andric 
8295ffd83dbSDimitry Andric   FwdRegWorklist ForwardedRegWorklist;
8305ffd83dbSDimitry Andric 
8315ffd83dbSDimitry Andric   const DIExpression *EmptyExpr =
8325ffd83dbSDimitry Andric       DIExpression::get(MF->getFunction().getContext(), {});
8335ffd83dbSDimitry Andric 
8348bcb0991SDimitry Andric   // Add all the forwarding registers into the ForwardedRegWorklist.
835fe6060f1SDimitry Andric   for (const auto &ArgReg : CallFwdRegsInfo->second) {
8365ffd83dbSDimitry Andric     bool InsertedReg =
8375ffd83dbSDimitry Andric         ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
8385ffd83dbSDimitry Andric             .second;
8398bcb0991SDimitry Andric     assert(InsertedReg && "Single register used to forward two arguments?");
8408bcb0991SDimitry Andric     (void)InsertedReg;
8418bcb0991SDimitry Andric   }
8428bcb0991SDimitry Andric 
843e8d8bef9SDimitry Andric   // Do not emit CSInfo for undef forwarding registers.
844fcaf7f86SDimitry Andric   for (const auto &MO : CallMI->uses())
845e8d8bef9SDimitry Andric     if (MO.isReg() && MO.isUndef())
846e8d8bef9SDimitry Andric       ForwardedRegWorklist.erase(MO.getReg());
847e8d8bef9SDimitry Andric 
8488bcb0991SDimitry Andric   // We erase, from the ForwardedRegWorklist, those forwarding registers for
8498bcb0991SDimitry Andric   // which we successfully describe a loaded value (by using
8508bcb0991SDimitry Andric   // the describeLoadedValue()). For those remaining arguments in the working
8518bcb0991SDimitry Andric   // list, for which we do not describe a loaded value by
8528bcb0991SDimitry Andric   // the describeLoadedValue(), we try to generate an entry value expression
8535ffd83dbSDimitry Andric   // for their call site value description, if the call is within the entry MBB.
8548bcb0991SDimitry Andric   // TODO: Handle situations when call site parameter value can be described
8555ffd83dbSDimitry Andric   // as the entry value within basic blocks other than the first one.
8568bcb0991SDimitry Andric   bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
8578bcb0991SDimitry Andric 
8585ffd83dbSDimitry Andric   // Search for a loading value in forwarding registers inside call delay slot.
859bdd1243dSDimitry Andric   ClobberedRegSet ClobberedRegUnits;
8605ffd83dbSDimitry Andric   if (CallMI->hasDelaySlot()) {
8615ffd83dbSDimitry Andric     auto Suc = std::next(CallMI->getIterator());
8625ffd83dbSDimitry Andric     // Only one-instruction delay slot is supported.
8635ffd83dbSDimitry Andric     auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
8645ffd83dbSDimitry Andric     (void)BundleEnd;
8655ffd83dbSDimitry Andric     assert(std::next(Suc) == BundleEnd &&
8665ffd83dbSDimitry Andric            "More than one instruction in call delay slot");
8675ffd83dbSDimitry Andric     // Try to interpret value loaded by instruction.
868bdd1243dSDimitry Andric     if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params, ClobberedRegUnits))
8698bcb0991SDimitry Andric       return;
8708bcb0991SDimitry Andric   }
8718bcb0991SDimitry Andric 
872480093f4SDimitry Andric   // Search for a loading value in forwarding registers.
8738bcb0991SDimitry Andric   for (; I != MBB->rend(); ++I) {
8745ffd83dbSDimitry Andric     // Try to interpret values loaded by instruction.
875bdd1243dSDimitry Andric     if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params, ClobberedRegUnits))
8768bcb0991SDimitry Andric       return;
8778bcb0991SDimitry Andric   }
8788bcb0991SDimitry Andric 
8798bcb0991SDimitry Andric   // Emit the call site parameter's value as an entry value.
8808bcb0991SDimitry Andric   if (ShouldTryEmitEntryVals) {
8818bcb0991SDimitry Andric     // Create an expression where the register's entry value is used.
8828bcb0991SDimitry Andric     DIExpression *EntryExpr = DIExpression::get(
8838bcb0991SDimitry Andric         MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
884fe6060f1SDimitry Andric     for (auto &RegEntry : ForwardedRegWorklist) {
8855ffd83dbSDimitry Andric       MachineLocation MLoc(RegEntry.first);
8865ffd83dbSDimitry Andric       finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
8878bcb0991SDimitry Andric     }
8888bcb0991SDimitry Andric   }
8898bcb0991SDimitry Andric }
8908bcb0991SDimitry Andric 
8910b57cec5SDimitry Andric void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
8920b57cec5SDimitry Andric                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
8930b57cec5SDimitry Andric                                             const MachineFunction &MF) {
8940b57cec5SDimitry Andric   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
8950b57cec5SDimitry Andric   // the subprogram is required to have one.
8960b57cec5SDimitry Andric   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
8970b57cec5SDimitry Andric     return;
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   // Use DW_AT_call_all_calls to express that call site entries are present
9000b57cec5SDimitry Andric   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
9010b57cec5SDimitry Andric   // because one of its requirements is not met: call site entries for
9020b57cec5SDimitry Andric   // optimized-out calls are elided.
9038bcb0991SDimitry Andric   CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9060b57cec5SDimitry Andric   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
9075ffd83dbSDimitry Andric 
9085ffd83dbSDimitry Andric   // Delay slot support check.
9095ffd83dbSDimitry Andric   auto delaySlotSupported = [&](const MachineInstr &MI) {
9105ffd83dbSDimitry Andric     if (!MI.isBundledWithSucc())
9115ffd83dbSDimitry Andric       return false;
9125ffd83dbSDimitry Andric     auto Suc = std::next(MI.getIterator());
9135ffd83dbSDimitry Andric     auto CallInstrBundle = getBundleStart(MI.getIterator());
9145ffd83dbSDimitry Andric     (void)CallInstrBundle;
9155ffd83dbSDimitry Andric     auto DelaySlotBundle = getBundleStart(Suc);
9165ffd83dbSDimitry Andric     (void)DelaySlotBundle;
9175ffd83dbSDimitry Andric     // Ensure that label after call is following delay slot instruction.
9185ffd83dbSDimitry Andric     // Ex. CALL_INSTRUCTION {
9195ffd83dbSDimitry Andric     //       DELAY_SLOT_INSTRUCTION }
9205ffd83dbSDimitry Andric     //      LABEL_AFTER_CALL
9215ffd83dbSDimitry Andric     assert(getLabelAfterInsn(&*CallInstrBundle) ==
9225ffd83dbSDimitry Andric                getLabelAfterInsn(&*DelaySlotBundle) &&
9235ffd83dbSDimitry Andric            "Call and its successor instruction don't have same label after.");
9245ffd83dbSDimitry Andric     return true;
9255ffd83dbSDimitry Andric   };
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   // Emit call site entries for each call or tail call in the function.
9280b57cec5SDimitry Andric   for (const MachineBasicBlock &MBB : MF) {
9290b57cec5SDimitry Andric     for (const MachineInstr &MI : MBB.instrs()) {
930480093f4SDimitry Andric       // Bundles with call in them will pass the isCall() test below but do not
931480093f4SDimitry Andric       // have callee operand information so skip them here. Iterator will
932480093f4SDimitry Andric       // eventually reach the call MI.
933480093f4SDimitry Andric       if (MI.isBundle())
934480093f4SDimitry Andric         continue;
935480093f4SDimitry Andric 
9360b57cec5SDimitry Andric       // Skip instructions which aren't calls. Both calls and tail-calling jump
9370b57cec5SDimitry Andric       // instructions (e.g TAILJMPd64) are classified correctly here.
9385ffd83dbSDimitry Andric       if (!MI.isCandidateForCallSiteEntry())
9390b57cec5SDimitry Andric         continue;
9400b57cec5SDimitry Andric 
9415ffd83dbSDimitry Andric       // Skip instructions marked as frame setup, as they are not interesting to
9425ffd83dbSDimitry Andric       // the user.
9435ffd83dbSDimitry Andric       if (MI.getFlag(MachineInstr::FrameSetup))
9445ffd83dbSDimitry Andric         continue;
9455ffd83dbSDimitry Andric 
9465ffd83dbSDimitry Andric       // Check if delay slot support is enabled.
9475ffd83dbSDimitry Andric       if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
9480b57cec5SDimitry Andric         return;
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric       // If this is a direct call, find the callee's subprogram.
9518bcb0991SDimitry Andric       // In the case of an indirect call find the register that holds
9528bcb0991SDimitry Andric       // the callee.
953fe6060f1SDimitry Andric       const MachineOperand &CalleeOp = TII->getCalleeOperand(MI);
954fe6060f1SDimitry Andric       if (!CalleeOp.isGlobal() &&
955bdd1243dSDimitry Andric           (!CalleeOp.isReg() || !CalleeOp.getReg().isPhysical()))
9560b57cec5SDimitry Andric         continue;
9570b57cec5SDimitry Andric 
9588bcb0991SDimitry Andric       unsigned CallReg = 0;
95969ade1e0SDimitry Andric       const DISubprogram *CalleeSP = nullptr;
9608bcb0991SDimitry Andric       const Function *CalleeDecl = nullptr;
9618bcb0991SDimitry Andric       if (CalleeOp.isReg()) {
9628bcb0991SDimitry Andric         CallReg = CalleeOp.getReg();
9638bcb0991SDimitry Andric         if (!CallReg)
9648bcb0991SDimitry Andric           continue;
9658bcb0991SDimitry Andric       } else {
9668bcb0991SDimitry Andric         CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
9678bcb0991SDimitry Andric         if (!CalleeDecl || !CalleeDecl->getSubprogram())
9688bcb0991SDimitry Andric           continue;
96969ade1e0SDimitry Andric         CalleeSP = CalleeDecl->getSubprogram();
9708bcb0991SDimitry Andric       }
9718bcb0991SDimitry Andric 
9720b57cec5SDimitry Andric       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric       bool IsTail = TII->isTailCall(MI);
9750b57cec5SDimitry Andric 
976480093f4SDimitry Andric       // If MI is in a bundle, the label was created after the bundle since
977480093f4SDimitry Andric       // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
978480093f4SDimitry Andric       // to search for that label below.
979480093f4SDimitry Andric       const MachineInstr *TopLevelCallMI =
980480093f4SDimitry Andric           MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
981480093f4SDimitry Andric 
9825ffd83dbSDimitry Andric       // For non-tail calls, the return PC is needed to disambiguate paths in
9835ffd83dbSDimitry Andric       // the call graph which could lead to some target function. For tail
9845ffd83dbSDimitry Andric       // calls, no return PC information is needed, unless tuning for GDB in
9855ffd83dbSDimitry Andric       // DWARF4 mode in which case we fake a return PC for compatibility.
9868bcb0991SDimitry Andric       const MCSymbol *PCAddr =
9875ffd83dbSDimitry Andric           (!IsTail || CU.useGNUAnalogForDwarf5Feature())
988480093f4SDimitry Andric               ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
9898bcb0991SDimitry Andric               : nullptr;
9908bcb0991SDimitry Andric 
9915ffd83dbSDimitry Andric       // For tail calls, it's necessary to record the address of the branch
9925ffd83dbSDimitry Andric       // instruction so that the debugger can show where the tail call occurred.
9935ffd83dbSDimitry Andric       const MCSymbol *CallAddr =
9945ffd83dbSDimitry Andric           IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
9955ffd83dbSDimitry Andric 
9965ffd83dbSDimitry Andric       assert((IsTail || PCAddr) && "Non-tail call without return PC");
9978bcb0991SDimitry Andric 
9980b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
9998bcb0991SDimitry Andric                         << (CalleeDecl ? CalleeDecl->getName()
10008bcb0991SDimitry Andric                                        : StringRef(MF.getSubtarget()
10018bcb0991SDimitry Andric                                                        .getRegisterInfo()
10028bcb0991SDimitry Andric                                                        ->getName(CallReg)))
10038bcb0991SDimitry Andric                         << (IsTail ? " [IsTail]" : "") << "\n");
10048bcb0991SDimitry Andric 
10055ffd83dbSDimitry Andric       DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
100669ade1e0SDimitry Andric           ScopeDIE, CalleeSP, IsTail, PCAddr, CallAddr, CallReg);
10078bcb0991SDimitry Andric 
10085ffd83dbSDimitry Andric       // Optionally emit call-site-param debug info.
10095ffd83dbSDimitry Andric       if (emitDebugEntryValues()) {
10108bcb0991SDimitry Andric         ParamSet Params;
10118bcb0991SDimitry Andric         // Try to interpret values of call site parameters.
10128bcb0991SDimitry Andric         collectCallSiteParameters(&MI, Params);
10138bcb0991SDimitry Andric         CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
10148bcb0991SDimitry Andric       }
10150b57cec5SDimitry Andric     }
10160b57cec5SDimitry Andric   }
10170b57cec5SDimitry Andric }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
10200b57cec5SDimitry Andric   if (!U.hasDwarfPubSections())
10210b57cec5SDimitry Andric     return;
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
10240b57cec5SDimitry Andric }
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
10270b57cec5SDimitry Andric                                       DwarfCompileUnit &NewCU) {
10280b57cec5SDimitry Andric   DIE &Die = NewCU.getUnitDie();
10290b57cec5SDimitry Andric   StringRef FN = DIUnit->getFilename();
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric   StringRef Producer = DIUnit->getProducer();
10320b57cec5SDimitry Andric   StringRef Flags = DIUnit->getFlags();
10330b57cec5SDimitry Andric   if (!Flags.empty() && !useAppleExtensionAttributes()) {
10340b57cec5SDimitry Andric     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
10350b57cec5SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
10360b57cec5SDimitry Andric   } else
10370b57cec5SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
10400b57cec5SDimitry Andric                 DIUnit->getSourceLanguage());
10410b57cec5SDimitry Andric   NewCU.addString(Die, dwarf::DW_AT_name, FN);
10425ffd83dbSDimitry Andric   StringRef SysRoot = DIUnit->getSysRoot();
10435ffd83dbSDimitry Andric   if (!SysRoot.empty())
10445ffd83dbSDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
10455ffd83dbSDimitry Andric   StringRef SDK = DIUnit->getSDK();
10465ffd83dbSDimitry Andric   if (!SDK.empty())
10475ffd83dbSDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
10480b57cec5SDimitry Andric 
1049*fe013be4SDimitry Andric   if (!useSplitDwarf()) {
10500b57cec5SDimitry Andric     // Add DW_str_offsets_base to the unit DIE, except for split units.
1051*fe013be4SDimitry Andric     if (useSegmentedStringOffsetsTable())
10520b57cec5SDimitry Andric       NewCU.addStringOffsetsStart();
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric     NewCU.initStmtList();
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric     // If we're using split dwarf the compilation dir is going to be in the
10570b57cec5SDimitry Andric     // skeleton CU and so we don't need to duplicate it here.
10580b57cec5SDimitry Andric     if (!CompilationDir.empty())
10590b57cec5SDimitry Andric       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
10600b57cec5SDimitry Andric     addGnuPubAttributes(NewCU, Die);
10610b57cec5SDimitry Andric   }
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric   if (useAppleExtensionAttributes()) {
10640b57cec5SDimitry Andric     if (DIUnit->isOptimized())
10650b57cec5SDimitry Andric       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric     StringRef Flags = DIUnit->getFlags();
10680b57cec5SDimitry Andric     if (!Flags.empty())
10690b57cec5SDimitry Andric       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric     if (unsigned RVer = DIUnit->getRuntimeVersion())
10720b57cec5SDimitry Andric       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
10730b57cec5SDimitry Andric                     dwarf::DW_FORM_data1, RVer);
10740b57cec5SDimitry Andric   }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   if (DIUnit->getDWOId()) {
10770b57cec5SDimitry Andric     // This CU is either a clang module DWO or a skeleton CU.
10780b57cec5SDimitry Andric     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
10790b57cec5SDimitry Andric                   DIUnit->getDWOId());
1080480093f4SDimitry Andric     if (!DIUnit->getSplitDebugFilename().empty()) {
10810b57cec5SDimitry Andric       // This is a prefabricated skeleton CU.
1082480093f4SDimitry Andric       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1083480093f4SDimitry Andric                                          ? dwarf::DW_AT_dwo_name
1084480093f4SDimitry Andric                                          : dwarf::DW_AT_GNU_dwo_name;
1085480093f4SDimitry Andric       NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1086480093f4SDimitry Andric     }
10870b57cec5SDimitry Andric   }
10880b57cec5SDimitry Andric }
10890b57cec5SDimitry Andric // Create new DwarfCompileUnit for the given metadata node with tag
10900b57cec5SDimitry Andric // DW_TAG_compile_unit.
10910b57cec5SDimitry Andric DwarfCompileUnit &
10920b57cec5SDimitry Andric DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
10930b57cec5SDimitry Andric   if (auto *CU = CUMap.lookup(DIUnit))
10940b57cec5SDimitry Andric     return *CU;
10950b57cec5SDimitry Andric 
1096*fe013be4SDimitry Andric   if (useSplitDwarf() &&
1097*fe013be4SDimitry Andric       !shareAcrossDWOCUs() &&
1098*fe013be4SDimitry Andric       (!DIUnit->getSplitDebugInlining() ||
1099*fe013be4SDimitry Andric        DIUnit->getEmissionKind() == DICompileUnit::FullDebug) &&
1100*fe013be4SDimitry Andric       !CUMap.empty()) {
1101*fe013be4SDimitry Andric     return *CUMap.begin()->second;
1102*fe013be4SDimitry Andric   }
11030b57cec5SDimitry Andric   CompilationDir = DIUnit->getDirectory();
11040b57cec5SDimitry Andric 
11058bcb0991SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
11060b57cec5SDimitry Andric       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
11070b57cec5SDimitry Andric   DwarfCompileUnit &NewCU = *OwnedUnit;
11080b57cec5SDimitry Andric   InfoHolder.addUnit(std::move(OwnedUnit));
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric   // LTO with assembly output shares a single line table amongst multiple CUs.
11110b57cec5SDimitry Andric   // To avoid the compilation directory being ambiguous, let the line table
11120b57cec5SDimitry Andric   // explicitly describe the directory of all files, never relying on the
11130b57cec5SDimitry Andric   // compilation directory.
11140b57cec5SDimitry Andric   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
11150b57cec5SDimitry Andric     Asm->OutStreamer->emitDwarfFile0Directive(
1116e8d8bef9SDimitry Andric         CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1117e8d8bef9SDimitry Andric         DIUnit->getSource(), NewCU.getUniqueID());
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   if (useSplitDwarf()) {
11200b57cec5SDimitry Andric     NewCU.setSkeleton(constructSkeletonCU(NewCU));
11210b57cec5SDimitry Andric     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
11220b57cec5SDimitry Andric   } else {
11230b57cec5SDimitry Andric     finishUnitAttributes(DIUnit, NewCU);
11240b57cec5SDimitry Andric     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
11250b57cec5SDimitry Andric   }
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric   CUMap.insert({DIUnit, &NewCU});
11280b57cec5SDimitry Andric   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
11290b57cec5SDimitry Andric   return NewCU;
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric /// Sort and unique GVEs by comparing their fragment offset.
11330b57cec5SDimitry Andric static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
11340b57cec5SDimitry Andric sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
11350b57cec5SDimitry Andric   llvm::sort(
11360b57cec5SDimitry Andric       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
11370b57cec5SDimitry Andric         // Sort order: first null exprs, then exprs without fragment
11380b57cec5SDimitry Andric         // info, then sort by fragment offset in bits.
11390b57cec5SDimitry Andric         // FIXME: Come up with a more comprehensive comparator so
11400b57cec5SDimitry Andric         // the sorting isn't non-deterministic, and so the following
11410b57cec5SDimitry Andric         // std::unique call works correctly.
11420b57cec5SDimitry Andric         if (!A.Expr || !B.Expr)
11430b57cec5SDimitry Andric           return !!B.Expr;
11440b57cec5SDimitry Andric         auto FragmentA = A.Expr->getFragmentInfo();
11450b57cec5SDimitry Andric         auto FragmentB = B.Expr->getFragmentInfo();
11460b57cec5SDimitry Andric         if (!FragmentA || !FragmentB)
11470b57cec5SDimitry Andric           return !!FragmentB;
11480b57cec5SDimitry Andric         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
11490b57cec5SDimitry Andric       });
11500b57cec5SDimitry Andric   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
11510b57cec5SDimitry Andric                          [](DwarfCompileUnit::GlobalExpr A,
11520b57cec5SDimitry Andric                             DwarfCompileUnit::GlobalExpr B) {
11530b57cec5SDimitry Andric                            return A.Expr == B.Expr;
11540b57cec5SDimitry Andric                          }),
11550b57cec5SDimitry Andric              GVEs.end());
11560b57cec5SDimitry Andric   return GVEs;
11570b57cec5SDimitry Andric }
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric // Emit all Dwarf sections that should come prior to the content. Create
11600b57cec5SDimitry Andric // global DIEs and emit initial debug info sections. This is invoked by
11610b57cec5SDimitry Andric // the target AsmPrinter.
1162e8d8bef9SDimitry Andric void DwarfDebug::beginModule(Module *M) {
1163e8d8bef9SDimitry Andric   DebugHandlerBase::beginModule(M);
11640b57cec5SDimitry Andric 
1165e8d8bef9SDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
1166e8d8bef9SDimitry Andric     return;
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
11690b57cec5SDimitry Andric                                        M->debug_compile_units_end());
1170e8d8bef9SDimitry Andric   assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1171e8d8bef9SDimitry Andric   assert(MMI->hasDebugInfo() &&
1172e8d8bef9SDimitry Andric          "DebugInfoAvailabilty unexpectedly not initialized");
11730b57cec5SDimitry Andric   SingleCU = NumDebugCUs == 1;
11740b57cec5SDimitry Andric   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
11750b57cec5SDimitry Andric       GVMap;
11760b57cec5SDimitry Andric   for (const GlobalVariable &Global : M->globals()) {
11770b57cec5SDimitry Andric     SmallVector<DIGlobalVariableExpression *, 1> GVs;
11780b57cec5SDimitry Andric     Global.getDebugInfo(GVs);
11790b57cec5SDimitry Andric     for (auto *GVE : GVs)
11800b57cec5SDimitry Andric       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
11810b57cec5SDimitry Andric   }
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric   // Create the symbol that designates the start of the unit's contribution
11840b57cec5SDimitry Andric   // to the string offsets table. In a split DWARF scenario, only the skeleton
11850b57cec5SDimitry Andric   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
11860b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable())
11870b57cec5SDimitry Andric     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
11880b57cec5SDimitry Andric         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   // Create the symbols that designates the start of the DWARF v5 range list
11920b57cec5SDimitry Andric   // and locations list tables. They are located past the table headers.
11930b57cec5SDimitry Andric   if (getDwarfVersion() >= 5) {
11940b57cec5SDimitry Andric     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
11950b57cec5SDimitry Andric     Holder.setRnglistsTableBaseSym(
11960b57cec5SDimitry Andric         Asm->createTempSymbol("rnglists_table_base"));
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric     if (useSplitDwarf())
11990b57cec5SDimitry Andric       InfoHolder.setRnglistsTableBaseSym(
12000b57cec5SDimitry Andric           Asm->createTempSymbol("rnglists_dwo_table_base"));
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // Create the symbol that points to the first entry following the debug
12040b57cec5SDimitry Andric   // address table (.debug_addr) header.
12050b57cec5SDimitry Andric   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1206480093f4SDimitry Andric   DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   for (DICompileUnit *CUNode : M->debug_compile_units()) {
1209*fe013be4SDimitry Andric     if (CUNode->getImportedEntities().empty() &&
1210*fe013be4SDimitry Andric         CUNode->getEnumTypes().empty() && CUNode->getRetainedTypes().empty() &&
12110b57cec5SDimitry Andric         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
12120b57cec5SDimitry Andric       continue;
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric     // Global Variables.
12170b57cec5SDimitry Andric     for (auto *GVE : CUNode->getGlobalVariables()) {
12180b57cec5SDimitry Andric       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
12190b57cec5SDimitry Andric       // already know about the variable and it isn't adding a constant
12200b57cec5SDimitry Andric       // expression.
12210b57cec5SDimitry Andric       auto &GVMapEntry = GVMap[GVE->getVariable()];
12220b57cec5SDimitry Andric       auto *Expr = GVE->getExpression();
12230b57cec5SDimitry Andric       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
12240b57cec5SDimitry Andric         GVMapEntry.push_back({nullptr, Expr});
12250b57cec5SDimitry Andric     }
1226fe6060f1SDimitry Andric 
12270b57cec5SDimitry Andric     DenseSet<DIGlobalVariable *> Processed;
12280b57cec5SDimitry Andric     for (auto *GVE : CUNode->getGlobalVariables()) {
12290b57cec5SDimitry Andric       DIGlobalVariable *GV = GVE->getVariable();
12300b57cec5SDimitry Andric       if (Processed.insert(GV).second)
12310b57cec5SDimitry Andric         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
12320b57cec5SDimitry Andric     }
12330b57cec5SDimitry Andric 
12340eae32dcSDimitry Andric     for (auto *Ty : CUNode->getEnumTypes())
12350b57cec5SDimitry Andric       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
12360eae32dcSDimitry Andric 
12370b57cec5SDimitry Andric     for (auto *Ty : CUNode->getRetainedTypes()) {
12380b57cec5SDimitry Andric       // The retained types array by design contains pointers to
12390b57cec5SDimitry Andric       // MDNodes rather than DIRefs. Unique them here.
12400b57cec5SDimitry Andric       if (DIType *RT = dyn_cast<DIType>(Ty))
12410b57cec5SDimitry Andric         // There is no point in force-emitting a forward declaration.
12420b57cec5SDimitry Andric         CU.getOrCreateTypeDIE(RT);
12430b57cec5SDimitry Andric     }
12440b57cec5SDimitry Andric   }
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric void DwarfDebug::finishEntityDefinitions() {
12480b57cec5SDimitry Andric   for (const auto &Entity : ConcreteEntities) {
12490b57cec5SDimitry Andric     DIE *Die = Entity->getDIE();
12500b57cec5SDimitry Andric     assert(Die);
12510b57cec5SDimitry Andric     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
12520b57cec5SDimitry Andric     // in the ConcreteEntities list, rather than looking it up again here.
12530b57cec5SDimitry Andric     // DIE::getUnit isn't simple - it walks parent pointers, etc.
12540b57cec5SDimitry Andric     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
12550b57cec5SDimitry Andric     assert(Unit);
12560b57cec5SDimitry Andric     Unit->finishEntityDefinition(Entity.get());
12570b57cec5SDimitry Andric   }
12580b57cec5SDimitry Andric }
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric void DwarfDebug::finishSubprogramDefinitions() {
12610b57cec5SDimitry Andric   for (const DISubprogram *SP : ProcessedSPNodes) {
12620b57cec5SDimitry Andric     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
12630b57cec5SDimitry Andric     forBothCUs(
12640b57cec5SDimitry Andric         getOrCreateDwarfCompileUnit(SP->getUnit()),
12650b57cec5SDimitry Andric         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric }
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric void DwarfDebug::finalizeModuleInfo() {
12700b57cec5SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric   finishSubprogramDefinitions();
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   finishEntityDefinitions();
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   // Include the DWO file name in the hash if there's more than one CU.
12770b57cec5SDimitry Andric   // This handles ThinLTO's situation where imported CUs may very easily be
12780b57cec5SDimitry Andric   // duplicate with the same CU partially imported into another ThinLTO unit.
12790b57cec5SDimitry Andric   StringRef DWOName;
12800b57cec5SDimitry Andric   if (CUMap.size() > 1)
12810b57cec5SDimitry Andric     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
12820b57cec5SDimitry Andric 
1283*fe013be4SDimitry Andric   bool HasEmittedSplitCU = false;
1284*fe013be4SDimitry Andric 
12850b57cec5SDimitry Andric   // Handle anything that needs to be done on a per-unit basis after
12860b57cec5SDimitry Andric   // all other generation.
12870b57cec5SDimitry Andric   for (const auto &P : CUMap) {
12880b57cec5SDimitry Andric     auto &TheCU = *P.second;
12890b57cec5SDimitry Andric     if (TheCU.getCUNode()->isDebugDirectivesOnly())
12900b57cec5SDimitry Andric       continue;
12910b57cec5SDimitry Andric     // Emit DW_AT_containing_type attribute to connect types with their
12920b57cec5SDimitry Andric     // vtable holding type.
12930b57cec5SDimitry Andric     TheCU.constructContainingTypeDIEs();
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric     // Add CU specific attributes if we need to add any.
12960b57cec5SDimitry Andric     // If we're splitting the dwarf out now that we've got the entire
12970b57cec5SDimitry Andric     // CU then add the dwo id to it.
12980b57cec5SDimitry Andric     auto *SkCU = TheCU.getSkeleton();
1299480093f4SDimitry Andric 
1300480093f4SDimitry Andric     bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1301480093f4SDimitry Andric 
1302480093f4SDimitry Andric     if (HasSplitUnit) {
1303*fe013be4SDimitry Andric       (void)HasEmittedSplitCU;
1304*fe013be4SDimitry Andric       assert((shareAcrossDWOCUs() || !HasEmittedSplitCU) &&
1305*fe013be4SDimitry Andric              "Multiple CUs emitted into a single dwo file");
1306*fe013be4SDimitry Andric       HasEmittedSplitCU = true;
1307480093f4SDimitry Andric       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1308480093f4SDimitry Andric                                          ? dwarf::DW_AT_dwo_name
1309480093f4SDimitry Andric                                          : dwarf::DW_AT_GNU_dwo_name;
13100b57cec5SDimitry Andric       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1311480093f4SDimitry Andric       TheCU.addString(TheCU.getUnitDie(), attrDWOName,
13120b57cec5SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1313480093f4SDimitry Andric       SkCU->addString(SkCU->getUnitDie(), attrDWOName,
13140b57cec5SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
13150b57cec5SDimitry Andric       // Emit a unique identifier for this CU.
13160b57cec5SDimitry Andric       uint64_t ID =
1317e8d8bef9SDimitry Andric           DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
13180b57cec5SDimitry Andric       if (getDwarfVersion() >= 5) {
13190b57cec5SDimitry Andric         TheCU.setDWOId(ID);
13200b57cec5SDimitry Andric         SkCU->setDWOId(ID);
13210b57cec5SDimitry Andric       } else {
13220b57cec5SDimitry Andric         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
13230b57cec5SDimitry Andric                       dwarf::DW_FORM_data8, ID);
13240b57cec5SDimitry Andric         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
13250b57cec5SDimitry Andric                       dwarf::DW_FORM_data8, ID);
13260b57cec5SDimitry Andric       }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
13290b57cec5SDimitry Andric         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
13300b57cec5SDimitry Andric         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
13310b57cec5SDimitry Andric                               Sym, Sym);
13320b57cec5SDimitry Andric       }
13330b57cec5SDimitry Andric     } else if (SkCU) {
13340b57cec5SDimitry Andric       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
13350b57cec5SDimitry Andric     }
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric     // If we have code split among multiple sections or non-contiguous
13380b57cec5SDimitry Andric     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
13390b57cec5SDimitry Andric     // remain in the .o file, otherwise add a DW_AT_low_pc.
13400b57cec5SDimitry Andric     // FIXME: We should use ranges allow reordering of code ala
13410b57cec5SDimitry Andric     // .subsections_via_symbols in mach-o. This would mean turning on
13420b57cec5SDimitry Andric     // ranges for all subprogram DIEs for mach-o.
13430b57cec5SDimitry Andric     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric     if (unsigned NumRanges = TheCU.getRanges().size()) {
13460b57cec5SDimitry Andric       if (NumRanges > 1 && useRangesSection())
13470b57cec5SDimitry Andric         // A DW_AT_low_pc attribute may also be specified in combination with
13480b57cec5SDimitry Andric         // DW_AT_ranges to specify the default base address for use in
13490b57cec5SDimitry Andric         // location lists (see Section 2.6.2) and range lists (see Section
13500b57cec5SDimitry Andric         // 2.17.3).
13510b57cec5SDimitry Andric         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
13520b57cec5SDimitry Andric       else
13538bcb0991SDimitry Andric         U.setBaseAddress(TheCU.getRanges().front().Begin);
13540b57cec5SDimitry Andric       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
13550b57cec5SDimitry Andric     }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric     // We don't keep track of which addresses are used in which CU so this
13580b57cec5SDimitry Andric     // is a bit pessimistic under LTO.
13595ffd83dbSDimitry Andric     if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
13600b57cec5SDimitry Andric       U.addAddrTableBase();
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric     if (getDwarfVersion() >= 5) {
13630b57cec5SDimitry Andric       if (U.hasRangeLists())
13640b57cec5SDimitry Andric         U.addRnglistsBase();
13650b57cec5SDimitry Andric 
1366*fe013be4SDimitry Andric       if (!DebugLocs.getLists().empty() && !useSplitDwarf()) {
13678bcb0991SDimitry Andric         U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
13688bcb0991SDimitry Andric                           DebugLocs.getSym(),
13698bcb0991SDimitry Andric                           TLOF.getDwarfLoclistsSection()->getBeginSymbol());
13708bcb0991SDimitry Andric       }
13710b57cec5SDimitry Andric     }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric     auto *CUNode = cast<DICompileUnit>(P.first);
13745ffd83dbSDimitry Andric     // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
13755ffd83dbSDimitry Andric     // attribute.
1376480093f4SDimitry Andric     if (CUNode->getMacros()) {
1377e8d8bef9SDimitry Andric       if (UseDebugMacroSection) {
1378480093f4SDimitry Andric         if (useSplitDwarf())
13795ffd83dbSDimitry Andric           TheCU.addSectionDelta(
13805ffd83dbSDimitry Andric               TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
13815ffd83dbSDimitry Andric               TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
1382e8d8bef9SDimitry Andric         else {
1383e8d8bef9SDimitry Andric           dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1384e8d8bef9SDimitry Andric                                             ? dwarf::DW_AT_macros
1385e8d8bef9SDimitry Andric                                             : dwarf::DW_AT_GNU_macros;
1386e8d8bef9SDimitry Andric           U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
13875ffd83dbSDimitry Andric                             TLOF.getDwarfMacroSection()->getBeginSymbol());
1388e8d8bef9SDimitry Andric         }
13895ffd83dbSDimitry Andric       } else {
13905ffd83dbSDimitry Andric         if (useSplitDwarf())
13915ffd83dbSDimitry Andric           TheCU.addSectionDelta(
13925ffd83dbSDimitry Andric               TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1393480093f4SDimitry Andric               U.getMacroLabelBegin(),
1394480093f4SDimitry Andric               TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1395480093f4SDimitry Andric         else
13960b57cec5SDimitry Andric           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
13970b57cec5SDimitry Andric                             U.getMacroLabelBegin(),
13980b57cec5SDimitry Andric                             TLOF.getDwarfMacinfoSection()->getBeginSymbol());
13990b57cec5SDimitry Andric       }
1400480093f4SDimitry Andric     }
14015ffd83dbSDimitry Andric     }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
14040b57cec5SDimitry Andric   for (auto *CUNode : MMI->getModule()->debug_compile_units())
14050b57cec5SDimitry Andric     if (CUNode->getDWOId())
14060b57cec5SDimitry Andric       getOrCreateDwarfCompileUnit(CUNode);
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric   // Compute DIE offsets and sizes.
14090b57cec5SDimitry Andric   InfoHolder.computeSizeAndOffsets();
14100b57cec5SDimitry Andric   if (useSplitDwarf())
14110b57cec5SDimitry Andric     SkeletonHolder.computeSizeAndOffsets();
14120b57cec5SDimitry Andric }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric // Emit all Dwarf sections that should come after the content.
14150b57cec5SDimitry Andric void DwarfDebug::endModule() {
1416349cc55cSDimitry Andric   // Terminate the pending line table.
1417349cc55cSDimitry Andric   if (PrevCU)
1418349cc55cSDimitry Andric     terminateLineTable(PrevCU);
1419349cc55cSDimitry Andric   PrevCU = nullptr;
14200b57cec5SDimitry Andric   assert(CurFn == nullptr);
14210b57cec5SDimitry Andric   assert(CurMI == nullptr);
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric   for (const auto &P : CUMap) {
1424*fe013be4SDimitry Andric     const auto *CUNode = cast<DICompileUnit>(P.first);
1425*fe013be4SDimitry Andric     DwarfCompileUnit *CU = &*P.second;
1426*fe013be4SDimitry Andric 
1427*fe013be4SDimitry Andric     // Emit imported entities.
1428*fe013be4SDimitry Andric     for (auto *IE : CUNode->getImportedEntities()) {
1429*fe013be4SDimitry Andric       assert(!isa_and_nonnull<DILocalScope>(IE->getScope()) &&
1430*fe013be4SDimitry Andric              "Unexpected function-local entity in 'imports' CU field.");
1431*fe013be4SDimitry Andric       CU->getOrCreateImportedEntityDIE(IE);
1432*fe013be4SDimitry Andric     }
1433*fe013be4SDimitry Andric     for (const auto *D : CU->getDeferredLocalDecls()) {
1434*fe013be4SDimitry Andric       if (auto *IE = dyn_cast<DIImportedEntity>(D))
1435*fe013be4SDimitry Andric         CU->getOrCreateImportedEntityDIE(IE);
1436*fe013be4SDimitry Andric       else
1437*fe013be4SDimitry Andric         llvm_unreachable("Unexpected local retained node!");
1438*fe013be4SDimitry Andric     }
1439*fe013be4SDimitry Andric 
1440*fe013be4SDimitry Andric     // Emit base types.
1441*fe013be4SDimitry Andric     CU->createBaseTypeDIEs();
14420b57cec5SDimitry Andric   }
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric   // If we aren't actually generating debug info (check beginModule -
1445e8d8bef9SDimitry Andric   // conditionalized on the presence of the llvm.dbg.cu metadata node)
1446e8d8bef9SDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
14470b57cec5SDimitry Andric     return;
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   // Finalize the debug info for the module.
14500b57cec5SDimitry Andric   finalizeModuleInfo();
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   if (useSplitDwarf())
1453480093f4SDimitry Andric     // Emit debug_loc.dwo/debug_loclists.dwo section.
14540b57cec5SDimitry Andric     emitDebugLocDWO();
14550b57cec5SDimitry Andric   else
1456480093f4SDimitry Andric     // Emit debug_loc/debug_loclists section.
14570b57cec5SDimitry Andric     emitDebugLoc();
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric   // Corresponding abbreviations into a abbrev section.
14600b57cec5SDimitry Andric   emitAbbreviations();
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   // Emit all the DIEs into a debug info section.
14630b57cec5SDimitry Andric   emitDebugInfo();
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   // Emit info into a debug aranges section.
14660b57cec5SDimitry Andric   if (GenerateARangeSection)
14670b57cec5SDimitry Andric     emitDebugARanges();
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   // Emit info into a debug ranges section.
14700b57cec5SDimitry Andric   emitDebugRanges();
14710b57cec5SDimitry Andric 
1472480093f4SDimitry Andric   if (useSplitDwarf())
1473480093f4SDimitry Andric   // Emit info into a debug macinfo.dwo section.
1474480093f4SDimitry Andric     emitDebugMacinfoDWO();
1475480093f4SDimitry Andric   else
14765ffd83dbSDimitry Andric     // Emit info into a debug macinfo/macro section.
14770b57cec5SDimitry Andric     emitDebugMacinfo();
14780b57cec5SDimitry Andric 
14795ffd83dbSDimitry Andric   emitDebugStr();
14805ffd83dbSDimitry Andric 
14810b57cec5SDimitry Andric   if (useSplitDwarf()) {
14820b57cec5SDimitry Andric     emitDebugStrDWO();
14830b57cec5SDimitry Andric     emitDebugInfoDWO();
14840b57cec5SDimitry Andric     emitDebugAbbrevDWO();
14850b57cec5SDimitry Andric     emitDebugLineDWO();
14860b57cec5SDimitry Andric     emitDebugRangesDWO();
14870b57cec5SDimitry Andric   }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   emitDebugAddr();
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   // Emit info into the dwarf accelerator table sections.
14920b57cec5SDimitry Andric   switch (getAccelTableKind()) {
14930b57cec5SDimitry Andric   case AccelTableKind::Apple:
14940b57cec5SDimitry Andric     emitAccelNames();
14950b57cec5SDimitry Andric     emitAccelObjC();
14960b57cec5SDimitry Andric     emitAccelNamespaces();
14970b57cec5SDimitry Andric     emitAccelTypes();
14980b57cec5SDimitry Andric     break;
14990b57cec5SDimitry Andric   case AccelTableKind::Dwarf:
15000b57cec5SDimitry Andric     emitAccelDebugNames();
15010b57cec5SDimitry Andric     break;
15020b57cec5SDimitry Andric   case AccelTableKind::None:
15030b57cec5SDimitry Andric     break;
15040b57cec5SDimitry Andric   case AccelTableKind::Default:
15050b57cec5SDimitry Andric     llvm_unreachable("Default should have already been resolved.");
15060b57cec5SDimitry Andric   }
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric   // Emit the pubnames and pubtypes sections if requested.
15090b57cec5SDimitry Andric   emitDebugPubSections();
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric   // clean up.
15120b57cec5SDimitry Andric   // FIXME: AbstractVariables.clear();
15130b57cec5SDimitry Andric }
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
15160b57cec5SDimitry Andric     const DINode *Node, const MDNode *ScopeNode) {
15170b57cec5SDimitry Andric   if (CU.getExistingAbstractEntity(Node))
15180b57cec5SDimitry Andric     return;
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric   if (LexicalScope *Scope =
15210b57cec5SDimitry Andric           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
15220b57cec5SDimitry Andric     CU.createAbstractEntity(Node, Scope);
15230b57cec5SDimitry Andric }
15240b57cec5SDimitry Andric 
1525*fe013be4SDimitry Andric static const DILocalScope *getRetainedNodeScope(const MDNode *N) {
1526*fe013be4SDimitry Andric   const DIScope *S;
1527*fe013be4SDimitry Andric   if (const auto *LV = dyn_cast<DILocalVariable>(N))
1528*fe013be4SDimitry Andric     S = LV->getScope();
1529*fe013be4SDimitry Andric   else if (const auto *L = dyn_cast<DILabel>(N))
1530*fe013be4SDimitry Andric     S = L->getScope();
1531*fe013be4SDimitry Andric   else if (const auto *IE = dyn_cast<DIImportedEntity>(N))
1532*fe013be4SDimitry Andric     S = IE->getScope();
1533*fe013be4SDimitry Andric   else
1534*fe013be4SDimitry Andric     llvm_unreachable("Unexpected retained node!");
1535*fe013be4SDimitry Andric 
1536*fe013be4SDimitry Andric   // Ensure the scope is not a DILexicalBlockFile.
1537*fe013be4SDimitry Andric   return cast<DILocalScope>(S)->getNonLexicalBlockFileScope();
1538*fe013be4SDimitry Andric }
1539*fe013be4SDimitry Andric 
15400b57cec5SDimitry Andric // Collect variable information from side table maintained by MF.
15410b57cec5SDimitry Andric void DwarfDebug::collectVariableInfoFromMFTable(
15420b57cec5SDimitry Andric     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
15430b57cec5SDimitry Andric   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
15445ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
15450b57cec5SDimitry Andric   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
15460b57cec5SDimitry Andric     if (!VI.Var)
15470b57cec5SDimitry Andric       continue;
15480b57cec5SDimitry Andric     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
15490b57cec5SDimitry Andric            "Expected inlined-at fields to agree");
15500b57cec5SDimitry Andric 
15510b57cec5SDimitry Andric     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
15520b57cec5SDimitry Andric     Processed.insert(Var);
15530b57cec5SDimitry Andric     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
15565ffd83dbSDimitry Andric     if (!Scope) {
15575ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
15585ffd83dbSDimitry Andric                         << ", no variable scope found\n");
15590b57cec5SDimitry Andric       continue;
15605ffd83dbSDimitry Andric     }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
15638bcb0991SDimitry Andric     auto RegVar = std::make_unique<DbgVariable>(
15640b57cec5SDimitry Andric                     cast<DILocalVariable>(Var.first), Var.second);
1565*fe013be4SDimitry Andric     if (VI.inStackSlot())
1566*fe013be4SDimitry Andric       RegVar->initializeMMI(VI.Expr, VI.getStackSlot());
1567*fe013be4SDimitry Andric     else {
1568*fe013be4SDimitry Andric       MachineLocation MLoc(VI.getEntryValueRegister(), /*IsIndirect*/ true);
1569*fe013be4SDimitry Andric       auto LocEntry = DbgValueLocEntry(MLoc);
1570*fe013be4SDimitry Andric       RegVar->initializeDbgValue(DbgValueLoc(VI.Expr, LocEntry));
1571*fe013be4SDimitry Andric     }
15725ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
15735ffd83dbSDimitry Andric                       << "\n");
1574fe6060f1SDimitry Andric 
1575*fe013be4SDimitry Andric     if (DbgVariable *DbgVar = MFVars.lookup(Var)) {
1576*fe013be4SDimitry Andric       if (DbgVar->getValueLoc())
1577*fe013be4SDimitry Andric         LLVM_DEBUG(dbgs() << "Dropping repeated entry value debug info for "
1578*fe013be4SDimitry Andric                              "variable "
1579*fe013be4SDimitry Andric                           << VI.Var->getName() << "\n");
1580*fe013be4SDimitry Andric       else
15810b57cec5SDimitry Andric         DbgVar->addMMIEntry(*RegVar);
1582*fe013be4SDimitry Andric     } else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
15830b57cec5SDimitry Andric       MFVars.insert({Var, RegVar.get()});
15840b57cec5SDimitry Andric       ConcreteEntities.push_back(std::move(RegVar));
15850b57cec5SDimitry Andric     }
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.
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)]
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();
17165ffd83dbSDimitry Andric       EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].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 
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.
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())) {
19190b57cec5SDimitry Andric         RegVar->initializeDbgValue(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.
19290b57cec5SDimitry Andric     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
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) {
19390b57cec5SDimitry Andric       RegVar->initializeDbgValue(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 
1984*fe013be4SDimitry Andric   // Collect info for retained nodes.
19850b57cec5SDimitry Andric   for (const DINode *DN : SP->getRetainedNodes()) {
1986*fe013be4SDimitry Andric     const auto *LS = getRetainedNodeScope(DN);
1987*fe013be4SDimitry Andric     if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
19880b57cec5SDimitry Andric       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
19890b57cec5SDimitry Andric         continue;
1990*fe013be4SDimitry Andric       LexicalScope *LexS = LScopes.findLexicalScope(LS);
1991*fe013be4SDimitry Andric       if (LexS)
1992*fe013be4SDimitry Andric         createConcreteEntity(TheCU, *LexS, DN, nullptr);
1993*fe013be4SDimitry Andric     } else {
1994*fe013be4SDimitry Andric       LocalDeclsPerLS[LS].insert(DN);
19950b57cec5SDimitry Andric     }
19960b57cec5SDimitry Andric   }
19970b57cec5SDimitry Andric }
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric // Process beginning of an instruction.
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 
2065*fe013be4SDimitry Andric   bool PrevInstInSameSection =
2066*fe013be4SDimitry Andric       (!PrevInstBB ||
2067*fe013be4SDimitry Andric        PrevInstBB->getSectionIDNum() == MI->getParent()->getSectionIDNum());
2068*fe013be4SDimitry 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 
2136*fe013be4SDimitry 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;
2140*fe013be4SDimitry Andric   const Function &F = MF->getFunction();
2141*fe013be4SDimitry Andric 
2142*fe013be4SDimitry Andric   // Some instructions may be inserted into prologue after this function. Must
2143*fe013be4SDimitry Andric   // keep prologue for these cases.
2144*fe013be4SDimitry Andric   bool IsEmptyPrologue =
2145*fe013be4SDimitry Andric       !(F.hasPrologueData() || F.getMetadata(LLVMContext::MD_func_sanitize));
2146349cc55cSDimitry Andric   for (const auto &MBB : *MF) {
2147349cc55cSDimitry Andric     for (const auto &MI : MBB) {
2148*fe013be4SDimitry Andric       if (!MI.isMetaInstruction()) {
2149*fe013be4SDimitry Andric         if (!MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) {
2150*fe013be4SDimitry Andric           // Scan forward to try to find a non-zero line number. The
2151*fe013be4SDimitry Andric           // prologue_end marks the first breakpoint in the function after the
2152*fe013be4SDimitry Andric           // frame setup, and a compiler-generated line 0 location is not a
2153*fe013be4SDimitry Andric           // meaningful breakpoint. If none is found, return the first
2154*fe013be4SDimitry Andric           // location after the frame setup.
2155349cc55cSDimitry Andric           if (MI.getDebugLoc().getLine())
2156*fe013be4SDimitry Andric             return std::make_pair(MI.getDebugLoc(), IsEmptyPrologue);
2157*fe013be4SDimitry Andric 
2158349cc55cSDimitry Andric           LineZeroLoc = MI.getDebugLoc();
2159349cc55cSDimitry Andric         }
2160*fe013be4SDimitry Andric         IsEmptyPrologue = false;
2161349cc55cSDimitry Andric       }
2162349cc55cSDimitry Andric     }
2163*fe013be4SDimitry Andric   }
2164*fe013be4SDimitry 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.
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 
21890b57cec5SDimitry Andric DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
21900b57cec5SDimitry Andric                                              unsigned CUID) {
2191*fe013be4SDimitry Andric   std::pair<DebugLoc, bool> PrologEnd = findPrologueEndLoc(&MF);
2192*fe013be4SDimitry Andric   DebugLoc PrologEndLoc = PrologEnd.first;
2193*fe013be4SDimitry Andric   bool IsEmptyPrologue = PrologEnd.second;
2194*fe013be4SDimitry Andric 
21950b57cec5SDimitry Andric   // Get beginning of function.
2196*fe013be4SDimitry Andric   if (PrologEndLoc) {
2197*fe013be4SDimitry Andric     // If the prolog is empty, no need to generate scope line for the proc.
2198*fe013be4SDimitry Andric     if (IsEmptyPrologue)
2199*fe013be4SDimitry Andric       return PrologEndLoc;
2200*fe013be4SDimitry 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.
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
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 
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 
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.
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());
2279*fe013be4SDimitry 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) {
2300*fe013be4SDimitry Andric     for (const auto &R : Asm->MBBSectionRanges)
2301*fe013be4SDimitry Andric       addArangeLabel(SymbolCU(&TheCU, R.second.BeginLabel));
2302*fe013be4SDimitry 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
2310*fe013be4SDimitry 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()) {
2315*fe013be4SDimitry Andric       const auto *LS = getRetainedNodeScope(DN);
2316*fe013be4SDimitry Andric       // Ensure LexicalScope is created for the scope of this node.
2317*fe013be4SDimitry Andric       auto *LexS = LScopes.getOrCreateAbstractScope(LS);
2318*fe013be4SDimitry Andric       assert(LexS && "Expected the LexicalScope to be created.");
2319*fe013be4SDimitry Andric       if (isa<DILocalVariable>(DN) || isa<DILabel>(DN)) {
23200b57cec5SDimitry Andric         // Collect info for variables/labels that were optimized out.
2321*fe013be4SDimitry Andric         if (!Processed.insert(InlinedEntity(DN, nullptr)).second ||
2322*fe013be4SDimitry Andric             TheCU.getExistingAbstractEntity(DN))
2323*fe013be4SDimitry Andric           continue;
2324*fe013be4SDimitry Andric         TheCU.createAbstractEntity(DN, LexS);
2325*fe013be4SDimitry Andric       } else {
2326*fe013be4SDimitry Andric         // Remember the node if this is a local declarations.
2327*fe013be4SDimitry Andric         LocalDeclsPerLS[LS].insert(DN);
2328*fe013be4SDimitry Andric       }
2329*fe013be4SDimitry Andric       assert(
2330*fe013be4SDimitry Andric           LScopes.getAbstractScopesList().size() == NumAbstractSubprograms &&
2331*fe013be4SDimitry 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();
2352*fe013be4SDimitry 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.
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.
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.
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 
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>
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 
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.
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.
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.
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.
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.
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:
24860b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
24870b57cec5SDimitry Andric   case dwarf::DW_TAG_namespace:
24880b57cec5SDimitry Andric     return dwarf::GIEK_TYPE;
24890b57cec5SDimitry Andric   case dwarf::DW_TAG_subprogram:
24900b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
24910b57cec5SDimitry Andric   case dwarf::DW_TAG_variable:
24920b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
24930b57cec5SDimitry Andric   case dwarf::DW_TAG_enumerator:
24940b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
24950b57cec5SDimitry Andric                                           dwarf::GIEL_STATIC);
24960b57cec5SDimitry Andric   default:
24970b57cec5SDimitry Andric     return dwarf::GIEK_NONE;
24980b57cec5SDimitry Andric   }
24990b57cec5SDimitry Andric }
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric /// emitDebugPubSections - Emit visible names and types into debug pubnames and
25020b57cec5SDimitry Andric /// pubtypes sections.
25030b57cec5SDimitry Andric void DwarfDebug::emitDebugPubSections() {
25040b57cec5SDimitry Andric   for (const auto &NU : CUMap) {
25050b57cec5SDimitry Andric     DwarfCompileUnit *TheU = NU.second;
25060b57cec5SDimitry Andric     if (!TheU->hasDwarfPubSections())
25070b57cec5SDimitry Andric       continue;
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
25100b57cec5SDimitry Andric                     DICompileUnit::DebugNameTableKind::GNU;
25110b57cec5SDimitry Andric 
251281ad6265SDimitry Andric     Asm->OutStreamer->switchSection(
25130b57cec5SDimitry Andric         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
25140b57cec5SDimitry Andric                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
25150b57cec5SDimitry Andric     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
25160b57cec5SDimitry Andric 
251781ad6265SDimitry Andric     Asm->OutStreamer->switchSection(
25180b57cec5SDimitry Andric         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
25190b57cec5SDimitry Andric                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
25200b57cec5SDimitry Andric     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
25210b57cec5SDimitry Andric   }
25220b57cec5SDimitry Andric }
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
25250b57cec5SDimitry Andric   if (useSectionsAsReferences())
25265ffd83dbSDimitry Andric     Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
25270b57cec5SDimitry Andric                          CU.getDebugSectionOffset());
25280b57cec5SDimitry Andric   else
25290b57cec5SDimitry Andric     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
25300b57cec5SDimitry Andric }
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
25330b57cec5SDimitry Andric                                      DwarfCompileUnit *TheU,
25340b57cec5SDimitry Andric                                      const StringMap<const DIE *> &Globals) {
25350b57cec5SDimitry Andric   if (auto *Skeleton = TheU->getSkeleton())
25360b57cec5SDimitry Andric     TheU = Skeleton;
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric   // Emit the header.
2539fe6060f1SDimitry Andric   MCSymbol *EndLabel = Asm->emitDwarfUnitLength(
2540fe6060f1SDimitry Andric       "pub" + Name, "Length of Public " + Name + " Info");
25410b57cec5SDimitry Andric 
25420b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("DWARF Version");
25430b57cec5SDimitry Andric   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
25460b57cec5SDimitry Andric   emitSectionReference(*TheU);
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Compilation Unit Length");
2549e8d8bef9SDimitry Andric   Asm->emitDwarfLengthOrOffset(TheU->getLength());
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric   // Emit the pubnames for this compilation unit.
2552*fe013be4SDimitry Andric   SmallVector<std::pair<StringRef, const DIE *>, 0> Vec;
2553*fe013be4SDimitry Andric   for (const auto &GI : Globals)
2554*fe013be4SDimitry Andric     Vec.emplace_back(GI.first(), GI.second);
2555*fe013be4SDimitry Andric   llvm::sort(Vec, [](auto &A, auto &B) {
2556*fe013be4SDimitry Andric     return A.second->getOffset() < B.second->getOffset();
2557*fe013be4SDimitry Andric   });
2558*fe013be4SDimitry Andric   for (const auto &[Name, Entity] : Vec) {
25590b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("DIE offset");
2560e8d8bef9SDimitry Andric     Asm->emitDwarfLengthOrOffset(Entity->getOffset());
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric     if (GnuStyle) {
25630b57cec5SDimitry Andric       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
25640b57cec5SDimitry Andric       Asm->OutStreamer->AddComment(
25650b57cec5SDimitry Andric           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
25660b57cec5SDimitry Andric           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
25670b57cec5SDimitry Andric       Asm->emitInt8(Desc.toBits());
25680b57cec5SDimitry Andric     }
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("External Name");
2571*fe013be4SDimitry Andric     Asm->OutStreamer->emitBytes(StringRef(Name.data(), Name.size() + 1));
25720b57cec5SDimitry Andric   }
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("End Mark");
2575e8d8bef9SDimitry Andric   Asm->emitDwarfLengthOrOffset(0);
25765ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(EndLabel);
25770b57cec5SDimitry Andric }
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric /// Emit null-terminated strings into a debug str section.
25800b57cec5SDimitry Andric void DwarfDebug::emitDebugStr() {
25810b57cec5SDimitry Andric   MCSection *StringOffsetsSection = nullptr;
25820b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable()) {
25830b57cec5SDimitry Andric     emitStringOffsetsTableHeader();
25840b57cec5SDimitry Andric     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
25850b57cec5SDimitry Andric   }
25860b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
25870b57cec5SDimitry Andric   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
25880b57cec5SDimitry Andric                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
25890b57cec5SDimitry Andric }
25900b57cec5SDimitry Andric 
25910b57cec5SDimitry Andric void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
25920b57cec5SDimitry Andric                                    const DebugLocStream::Entry &Entry,
25930b57cec5SDimitry Andric                                    const DwarfCompileUnit *CU) {
25940b57cec5SDimitry Andric   auto &&Comments = DebugLocs.getComments(Entry);
25950b57cec5SDimitry Andric   auto Comment = Comments.begin();
25960b57cec5SDimitry Andric   auto End = Comments.end();
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric   // The expressions are inserted into a byte stream rather early (see
25990b57cec5SDimitry Andric   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
26000b57cec5SDimitry Andric   // need to reference a base_type DIE the offset of that DIE is not yet known.
26010b57cec5SDimitry Andric   // To deal with this we instead insert a placeholder early and then extract
26020b57cec5SDimitry Andric   // it here and replace it with the real reference.
26030b57cec5SDimitry Andric   unsigned PtrSize = Asm->MAI->getCodePointerSize();
26040b57cec5SDimitry Andric   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
26050b57cec5SDimitry Andric                                     DebugLocs.getBytes(Entry).size()),
26060b57cec5SDimitry Andric                           Asm->getDataLayout().isLittleEndian(), PtrSize);
26075ffd83dbSDimitry Andric   DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric   using Encoding = DWARFExpression::Operation::Encoding;
26108bcb0991SDimitry Andric   uint64_t Offset = 0;
2611fcaf7f86SDimitry Andric   for (const auto &Op : Expr) {
26120b57cec5SDimitry Andric     assert(Op.getCode() != dwarf::DW_OP_const_type &&
26130b57cec5SDimitry Andric            "3 operand ops not yet supported");
2614*fe013be4SDimitry Andric     assert(!Op.getSubCode() && "SubOps not yet supported");
2615e8d8bef9SDimitry Andric     Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
26160b57cec5SDimitry Andric     Offset++;
2617*fe013be4SDimitry Andric     for (unsigned I = 0; I < Op.getDescription().Op.size(); ++I) {
26180b57cec5SDimitry Andric       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
261904eeddc0SDimitry Andric         unsigned Length =
262004eeddc0SDimitry Andric           Streamer.emitDIERef(*CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die);
26210b57cec5SDimitry Andric         // Make sure comments stay aligned.
262204eeddc0SDimitry Andric         for (unsigned J = 0; J < Length; ++J)
26230b57cec5SDimitry Andric           if (Comment != End)
26240b57cec5SDimitry Andric             Comment++;
26250b57cec5SDimitry Andric       } else {
26268bcb0991SDimitry Andric         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2627e8d8bef9SDimitry Andric           Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
26280b57cec5SDimitry Andric       }
26290b57cec5SDimitry Andric       Offset = Op.getOperandEndOffset(I);
26300b57cec5SDimitry Andric     }
26310b57cec5SDimitry Andric     assert(Offset == Op.getEndOffset());
26320b57cec5SDimitry Andric   }
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
26360b57cec5SDimitry Andric                                    const DbgValueLoc &Value,
26370b57cec5SDimitry Andric                                    DwarfExpression &DwarfExpr) {
26380b57cec5SDimitry Andric   auto *DIExpr = Value.getExpression();
26390b57cec5SDimitry Andric   DIExpressionCursor ExprCursor(DIExpr);
26400b57cec5SDimitry Andric   DwarfExpr.addFragmentOffset(DIExpr);
2641fe6060f1SDimitry Andric 
2642fe6060f1SDimitry Andric   // If the DIExpr is is an Entry Value, we want to follow the same code path
2643fe6060f1SDimitry Andric   // regardless of whether the DBG_VALUE is variadic or not.
2644fe6060f1SDimitry Andric   if (DIExpr && DIExpr->isEntryValue()) {
2645fe6060f1SDimitry Andric     // Entry values can only be a single register with no additional DIExpr,
2646fe6060f1SDimitry Andric     // so just add it directly.
2647fe6060f1SDimitry Andric     assert(Value.getLocEntries().size() == 1);
2648fe6060f1SDimitry Andric     assert(Value.getLocEntries()[0].isLocation());
2649fe6060f1SDimitry Andric     MachineLocation Location = Value.getLocEntries()[0].getLoc();
2650fe6060f1SDimitry Andric     DwarfExpr.setLocation(Location, DIExpr);
2651fe6060f1SDimitry Andric 
2652fe6060f1SDimitry Andric     DwarfExpr.beginEntryValueExpression(ExprCursor);
2653fe6060f1SDimitry Andric 
2654fe6060f1SDimitry Andric     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2655fe6060f1SDimitry Andric     if (!DwarfExpr.addMachineRegExpression(TRI, ExprCursor, Location.getReg()))
2656fe6060f1SDimitry Andric       return;
2657fe6060f1SDimitry Andric     return DwarfExpr.addExpression(std::move(ExprCursor));
2658fe6060f1SDimitry Andric   }
2659fe6060f1SDimitry Andric 
26600b57cec5SDimitry Andric   // Regular entry.
2661fe6060f1SDimitry Andric   auto EmitValueLocEntry = [&DwarfExpr, &BT,
2662fe6060f1SDimitry Andric                             &AP](const DbgValueLocEntry &Entry,
2663fe6060f1SDimitry Andric                                  DIExpressionCursor &Cursor) -> bool {
2664fe6060f1SDimitry Andric     if (Entry.isInt()) {
26650b57cec5SDimitry Andric       if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
26660b57cec5SDimitry Andric                  BT->getEncoding() == dwarf::DW_ATE_signed_char))
2667fe6060f1SDimitry Andric         DwarfExpr.addSignedConstant(Entry.getInt());
26680b57cec5SDimitry Andric       else
2669fe6060f1SDimitry Andric         DwarfExpr.addUnsignedConstant(Entry.getInt());
2670fe6060f1SDimitry Andric     } else if (Entry.isLocation()) {
2671fe6060f1SDimitry Andric       MachineLocation Location = Entry.getLoc();
2672fe6060f1SDimitry Andric       if (Location.isIndirect())
2673fe6060f1SDimitry Andric         DwarfExpr.setMemoryLocationKind();
26740b57cec5SDimitry Andric 
26750b57cec5SDimitry Andric       const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
26760b57cec5SDimitry Andric       if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2677fe6060f1SDimitry Andric         return false;
2678fe6060f1SDimitry Andric     } else if (Entry.isTargetIndexLocation()) {
2679fe6060f1SDimitry Andric       TargetIndexLocation Loc = Entry.getTargetIndexLocation();
2680fe6060f1SDimitry Andric       // TODO TargetIndexLocation is a target-independent. Currently only the
2681fe6060f1SDimitry Andric       // WebAssembly-specific encoding is supported.
2682e8d8bef9SDimitry Andric       assert(AP.TM.getTargetTriple().isWasm());
26835ffd83dbSDimitry Andric       DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2684fe6060f1SDimitry Andric     } else if (Entry.isConstantFP()) {
2685e8d8bef9SDimitry Andric       if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2686fe6060f1SDimitry Andric           !Cursor) {
2687fe6060f1SDimitry Andric         DwarfExpr.addConstantFP(Entry.getConstantFP()->getValueAPF(), AP);
2688fe6060f1SDimitry Andric       } else if (Entry.getConstantFP()
2689fe6060f1SDimitry Andric                      ->getValueAPF()
2690fe6060f1SDimitry Andric                      .bitcastToAPInt()
2691fe6060f1SDimitry Andric                      .getBitWidth() <= 64 /*bits*/) {
2692fe6060f1SDimitry Andric         DwarfExpr.addUnsignedConstant(
2693fe6060f1SDimitry Andric             Entry.getConstantFP()->getValueAPF().bitcastToAPInt());
2694fe6060f1SDimitry Andric       } else {
2695fe6060f1SDimitry Andric         LLVM_DEBUG(
2696fe6060f1SDimitry Andric             dbgs() << "Skipped DwarfExpression creation for ConstantFP of size"
2697fe6060f1SDimitry Andric                    << Entry.getConstantFP()
2698fe6060f1SDimitry Andric                           ->getValueAPF()
2699fe6060f1SDimitry Andric                           .bitcastToAPInt()
2700fe6060f1SDimitry Andric                           .getBitWidth()
2701fe6060f1SDimitry Andric                    << " bits\n");
2702fe6060f1SDimitry Andric         return false;
2703fe6060f1SDimitry Andric       }
2704fe6060f1SDimitry Andric     }
2705fe6060f1SDimitry Andric     return true;
2706fe6060f1SDimitry Andric   };
2707fe6060f1SDimitry Andric 
2708fe6060f1SDimitry Andric   if (!Value.isVariadic()) {
2709fe6060f1SDimitry Andric     if (!EmitValueLocEntry(Value.getLocEntries()[0], ExprCursor))
2710fe6060f1SDimitry Andric       return;
2711fe6060f1SDimitry Andric     DwarfExpr.addExpression(std::move(ExprCursor));
2712e8d8bef9SDimitry Andric     return;
2713e8d8bef9SDimitry Andric   }
2714fe6060f1SDimitry Andric 
2715fe6060f1SDimitry Andric   // If any of the location entries are registers with the value 0, then the
2716fe6060f1SDimitry Andric   // location is undefined.
2717fe6060f1SDimitry Andric   if (any_of(Value.getLocEntries(), [](const DbgValueLocEntry &Entry) {
2718fe6060f1SDimitry Andric         return Entry.isLocation() && !Entry.getLoc().getReg();
2719fe6060f1SDimitry Andric       }))
2720fe6060f1SDimitry Andric     return;
2721fe6060f1SDimitry Andric 
2722fe6060f1SDimitry Andric   DwarfExpr.addExpression(
2723fe6060f1SDimitry Andric       std::move(ExprCursor),
2724fe6060f1SDimitry Andric       [EmitValueLocEntry, &Value](unsigned Idx,
2725fe6060f1SDimitry Andric                                   DIExpressionCursor &Cursor) -> bool {
2726fe6060f1SDimitry Andric         return EmitValueLocEntry(Value.getLocEntries()[Idx], Cursor);
2727fe6060f1SDimitry Andric       });
27280b57cec5SDimitry Andric }
27290b57cec5SDimitry Andric 
27300b57cec5SDimitry Andric void DebugLocEntry::finalize(const AsmPrinter &AP,
27310b57cec5SDimitry Andric                              DebugLocStream::ListBuilder &List,
27320b57cec5SDimitry Andric                              const DIBasicType *BT,
27330b57cec5SDimitry Andric                              DwarfCompileUnit &TheCU) {
27340b57cec5SDimitry Andric   assert(!Values.empty() &&
27350b57cec5SDimitry Andric          "location list entries without values are redundant");
27360b57cec5SDimitry Andric   assert(Begin != End && "unexpected location list entry with empty range");
27370b57cec5SDimitry Andric   DebugLocStream::EntryBuilder Entry(List, Begin, End);
27380b57cec5SDimitry Andric   BufferByteStreamer Streamer = Entry.getStreamer();
27390b57cec5SDimitry Andric   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
27400b57cec5SDimitry Andric   const DbgValueLoc &Value = Values[0];
27410b57cec5SDimitry Andric   if (Value.isFragment()) {
27420b57cec5SDimitry Andric     // Emit all fragments that belong to the same variable and range.
27430b57cec5SDimitry Andric     assert(llvm::all_of(Values, [](DbgValueLoc P) {
27440b57cec5SDimitry Andric           return P.isFragment();
27450b57cec5SDimitry Andric         }) && "all values are expected to be fragments");
27465ffd83dbSDimitry Andric     assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
27470b57cec5SDimitry Andric 
2748e8d8bef9SDimitry Andric     for (const auto &Fragment : Values)
27490b57cec5SDimitry Andric       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
27500b57cec5SDimitry Andric 
27510b57cec5SDimitry Andric   } else {
27520b57cec5SDimitry Andric     assert(Values.size() == 1 && "only fragments may have >1 value");
27530b57cec5SDimitry Andric     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
27540b57cec5SDimitry Andric   }
27550b57cec5SDimitry Andric   DwarfExpr.finalize();
2756480093f4SDimitry Andric   if (DwarfExpr.TagOffset)
2757480093f4SDimitry Andric     List.setTagOffset(*DwarfExpr.TagOffset);
27580b57cec5SDimitry Andric }
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
27610b57cec5SDimitry Andric                                            const DwarfCompileUnit *CU) {
27620b57cec5SDimitry Andric   // Emit the size.
27630b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Loc expr size");
27640b57cec5SDimitry Andric   if (getDwarfVersion() >= 5)
27655ffd83dbSDimitry Andric     Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
27660b57cec5SDimitry Andric   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
27670b57cec5SDimitry Andric     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
27680b57cec5SDimitry Andric   else {
27690b57cec5SDimitry Andric     // The entry is too big to fit into 16 bit, drop it as there is nothing we
27700b57cec5SDimitry Andric     // can do.
27710b57cec5SDimitry Andric     Asm->emitInt16(0);
27720b57cec5SDimitry Andric     return;
27730b57cec5SDimitry Andric   }
27740b57cec5SDimitry Andric   // Emit the entry.
27750b57cec5SDimitry Andric   APByteStreamer Streamer(*Asm);
27760b57cec5SDimitry Andric   emitDebugLocEntry(Streamer, Entry, CU);
27770b57cec5SDimitry Andric }
27780b57cec5SDimitry Andric 
27790b57cec5SDimitry Andric // Emit the header of a DWARF 5 range list table list table. Returns the symbol
27800b57cec5SDimitry Andric // that designates the end of the table for the caller to emit when the table is
27810b57cec5SDimitry Andric // complete.
27820b57cec5SDimitry Andric static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
27830b57cec5SDimitry Andric                                          const DwarfFile &Holder) {
27845ffd83dbSDimitry Andric   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
27850b57cec5SDimitry Andric 
27860b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Offset entry count");
27870b57cec5SDimitry Andric   Asm->emitInt32(Holder.getRangeLists().size());
27885ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
27890b57cec5SDimitry Andric 
27900b57cec5SDimitry Andric   for (const RangeSpanList &List : Holder.getRangeLists())
2791e8d8bef9SDimitry Andric     Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2792e8d8bef9SDimitry Andric                              Asm->getDwarfOffsetByteSize());
27930b57cec5SDimitry Andric 
27940b57cec5SDimitry Andric   return TableEnd;
27950b57cec5SDimitry Andric }
27960b57cec5SDimitry Andric 
27970b57cec5SDimitry Andric // Emit the header of a DWARF 5 locations list table. Returns the symbol that
27980b57cec5SDimitry Andric // designates the end of the table for the caller to emit when the table is
27990b57cec5SDimitry Andric // complete.
28000b57cec5SDimitry Andric static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
28018bcb0991SDimitry Andric                                          const DwarfDebug &DD) {
28025ffd83dbSDimitry Andric   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
28038bcb0991SDimitry Andric 
28048bcb0991SDimitry Andric   const auto &DebugLocs = DD.getDebugLocs();
28050b57cec5SDimitry Andric 
28060b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Offset entry count");
2807480093f4SDimitry Andric   Asm->emitInt32(DebugLocs.getLists().size());
28085ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(DebugLocs.getSym());
28090b57cec5SDimitry Andric 
2810480093f4SDimitry Andric   for (const auto &List : DebugLocs.getLists())
2811e8d8bef9SDimitry Andric     Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2812e8d8bef9SDimitry Andric                              Asm->getDwarfOffsetByteSize());
2813480093f4SDimitry Andric 
28140b57cec5SDimitry Andric   return TableEnd;
28150b57cec5SDimitry Andric }
28160b57cec5SDimitry Andric 
28178bcb0991SDimitry Andric template <typename Ranges, typename PayloadEmitter>
28188bcb0991SDimitry Andric static void emitRangeList(
28198bcb0991SDimitry Andric     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
28208bcb0991SDimitry Andric     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
28218bcb0991SDimitry Andric     unsigned StartxLength, unsigned EndOfList,
28228bcb0991SDimitry Andric     StringRef (*StringifyEnum)(unsigned),
28238bcb0991SDimitry Andric     bool ShouldUseBaseAddress,
28248bcb0991SDimitry Andric     PayloadEmitter EmitPayload) {
28258bcb0991SDimitry Andric 
28268bcb0991SDimitry Andric   auto Size = Asm->MAI->getCodePointerSize();
28278bcb0991SDimitry Andric   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
28288bcb0991SDimitry Andric 
28298bcb0991SDimitry Andric   // Emit our symbol so we can find the beginning of the range.
28305ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(Sym);
28318bcb0991SDimitry Andric 
28328bcb0991SDimitry Andric   // Gather all the ranges that apply to the same section so they can share
28338bcb0991SDimitry Andric   // a base address entry.
28348bcb0991SDimitry Andric   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
28358bcb0991SDimitry Andric 
28368bcb0991SDimitry Andric   for (const auto &Range : R)
28378bcb0991SDimitry Andric     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
28388bcb0991SDimitry Andric 
28398bcb0991SDimitry Andric   const MCSymbol *CUBase = CU.getBaseAddress();
28408bcb0991SDimitry Andric   bool BaseIsSet = false;
28418bcb0991SDimitry Andric   for (const auto &P : SectionRanges) {
28428bcb0991SDimitry Andric     auto *Base = CUBase;
28438bcb0991SDimitry Andric     if (!Base && ShouldUseBaseAddress) {
28448bcb0991SDimitry Andric       const MCSymbol *Begin = P.second.front()->Begin;
28458bcb0991SDimitry Andric       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
28468bcb0991SDimitry Andric       if (!UseDwarf5) {
28478bcb0991SDimitry Andric         Base = NewBase;
28488bcb0991SDimitry Andric         BaseIsSet = true;
28495ffd83dbSDimitry Andric         Asm->OutStreamer->emitIntValue(-1, Size);
28508bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  base address");
28515ffd83dbSDimitry Andric         Asm->OutStreamer->emitSymbolValue(Base, Size);
28528bcb0991SDimitry Andric       } else if (NewBase != Begin || P.second.size() > 1) {
28538bcb0991SDimitry Andric         // Only use a base address if
28548bcb0991SDimitry Andric         //  * the existing pool address doesn't match (NewBase != Begin)
28558bcb0991SDimitry Andric         //  * or, there's more than one entry to share the base address
28568bcb0991SDimitry Andric         Base = NewBase;
28578bcb0991SDimitry Andric         BaseIsSet = true;
28588bcb0991SDimitry Andric         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
28598bcb0991SDimitry Andric         Asm->emitInt8(BaseAddressx);
28608bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  base address index");
28615ffd83dbSDimitry Andric         Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
28628bcb0991SDimitry Andric       }
28638bcb0991SDimitry Andric     } else if (BaseIsSet && !UseDwarf5) {
28648bcb0991SDimitry Andric       BaseIsSet = false;
28658bcb0991SDimitry Andric       assert(!Base);
28665ffd83dbSDimitry Andric       Asm->OutStreamer->emitIntValue(-1, Size);
28675ffd83dbSDimitry Andric       Asm->OutStreamer->emitIntValue(0, Size);
28688bcb0991SDimitry Andric     }
28698bcb0991SDimitry Andric 
28708bcb0991SDimitry Andric     for (const auto *RS : P.second) {
28718bcb0991SDimitry Andric       const MCSymbol *Begin = RS->Begin;
28728bcb0991SDimitry Andric       const MCSymbol *End = RS->End;
28738bcb0991SDimitry Andric       assert(Begin && "Range without a begin symbol?");
28748bcb0991SDimitry Andric       assert(End && "Range without an end symbol?");
28758bcb0991SDimitry Andric       if (Base) {
28768bcb0991SDimitry Andric         if (UseDwarf5) {
28778bcb0991SDimitry Andric           // Emit offset_pair when we have a base.
28788bcb0991SDimitry Andric           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
28798bcb0991SDimitry Andric           Asm->emitInt8(OffsetPair);
28808bcb0991SDimitry Andric           Asm->OutStreamer->AddComment("  starting offset");
28815ffd83dbSDimitry Andric           Asm->emitLabelDifferenceAsULEB128(Begin, Base);
28828bcb0991SDimitry Andric           Asm->OutStreamer->AddComment("  ending offset");
28835ffd83dbSDimitry Andric           Asm->emitLabelDifferenceAsULEB128(End, Base);
28848bcb0991SDimitry Andric         } else {
28855ffd83dbSDimitry Andric           Asm->emitLabelDifference(Begin, Base, Size);
28865ffd83dbSDimitry Andric           Asm->emitLabelDifference(End, Base, Size);
28878bcb0991SDimitry Andric         }
28888bcb0991SDimitry Andric       } else if (UseDwarf5) {
28898bcb0991SDimitry Andric         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
28908bcb0991SDimitry Andric         Asm->emitInt8(StartxLength);
28918bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  start index");
28925ffd83dbSDimitry Andric         Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
28938bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  length");
28945ffd83dbSDimitry Andric         Asm->emitLabelDifferenceAsULEB128(End, Begin);
28958bcb0991SDimitry Andric       } else {
28965ffd83dbSDimitry Andric         Asm->OutStreamer->emitSymbolValue(Begin, Size);
28975ffd83dbSDimitry Andric         Asm->OutStreamer->emitSymbolValue(End, Size);
28988bcb0991SDimitry Andric       }
28998bcb0991SDimitry Andric       EmitPayload(*RS);
29008bcb0991SDimitry Andric     }
29018bcb0991SDimitry Andric   }
29028bcb0991SDimitry Andric 
29038bcb0991SDimitry Andric   if (UseDwarf5) {
29048bcb0991SDimitry Andric     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
29058bcb0991SDimitry Andric     Asm->emitInt8(EndOfList);
29068bcb0991SDimitry Andric   } else {
29078bcb0991SDimitry Andric     // Terminate the list with two 0 values.
29085ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, Size);
29095ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, Size);
29108bcb0991SDimitry Andric   }
29118bcb0991SDimitry Andric }
29128bcb0991SDimitry Andric 
2913480093f4SDimitry Andric // Handles emission of both debug_loclist / debug_loclist.dwo
29148bcb0991SDimitry Andric static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2915480093f4SDimitry Andric   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2916480093f4SDimitry Andric                 *List.CU, dwarf::DW_LLE_base_addressx,
2917480093f4SDimitry Andric                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2918480093f4SDimitry Andric                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
29198bcb0991SDimitry Andric                 /* ShouldUseBaseAddress */ true,
29208bcb0991SDimitry Andric                 [&](const DebugLocStream::Entry &E) {
29218bcb0991SDimitry Andric                   DD.emitDebugLocEntryLocation(E, List.CU);
29228bcb0991SDimitry Andric                 });
29238bcb0991SDimitry Andric }
29248bcb0991SDimitry Andric 
2925480093f4SDimitry Andric void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
29260b57cec5SDimitry Andric   if (DebugLocs.getLists().empty())
29270b57cec5SDimitry Andric     return;
29280b57cec5SDimitry Andric 
292981ad6265SDimitry Andric   Asm->OutStreamer->switchSection(Sec);
2930480093f4SDimitry Andric 
29310b57cec5SDimitry Andric   MCSymbol *TableEnd = nullptr;
2932480093f4SDimitry Andric   if (getDwarfVersion() >= 5)
29338bcb0991SDimitry Andric     TableEnd = emitLoclistsTableHeader(Asm, *this);
29340b57cec5SDimitry Andric 
29358bcb0991SDimitry Andric   for (const auto &List : DebugLocs.getLists())
29368bcb0991SDimitry Andric     emitLocList(*this, Asm, List);
29370b57cec5SDimitry Andric 
29380b57cec5SDimitry Andric   if (TableEnd)
29395ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(TableEnd);
29400b57cec5SDimitry Andric }
29410b57cec5SDimitry Andric 
2942480093f4SDimitry Andric // Emit locations into the .debug_loc/.debug_loclists section.
2943480093f4SDimitry Andric void DwarfDebug::emitDebugLoc() {
2944480093f4SDimitry Andric   emitDebugLocImpl(
2945480093f4SDimitry Andric       getDwarfVersion() >= 5
2946480093f4SDimitry Andric           ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2947480093f4SDimitry Andric           : Asm->getObjFileLowering().getDwarfLocSection());
2948480093f4SDimitry Andric }
2949480093f4SDimitry Andric 
2950480093f4SDimitry Andric // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
29510b57cec5SDimitry Andric void DwarfDebug::emitDebugLocDWO() {
2952480093f4SDimitry Andric   if (getDwarfVersion() >= 5) {
2953480093f4SDimitry Andric     emitDebugLocImpl(
2954480093f4SDimitry Andric         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2955480093f4SDimitry Andric 
2956480093f4SDimitry Andric     return;
2957480093f4SDimitry Andric   }
2958480093f4SDimitry Andric 
29590b57cec5SDimitry Andric   for (const auto &List : DebugLocs.getLists()) {
296081ad6265SDimitry Andric     Asm->OutStreamer->switchSection(
29610b57cec5SDimitry Andric         Asm->getObjFileLowering().getDwarfLocDWOSection());
29625ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(List.Label);
2963480093f4SDimitry Andric 
29640b57cec5SDimitry Andric     for (const auto &Entry : DebugLocs.getEntries(List)) {
29650b57cec5SDimitry Andric       // GDB only supports startx_length in pre-standard split-DWARF.
29660b57cec5SDimitry Andric       // (in v5 standard loclists, it currently* /only/ supports base_address +
29670b57cec5SDimitry Andric       // offset_pair, so the implementations can't really share much since they
29680b57cec5SDimitry Andric       // need to use different representations)
29690b57cec5SDimitry Andric       // * as of October 2018, at least
29705ffd83dbSDimitry Andric       //
29715ffd83dbSDimitry Andric       // In v5 (see emitLocList), this uses SectionLabels to reuse existing
29725ffd83dbSDimitry Andric       // addresses in the address pool to minimize object size/relocations.
29730b57cec5SDimitry Andric       Asm->emitInt8(dwarf::DW_LLE_startx_length);
29748bcb0991SDimitry Andric       unsigned idx = AddrPool.getIndex(Entry.Begin);
29755ffd83dbSDimitry Andric       Asm->emitULEB128(idx);
2976480093f4SDimitry Andric       // Also the pre-standard encoding is slightly different, emitting this as
2977480093f4SDimitry Andric       // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
29785ffd83dbSDimitry Andric       Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
29790b57cec5SDimitry Andric       emitDebugLocEntryLocation(Entry, List.CU);
29800b57cec5SDimitry Andric     }
29810b57cec5SDimitry Andric     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
29820b57cec5SDimitry Andric   }
29830b57cec5SDimitry Andric }
29840b57cec5SDimitry Andric 
29850b57cec5SDimitry Andric struct ArangeSpan {
29860b57cec5SDimitry Andric   const MCSymbol *Start, *End;
29870b57cec5SDimitry Andric };
29880b57cec5SDimitry Andric 
29890b57cec5SDimitry Andric // Emit a debug aranges section, containing a CU lookup for any
29900b57cec5SDimitry Andric // address we can tie back to a CU.
29910b57cec5SDimitry Andric void DwarfDebug::emitDebugARanges() {
29920b57cec5SDimitry Andric   // Provides a unique id per text section.
29930b57cec5SDimitry Andric   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric   // Filter labels by section.
29960b57cec5SDimitry Andric   for (const SymbolCU &SCU : ArangeLabels) {
29970b57cec5SDimitry Andric     if (SCU.Sym->isInSection()) {
29980b57cec5SDimitry Andric       // Make a note of this symbol and it's section.
29990b57cec5SDimitry Andric       MCSection *Section = &SCU.Sym->getSection();
30000b57cec5SDimitry Andric       if (!Section->getKind().isMetadata())
30010b57cec5SDimitry Andric         SectionMap[Section].push_back(SCU);
30020b57cec5SDimitry Andric     } else {
30030b57cec5SDimitry Andric       // Some symbols (e.g. common/bss on mach-o) can have no section but still
30040b57cec5SDimitry Andric       // appear in the output. This sucks as we rely on sections to build
30050b57cec5SDimitry Andric       // arange spans. We can do it without, but it's icky.
30060b57cec5SDimitry Andric       SectionMap[nullptr].push_back(SCU);
30070b57cec5SDimitry Andric     }
30080b57cec5SDimitry Andric   }
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
30110b57cec5SDimitry Andric 
30120b57cec5SDimitry Andric   for (auto &I : SectionMap) {
30130b57cec5SDimitry Andric     MCSection *Section = I.first;
30140b57cec5SDimitry Andric     SmallVector<SymbolCU, 8> &List = I.second;
30150b57cec5SDimitry Andric     if (List.size() < 1)
30160b57cec5SDimitry Andric       continue;
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric     // If we have no section (e.g. common), just write out
30190b57cec5SDimitry Andric     // individual spans for each symbol.
30200b57cec5SDimitry Andric     if (!Section) {
30210b57cec5SDimitry Andric       for (const SymbolCU &Cur : List) {
30220b57cec5SDimitry Andric         ArangeSpan Span;
30230b57cec5SDimitry Andric         Span.Start = Cur.Sym;
30240b57cec5SDimitry Andric         Span.End = nullptr;
30250b57cec5SDimitry Andric         assert(Cur.CU);
30260b57cec5SDimitry Andric         Spans[Cur.CU].push_back(Span);
30270b57cec5SDimitry Andric       }
30280b57cec5SDimitry Andric       continue;
30290b57cec5SDimitry Andric     }
30300b57cec5SDimitry Andric 
30310b57cec5SDimitry Andric     // Sort the symbols by offset within the section.
30320b57cec5SDimitry Andric     llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
303381ad6265SDimitry Andric       unsigned IA = A.Sym ? Asm->OutStreamer->getSymbolOrder(A.Sym) : 0;
303481ad6265SDimitry Andric       unsigned IB = B.Sym ? Asm->OutStreamer->getSymbolOrder(B.Sym) : 0;
30350b57cec5SDimitry Andric 
30360b57cec5SDimitry Andric       // Symbols with no order assigned should be placed at the end.
30370b57cec5SDimitry Andric       // (e.g. section end labels)
30380b57cec5SDimitry Andric       if (IA == 0)
30390b57cec5SDimitry Andric         return false;
30400b57cec5SDimitry Andric       if (IB == 0)
30410b57cec5SDimitry Andric         return true;
30420b57cec5SDimitry Andric       return IA < IB;
30430b57cec5SDimitry Andric     });
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric     // Insert a final terminator.
30460b57cec5SDimitry Andric     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric     // Build spans between each label.
30490b57cec5SDimitry Andric     const MCSymbol *StartSym = List[0].Sym;
30500b57cec5SDimitry Andric     for (size_t n = 1, e = List.size(); n < e; n++) {
30510b57cec5SDimitry Andric       const SymbolCU &Prev = List[n - 1];
30520b57cec5SDimitry Andric       const SymbolCU &Cur = List[n];
30530b57cec5SDimitry Andric 
30540b57cec5SDimitry Andric       // Try and build the longest span we can within the same CU.
30550b57cec5SDimitry Andric       if (Cur.CU != Prev.CU) {
30560b57cec5SDimitry Andric         ArangeSpan Span;
30570b57cec5SDimitry Andric         Span.Start = StartSym;
30580b57cec5SDimitry Andric         Span.End = Cur.Sym;
30590b57cec5SDimitry Andric         assert(Prev.CU);
30600b57cec5SDimitry Andric         Spans[Prev.CU].push_back(Span);
30610b57cec5SDimitry Andric         StartSym = Cur.Sym;
30620b57cec5SDimitry Andric       }
30630b57cec5SDimitry Andric     }
30640b57cec5SDimitry Andric   }
30650b57cec5SDimitry Andric 
30660b57cec5SDimitry Andric   // Start the dwarf aranges section.
306781ad6265SDimitry Andric   Asm->OutStreamer->switchSection(
30680b57cec5SDimitry Andric       Asm->getObjFileLowering().getDwarfARangesSection());
30690b57cec5SDimitry Andric 
30700b57cec5SDimitry Andric   unsigned PtrSize = Asm->MAI->getCodePointerSize();
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric   // Build a list of CUs used.
30730b57cec5SDimitry Andric   std::vector<DwarfCompileUnit *> CUs;
30740b57cec5SDimitry Andric   for (const auto &it : Spans) {
30750b57cec5SDimitry Andric     DwarfCompileUnit *CU = it.first;
30760b57cec5SDimitry Andric     CUs.push_back(CU);
30770b57cec5SDimitry Andric   }
30780b57cec5SDimitry Andric 
30790b57cec5SDimitry Andric   // Sort the CU list (again, to ensure consistent output order).
30800b57cec5SDimitry Andric   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
30810b57cec5SDimitry Andric     return A->getUniqueID() < B->getUniqueID();
30820b57cec5SDimitry Andric   });
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric   // Emit an arange table for each CU we used.
30850b57cec5SDimitry Andric   for (DwarfCompileUnit *CU : CUs) {
30860b57cec5SDimitry Andric     std::vector<ArangeSpan> &List = Spans[CU];
30870b57cec5SDimitry Andric 
30880b57cec5SDimitry Andric     // Describe the skeleton CU's offset and length, not the dwo file's.
30890b57cec5SDimitry Andric     if (auto *Skel = CU->getSkeleton())
30900b57cec5SDimitry Andric       CU = Skel;
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric     // Emit size of content not including length itself.
30930b57cec5SDimitry Andric     unsigned ContentSize =
30940b57cec5SDimitry Andric         sizeof(int16_t) +               // DWARF ARange version number
3095e8d8bef9SDimitry Andric         Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
3096e8d8bef9SDimitry Andric                                         // section
30970b57cec5SDimitry Andric         sizeof(int8_t) +                // Pointer Size (in bytes)
30980b57cec5SDimitry Andric         sizeof(int8_t);                 // Segment Size (in bytes)
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric     unsigned TupleSize = PtrSize * 2;
31010b57cec5SDimitry Andric 
31020b57cec5SDimitry Andric     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
3103e8d8bef9SDimitry Andric     unsigned Padding = offsetToAlignment(
3104e8d8bef9SDimitry Andric         Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
31050b57cec5SDimitry Andric 
31060b57cec5SDimitry Andric     ContentSize += Padding;
31070b57cec5SDimitry Andric     ContentSize += (List.size() + 1) * TupleSize;
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric     // For each compile unit, write the list of spans it covers.
3110e8d8bef9SDimitry Andric     Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
31110b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("DWARF Arange version number");
31120b57cec5SDimitry Andric     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
31130b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
31140b57cec5SDimitry Andric     emitSectionReference(*CU);
31150b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("Address Size (in bytes)");
31160b57cec5SDimitry Andric     Asm->emitInt8(PtrSize);
31170b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
31180b57cec5SDimitry Andric     Asm->emitInt8(0);
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric     Asm->OutStreamer->emitFill(Padding, 0xff);
31210b57cec5SDimitry Andric 
31220b57cec5SDimitry Andric     for (const ArangeSpan &Span : List) {
31235ffd83dbSDimitry Andric       Asm->emitLabelReference(Span.Start, PtrSize);
31240b57cec5SDimitry Andric 
312581ad6265SDimitry Andric       // Calculate the size as being from the span start to its end.
312681ad6265SDimitry Andric       //
312781ad6265SDimitry Andric       // If the size is zero, then round it up to one byte. The DWARF
312881ad6265SDimitry Andric       // specification requires that entries in this table have nonzero
312981ad6265SDimitry Andric       // lengths.
313081ad6265SDimitry Andric       auto SizeRef = SymSize.find(Span.Start);
313181ad6265SDimitry Andric       if ((SizeRef == SymSize.end() || SizeRef->second != 0) && Span.End) {
31325ffd83dbSDimitry Andric         Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
31330b57cec5SDimitry Andric       } else {
31340b57cec5SDimitry Andric         // For symbols without an end marker (e.g. common), we
31350b57cec5SDimitry Andric         // write a single arange entry containing just that one symbol.
313681ad6265SDimitry Andric         uint64_t Size;
313781ad6265SDimitry Andric         if (SizeRef == SymSize.end() || SizeRef->second == 0)
31380b57cec5SDimitry Andric           Size = 1;
313981ad6265SDimitry Andric         else
314081ad6265SDimitry Andric           Size = SizeRef->second;
31410b57cec5SDimitry Andric 
31425ffd83dbSDimitry Andric         Asm->OutStreamer->emitIntValue(Size, PtrSize);
31430b57cec5SDimitry Andric       }
31440b57cec5SDimitry Andric     }
31450b57cec5SDimitry Andric 
31460b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("ARange terminator");
31475ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, PtrSize);
31485ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, PtrSize);
31490b57cec5SDimitry Andric   }
31500b57cec5SDimitry Andric }
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric /// Emit a single range list. We handle both DWARF v5 and earlier.
31530b57cec5SDimitry Andric static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
31540b57cec5SDimitry Andric                           const RangeSpanList &List) {
3155480093f4SDimitry Andric   emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
31568bcb0991SDimitry Andric                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
31578bcb0991SDimitry Andric                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
31588bcb0991SDimitry Andric                 llvm::dwarf::RangeListEncodingString,
3159480093f4SDimitry Andric                 List.CU->getCUNode()->getRangesBaseAddress() ||
31608bcb0991SDimitry Andric                     DD.getDwarfVersion() >= 5,
31618bcb0991SDimitry Andric                 [](auto) {});
31620b57cec5SDimitry Andric }
31630b57cec5SDimitry Andric 
3164480093f4SDimitry Andric void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
3165480093f4SDimitry Andric   if (Holder.getRangeLists().empty())
3166480093f4SDimitry Andric     return;
3167480093f4SDimitry Andric 
3168480093f4SDimitry Andric   assert(useRangesSection());
3169480093f4SDimitry Andric   assert(!CUMap.empty());
3170480093f4SDimitry Andric   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
3171480093f4SDimitry Andric     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
3172480093f4SDimitry Andric   }));
3173480093f4SDimitry Andric 
317481ad6265SDimitry Andric   Asm->OutStreamer->switchSection(Section);
3175480093f4SDimitry Andric 
3176480093f4SDimitry Andric   MCSymbol *TableEnd = nullptr;
3177480093f4SDimitry Andric   if (getDwarfVersion() >= 5)
3178480093f4SDimitry Andric     TableEnd = emitRnglistsTableHeader(Asm, Holder);
3179480093f4SDimitry Andric 
31800b57cec5SDimitry Andric   for (const RangeSpanList &List : Holder.getRangeLists())
3181480093f4SDimitry Andric     emitRangeList(*this, Asm, List);
31820b57cec5SDimitry Andric 
31830b57cec5SDimitry Andric   if (TableEnd)
31845ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(TableEnd);
31850b57cec5SDimitry Andric }
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric /// Emit address ranges into the .debug_ranges section or into the DWARF v5
31880b57cec5SDimitry Andric /// .debug_rnglists section.
31890b57cec5SDimitry Andric void DwarfDebug::emitDebugRanges() {
31900b57cec5SDimitry Andric   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
31910b57cec5SDimitry Andric 
3192480093f4SDimitry Andric   emitDebugRangesImpl(Holder,
3193480093f4SDimitry Andric                       getDwarfVersion() >= 5
3194480093f4SDimitry Andric                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
3195480093f4SDimitry Andric                           : Asm->getObjFileLowering().getDwarfRangesSection());
31960b57cec5SDimitry Andric }
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric void DwarfDebug::emitDebugRangesDWO() {
3199480093f4SDimitry Andric   emitDebugRangesImpl(InfoHolder,
32000b57cec5SDimitry Andric                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
32010b57cec5SDimitry Andric }
32020b57cec5SDimitry Andric 
3203e8d8bef9SDimitry Andric /// Emit the header of a DWARF 5 macro section, or the GNU extension for
3204e8d8bef9SDimitry Andric /// DWARF 4.
32055ffd83dbSDimitry Andric static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
3206e8d8bef9SDimitry Andric                             const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
32075ffd83dbSDimitry Andric   enum HeaderFlagMask {
32085ffd83dbSDimitry Andric #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
32095ffd83dbSDimitry Andric #include "llvm/BinaryFormat/Dwarf.def"
32105ffd83dbSDimitry Andric   };
32115ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("Macro information version");
3212e8d8bef9SDimitry Andric   Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
3213e8d8bef9SDimitry Andric   // We emit the line offset flag unconditionally here, since line offset should
3214e8d8bef9SDimitry Andric   // be mostly present.
3215e8d8bef9SDimitry Andric   if (Asm->isDwarf64()) {
3216e8d8bef9SDimitry Andric     Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
3217e8d8bef9SDimitry Andric     Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3218e8d8bef9SDimitry Andric   } else {
32195ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3220e8d8bef9SDimitry Andric     Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3221e8d8bef9SDimitry Andric   }
32225ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("debug_line_offset");
3223e8d8bef9SDimitry Andric   if (DD.useSplitDwarf())
3224e8d8bef9SDimitry Andric     Asm->emitDwarfLengthOrOffset(0);
3225e8d8bef9SDimitry Andric   else
3226e8d8bef9SDimitry Andric     Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
32275ffd83dbSDimitry Andric }
32285ffd83dbSDimitry Andric 
32290b57cec5SDimitry Andric void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
32300b57cec5SDimitry Andric   for (auto *MN : Nodes) {
32310b57cec5SDimitry Andric     if (auto *M = dyn_cast<DIMacro>(MN))
32320b57cec5SDimitry Andric       emitMacro(*M);
32330b57cec5SDimitry Andric     else if (auto *F = dyn_cast<DIMacroFile>(MN))
32340b57cec5SDimitry Andric       emitMacroFile(*F, U);
32350b57cec5SDimitry Andric     else
32360b57cec5SDimitry Andric       llvm_unreachable("Unexpected DI type!");
32370b57cec5SDimitry Andric   }
32380b57cec5SDimitry Andric }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric void DwarfDebug::emitMacro(DIMacro &M) {
32410b57cec5SDimitry Andric   StringRef Name = M.getName();
32420b57cec5SDimitry Andric   StringRef Value = M.getValue();
32435ffd83dbSDimitry Andric 
3244e8d8bef9SDimitry Andric   // There should be one space between the macro name and the macro value in
3245e8d8bef9SDimitry Andric   // define entries. In undef entries, only the macro name is emitted.
3246e8d8bef9SDimitry Andric   std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3247e8d8bef9SDimitry Andric 
3248e8d8bef9SDimitry Andric   if (UseDebugMacroSection) {
3249e8d8bef9SDimitry Andric     if (getDwarfVersion() >= 5) {
32505ffd83dbSDimitry Andric       unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
32515ffd83dbSDimitry Andric                           ? dwarf::DW_MACRO_define_strx
32525ffd83dbSDimitry Andric                           : dwarf::DW_MACRO_undef_strx;
32535ffd83dbSDimitry Andric       Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
32545ffd83dbSDimitry Andric       Asm->emitULEB128(Type);
32555ffd83dbSDimitry Andric       Asm->OutStreamer->AddComment("Line Number");
32565ffd83dbSDimitry Andric       Asm->emitULEB128(M.getLine());
32575ffd83dbSDimitry Andric       Asm->OutStreamer->AddComment("Macro String");
3258e8d8bef9SDimitry Andric       Asm->emitULEB128(
3259e8d8bef9SDimitry Andric           InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3260e8d8bef9SDimitry Andric     } else {
3261e8d8bef9SDimitry Andric       unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3262e8d8bef9SDimitry Andric                           ? dwarf::DW_MACRO_GNU_define_indirect
3263e8d8bef9SDimitry Andric                           : dwarf::DW_MACRO_GNU_undef_indirect;
3264e8d8bef9SDimitry Andric       Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
3265e8d8bef9SDimitry Andric       Asm->emitULEB128(Type);
3266e8d8bef9SDimitry Andric       Asm->OutStreamer->AddComment("Line Number");
3267e8d8bef9SDimitry Andric       Asm->emitULEB128(M.getLine());
3268e8d8bef9SDimitry Andric       Asm->OutStreamer->AddComment("Macro String");
3269e8d8bef9SDimitry Andric       Asm->emitDwarfSymbolReference(
3270e8d8bef9SDimitry Andric           InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3271e8d8bef9SDimitry Andric     }
32725ffd83dbSDimitry Andric   } else {
32735ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
32745ffd83dbSDimitry Andric     Asm->emitULEB128(M.getMacinfoType());
32755ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment("Line Number");
32765ffd83dbSDimitry Andric     Asm->emitULEB128(M.getLine());
32775ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment("Macro String");
3278e8d8bef9SDimitry Andric     Asm->OutStreamer->emitBytes(Str);
32790b57cec5SDimitry Andric     Asm->emitInt8('\0');
32800b57cec5SDimitry Andric   }
32815ffd83dbSDimitry Andric }
32825ffd83dbSDimitry Andric 
32835ffd83dbSDimitry Andric void DwarfDebug::emitMacroFileImpl(
3284e8d8bef9SDimitry Andric     DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
32855ffd83dbSDimitry Andric     StringRef (*MacroFormToString)(unsigned Form)) {
32865ffd83dbSDimitry Andric 
32875ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
32885ffd83dbSDimitry Andric   Asm->emitULEB128(StartFile);
32895ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("Line Number");
3290e8d8bef9SDimitry Andric   Asm->emitULEB128(MF.getLine());
32915ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("File Number");
3292e8d8bef9SDimitry Andric   DIFile &F = *MF.getFile();
3293e8d8bef9SDimitry Andric   if (useSplitDwarf())
3294e8d8bef9SDimitry Andric     Asm->emitULEB128(getDwoLineTable(U)->getFile(
3295e8d8bef9SDimitry Andric         F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3296e8d8bef9SDimitry Andric         Asm->OutContext.getDwarfVersion(), F.getSource()));
3297e8d8bef9SDimitry Andric   else
3298e8d8bef9SDimitry Andric     Asm->emitULEB128(U.getOrCreateSourceID(&F));
3299e8d8bef9SDimitry Andric   handleMacroNodes(MF.getElements(), U);
33005ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
33015ffd83dbSDimitry Andric   Asm->emitULEB128(EndFile);
33025ffd83dbSDimitry Andric }
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
33055ffd83dbSDimitry Andric   // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
33065ffd83dbSDimitry Andric   // so for readibility/uniformity, We are explicitly emitting those.
33070b57cec5SDimitry Andric   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3308e8d8bef9SDimitry Andric   if (UseDebugMacroSection)
3309e8d8bef9SDimitry Andric     emitMacroFileImpl(
3310e8d8bef9SDimitry Andric         F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3311e8d8bef9SDimitry Andric         (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
33125ffd83dbSDimitry Andric   else
33135ffd83dbSDimitry Andric     emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
33145ffd83dbSDimitry Andric                       dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
33150b57cec5SDimitry Andric }
33160b57cec5SDimitry Andric 
3317480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
33180b57cec5SDimitry Andric   for (const auto &P : CUMap) {
33190b57cec5SDimitry Andric     auto &TheCU = *P.second;
33200b57cec5SDimitry Andric     auto *SkCU = TheCU.getSkeleton();
33210b57cec5SDimitry Andric     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
33220b57cec5SDimitry Andric     auto *CUNode = cast<DICompileUnit>(P.first);
33230b57cec5SDimitry Andric     DIMacroNodeArray Macros = CUNode->getMacros();
3324480093f4SDimitry Andric     if (Macros.empty())
3325480093f4SDimitry Andric       continue;
332681ad6265SDimitry Andric     Asm->OutStreamer->switchSection(Section);
33275ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3328e8d8bef9SDimitry Andric     if (UseDebugMacroSection)
3329e8d8bef9SDimitry Andric       emitMacroHeader(Asm, *this, U, getDwarfVersion());
33300b57cec5SDimitry Andric     handleMacroNodes(Macros, U);
33310b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("End Of Macro List Mark");
33320b57cec5SDimitry Andric     Asm->emitInt8(0);
33330b57cec5SDimitry Andric   }
3334480093f4SDimitry Andric }
3335480093f4SDimitry Andric 
33365ffd83dbSDimitry Andric /// Emit macros into a debug macinfo/macro section.
3337480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfo() {
33385ffd83dbSDimitry Andric   auto &ObjLower = Asm->getObjFileLowering();
3339e8d8bef9SDimitry Andric   emitDebugMacinfoImpl(UseDebugMacroSection
33405ffd83dbSDimitry Andric                            ? ObjLower.getDwarfMacroSection()
33415ffd83dbSDimitry Andric                            : ObjLower.getDwarfMacinfoSection());
3342480093f4SDimitry Andric }
3343480093f4SDimitry Andric 
3344480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfoDWO() {
33455ffd83dbSDimitry Andric   auto &ObjLower = Asm->getObjFileLowering();
3346e8d8bef9SDimitry Andric   emitDebugMacinfoImpl(UseDebugMacroSection
33475ffd83dbSDimitry Andric                            ? ObjLower.getDwarfMacroDWOSection()
33485ffd83dbSDimitry Andric                            : ObjLower.getDwarfMacinfoDWOSection());
3349480093f4SDimitry Andric }
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric // DWARF5 Experimental Separate Dwarf emitters.
33520b57cec5SDimitry Andric 
33530b57cec5SDimitry Andric void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
33540b57cec5SDimitry Andric                                   std::unique_ptr<DwarfCompileUnit> NewU) {
33550b57cec5SDimitry Andric 
33560b57cec5SDimitry Andric   if (!CompilationDir.empty())
33570b57cec5SDimitry Andric     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
33580b57cec5SDimitry Andric   addGnuPubAttributes(*NewU, Die);
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric   SkeletonHolder.addUnit(std::move(NewU));
33610b57cec5SDimitry Andric }
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
33640b57cec5SDimitry Andric 
33658bcb0991SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3366480093f4SDimitry Andric       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3367480093f4SDimitry Andric       UnitKind::Skeleton);
33680b57cec5SDimitry Andric   DwarfCompileUnit &NewCU = *OwnedUnit;
33690b57cec5SDimitry Andric   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
33700b57cec5SDimitry Andric 
33710b57cec5SDimitry Andric   NewCU.initStmtList();
33720b57cec5SDimitry Andric 
33730b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable())
33740b57cec5SDimitry Andric     NewCU.addStringOffsetsStart();
33750b57cec5SDimitry Andric 
33760b57cec5SDimitry Andric   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric   return NewCU;
33790b57cec5SDimitry Andric }
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric // Emit the .debug_info.dwo section for separated dwarf. This contains the
33820b57cec5SDimitry Andric // compile units that would normally be in debug_info.
33830b57cec5SDimitry Andric void DwarfDebug::emitDebugInfoDWO() {
33840b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf debug info?");
33850b57cec5SDimitry Andric   // Don't emit relocations into the dwo file.
33860b57cec5SDimitry Andric   InfoHolder.emitUnits(/* UseOffsets */ true);
33870b57cec5SDimitry Andric }
33880b57cec5SDimitry Andric 
33890b57cec5SDimitry Andric // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
33900b57cec5SDimitry Andric // abbreviations for the .debug_info.dwo section.
33910b57cec5SDimitry Andric void DwarfDebug::emitDebugAbbrevDWO() {
33920b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
33930b57cec5SDimitry Andric   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
33940b57cec5SDimitry Andric }
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric void DwarfDebug::emitDebugLineDWO() {
33970b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
33980b57cec5SDimitry Andric   SplitTypeUnitFileTable.Emit(
33990b57cec5SDimitry Andric       *Asm->OutStreamer, MCDwarfLineTableParams(),
34000b57cec5SDimitry Andric       Asm->getObjFileLowering().getDwarfLineDWOSection());
34010b57cec5SDimitry Andric }
34020b57cec5SDimitry Andric 
34030b57cec5SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
34040b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
34050b57cec5SDimitry Andric   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
34060b57cec5SDimitry Andric       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
34070b57cec5SDimitry Andric       InfoHolder.getStringOffsetsStartSym());
34080b57cec5SDimitry Andric }
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric // Emit the .debug_str.dwo section for separated dwarf. This contains the
34110b57cec5SDimitry Andric // string section and is identical in format to traditional .debug_str
34120b57cec5SDimitry Andric // sections.
34130b57cec5SDimitry Andric void DwarfDebug::emitDebugStrDWO() {
34140b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable())
34150b57cec5SDimitry Andric     emitStringOffsetsTableHeaderDWO();
34160b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
34170b57cec5SDimitry Andric   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
34180b57cec5SDimitry Andric   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
34190b57cec5SDimitry Andric                          OffSec, /* UseRelativeOffsets = */ false);
34200b57cec5SDimitry Andric }
34210b57cec5SDimitry Andric 
34220b57cec5SDimitry Andric // Emit address pool.
34230b57cec5SDimitry Andric void DwarfDebug::emitDebugAddr() {
34240b57cec5SDimitry Andric   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
34250b57cec5SDimitry Andric }
34260b57cec5SDimitry Andric 
34270b57cec5SDimitry Andric MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
34280b57cec5SDimitry Andric   if (!useSplitDwarf())
34290b57cec5SDimitry Andric     return nullptr;
34300b57cec5SDimitry Andric   const DICompileUnit *DIUnit = CU.getCUNode();
34310b57cec5SDimitry Andric   SplitTypeUnitFileTable.maybeSetRootFile(
34320b57cec5SDimitry Andric       DIUnit->getDirectory(), DIUnit->getFilename(),
3433e8d8bef9SDimitry Andric       getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
34340b57cec5SDimitry Andric   return &SplitTypeUnitFileTable;
34350b57cec5SDimitry Andric }
34360b57cec5SDimitry Andric 
34370b57cec5SDimitry Andric uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
34380b57cec5SDimitry Andric   MD5 Hash;
34390b57cec5SDimitry Andric   Hash.update(Identifier);
34400b57cec5SDimitry Andric   // ... take the least significant 8 bytes and return those. Our MD5
34410b57cec5SDimitry Andric   // implementation always returns its results in little endian, so we actually
34420b57cec5SDimitry Andric   // need the "high" word.
34430b57cec5SDimitry Andric   MD5::MD5Result Result;
34440b57cec5SDimitry Andric   Hash.final(Result);
34450b57cec5SDimitry Andric   return Result.high();
34460b57cec5SDimitry Andric }
34470b57cec5SDimitry Andric 
34480b57cec5SDimitry Andric void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
34490b57cec5SDimitry Andric                                       StringRef Identifier, DIE &RefDie,
34500b57cec5SDimitry Andric                                       const DICompositeType *CTy) {
34510b57cec5SDimitry Andric   // Fast path if we're building some type units and one has already used the
34520b57cec5SDimitry Andric   // address pool we know we're going to throw away all this work anyway, so
34530b57cec5SDimitry Andric   // don't bother building dependent types.
34541fd87a68SDimitry Andric   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
34550b57cec5SDimitry Andric     return;
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
34580b57cec5SDimitry Andric   if (!Ins.second) {
34590b57cec5SDimitry Andric     CU.addDIETypeSignature(RefDie, Ins.first->second);
34600b57cec5SDimitry Andric     return;
34610b57cec5SDimitry Andric   }
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric   bool TopLevelType = TypeUnitsUnderConstruction.empty();
34640b57cec5SDimitry Andric   AddrPool.resetUsedFlag();
34650b57cec5SDimitry Andric 
34668bcb0991SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
34670b57cec5SDimitry Andric                                                     getDwoLineTable(CU));
34680b57cec5SDimitry Andric   DwarfTypeUnit &NewTU = *OwnedUnit;
34690b57cec5SDimitry Andric   DIE &UnitDie = NewTU.getUnitDie();
34700b57cec5SDimitry Andric   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
34730b57cec5SDimitry Andric                 CU.getLanguage());
34740b57cec5SDimitry Andric 
34750b57cec5SDimitry Andric   uint64_t Signature = makeTypeSignature(Identifier);
34760b57cec5SDimitry Andric   NewTU.setTypeSignature(Signature);
34770b57cec5SDimitry Andric   Ins.first->second = Signature;
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   if (useSplitDwarf()) {
34800b57cec5SDimitry Andric     MCSection *Section =
34810b57cec5SDimitry Andric         getDwarfVersion() <= 4
34820b57cec5SDimitry Andric             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
34830b57cec5SDimitry Andric             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
34840b57cec5SDimitry Andric     NewTU.setSection(Section);
34850b57cec5SDimitry Andric   } else {
34860b57cec5SDimitry Andric     MCSection *Section =
34870b57cec5SDimitry Andric         getDwarfVersion() <= 4
34880b57cec5SDimitry Andric             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
34890b57cec5SDimitry Andric             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
34900b57cec5SDimitry Andric     NewTU.setSection(Section);
34910b57cec5SDimitry Andric     // Non-split type units reuse the compile unit's line table.
34920b57cec5SDimitry Andric     CU.applyStmtList(UnitDie);
34930b57cec5SDimitry Andric   }
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
34960b57cec5SDimitry Andric   // units.
34970b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
34980b57cec5SDimitry Andric     NewTU.addStringOffsetsStart();
34990b57cec5SDimitry Andric 
35000b57cec5SDimitry Andric   NewTU.setType(NewTU.createTypeDIE(CTy));
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric   if (TopLevelType) {
35030b57cec5SDimitry Andric     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
35040b57cec5SDimitry Andric     TypeUnitsUnderConstruction.clear();
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric     // Types referencing entries in the address table cannot be placed in type
35070b57cec5SDimitry Andric     // units.
35081fd87a68SDimitry Andric     if (AddrPool.hasBeenUsed()) {
35090b57cec5SDimitry Andric 
35100b57cec5SDimitry Andric       // Remove all the types built while building this type.
35110b57cec5SDimitry Andric       // This is pessimistic as some of these types might not be dependent on
35120b57cec5SDimitry Andric       // the type that used an address.
35130b57cec5SDimitry Andric       for (const auto &TU : TypeUnitsToAdd)
35140b57cec5SDimitry Andric         TypeSignatures.erase(TU.second);
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric       // Construct this type in the CU directly.
35170b57cec5SDimitry Andric       // This is inefficient because all the dependent types will be rebuilt
35180b57cec5SDimitry Andric       // from scratch, including building them in type units, discovering that
35190b57cec5SDimitry Andric       // they depend on addresses, throwing them out and rebuilding them.
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());
35290b57cec5SDimitry Andric     }
35300b57cec5SDimitry Andric   }
35310b57cec5SDimitry Andric   CU.addDIETypeSignature(RefDie, Signature);
35320b57cec5SDimitry Andric }
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric // Add the Name along with its companion DIE to the appropriate accelerator
35350b57cec5SDimitry Andric // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
35360b57cec5SDimitry Andric // AccelTableKind::Apple, we use the table we got as an argument). If
35370b57cec5SDimitry Andric // accelerator tables are disabled, this function does nothing.
35380b57cec5SDimitry Andric template <typename DataT>
35390b57cec5SDimitry Andric void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
35400b57cec5SDimitry Andric                                   AccelTable<DataT> &AppleAccel, StringRef Name,
35410b57cec5SDimitry Andric                                   const DIE &Die) {
3542*fe013be4SDimitry Andric   if (getAccelTableKind() == AccelTableKind::None || Name.empty())
35430b57cec5SDimitry Andric     return;
35440b57cec5SDimitry Andric 
35450b57cec5SDimitry Andric   if (getAccelTableKind() != AccelTableKind::Apple &&
3546*fe013be4SDimitry Andric       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Apple &&
35470b57cec5SDimitry Andric       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
35480b57cec5SDimitry Andric     return;
35490b57cec5SDimitry Andric 
35500b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
35510b57cec5SDimitry Andric   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
35520b57cec5SDimitry Andric 
35530b57cec5SDimitry Andric   switch (getAccelTableKind()) {
35540b57cec5SDimitry Andric   case AccelTableKind::Apple:
35550b57cec5SDimitry Andric     AppleAccel.addName(Ref, Die);
35560b57cec5SDimitry Andric     break;
35570b57cec5SDimitry Andric   case AccelTableKind::Dwarf:
35580b57cec5SDimitry Andric     AccelDebugNames.addName(Ref, Die);
35590b57cec5SDimitry Andric     break;
35600b57cec5SDimitry Andric   case AccelTableKind::Default:
35610b57cec5SDimitry Andric     llvm_unreachable("Default should have already been resolved.");
35620b57cec5SDimitry Andric   case AccelTableKind::None:
35630b57cec5SDimitry Andric     llvm_unreachable("None handled above");
35640b57cec5SDimitry Andric   }
35650b57cec5SDimitry Andric }
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
35680b57cec5SDimitry Andric                               const DIE &Die) {
35690b57cec5SDimitry Andric   addAccelNameImpl(CU, AccelNames, Name, Die);
35700b57cec5SDimitry Andric }
35710b57cec5SDimitry Andric 
35720b57cec5SDimitry Andric void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
35730b57cec5SDimitry Andric                               const DIE &Die) {
35740b57cec5SDimitry Andric   // ObjC names go only into the Apple accelerator tables.
35750b57cec5SDimitry Andric   if (getAccelTableKind() == AccelTableKind::Apple)
35760b57cec5SDimitry Andric     addAccelNameImpl(CU, AccelObjC, Name, Die);
35770b57cec5SDimitry Andric }
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
35800b57cec5SDimitry Andric                                    const DIE &Die) {
35810b57cec5SDimitry Andric   addAccelNameImpl(CU, AccelNamespace, Name, Die);
35820b57cec5SDimitry Andric }
35830b57cec5SDimitry Andric 
35840b57cec5SDimitry Andric void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
35850b57cec5SDimitry Andric                               const DIE &Die, char Flags) {
35860b57cec5SDimitry Andric   addAccelNameImpl(CU, AccelTypes, Name, Die);
35870b57cec5SDimitry Andric }
35880b57cec5SDimitry Andric 
35890b57cec5SDimitry Andric uint16_t DwarfDebug::getDwarfVersion() const {
35900b57cec5SDimitry Andric   return Asm->OutStreamer->getContext().getDwarfVersion();
35910b57cec5SDimitry Andric }
35920b57cec5SDimitry Andric 
3593e8d8bef9SDimitry Andric dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
3594e8d8bef9SDimitry Andric   if (Asm->getDwarfVersion() >= 4)
3595e8d8bef9SDimitry Andric     return dwarf::Form::DW_FORM_sec_offset;
3596e8d8bef9SDimitry Andric   assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
3597e8d8bef9SDimitry Andric          "DWARF64 is not defined prior DWARFv3");
3598e8d8bef9SDimitry Andric   return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3599e8d8bef9SDimitry Andric                           : dwarf::Form::DW_FORM_data4;
3600e8d8bef9SDimitry Andric }
3601e8d8bef9SDimitry Andric 
36020b57cec5SDimitry Andric const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3603*fe013be4SDimitry Andric   return SectionLabels.lookup(S);
36040b57cec5SDimitry Andric }
3605*fe013be4SDimitry Andric 
36065ffd83dbSDimitry Andric void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
36075ffd83dbSDimitry Andric   if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
36085ffd83dbSDimitry Andric     if (useSplitDwarf() || getDwarfVersion() >= 5)
36095ffd83dbSDimitry Andric       AddrPool.getIndex(S);
36105ffd83dbSDimitry Andric }
3611e8d8bef9SDimitry Andric 
3612bdd1243dSDimitry Andric std::optional<MD5::MD5Result>
3613bdd1243dSDimitry Andric DwarfDebug::getMD5AsBytes(const DIFile *File) const {
3614e8d8bef9SDimitry Andric   assert(File);
3615e8d8bef9SDimitry Andric   if (getDwarfVersion() < 5)
3616bdd1243dSDimitry Andric     return std::nullopt;
3617bdd1243dSDimitry Andric   std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3618e8d8bef9SDimitry Andric   if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3619bdd1243dSDimitry Andric     return std::nullopt;
3620e8d8bef9SDimitry Andric 
3621e8d8bef9SDimitry Andric   // Convert the string checksum to an MD5Result for the streamer.
3622e8d8bef9SDimitry Andric   // The verifier validates the checksum so we assume it's okay.
3623e8d8bef9SDimitry Andric   // An MD5 checksum is 16 bytes.
3624e8d8bef9SDimitry Andric   std::string ChecksumString = fromHex(Checksum->Value);
3625e8d8bef9SDimitry Andric   MD5::MD5Result CKMem;
362681ad6265SDimitry Andric   std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.data());
3627e8d8bef9SDimitry Andric   return CKMem;
3628e8d8bef9SDimitry Andric }
3629*fe013be4SDimitry Andric 
3630*fe013be4SDimitry Andric bool DwarfDebug::alwaysUseRanges(const DwarfCompileUnit &CU) const {
3631*fe013be4SDimitry Andric   if (MinimizeAddr == MinimizeAddrInV5::Ranges)
3632*fe013be4SDimitry Andric     return true;
3633*fe013be4SDimitry Andric   if (MinimizeAddr != MinimizeAddrInV5::Default)
3634*fe013be4SDimitry Andric     return false;
3635*fe013be4SDimitry Andric   if (useSplitDwarf())
3636*fe013be4SDimitry Andric     return true;
3637*fe013be4SDimitry Andric   return false;
3638*fe013be4SDimitry Andric }
3639