1//===- DWARFEmitterImpl.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "DWARFEmitterImpl.h"
10#include "llvm/MC/MCAsmBackend.h"
11#include "llvm/MC/MCCodeEmitter.h"
12#include "llvm/MC/MCInstPrinter.h"
13#include "llvm/MC/MCObjectWriter.h"
14#include "llvm/MC/MCTargetOptions.h"
15#include "llvm/MC/TargetRegistry.h"
16#include "llvm/Support/FormattedStream.h"
17
18using namespace llvm;
19using namespace dwarf_linker;
20using namespace dwarf_linker::parallel;
21
22Error DwarfEmitterImpl::init(Triple TheTriple,
23 StringRef Swift5ReflectionSegmentName) {
24 std::string ErrorStr;
25 std::string TripleName;
26
27 // Get the target.
28 const Target *TheTarget =
29 TargetRegistry::lookupTarget(ArchName: TripleName, TheTriple, Error&: ErrorStr);
30 if (!TheTarget)
31 return createStringError(EC: std::errc::invalid_argument, Fmt: ErrorStr.c_str());
32 TripleName = TheTriple.getTriple();
33
34 // Create all the MC Objects.
35 MRI.reset(p: TheTarget->createMCRegInfo(TT: TheTriple));
36 if (!MRI)
37 return createStringError(EC: std::errc::invalid_argument,
38 Fmt: "no register info for target %s",
39 Vals: TripleName.c_str());
40
41 MCOptions.AsmVerbose = true;
42 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;
43 MAI.reset(p: TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
44 if (!MAI)
45 return createStringError(EC: std::errc::invalid_argument,
46 Fmt: "no asm info for target %s", Vals: TripleName.c_str());
47
48 MSTI.reset(p: TheTarget->createMCSubtargetInfo(TheTriple, CPU: "", Features: ""));
49 if (!MSTI)
50 return createStringError(EC: std::errc::invalid_argument,
51 Fmt: "no subtarget info for target %s",
52 Vals: TripleName.c_str());
53
54 MC.reset(p: new MCContext(TheTriple, *MAI, *MRI, *MSTI, nullptr, true,
55 Swift5ReflectionSegmentName));
56 MOFI.reset(p: TheTarget->createMCObjectFileInfo(Ctx&: *MC, /*PIC=*/false, LargeCodeModel: false));
57 MC->setObjectFileInfo(MOFI.get());
58
59 MAB = TheTarget->createMCAsmBackend(STI: *MSTI, MRI: *MRI, Options: MCOptions);
60 if (!MAB)
61 return createStringError(EC: std::errc::invalid_argument,
62 Fmt: "no asm backend for target %s",
63 Vals: TripleName.c_str());
64
65 MII.reset(p: TheTarget->createMCInstrInfo());
66 if (!MII)
67 return createStringError(EC: std::errc::invalid_argument,
68 Fmt: "no instr info info for target %s",
69 Vals: TripleName.c_str());
70
71 MCE = TheTarget->createMCCodeEmitter(II: *MII, Ctx&: *MC);
72 if (!MCE)
73 return createStringError(EC: std::errc::invalid_argument,
74 Fmt: "no code emitter for target %s",
75 Vals: TripleName.c_str());
76
77 switch (OutFileType) {
78 case DWARFLinker::OutputFileType::Assembly: {
79 std::unique_ptr<MCInstPrinter> MIP(TheTarget->createMCInstPrinter(
80 T: TheTriple, SyntaxVariant: MAI->getAssemblerDialect(), MAI: *MAI, MII: *MII, MRI: *MRI));
81 MS = TheTarget->createAsmStreamer(
82 Ctx&: *MC, OS: std::make_unique<formatted_raw_ostream>(args&: OutFile), IP: std::move(MIP),
83 CE: std::unique_ptr<MCCodeEmitter>(MCE),
84 TAB: std::unique_ptr<MCAsmBackend>(MAB));
85 break;
86 }
87 case DWARFLinker::OutputFileType::Object: {
88 MS = TheTarget->createMCObjectStreamer(
89 T: TheTriple, Ctx&: *MC, TAB: std::unique_ptr<MCAsmBackend>(MAB),
90 OW: MAB->createObjectWriter(OS&: OutFile), Emitter: std::unique_ptr<MCCodeEmitter>(MCE),
91 STI: *MSTI);
92 break;
93 }
94 }
95
96 if (!MS)
97 return createStringError(EC: std::errc::invalid_argument,
98 Fmt: "no object streamer for target %s",
99 Vals: TripleName.c_str());
100
101 // Finally create the AsmPrinter we'll use to emit the DIEs.
102 TM.reset(p: TheTarget->createTargetMachine(TT: TheTriple, CPU: "", Features: "", Options: TargetOptions(),
103 RM: std::nullopt));
104 if (!TM)
105 return createStringError(EC: std::errc::invalid_argument,
106 Fmt: "no target machine for target %s",
107 Vals: TripleName.c_str());
108
109 Asm.reset(p: TheTarget->createAsmPrinter(TM&: *TM, Streamer: std::unique_ptr<MCStreamer>(MS)));
110 if (!Asm)
111 return createStringError(EC: std::errc::invalid_argument,
112 Fmt: "no asm printer for target %s",
113 Vals: TripleName.c_str());
114 Asm->setDwarfUsesRelocationsAcrossSections(false);
115
116 DebugInfoSectionSize = 0;
117
118 return Error::success();
119}
120
121void DwarfEmitterImpl::emitAbbrevs(
122 const SmallVector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
123 unsigned DwarfVersion) {
124 MS->switchSection(Section: MOFI->getDwarfAbbrevSection());
125 MC->setDwarfVersion(DwarfVersion);
126 Asm->emitDwarfAbbrevs(Abbrevs);
127}
128
129void DwarfEmitterImpl::emitCompileUnitHeader(DwarfUnit &Unit) {
130 MS->switchSection(Section: MOFI->getDwarfInfoSection());
131 MC->setDwarfVersion(Unit.getVersion());
132
133 // Emit size of content not including length itself. The size has already
134 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
135 // account for the length field.
136 Asm->emitInt32(Value: Unit.getUnitSize() - 4);
137 Asm->emitInt16(Value: Unit.getVersion());
138
139 if (Unit.getVersion() >= 5) {
140 dwarf::Tag RootTag = Unit.getTag();
141 Asm->emitInt8(Value: RootTag == dwarf::DW_TAG_partial_unit ? dwarf::DW_UT_partial
142 : dwarf::DW_UT_compile);
143 Asm->emitInt8(Value: Unit.getFormParams().AddrSize);
144 // Proper offset to the abbreviations table will be set later.
145 Asm->emitInt32(Value: 0);
146 DebugInfoSectionSize += 12;
147 } else {
148 // Proper offset to the abbreviations table will be set later.
149 Asm->emitInt32(Value: 0);
150 Asm->emitInt8(Value: Unit.getFormParams().AddrSize);
151 DebugInfoSectionSize += 11;
152 }
153}
154
155void DwarfEmitterImpl::emitDIE(DIE &Die) {
156 MS->switchSection(Section: MOFI->getDwarfInfoSection());
157 Asm->emitDwarfDIE(Die);
158 DebugInfoSectionSize += Die.getSize();
159}
160
161void DwarfEmitterImpl::emitDebugNames(DWARF5AccelTable &Table,
162 DebugNamesUnitsOffsets &CUOffsets,
163 CompUnitIDToIdx &CUidToIdx) {
164 if (CUOffsets.empty())
165 return;
166
167 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfDebugNamesSection());
168 dwarf::Form Form =
169 DIEInteger::BestForm(/*IsSigned*/ false, Int: (uint64_t)CUidToIdx.size() - 1);
170 // FIXME: add support for type units + .debug_names. For now the behavior is
171 // unsupported.
172 emitDWARF5AccelTable(
173 Asm: Asm.get(), Contents&: Table, CUs: CUOffsets,
174 getIndexForEntry: [&](const DWARF5AccelTableData &Entry)
175 -> std::optional<DWARF5AccelTable::UnitIndexAndEncoding> {
176 if (CUidToIdx.size() > 1)
177 return {{.Index: CUidToIdx[Entry.getUnitID()],
178 .Encoding: {.Index: dwarf::DW_IDX_compile_unit, .Form: Form}}};
179 return std::nullopt;
180 });
181}
182
183void DwarfEmitterImpl::emitAppleNamespaces(
184 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
185 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelNamespaceSection());
186 auto *SectionBegin = Asm->createTempSymbol(Name: "namespac_begin");
187 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
188 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "namespac", SecBegin: SectionBegin);
189}
190
191void DwarfEmitterImpl::emitAppleNames(
192 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
193 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelNamesSection());
194 auto *SectionBegin = Asm->createTempSymbol(Name: "names_begin");
195 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
196 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "names", SecBegin: SectionBegin);
197}
198
199void DwarfEmitterImpl::emitAppleObjc(
200 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
201 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelObjCSection());
202 auto *SectionBegin = Asm->createTempSymbol(Name: "objc_begin");
203 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
204 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "objc", SecBegin: SectionBegin);
205}
206
207void DwarfEmitterImpl::emitAppleTypes(
208 AccelTable<AppleAccelTableStaticTypeData> &Table) {
209 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelTypesSection());
210 auto *SectionBegin = Asm->createTempSymbol(Name: "types_begin");
211 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
212 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "types", SecBegin: SectionBegin);
213}
214