Skip to main content

cranelift_codegen/isa/
mod.rs

1//! Instruction Set Architectures.
2//!
3//! The `isa` module provides a `TargetIsa` trait which provides the behavior specialization needed
4//! by the ISA-independent code generator. The sub-modules of this module provide definitions for
5//! the instruction sets that Cranelift can target. Each sub-module has it's own implementation of
6//! `TargetIsa`.
7//!
8//! # Constructing a `TargetIsa` instance
9//!
10//! The target ISA is built from the following information:
11//!
12//! - The name of the target ISA as a string. Cranelift is a cross-compiler, so the ISA to target
13//!   can be selected dynamically. Individual ISAs can be left out when Cranelift is compiled, so a
14//!   string is used to identify the proper sub-module.
15//! - Values for settings that apply to all ISAs. This is represented by a `settings::Flags`
16//!   instance.
17//! - Values for ISA-specific settings.
18//!
19//! The `isa::lookup()` function is the main entry point which returns an `isa::Builder`
20//! appropriate for the requested ISA:
21//!
22//! ```
23//! # #[macro_use] extern crate target_lexicon;
24//! use cranelift_codegen::isa;
25//! use cranelift_codegen::settings::{self, Configurable};
26//! use core::str::FromStr;
27//! use target_lexicon::Triple;
28//!
29//! let shared_builder = settings::builder();
30//! let shared_flags = settings::Flags::new(shared_builder);
31//!
32//! match isa::lookup(triple!("x86_64")) {
33//!     Err(_) => {
34//!         // The x86_64 target ISA is not available.
35//!     }
36//!     Ok(mut isa_builder) => {
37//!         isa_builder.set("use_popcnt", "on");
38//!         let isa = isa_builder.finish(shared_flags);
39//!     }
40//! }
41//! ```
42//!
43//! The configured target ISA trait object is a `Box<TargetIsa>` which can be used for multiple
44//! concurrent function compilations.
45
46use crate::dominator_tree::DominatorTree;
47pub use crate::isa::call_conv::CallConv;
48use crate::loop_analysis::LoopAnalysis;
49
50use crate::CodegenResult;
51use crate::ir::{self, Function, Type};
52#[cfg(feature = "unwind")]
53use crate::isa::unwind::{UnwindInfoKind, systemv::RegisterMappingError};
54use crate::machinst::{CompiledCodeStencil, TextSectionBuilder};
55use crate::settings;
56use crate::settings::Configurable;
57use crate::settings::SetResult;
58use crate::{Reg, flowgraph};
59use alloc::string::String;
60use alloc::{boxed::Box, sync::Arc, vec::Vec};
61use core::fmt;
62use core::fmt::{Debug, Formatter};
63use cranelift_control::ControlPlane;
64use target_lexicon::{Architecture, PointerWidth, Triple, triple};
65
66// This module is made public here for benchmarking purposes. No guarantees are
67// made regarding API stability.
68#[cfg(feature = "x86")]
69pub mod x64;
70
71#[cfg(feature = "arm64")]
72pub mod aarch64;
73
74#[cfg(feature = "riscv64")]
75pub mod riscv64;
76
77#[cfg(feature = "s390x")]
78mod s390x;
79
80#[cfg(feature = "pulley")]
81mod pulley32;
82#[cfg(feature = "pulley")]
83mod pulley64;
84#[cfg(feature = "pulley")]
85mod pulley_shared;
86
87pub mod unwind;
88
89mod call_conv;
90mod winch;
91
92/// Returns a builder that can create a corresponding `TargetIsa`
93/// or `Err(LookupError::SupportDisabled)` if not enabled.
94macro_rules! isa_builder {
95    ($name: ident, $cfg_terms: tt, $triple: ident) => {{
96        #[cfg $cfg_terms]
97        {
98            Ok($name::isa_builder($triple))
99        }
100        #[cfg(not $cfg_terms)]
101        {
102            Err(LookupError::SupportDisabled)
103        }
104    }};
105}
106
107/// Look for an ISA for the given `triple`.
108/// Return a builder that can create a corresponding `TargetIsa`.
109pub fn lookup(triple: Triple) -> Result<Builder, LookupError> {
110    match triple.architecture {
111        Architecture::X86_64 => {
112            isa_builder!(x64, (feature = "x86"), triple)
113        }
114        Architecture::Aarch64 { .. } => isa_builder!(aarch64, (feature = "arm64"), triple),
115        Architecture::S390x { .. } => isa_builder!(s390x, (feature = "s390x"), triple),
116        Architecture::Riscv64 { .. } => isa_builder!(riscv64, (feature = "riscv64"), triple),
117        Architecture::Pulley32 | Architecture::Pulley32be => {
118            isa_builder!(pulley32, (feature = "pulley"), triple)
119        }
120        Architecture::Pulley64 | Architecture::Pulley64be => {
121            isa_builder!(pulley64, (feature = "pulley"), triple)
122        }
123        _ => Err(LookupError::Unsupported),
124    }
125}
126
127/// The string names of all the supported, but possibly not enabled, architectures. The elements of
128/// this slice are suitable to be passed to the [lookup_by_name] function to obtain the default
129/// configuration for that architecture.
130pub const ALL_ARCHITECTURES: &[&str] = &["x86_64", "aarch64", "s390x", "riscv64"];
131
132/// Look for a supported ISA with the given `name`.
133/// Return a builder that can create a corresponding `TargetIsa`.
134pub fn lookup_by_name(name: &str) -> Result<Builder, LookupError> {
135    lookup(triple!(name))
136}
137
138/// Describes reason for target lookup failure
139#[derive(PartialEq, Eq, Copy, Clone, Debug)]
140pub enum LookupError {
141    /// Support for this target was disabled in the current build.
142    SupportDisabled,
143
144    /// Support for this target has not yet been implemented.
145    Unsupported,
146}
147
148// This is manually implementing Error and Display instead of using thiserror to reduce the amount
149// of dependencies used by Cranelift.
150impl core::error::Error for LookupError {}
151
152impl fmt::Display for LookupError {
153    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
154        match self {
155            LookupError::SupportDisabled => write!(f, "Support for this target is disabled"),
156            LookupError::Unsupported => {
157                write!(f, "Support for this target has not been implemented yet")
158            }
159        }
160    }
161}
162
163/// The type of a polymorphic TargetISA object which is 'static.
164pub type OwnedTargetIsa = Arc<dyn TargetIsa>;
165
166/// Type alias of `IsaBuilder` used for building Cranelift's ISAs.
167pub type Builder = IsaBuilder<CodegenResult<OwnedTargetIsa>>;
168
169/// Builder for a `TargetIsa`.
170/// Modify the ISA-specific settings before creating the `TargetIsa` trait object with `finish`.
171#[derive(Clone)]
172pub struct IsaBuilder<T> {
173    triple: Triple,
174    setup: settings::Builder,
175    constructor: fn(Triple, settings::Flags, &settings::Builder) -> T,
176}
177
178impl<T> IsaBuilder<T> {
179    /// Creates a new ISA-builder from its components, namely the `triple` for
180    /// the ISA, the ISA-specific settings builder, and a final constructor
181    /// function to generate the ISA from its components.
182    pub fn new(
183        triple: Triple,
184        setup: settings::Builder,
185        constructor: fn(Triple, settings::Flags, &settings::Builder) -> T,
186    ) -> Self {
187        IsaBuilder {
188            triple,
189            setup,
190            constructor,
191        }
192    }
193
194    /// Creates a new [Builder] from a [TargetIsa], copying all flags in the
195    /// process.
196    pub fn from_target_isa(target_isa: &dyn TargetIsa) -> Builder {
197        // We should always be able to find the builder for the TargetISA, since presumably we
198        // also generated the previous TargetISA at some point
199        let triple = target_isa.triple().clone();
200        let mut builder = self::lookup(triple).expect("Could not find triple for target ISA");
201
202        // Copy ISA Flags
203        for flag in target_isa.isa_flags() {
204            builder.set(&flag.name, &flag.value_string()).unwrap();
205        }
206
207        builder
208    }
209
210    /// Gets the triple for the builder.
211    pub fn triple(&self) -> &Triple {
212        &self.triple
213    }
214
215    /// Iterates the available settings in the builder.
216    pub fn iter(&self) -> impl Iterator<Item = settings::Setting> + use<T> {
217        self.setup.iter()
218    }
219
220    /// Combine the ISA-specific settings with the provided
221    /// ISA-independent settings and allocate a fully configured
222    /// `TargetIsa` trait object. May return an error if some of the
223    /// flags are inconsistent or incompatible: for example, some
224    /// platform-independent features, like general SIMD support, may
225    /// need certain ISA extensions to be enabled.
226    pub fn finish(&self, shared_flags: settings::Flags) -> T {
227        (self.constructor)(self.triple.clone(), shared_flags, &self.setup)
228    }
229}
230
231impl<T> settings::Configurable for IsaBuilder<T> {
232    fn set(&mut self, name: &str, value: &str) -> SetResult<()> {
233        self.setup.set(name, value)
234    }
235
236    fn enable(&mut self, name: &str) -> SetResult<()> {
237        self.setup.enable(name)
238    }
239}
240
241/// After determining that an instruction doesn't have an encoding, how should we proceed to
242/// legalize it?
243///
244/// The `Encodings` iterator returns a legalization function to call.
245pub type Legalize =
246    fn(ir::Inst, &mut ir::Function, &mut flowgraph::ControlFlowGraph, &dyn TargetIsa) -> bool;
247
248/// This struct provides information that a frontend may need to know about a target to
249/// produce Cranelift IR for the target.
250#[derive(Clone, Copy, Hash)]
251pub struct TargetFrontendConfig {
252    /// The default calling convention of the target.
253    pub default_call_conv: CallConv,
254
255    /// The pointer width of the target.
256    pub pointer_width: PointerWidth,
257
258    /// The log2 of the target's page size and alignment.
259    ///
260    /// Note that this may be an upper-bound that is larger than necessary for
261    /// some platforms since it may depend on runtime configuration.
262    pub page_size_align_log2: u8,
263}
264
265impl TargetFrontendConfig {
266    /// Get the pointer type of this target.
267    pub fn pointer_type(self) -> ir::Type {
268        ir::Type::int(self.pointer_bits() as u16).unwrap()
269    }
270
271    /// Get the width of pointers on this target, in units of bits.
272    pub fn pointer_bits(self) -> u8 {
273        self.pointer_width.bits()
274    }
275
276    /// Get the width of pointers on this target, in units of bytes.
277    pub fn pointer_bytes(self) -> u8 {
278        self.pointer_width.bytes()
279    }
280}
281
282/// Methods that are specialized to a target ISA.
283///
284/// Implies a Display trait that shows the shared flags, as well as any ISA-specific flags.
285pub trait TargetIsa: fmt::Display + Send + Sync {
286    /// Get the name of this ISA.
287    fn name(&self) -> &'static str;
288
289    /// Get the target triple that was used to make this trait object.
290    fn triple(&self) -> &Triple;
291
292    /// Get the ISA-independent flags that were used to make this trait object.
293    fn flags(&self) -> &settings::Flags;
294
295    /// Get the ISA-dependent flag values that were used to make this trait object.
296    fn isa_flags(&self) -> Vec<settings::Value>;
297
298    /// Get the ISA-dependent flag values as raw bytes for hashing.
299    fn isa_flags_hash_key(&self) -> IsaFlagsHashKey<'_>;
300
301    /// Get a flag indicating whether branch protection is enabled.
302    fn is_branch_protection_enabled(&self) -> bool {
303        false
304    }
305
306    /// Get the ISA-dependent maximum vector register size, in bytes.
307    fn dynamic_vector_bytes(&self, dynamic_ty: ir::Type) -> u32;
308
309    /// Compile the given function.
310    fn compile_function(
311        &self,
312        func: &Function,
313        domtree: &DominatorTree,
314        loop_analysis: &LoopAnalysis,
315        regalloc_ctx: &mut regalloc2::Ctx,
316        want_disasm: bool,
317        ctrl_plane: &mut ControlPlane,
318    ) -> CodegenResult<CompiledCodeStencil>;
319
320    #[cfg(feature = "unwind")]
321    /// Map a regalloc::Reg to its corresponding DWARF register.
322    fn map_regalloc_reg_to_dwarf(
323        &self,
324        _: crate::machinst::Reg,
325    ) -> Result<u16, RegisterMappingError> {
326        Err(RegisterMappingError::UnsupportedArchitecture)
327    }
328
329    /// Creates unwind information for the function.
330    ///
331    /// Returns `None` if there is no unwind information for the function.
332    #[cfg(feature = "unwind")]
333    fn emit_unwind_info(
334        &self,
335        result: &crate::machinst::CompiledCode,
336        kind: UnwindInfoKind,
337    ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>>;
338
339    /// Creates a new System V Common Information Entry for the ISA.
340    ///
341    /// Returns `None` if the ISA does not support System V unwind information.
342    #[cfg(feature = "unwind")]
343    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
344        // By default, an ISA cannot create a System V CIE
345        None
346    }
347
348    /// Returns an object that can be used to build the text section of an
349    /// executable.
350    ///
351    /// This object will internally attempt to handle as many relocations as
352    /// possible using relative calls/jumps/etc between functions.
353    ///
354    /// The `num_labeled_funcs` argument here is the number of functions which
355    /// will be "labeled" or might have calls between them, typically the number
356    /// of defined functions in the object file.
357    fn text_section_builder(&self, num_labeled_funcs: usize) -> Box<dyn TextSectionBuilder>;
358
359    /// Returns the minimum function alignment and the preferred function
360    /// alignment, for performance, required by this ISA.
361    fn function_alignment(&self) -> FunctionAlignment;
362
363    /// The log2 of the target's page size and alignment.
364    ///
365    /// Note that this may be an upper-bound that is larger than necessary for
366    /// some platforms since it may depend on runtime configuration.
367    fn page_size_align_log2(&self) -> u8;
368
369    /// Create a polymorphic TargetIsa from this specific implementation.
370    fn wrapped(self) -> OwnedTargetIsa
371    where
372        Self: Sized + 'static,
373    {
374        Arc::new(self)
375    }
376
377    /// Generate a `Capstone` context for disassembling bytecode for this architecture.
378    #[cfg(feature = "disas")]
379    fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
380        Err(capstone::Error::UnsupportedArch)
381    }
382
383    /// Return the string representation of "reg" accessed as "size" bytes.
384    /// The returned string will match the usual disassemly view of "reg".
385    fn pretty_print_reg(&self, reg: Reg, size: u8) -> String;
386
387    /// Returns whether this ISA has a native fused-multiply-and-add instruction
388    /// for floats.
389    ///
390    /// Currently this only returns false on x86 when some native features are
391    /// not detected.
392    fn has_native_fma(&self) -> bool;
393
394    /// Returns whether this ISA supports vector loads and stores of `ty`.
395    ///
396    /// By default, vectors up to 128 bits are supported.
397    fn supports_vector_load_store(&self, ty: Type) -> bool {
398        ty.is_vector() && ty.bits() <= 128
399    }
400
401    /// Returns whether this ISA has instructions for `ceil`, `floor`, etc.
402    fn has_round(&self) -> bool;
403
404    /// Returns whether the CLIF `blendv` instruction is implemented for
405    /// this ISA for the specified type.
406    fn has_blendv_lowering(&self, ty: Type) -> bool;
407
408    /// Returns whether the CLIF `x86_pshufb` instruction is implemented for
409    /// this ISA.
410    fn has_x86_pshufb_lowering(&self) -> bool;
411
412    /// Returns whether the CLIF `x86_pmulhrsw` instruction is implemented for
413    /// this ISA.
414    fn has_x86_pmulhrsw_lowering(&self) -> bool;
415
416    /// Returns whether the CLIF `x86_pmaddubsw` instruction is implemented for
417    /// this ISA.
418    fn has_x86_pmaddubsw_lowering(&self) -> bool;
419
420    /// Returns the mode of extension used for integer arguments smaller than
421    /// the pointer width in function signatures.
422    ///
423    /// Some platform ABIs require that smaller-than-pointer-width values are
424    /// either zero or sign-extended to the full register width. This value is
425    /// propagated to the `AbiParam` value created for signatures. Note that not
426    /// all ABIs for all platforms require extension of any form, so this is
427    /// generally only necessary for the `default_call_conv`.
428    fn default_argument_extension(&self) -> ir::ArgumentExtension;
429}
430
431/// A wrapper around the ISA-dependent flags types which only implements `Hash`.
432#[derive(Hash)]
433pub struct IsaFlagsHashKey<'a>(&'a [u8]);
434
435/// Function alignment specifications as required by an ISA, returned by
436/// [`TargetIsa::function_alignment`].
437#[derive(Copy, Clone)]
438pub struct FunctionAlignment {
439    /// The minimum alignment required by an ISA, where all functions must be
440    /// aligned to at least this amount.
441    pub minimum: u32,
442    /// A "preferred" alignment which should be used for more
443    /// performance-sensitive situations. This can involve cache-line-aligning
444    /// for example to get more of a small function into fewer cache lines.
445    pub preferred: u32,
446}
447
448/// Methods implemented for free for target ISA!
449impl<'a> dyn TargetIsa + 'a {
450    /// Get the default calling convention of this target.
451    pub fn default_call_conv(&self) -> CallConv {
452        CallConv::triple_default(self.triple())
453    }
454
455    /// Get the endianness of this ISA.
456    pub fn endianness(&self) -> ir::Endianness {
457        match self.triple().endianness().unwrap() {
458            target_lexicon::Endianness::Little => ir::Endianness::Little,
459            target_lexicon::Endianness::Big => ir::Endianness::Big,
460        }
461    }
462
463    /// Returns the minimum symbol alignment for this ISA.
464    pub fn symbol_alignment(&self) -> u64 {
465        match self.triple().architecture {
466            // All symbols need to be aligned to at least 2 on s390x.
467            Architecture::S390x => 2,
468            _ => 1,
469        }
470    }
471
472    /// Get the pointer type of this ISA.
473    pub fn pointer_type(&self) -> ir::Type {
474        ir::Type::int(self.pointer_bits() as u16).unwrap()
475    }
476
477    /// Get the width of pointers on this ISA.
478    pub(crate) fn pointer_width(&self) -> PointerWidth {
479        self.triple().pointer_width().unwrap()
480    }
481
482    /// Get the width of pointers on this ISA, in units of bits.
483    pub fn pointer_bits(&self) -> u8 {
484        self.pointer_width().bits()
485    }
486
487    /// Get the width of pointers on this ISA, in units of bytes.
488    pub fn pointer_bytes(&self) -> u8 {
489        self.pointer_width().bytes()
490    }
491
492    /// Get the information needed by frontends producing Cranelift IR.
493    pub fn frontend_config(&self) -> TargetFrontendConfig {
494        TargetFrontendConfig {
495            default_call_conv: self.default_call_conv(),
496            pointer_width: self.pointer_width(),
497            page_size_align_log2: self.page_size_align_log2(),
498        }
499    }
500}
501
502impl Debug for &dyn TargetIsa {
503    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
504        write!(
505            f,
506            "TargetIsa {{ triple: {:?}, pointer_width: {:?}}}",
507            self.triple(),
508            self.pointer_width()
509        )
510    }
511}