Path: blob/main/cranelift/codegen/src/isa/riscv64/mod.rs
1693 views
//! risc-v 64-bit Instruction Set Architecture.12use crate::dominator_tree::DominatorTree;3use crate::ir::{Function, Type};4use crate::isa::riscv64::settings as riscv_settings;5use crate::isa::{6Builder as IsaBuilder, FunctionAlignment, IsaFlagsHashKey, OwnedTargetIsa, TargetIsa,7};8use crate::machinst::{9CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet,10TextSectionBuilder, VCode, compile,11};12use crate::result::CodegenResult;13use crate::settings::{self as shared_settings, Flags};14use crate::{CodegenError, ir};15use alloc::{boxed::Box, vec::Vec};16use core::fmt;17use cranelift_control::ControlPlane;18use std::string::String;19use target_lexicon::{Architecture, Triple};20mod abi;21pub(crate) mod inst;22mod lower;23mod settings;24#[cfg(feature = "unwind")]25use crate::isa::unwind::systemv;2627use self::inst::EmitInfo;2829/// An riscv64 backend.30pub struct Riscv64Backend {31triple: Triple,32flags: shared_settings::Flags,33isa_flags: riscv_settings::Flags,34}3536impl Riscv64Backend {37/// Create a new riscv64 backend with the given (shared) flags.38pub fn new_with_flags(39triple: Triple,40flags: shared_settings::Flags,41isa_flags: riscv_settings::Flags,42) -> Riscv64Backend {43Riscv64Backend {44triple,45flags,46isa_flags,47}48}4950/// This performs lowering to VCode, register-allocates the code, computes block layout and51/// finalizes branches. The result is ready for binary emission.52fn compile_vcode(53&self,54func: &Function,55domtree: &DominatorTree,56ctrl_plane: &mut ControlPlane,57) -> CodegenResult<(VCode<inst::Inst>, regalloc2::Output)> {58let emit_info = EmitInfo::new(self.flags.clone(), self.isa_flags.clone());59let sigs = SigSet::new::<abi::Riscv64MachineDeps>(func, &self.flags)?;60let abi = abi::Riscv64Callee::new(func, self, &self.isa_flags, &sigs)?;61compile::compile::<Riscv64Backend>(func, domtree, self, abi, emit_info, sigs, ctrl_plane)62}63}6465impl TargetIsa for Riscv64Backend {66fn compile_function(67&self,68func: &Function,69domtree: &DominatorTree,70want_disasm: bool,71ctrl_plane: &mut ControlPlane,72) -> CodegenResult<CompiledCodeStencil> {73let (vcode, regalloc_result) = self.compile_vcode(func, domtree, ctrl_plane)?;7475let want_disasm = want_disasm || log::log_enabled!(log::Level::Debug);76let emit_result = vcode.emit(®alloc_result, want_disasm, &self.flags, ctrl_plane);77let frame_size = emit_result.frame_size;78let value_labels_ranges = emit_result.value_labels_ranges;79let buffer = emit_result.buffer;80let sized_stackslot_offsets = emit_result.sized_stackslot_offsets;81let dynamic_stackslot_offsets = emit_result.dynamic_stackslot_offsets;8283if let Some(disasm) = emit_result.disasm.as_ref() {84log::debug!("disassembly:\n{disasm}");85}8687Ok(CompiledCodeStencil {88buffer,89frame_size,90vcode: emit_result.disasm,91value_labels_ranges,92sized_stackslot_offsets,93dynamic_stackslot_offsets,94bb_starts: emit_result.bb_offsets,95bb_edges: emit_result.bb_edges,96})97}9899fn name(&self) -> &'static str {100"riscv64"101}102fn dynamic_vector_bytes(&self, _dynamic_ty: ir::Type) -> u32 {10316104}105106fn triple(&self) -> &Triple {107&self.triple108}109110fn flags(&self) -> &shared_settings::Flags {111&self.flags112}113114fn isa_flags(&self) -> Vec<shared_settings::Value> {115self.isa_flags.iter().collect()116}117118fn isa_flags_hash_key(&self) -> IsaFlagsHashKey<'_> {119IsaFlagsHashKey(self.isa_flags.hash_key())120}121122#[cfg(feature = "unwind")]123fn emit_unwind_info(124&self,125result: &CompiledCode,126kind: crate::isa::unwind::UnwindInfoKind,127) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {128use crate::isa::unwind::UnwindInfo;129use crate::isa::unwind::UnwindInfoKind;130Ok(match kind {131UnwindInfoKind::SystemV => {132let mapper = self::inst::unwind::systemv::RegisterMapper;133Some(UnwindInfo::SystemV(134crate::isa::unwind::systemv::create_unwind_info_from_insts(135&result.buffer.unwind_info[..],136result.buffer.data().len(),137&mapper,138)?,139))140}141UnwindInfoKind::Windows => None,142_ => None,143})144}145146#[cfg(feature = "unwind")]147fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {148Some(inst::unwind::systemv::create_cie())149}150151fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {152Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))153}154155#[cfg(feature = "unwind")]156fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, systemv::RegisterMappingError> {157inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)158}159160fn function_alignment(&self) -> FunctionAlignment {161inst::Inst::function_alignment()162}163164fn page_size_align_log2(&self) -> u8 {165debug_assert_eq!(1 << 12, 0x1000);16612167}168169#[cfg(feature = "disas")]170fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {171use capstone::prelude::*;172let mut cs_builder = Capstone::new().riscv().mode(arch::riscv::ArchMode::RiscV64);173174// Enable C instruction decoding if we have compressed instructions enabled.175//176// We can't enable this unconditionally because it will cause Capstone to177// emit weird instructions and generally mess up when it encounters unknown178// instructions, such as any Zba,Zbb,Zbc or Vector instructions.179//180// This causes the default disassembly to be quite unreadable, so enable181// it only when we are actually going to be using them.182let uses_compressed = self183.isa_flags()184.iter()185.filter(|f| ["has_zca", "has_zcb", "has_zcd"].contains(&f.name))186.any(|f| f.as_bool().unwrap_or(false));187if uses_compressed {188cs_builder = cs_builder.extra_mode([arch::riscv::ArchExtraMode::RiscVC].into_iter());189}190191let mut cs = cs_builder.build()?;192193// Similar to AArch64, RISC-V uses inline constants rather than a separate194// constant pool. We want to skip disassembly over inline constants instead195// of stopping on invalid bytes.196cs.set_skipdata(true)?;197Ok(cs)198}199200fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {201// TODO-RISC-V: implement proper register pretty-printing.202format!("{reg:?}")203}204205fn has_native_fma(&self) -> bool {206true207}208209fn has_round(&self) -> bool {210true211}212213fn has_x86_blendv_lowering(&self, _: Type) -> bool {214false215}216217fn has_x86_pshufb_lowering(&self) -> bool {218false219}220221fn has_x86_pmulhrsw_lowering(&self) -> bool {222false223}224225fn has_x86_pmaddubsw_lowering(&self) -> bool {226false227}228229fn default_argument_extension(&self) -> ir::ArgumentExtension {230// According to https://riscv.org/wp-content/uploads/2024/12/riscv-calling.pdf231// it says:232//233// > In RV64, 32-bit types, such as int, are stored in integer234// > registers as proper sign extensions of their 32-bit values; that235// > is, bits 63..31 are all equal. This restriction holds even for236// > unsigned 32-bit types.237//238// leading to `sext` here.239ir::ArgumentExtension::Sext240}241}242243impl fmt::Display for Riscv64Backend {244fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {245f.debug_struct("MachBackend")246.field("name", &self.name())247.field("triple", &self.triple())248.field("flags", &format!("{}", self.flags()))249.finish()250}251}252253/// Create a new `isa::Builder`.254pub fn isa_builder(triple: Triple) -> IsaBuilder {255match triple.architecture {256Architecture::Riscv64(..) => {}257_ => unreachable!(),258}259IsaBuilder {260triple,261setup: riscv_settings::builder(),262constructor: isa_constructor,263}264}265266fn isa_constructor(267triple: Triple,268shared_flags: Flags,269builder: &shared_settings::Builder,270) -> CodegenResult<OwnedTargetIsa> {271let isa_flags = riscv_settings::Flags::new(&shared_flags, builder);272273// The RISC-V backend does not work without at least the G extension enabled.274// The G extension is simply a combination of the following extensions:275// - I: Base Integer Instruction Set276// - M: Integer Multiplication and Division277// - A: Atomic Instructions278// - F: Single-Precision Floating-Point279// - D: Double-Precision Floating-Point280// - Zicsr: Control and Status Register Instructions281// - Zifencei: Instruction-Fetch Fence282//283// Ensure that those combination of features is enabled.284if !isa_flags.has_g() {285return Err(CodegenError::Unsupported(286"The RISC-V Backend currently requires all the features in the G Extension enabled"287.into(),288));289}290291let backend = Riscv64Backend::new_with_flags(triple, shared_flags, isa_flags);292Ok(backend.wrapped())293}294295296