Skip to main content

cranelift_codegen/isa/riscv64/
mod.rs

1//! risc-v 64-bit Instruction Set Architecture.
2
3use crate::dominator_tree::DominatorTree;
4use crate::ir::{Function, Type};
5use crate::isa::riscv64::settings as riscv_settings;
6use crate::isa::{
7    Builder as IsaBuilder, FunctionAlignment, IsaFlagsHashKey, OwnedTargetIsa, TargetIsa,
8};
9use crate::machinst::CompiledCode;
10use crate::machinst::{
11    CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, TextSectionBuilder, VCode,
12    compile,
13};
14use crate::result::CodegenResult;
15use crate::settings::{self as shared_settings, Flags};
16use crate::{CodegenError, ir};
17use alloc::string::String;
18use alloc::{boxed::Box, vec::Vec};
19use core::fmt;
20use cranelift_control::ControlPlane;
21use target_lexicon::{Architecture, Triple};
22mod abi;
23pub(crate) mod inst;
24mod lower;
25mod settings;
26#[cfg(feature = "unwind")]
27use crate::isa::unwind::systemv;
28
29use self::inst::EmitInfo;
30
31/// An riscv64 backend.
32pub struct Riscv64Backend {
33    triple: Triple,
34    flags: shared_settings::Flags,
35    isa_flags: riscv_settings::Flags,
36}
37
38impl Riscv64Backend {
39    fn supports_vector_element_type(&self, ty: Type) -> bool {
40        use ir::types::*;
41
42        match ty {
43            I8 | I16 | I32 | I64 => true,
44            // FP16 vector operations require Zvfh.
45            F16 => self.isa_flags.has_f() && self.isa_flags.has_zvfh(),
46            F32 => self.isa_flags.has_f(),
47            F64 => self.isa_flags.has_d(),
48            _ => false,
49        }
50    }
51
52    /// Create a new riscv64 backend with the given (shared) flags.
53    pub fn new_with_flags(
54        triple: Triple,
55        flags: shared_settings::Flags,
56        isa_flags: riscv_settings::Flags,
57    ) -> Riscv64Backend {
58        Riscv64Backend {
59            triple,
60            flags,
61            isa_flags,
62        }
63    }
64
65    /// This performs lowering to VCode, register-allocates the code, computes block layout and
66    /// finalizes branches. The result is ready for binary emission.
67    fn compile_vcode(
68        &self,
69        func: &Function,
70        domtree: &DominatorTree,
71        regalloc_ctx: &mut regalloc2::Ctx,
72        ctrl_plane: &mut ControlPlane,
73    ) -> CodegenResult<VCode<inst::Inst>> {
74        let emit_info = EmitInfo::new(self.flags.clone(), self.isa_flags.clone());
75        let sigs = SigSet::new::<abi::Riscv64MachineDeps>(func, &self.flags)?;
76        let abi = abi::Riscv64Callee::new(func, self, &self.isa_flags, &sigs)?;
77        compile::compile::<Riscv64Backend>(
78            func,
79            domtree,
80            regalloc_ctx,
81            self,
82            abi,
83            emit_info,
84            sigs,
85            ctrl_plane,
86        )
87    }
88}
89
90impl TargetIsa for Riscv64Backend {
91    fn compile_function(
92        &self,
93        func: &Function,
94        domtree: &DominatorTree,
95        regalloc_ctx: &mut regalloc2::Ctx,
96        want_disasm: bool,
97        ctrl_plane: &mut ControlPlane,
98    ) -> CodegenResult<CompiledCodeStencil> {
99        let vcode = self.compile_vcode(func, domtree, regalloc_ctx, ctrl_plane)?;
100
101        let want_disasm = want_disasm || log::log_enabled!(log::Level::Debug);
102        let emit_result = vcode.emit(&regalloc_ctx.output, want_disasm, &self.flags, ctrl_plane)?;
103        let value_labels_ranges = emit_result.value_labels_ranges;
104        let buffer = emit_result.buffer;
105
106        if let Some(disasm) = emit_result.disasm.as_ref() {
107            log::debug!("disassembly:\n{disasm}");
108        }
109
110        Ok(CompiledCodeStencil(CompiledCode {
111            buffer,
112            vcode: emit_result.disasm,
113            value_labels_ranges,
114            bb_starts: emit_result.bb_offsets,
115            bb_edges: emit_result.bb_edges,
116        }))
117    }
118
119    fn name(&self) -> &'static str {
120        "riscv64"
121    }
122    fn dynamic_vector_bytes(&self, _dynamic_ty: ir::Type) -> u32 {
123        16
124    }
125
126    fn triple(&self) -> &Triple {
127        &self.triple
128    }
129
130    fn flags(&self) -> &shared_settings::Flags {
131        &self.flags
132    }
133
134    fn isa_flags(&self) -> Vec<shared_settings::Value> {
135        self.isa_flags.iter().collect()
136    }
137
138    fn isa_flags_hash_key(&self) -> IsaFlagsHashKey<'_> {
139        IsaFlagsHashKey(self.isa_flags.hash_key())
140    }
141
142    #[cfg(feature = "unwind")]
143    fn emit_unwind_info(
144        &self,
145        result: &CompiledCode,
146        kind: crate::isa::unwind::UnwindInfoKind,
147    ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
148        use crate::isa::unwind::UnwindInfo;
149        use crate::isa::unwind::UnwindInfoKind;
150        Ok(match kind {
151            UnwindInfoKind::SystemV => {
152                let mapper = self::inst::unwind::systemv::RegisterMapper;
153                Some(UnwindInfo::SystemV(
154                    crate::isa::unwind::systemv::create_unwind_info_from_insts(
155                        &result.buffer.unwind_info[..],
156                        result.buffer.data().len(),
157                        &mapper,
158                    )?,
159                ))
160            }
161            UnwindInfoKind::Windows => None,
162            _ => None,
163        })
164    }
165
166    #[cfg(feature = "unwind")]
167    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
168        Some(inst::unwind::systemv::create_cie())
169    }
170
171    fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {
172        Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))
173    }
174
175    #[cfg(feature = "unwind")]
176    fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, systemv::RegisterMappingError> {
177        inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)
178    }
179
180    fn function_alignment(&self) -> FunctionAlignment {
181        inst::Inst::function_alignment()
182    }
183
184    fn page_size_align_log2(&self) -> u8 {
185        debug_assert_eq!(1 << 12, 0x1000);
186        12
187    }
188
189    #[cfg(feature = "disas")]
190    fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
191        use capstone::prelude::*;
192        let mut cs_builder = Capstone::new().riscv().mode(arch::riscv::ArchMode::RiscV64);
193
194        // Enable C instruction decoding if we have compressed instructions enabled.
195        //
196        // We can't enable this unconditionally because it will cause Capstone to
197        // emit weird instructions and generally mess up when it encounters unknown
198        // instructions, such as any Zba,Zbb,Zbc or Vector instructions.
199        //
200        // This causes the default disassembly to be quite unreadable, so enable
201        // it only when we are actually going to be using them.
202        let uses_compressed = self
203            .isa_flags()
204            .iter()
205            .filter(|f| ["has_zca", "has_zcb", "has_zcd"].contains(&f.name))
206            .any(|f| f.as_bool().unwrap_or(false));
207        if uses_compressed {
208            cs_builder = cs_builder.extra_mode([arch::riscv::ArchExtraMode::RiscVC].into_iter());
209        }
210
211        let mut cs = cs_builder.build()?;
212
213        // Similar to AArch64, RISC-V uses inline constants rather than a separate
214        // constant pool. We want to skip disassembly over inline constants instead
215        // of stopping on invalid bytes.
216        cs.set_skipdata(true)?;
217        Ok(cs)
218    }
219
220    fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {
221        // TODO-RISC-V: implement proper register pretty-printing.
222        format!("{reg:?}")
223    }
224
225    fn has_native_fma(&self) -> bool {
226        true
227    }
228
229    fn supports_vector_load_store(&self, ty: Type) -> bool {
230        ty.is_vector()
231            && u64::from(ty.bits()) <= self.isa_flags.min_vec_reg_size()
232            && self.supports_vector_element_type(ty.lane_type())
233    }
234
235    fn has_round(&self) -> bool {
236        true
237    }
238
239    fn has_blendv_lowering(&self, _: Type) -> bool {
240        false
241    }
242
243    fn has_x86_pshufb_lowering(&self) -> bool {
244        false
245    }
246
247    fn has_x86_pmulhrsw_lowering(&self) -> bool {
248        false
249    }
250
251    fn has_x86_pmaddubsw_lowering(&self) -> bool {
252        false
253    }
254
255    fn default_argument_extension(&self) -> ir::ArgumentExtension {
256        // According to https://riscv.org/wp-content/uploads/2024/12/riscv-calling.pdf
257        // it says:
258        //
259        // > In RV64, 32-bit types, such as int, are stored in integer
260        // > registers as proper sign extensions of their 32-bit values; that
261        // > is, bits 63..31 are all equal. This restriction holds even for
262        // > unsigned 32-bit types.
263        //
264        // leading to `sext` here.
265        ir::ArgumentExtension::Sext
266    }
267}
268
269impl fmt::Display for Riscv64Backend {
270    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
271        f.debug_struct("MachBackend")
272            .field("name", &self.name())
273            .field("triple", &self.triple())
274            .field("flags", &format!("{}", self.flags()))
275            .finish()
276    }
277}
278
279/// Create a new `isa::Builder`.
280pub fn isa_builder(triple: Triple) -> IsaBuilder {
281    match triple.architecture {
282        Architecture::Riscv64(..) => {}
283        _ => unreachable!(),
284    }
285    IsaBuilder {
286        triple,
287        setup: riscv_settings::builder(),
288        constructor: isa_constructor,
289    }
290}
291
292fn isa_constructor(
293    triple: Triple,
294    shared_flags: Flags,
295    builder: &shared_settings::Builder,
296) -> CodegenResult<OwnedTargetIsa> {
297    let isa_flags = riscv_settings::Flags::new(&shared_flags, builder);
298
299    // The RISC-V backend does not work without at least the G extension enabled.
300    // The G extension is simply a combination of the following extensions:
301    // - I: Base Integer Instruction Set
302    // - M: Integer Multiplication and Division
303    // - A: Atomic Instructions
304    // - F: Single-Precision Floating-Point
305    // - D: Double-Precision Floating-Point
306    // - Zicsr: Control and Status Register Instructions
307    // - Zifencei: Instruction-Fetch Fence
308    //
309    // Ensure that those combination of features is enabled.
310    if !(isa_flags.has_m()
311        && isa_flags.has_a()
312        && isa_flags.has_f()
313        && isa_flags.has_d()
314        && isa_flags.has_zicsr()
315        && isa_flags.has_zifencei())
316    {
317        return Err(CodegenError::Unsupported(
318            "The RISC-V Backend currently requires all the features in the G Extension enabled"
319                .into(),
320        ));
321    }
322
323    let backend = Riscv64Backend::new_with_flags(triple, shared_flags, isa_flags);
324    Ok(backend.wrapped())
325}