1//===-- RISCVELFStreamer.cpp - RISC-V ELF Target Streamer Methods ---------===//
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// This file provides RISC-V specific target streamer methods.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RISCVELFStreamer.h"
14#include "RISCVBaseInfo.h"
15#include "RISCVMCTargetDesc.h"
16#include "llvm/BinaryFormat/ELF.h"
17#include "llvm/MC/MCAsmBackend.h"
18#include "llvm/MC/MCAssembler.h"
19#include "llvm/MC/MCCodeEmitter.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCELFObjectWriter.h"
22#include "llvm/MC/MCSubtargetInfo.h"
23
24using namespace llvm;
25
26// This part is for ELF object output.
27RISCVTargetELFStreamer::RISCVTargetELFStreamer(MCStreamer &S,
28 const MCSubtargetInfo &STI)
29 : RISCVTargetStreamer(S), CurrentVendor("riscv") {
30 setFlagsFromFeatures(STI);
31}
32
33RISCVELFStreamer::RISCVELFStreamer(MCContext &C,
34 std::unique_ptr<MCAsmBackend> MAB,
35 std::unique_ptr<MCObjectWriter> MOW,
36 std::unique_ptr<MCCodeEmitter> MCE)
37 : MCELFStreamer(C, std::move(MAB), std::move(MOW), std::move(MCE)) {}
38
39RISCVELFStreamer &RISCVTargetELFStreamer::getStreamer() {
40 return static_cast<RISCVELFStreamer &>(Streamer);
41}
42
43void RISCVTargetELFStreamer::setFlagsFromFeatures(const MCSubtargetInfo &STI) {
44 RISCVTargetStreamer::setFlagsFromFeatures(STI);
45
46 // Compute the initial ISA string. This serves two purposes:
47 // 1. Deduplication: subsequent .option arch/rvc/norvc directives compare
48 // against ArchString to avoid propagating redundant ISA updates.
49 // 2. Initial symbol: seed the streamer's active ISA so a "$x<ArchString>"
50 // mapping symbol is emitted before the first instruction, recording
51 // the full ISA in the object even when no .option directive is present.
52 if (auto ParseResult = RISCVFeatures::parseFeatureBits(STI)) {
53 InitialArchString = (*ParseResult)->toString();
54 setArchString(InitialArchString);
55 } else {
56 consumeError(Err: ParseResult.takeError());
57 }
58}
59
60void RISCVTargetELFStreamer::setArchString(StringRef Arch) {
61 if (Arch == ArchString)
62 return;
63 ArchString = std::string(Arch);
64 getStreamer().setMappingSymbolArch(Arch);
65}
66
67void RISCVTargetELFStreamer::emitDirectiveOptionPush() {
68 ArchStringStack.push_back(Elt: ArchString);
69}
70
71void RISCVTargetELFStreamer::emitDirectiveOptionPop() {
72 if (!ArchStringStack.empty())
73 setArchString(ArchStringStack.pop_back_val());
74}
75
76void RISCVTargetELFStreamer::emitDirectiveOptionExact() {}
77void RISCVTargetELFStreamer::emitDirectiveOptionNoExact() {}
78void RISCVTargetELFStreamer::emitDirectiveOptionPIC() {}
79void RISCVTargetELFStreamer::emitDirectiveOptionNoPIC() {}
80void RISCVTargetELFStreamer::emitDirectiveOptionRelax() {}
81void RISCVTargetELFStreamer::emitDirectiveOptionNoRelax() {}
82void RISCVTargetELFStreamer::emitDirectiveOptionRVC() {}
83void RISCVTargetELFStreamer::emitDirectiveOptionNoRVC() {}
84
85void RISCVTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
86 getStreamer().setAttributeItem(Attribute, Value, /*OverwriteExisting=*/true);
87}
88
89void RISCVTargetELFStreamer::emitTextAttribute(unsigned Attribute,
90 StringRef String) {
91 getStreamer().setAttributeItem(Attribute, Value: String, /*OverwriteExisting=*/true);
92}
93
94void RISCVTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
95 unsigned IntValue,
96 StringRef StringValue) {
97 getStreamer().setAttributeItems(Attribute, IntValue, StringValue,
98 /*OverwriteExisting=*/true);
99}
100
101void RISCVTargetELFStreamer::finishAttributeSection() {
102 RISCVELFStreamer &S = getStreamer();
103 if (S.Contents.empty())
104 return;
105
106 S.emitAttributesSection(Vendor: CurrentVendor, Section: ".riscv.attributes",
107 Type: ELF::SHT_RISCV_ATTRIBUTES, AttributeSection);
108}
109
110void RISCVTargetELFStreamer::finish() {
111 RISCVTargetStreamer::finish();
112 ELFObjectWriter &W = getStreamer().getWriter();
113 RISCVABI::ABI ABI = getTargetABI();
114
115 unsigned EFlags = W.getELFHeaderEFlags();
116
117 if (hasRVC())
118 EFlags |= ELF::EF_RISCV_RVC;
119 if (hasTSO())
120 EFlags |= ELF::EF_RISCV_TSO;
121
122 if (RISCVABI::isRVE(TargetABI: ABI))
123 EFlags |= ELF::EF_RISCV_RVE;
124
125 if (RISCVABI::isSoftFP(TargetABI: ABI))
126 EFlags |= ELF::EF_RISCV_FLOAT_ABI_SOFT;
127 else if (RISCVABI::isSingleFP(TargetABI: ABI))
128 EFlags |= ELF::EF_RISCV_FLOAT_ABI_SINGLE;
129 else if (RISCVABI::isDoubleFP(TargetABI: ABI))
130 EFlags |= ELF::EF_RISCV_FLOAT_ABI_DOUBLE;
131 else
132 assert(ABI == RISCVABI::ABI::Unknown);
133
134 W.setELFHeaderEFlags(EFlags);
135}
136
137void RISCVTargetELFStreamer::reset() {
138 AttributeSection = nullptr;
139 ArchString = InitialArchString;
140 ArchStringStack.clear();
141 // Re-seed the streamer's active ISA so the first instruction after reset
142 // still records the full ISA via "$x<ISA>", matching the behaviour set up
143 // in the constructor.
144 if (!InitialArchString.empty())
145 getStreamer().setMappingSymbolArch(InitialArchString);
146}
147
148void RISCVTargetELFStreamer::emitDirectiveVariantCC(MCSymbol &Symbol) {
149 getStreamer().getAssembler().registerSymbol(Symbol);
150 static_cast<MCSymbolELF &>(Symbol).setOther(ELF::STO_RISCV_VARIANT_CC);
151}
152
153void RISCVELFStreamer::reset() {
154 MCELFStreamer::reset();
155 LastMappingSymbols.clear();
156 LastEMS = EMS_None;
157 MappingSymbolArch.clear();
158 LastEmittedArch.clear();
159 LastEmittedArchInSection.clear();
160 // Call target streamer reset last: it may call setMappingSymbolArch to
161 // re-seed the initial ISA after our state has been cleared.
162 static_cast<RISCVTargetStreamer *>(getTargetStreamer())->reset();
163}
164
165void RISCVELFStreamer::emitDataMappingSymbol() {
166 if (LastEMS == EMS_Data)
167 return;
168 emitMappingSymbol(Name: "$d");
169 LastEMS = EMS_Data;
170}
171
172void RISCVELFStreamer::emitInstructionsMappingSymbol() {
173 // Emit a mapping symbol at the start of each instruction run, and whenever
174 // the active ISA has changed since the last one emitted in this section.
175 // The symbol takes the form "$x<ISA>" when MappingSymbolArch is known, or
176 // plain "$x" as a fallback. The comparison with LastEmittedArch provides
177 // deduplication: repeating .option arch with the same ISA, or re-entering a
178 // section whose last mapping symbol already matches the active ISA, emits
179 // no redundant symbol.
180 bool NeedSymbol =
181 LastEMS != EMS_Instructions || LastEmittedArch != MappingSymbolArch;
182 if (NeedSymbol) {
183 if (MappingSymbolArch.empty())
184 emitMappingSymbol(Name: "$x");
185 else
186 emitMappingSymbol(Name: "$x" + MappingSymbolArch);
187 LastEmittedArch = MappingSymbolArch;
188 }
189 LastEMS = EMS_Instructions;
190}
191
192void RISCVELFStreamer::emitMappingSymbol(StringRef Name) {
193 auto *Symbol =
194 static_cast<MCSymbolELF *>(getContext().createLocalSymbol(Name));
195 emitLabel(Symbol);
196 Symbol->setType(ELF::STT_NOTYPE);
197 Symbol->setBinding(ELF::STB_LOCAL);
198}
199
200void RISCVELFStreamer::setMappingSymbolArch(StringRef Arch) {
201 MappingSymbolArch = std::string(Arch);
202}
203
204void RISCVELFStreamer::changeSection(MCSection *Section, uint32_t Subsection) {
205 // We have to keep track of the mapping symbol state of any sections we
206 // use. Each one should start off as EMS_None, which is provided as the
207 // default constructor by DenseMap::lookup. The last ISA suffix emitted in
208 // each section is also preserved so that re-entering a section only emits a
209 // new "$x<ISA>" symbol when the active ISA has actually changed.
210 const MCSection *Cur = getCurrentSection().first;
211 LastMappingSymbols[Cur] = LastEMS;
212 LastEmittedArchInSection[Cur] = LastEmittedArch;
213 LastEMS = LastMappingSymbols.lookup(Val: Section);
214 auto It = LastEmittedArchInSection.find(Val: Section);
215 LastEmittedArch = It != LastEmittedArchInSection.end() ? It->second : "";
216
217 MCELFStreamer::changeSection(Section, Subsection);
218}
219
220void RISCVELFStreamer::emitInstruction(const MCInst &Inst,
221 const MCSubtargetInfo &STI) {
222 emitInstructionsMappingSymbol();
223 MCELFStreamer::emitInstruction(Inst, STI);
224}
225
226void RISCVELFStreamer::emitBytes(StringRef Data) {
227 emitDataMappingSymbol();
228 MCELFStreamer::emitBytes(Data);
229}
230
231void RISCVELFStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
232 SMLoc Loc) {
233 emitDataMappingSymbol();
234 MCELFStreamer::emitFill(NumBytes, FillValue, Loc);
235}
236
237void RISCVELFStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
238 SMLoc Loc) {
239 emitDataMappingSymbol();
240 MCELFStreamer::emitValueImpl(Value, Size, Loc);
241}
242
243MCStreamer *llvm::createRISCVELFStreamer(const Triple &, MCContext &C,
244 std::unique_ptr<MCAsmBackend> &&MAB,
245 std::unique_ptr<MCObjectWriter> &&MOW,
246 std::unique_ptr<MCCodeEmitter> &&MCE) {
247 return new RISCVELFStreamer(C, std::move(MAB), std::move(MOW),
248 std::move(MCE));
249}
250
251void RISCVTargetELFStreamer::emitNoteGnuPropertySection(
252 const uint32_t Feature1And) {
253 MCStreamer &OutStreamer = getStreamer();
254 MCContext &Ctx = OutStreamer.getContext();
255
256 const Triple &Triple = Ctx.getTargetTriple();
257 Align NoteAlign;
258 uint64_t DescSize;
259 if (Triple.isArch64Bit()) {
260 NoteAlign = Align(8);
261 DescSize = 16;
262 } else {
263 assert(Triple.isArch32Bit());
264 NoteAlign = Align(4);
265 DescSize = 12;
266 }
267
268 assert(Ctx.getObjectFileType() == MCContext::Environment::IsELF);
269 MCSection *const NoteSection =
270 Ctx.getELFSection(Section: ".note.gnu.property", Type: ELF::SHT_NOTE, Flags: ELF::SHF_ALLOC);
271 OutStreamer.pushSection();
272 OutStreamer.switchSection(Section: NoteSection);
273
274 // Emit the note header
275 OutStreamer.emitValueToAlignment(Alignment: NoteAlign);
276 OutStreamer.emitIntValue(Value: 4, Size: 4); // n_namsz
277 OutStreamer.emitIntValue(Value: DescSize, Size: 4); // n_descsz
278 OutStreamer.emitIntValue(Value: ELF::NT_GNU_PROPERTY_TYPE_0, Size: 4); // n_type
279 OutStreamer.emitBytes(Data: StringRef("GNU", 4)); // n_name
280
281 // Emit n_desc field
282
283 // Emit the feature_1_and property
284 OutStreamer.emitIntValue(Value: ELF::GNU_PROPERTY_RISCV_FEATURE_1_AND, Size: 4); // pr_type
285 OutStreamer.emitIntValue(Value: 4, Size: 4); // pr_datasz
286 OutStreamer.emitIntValue(Value: Feature1And, Size: 4); // pr_data
287 OutStreamer.emitValueToAlignment(Alignment: NoteAlign); // pr_padding
288
289 OutStreamer.popSection();
290}
291