LLVM 24.0.0git
RISCVELFStreamer.cpp
Go to the documentation of this file.
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 "RISCVAsmBackend.h"
15#include "RISCVBaseInfo.h"
16#include "RISCVMCTargetDesc.h"
19#include "llvm/MC/MCAssembler.h"
21#include "llvm/MC/MCContext.h"
24
25using namespace llvm;
26
27// This part is for ELF object output.
29 const MCSubtargetInfo &STI)
30 : RISCVTargetStreamer(S), CurrentVendor("riscv") {
32 auto &MAB = static_cast<RISCVAsmBackend &>(MCA.getBackend());
33 StringRef ABIName = MAB.getTargetOptions().getABIName();
34 // We have to recompute the ABI rather than casting STI to RISCVSubtarget
35 // since MC tools like llvm-mc call this when STI is MCSubtargetInfo instead.
36 // Using RISCVSubtarget requires a TargetMachine, which the MC-only tools
37 // deliberately don't link.
38 // TODO: Might be cleaner to have callers set the ABI instead of computing
39 // it twice which introduces a chance of it being out of sync.
40 if (auto ABIOrErr = RISCVABI::computeTargetABI(STI, ABIName)) {
41 setTargetABI(*ABIOrErr);
42 } else {
43 // Do not set TargetABI here if invalid: RISCVSubtarget/RISCVAsmPrinter
44 // (in codegen) or RISCVAsmParser::onBeginOfFile() (in llvm-mc) will
45 // resolve or diagnose it with proper contexts.
46 consumeError(ABIOrErr.takeError());
47 }
49
50 // Compute the initial ISA string. This serves two purposes:
51 // 1. Deduplication: subsequent .option arch/rvc/norvc directives compare
52 // against ArchString to avoid propagating redundant ISA updates.
53 // 2. Initial symbol: seed the streamer's active ISA so a "$x<ArchString>"
54 // mapping symbol is emitted before the first instruction, recording
55 // the full ISA in the object even when no .option directive is present.
57 InitialArchString = (*ParseResult)->toString();
58 ArchString = InitialArchString;
60 }
61}
62
64 std::unique_ptr<MCAsmBackend> MAB,
65 std::unique_ptr<MCObjectWriter> MOW,
66 std::unique_ptr<MCCodeEmitter> MCE)
67 : MCELFStreamer(C, std::move(MAB), std::move(MOW), std::move(MCE)) {}
68
72
74 if (Arch == ArchString)
75 return;
76 ArchString = std::string(Arch);
78}
79
81 ArchStringStack.push_back(ArchString);
82}
83
85 if (!ArchStringStack.empty())
86 setArchString(ArchStringStack.pop_back_val());
87}
88
97
98void RISCVTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
99 getStreamer().setAttributeItem(Attribute, Value, /*OverwriteExisting=*/true);
100}
101
102void RISCVTargetELFStreamer::emitTextAttribute(unsigned Attribute,
104 getStreamer().setAttributeItem(Attribute, String, /*OverwriteExisting=*/true);
105}
106
107void RISCVTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
108 unsigned IntValue,
109 StringRef StringValue) {
110 getStreamer().setAttributeItems(Attribute, IntValue, StringValue,
111 /*OverwriteExisting=*/true);
112}
113
115 RISCVELFStreamer &S = getStreamer();
116 if (S.Contents.empty())
117 return;
118
119 S.emitAttributesSection(CurrentVendor, ".riscv.attributes",
120 ELF::SHT_RISCV_ATTRIBUTES, AttributeSection);
121}
122
127
128 unsigned EFlags = W.getELFHeaderEFlags();
129
130 if (hasRVC())
131 EFlags |= ELF::EF_RISCV_RVC;
132 if (hasTSO())
133 EFlags |= ELF::EF_RISCV_TSO;
134
135 switch (ABI) {
140 break;
146 break;
152 break;
157 EFlags |= ELF::EF_RISCV_RVE;
158 break;
160 llvm_unreachable("Improperly initialised target ABI");
161 }
162
163 W.setELFHeaderEFlags(EFlags);
164}
165
167 AttributeSection = nullptr;
168 ArchString = InitialArchString;
169 ArchStringStack.clear();
170 // Re-seed the streamer's active ISA so the first instruction after reset
171 // still records the full ISA via "$x<ISA>", matching the behaviour set up
172 // in the constructor.
173 if (!InitialArchString.empty())
174 getStreamer().setMappingSymbolArch(InitialArchString);
175}
176
181
184 LastMappingSymbols.clear();
185 LastEMS = EMS_None;
186 MappingSymbolArch.clear();
187 LastEmittedArch.clear();
188 LastEmittedArchInSection.clear();
189 // Call target streamer reset last: it may call setMappingSymbolArch to
190 // re-seed the initial ISA after our state has been cleared.
191 static_cast<RISCVTargetStreamer *>(getTargetStreamer())->reset();
192}
193
194void RISCVELFStreamer::emitDataMappingSymbol() {
195 if (LastEMS == EMS_Data)
196 return;
197 emitMappingSymbol("$d");
198 LastEMS = EMS_Data;
199}
200
201void RISCVELFStreamer::emitInstructionsMappingSymbol() {
202 // Emit a mapping symbol at the start of each instruction run, and whenever
203 // the active ISA has changed since the last one emitted in this section.
204 // The symbol takes the form "$x<ISA>" when MappingSymbolArch is known, or
205 // plain "$x" as a fallback. The comparison with LastEmittedArch provides
206 // deduplication: repeating .option arch with the same ISA, or re-entering a
207 // section whose last mapping symbol already matches the active ISA, emits
208 // no redundant symbol.
209 bool NeedSymbol =
210 LastEMS != EMS_Instructions || LastEmittedArch != MappingSymbolArch;
211 if (NeedSymbol) {
212 if (MappingSymbolArch.empty())
213 emitMappingSymbol("$x");
214 else
215 emitMappingSymbol("$x" + MappingSymbolArch);
216 LastEmittedArch = MappingSymbolArch;
217 }
218 LastEMS = EMS_Instructions;
219}
220
221void RISCVELFStreamer::emitMappingSymbol(StringRef Name) {
222 auto *Symbol =
223 static_cast<MCSymbolELF *>(getContext().createLocalSymbol(Name));
224 emitLabel(Symbol);
225 Symbol->setType(ELF::STT_NOTYPE);
226 Symbol->setBinding(ELF::STB_LOCAL);
227}
228
230 MappingSymbolArch = std::string(Arch);
231}
232
234 // We have to keep track of the mapping symbol state of any sections we
235 // use. Each one should start off as EMS_None, which is provided as the
236 // default constructor by DenseMap::lookup. The last ISA suffix emitted in
237 // each section is also preserved so that re-entering a section only emits a
238 // new "$x<ISA>" symbol when the active ISA has actually changed.
239 const MCSection *Prev = getPreviousSection().first;
240 LastMappingSymbols[Prev] = LastEMS;
241 LastEmittedArchInSection[Prev] = LastEmittedArch;
242 LastEMS = LastMappingSymbols.lookup(Section);
243 auto It = LastEmittedArchInSection.find(Section);
244 LastEmittedArch = It != LastEmittedArchInSection.end() ? It->second : "";
245
246 MCELFStreamer::changeSection(Section, Subsection);
247}
248
250 const MCSubtargetInfo &STI) {
251 emitInstructionsMappingSymbol();
253}
254
256 emitDataMappingSymbol();
258}
259
260void RISCVELFStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
261 SMLoc Loc) {
262 emitDataMappingSymbol();
263 MCELFStreamer::emitFill(NumBytes, FillValue, Loc);
264}
265
267 SMLoc Loc) {
268 emitDataMappingSymbol();
270}
271
273 std::unique_ptr<MCAsmBackend> &&MAB,
274 std::unique_ptr<MCObjectWriter> &&MOW,
275 std::unique_ptr<MCCodeEmitter> &&MCE) {
276 return new RISCVELFStreamer(C, std::move(MAB), std::move(MOW),
277 std::move(MCE));
278}
279
281 const uint32_t Feature1And) {
282 MCStreamer &OutStreamer = getStreamer();
283 MCContext &Ctx = OutStreamer.getContext();
284
285 const Triple &Triple = Ctx.getTargetTriple();
286 Align NoteAlign;
287 uint64_t DescSize;
288 if (Triple.isArch64Bit()) {
289 NoteAlign = Align(8);
290 DescSize = 16;
291 } else {
293 NoteAlign = Align(4);
294 DescSize = 12;
295 }
296
297 assert(Ctx.getObjectFileType() == MCContext::Environment::IsELF);
298 MCSection *const NoteSection =
299 Ctx.getELFSection(".note.gnu.property", ELF::SHT_NOTE, ELF::SHF_ALLOC);
300 OutStreamer.pushSection();
301 OutStreamer.switchSection(NoteSection);
302
303 // Emit the note header
304 OutStreamer.emitValueToAlignment(NoteAlign);
305 OutStreamer.emitIntValue(4, 4); // n_namsz
306 OutStreamer.emitIntValue(DescSize, 4); // n_descsz
307 OutStreamer.emitIntValue(ELF::NT_GNU_PROPERTY_TYPE_0, 4); // n_type
308 OutStreamer.emitBytes(StringRef("GNU", 4)); // n_name
309
310 // Emit n_desc field
311
312 // Emit the feature_1_and property
313 OutStreamer.emitIntValue(ELF::GNU_PROPERTY_RISCV_FEATURE_1_AND, 4); // pr_type
314 OutStreamer.emitIntValue(4, 4); // pr_datasz
315 OutStreamer.emitIntValue(Feature1And, 4); // pr_data
316 OutStreamer.emitValueToAlignment(NoteAlign); // pr_padding
317
318 OutStreamer.popSection();
319}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
MCAsmBackend & getBackend() const
LLVM_ABI bool registerSymbol(const MCSymbol &Symbol)
Context object for machine code objects.
Definition MCContext.h:83
LLVM_ABI MCSymbol * createLocalSymbol(StringRef Name)
Create a local, non-temporary symbol like an ELF mapping symbol.
SmallVector< AttributeItem, 64 > Contents
void emitAttributesSection(StringRef Vendor, const Twine &Section, unsigned Type, MCSection *&AttributeSection)
void changeSection(MCSection *Section, uint32_t Subsection=0) override
This is called by popSection and switchSection, if the current section changes.
void setAttributeItems(unsigned Attribute, unsigned IntValue, StringRef StringValue, bool OverwriteExisting)
ELFObjectWriter & getWriter()
void setAttributeItem(unsigned Attribute, unsigned Value, bool OverwriteExisting)
void reset() override
state management
void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc()) override
Emit a label for Symbol into the current section.
MCELFStreamer(MCContext &Context, std::unique_ptr< MCAsmBackend > TAB, std::unique_ptr< MCObjectWriter > OW, std::unique_ptr< MCCodeEmitter > Emitter)
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
void emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc=SMLoc()) override
Emit Size bytes worth of the value specified by FillValue.
MCAssembler & getAssembler()
void emitBytes(StringRef Data) override
Emit the bytes in Data into the output.
void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override
Emit the given Instruction into the current section.
void emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc()) override
Emit the expression Value into the output as a native integer of the given Size bytes.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
Streaming machine code generation interface.
Definition MCStreamer.h:222
MCSectionSubPair getPreviousSection() const
Return the previous section that the streamer is emitting code to.
Definition MCStreamer.h:443
virtual bool popSection()
Restore the current and previous section from the section stack.
MCContext & getContext() const
Definition MCStreamer.h:326
virtual void emitValueToAlignment(Align Alignment, int64_t Fill=0, uint8_t FillLen=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
MCTargetStreamer * getTargetStreamer()
Definition MCStreamer.h:336
virtual void emitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers.
void pushSection()
Save the current and previous section on the section stack.
Definition MCStreamer.h:460
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
Generic base class for all target subtargets.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
MCStreamer & Streamer
Definition MCStreamer.h:97
This class represents success/failure for parsing-like operations that find it important to chain tog...
void setMappingSymbolArch(StringRef Arch)
void changeSection(MCSection *Section, uint32_t Subsection) override
This is called by popSection and switchSection, if the current section changes.
void emitBytes(StringRef Data) override
Emit the bytes in Data into the output.
RISCVELFStreamer(MCContext &C, std::unique_ptr< MCAsmBackend > MAB, std::unique_ptr< MCObjectWriter > MOW, std::unique_ptr< MCCodeEmitter > MCE)
void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override
Emit the given Instruction into the current section.
void emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc) override
Emit Size bytes worth of the value specified by FillValue.
void emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) override
Emit the expression Value into the output as a native integer of the given Size bytes.
void setArchString(StringRef Arch) override
void emitNoteGnuPropertySection(const uint32_t Feature1And)
void emitDirectiveOptionNoExact() override
RISCVTargetELFStreamer(MCStreamer &S, const MCSubtargetInfo &STI)
void emitDirectiveVariantCC(MCSymbol &Symbol) override
RISCVELFStreamer & getStreamer()
void emitDirectiveOptionNoRelax() override
RISCVABI::ABI getTargetABI() const
void setFlagsFromFeatures(const MCSubtargetInfo &STI)
void setTargetABI(RISCVABI::ABI ABI)
Represents a location in source code.
Definition SMLoc.h:22
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
LLVM_ABI bool isArch64Bit() const
Test whether the architecture is 64-bit.
Definition Triple.cpp:1827
LLVM_ABI bool isArch32Bit() const
Test whether the architecture is 32-bit.
Definition Triple.cpp:1831
LLVM Value Representation.
Definition Value.h:75
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ NT_GNU_PROPERTY_TYPE_0
Definition ELF.h:1822
@ SHF_ALLOC
Definition ELF.h:1259
@ SHT_RISCV_ATTRIBUTES
Definition ELF.h:1242
@ SHT_NOTE
Definition ELF.h:1163
@ STB_LOCAL
Definition ELF.h:1415
@ STT_NOTYPE
Definition ELF.h:1427
@ STO_RISCV_VARIANT_CC
Definition ELF.h:733
@ GNU_PROPERTY_RISCV_FEATURE_1_AND
Definition ELF.h:1858
@ EF_RISCV_RVE
Definition ELF.h:718
@ EF_RISCV_RVC
Definition ELF.h:712
@ EF_RISCV_TSO
Definition ELF.h:719
@ EF_RISCV_FLOAT_ABI_SINGLE
Definition ELF.h:715
@ EF_RISCV_FLOAT_ABI_DOUBLE
Definition ELF.h:716
Expected< ABI > computeTargetABI(const MCSubtargetInfo &STI, StringRef ABIName)
llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatureBits(const MCSubtargetInfo &STI)
This is an optimization pass for GlobalISel generic memory operations.
MCStreamer * createRISCVELFStreamer(const Triple &, MCContext &C, std::unique_ptr< MCAsmBackend > &&MAB, std::unique_ptr< MCObjectWriter > &&MOW, std::unique_ptr< MCCodeEmitter > &&MCE)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39