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 std::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 
46 use crate::dominator_tree::DominatorTree;
47 pub use crate::isa::call_conv::CallConv;
48 
49 use crate::flowgraph;
50 use crate::ir::{self, Function, Type};
51 #[cfg(feature = "unwind")]
52 use crate::isa::unwind::{systemv::RegisterMappingError, UnwindInfoKind};
53 use crate::machinst::{CompiledCode, CompiledCodeStencil, TextSectionBuilder};
54 use crate::settings;
55 use crate::settings::SetResult;
56 use crate::CodegenResult;
57 use alloc::{boxed::Box, sync::Arc, vec::Vec};
58 use core::fmt;
59 use core::fmt::{Debug, Formatter};
60 use cranelift_control::ControlPlane;
61 use target_lexicon::{triple, Architecture, PointerWidth, Triple};
62 
63 // This module is made public here for benchmarking purposes. No guarantees are
64 // made regarding API stability.
65 #[cfg(feature = "x86")]
66 pub mod x64;
67 
68 #[cfg(feature = "arm64")]
69 pub mod aarch64;
70 
71 #[cfg(feature = "riscv64")]
72 pub mod riscv64;
73 
74 #[cfg(feature = "s390x")]
75 mod s390x;
76 
77 pub mod unwind;
78 
79 mod call_conv;
80 
81 /// Returns a builder that can create a corresponding `TargetIsa`
82 /// or `Err(LookupError::SupportDisabled)` if not enabled.
83 macro_rules! isa_builder {
84     ($name: ident, $cfg_terms: tt, $triple: ident) => {{
85         #[cfg $cfg_terms]
86         {
87             Ok($name::isa_builder($triple))
88         }
89         #[cfg(not $cfg_terms)]
90         {
91             Err(LookupError::SupportDisabled)
92         }
93     }};
94 }
95 
96 /// Look for an ISA for the given `triple`.
97 /// Return a builder that can create a corresponding `TargetIsa`.
98 pub fn lookup(triple: Triple) -> Result<Builder, LookupError> {
99     match triple.architecture {
100         Architecture::X86_64 => {
101             isa_builder!(x64, (feature = "x86"), triple)
102         }
103         Architecture::Aarch64 { .. } => isa_builder!(aarch64, (feature = "arm64"), triple),
104         Architecture::S390x { .. } => isa_builder!(s390x, (feature = "s390x"), triple),
105         Architecture::Riscv64 { .. } => isa_builder!(riscv64, (feature = "riscv64"), triple),
106         _ => Err(LookupError::Unsupported),
107     }
108 }
109 
110 /// The string names of all the supported, but possibly not enabled, architectures. The elements of
111 /// this slice are suitable to be passed to the [lookup_by_name] function to obtain the default
112 /// configuration for that architecture.
113 pub const ALL_ARCHITECTURES: &[&str] = &["x86_64", "aarch64", "s390x", "riscv64"];
114 
115 /// Look for a supported ISA with the given `name`.
116 /// Return a builder that can create a corresponding `TargetIsa`.
117 pub fn lookup_by_name(name: &str) -> Result<Builder, LookupError> {
118     lookup(triple!(name))
119 }
120 
121 /// Describes reason for target lookup failure
122 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
123 pub enum LookupError {
124     /// Support for this target was disabled in the current build.
125     SupportDisabled,
126 
127     /// Support for this target has not yet been implemented.
128     Unsupported,
129 }
130 
131 // This is manually implementing Error and Display instead of using thiserror to reduce the amount
132 // of dependencies used by Cranelift.
133 impl std::error::Error for LookupError {}
134 
135 impl fmt::Display for LookupError {
136     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
137         match self {
138             LookupError::SupportDisabled => write!(f, "Support for this target is disabled"),
139             LookupError::Unsupported => {
140                 write!(f, "Support for this target has not been implemented yet")
141             }
142         }
143     }
144 }
145 
146 /// The type of a polymorphic TargetISA object which is 'static.
147 pub type OwnedTargetIsa = Arc<dyn TargetIsa>;
148 
149 /// Type alias of `IsaBuilder` used for building Cranelift's ISAs.
150 pub type Builder = IsaBuilder<CodegenResult<OwnedTargetIsa>>;
151 
152 /// Builder for a `TargetIsa`.
153 /// Modify the ISA-specific settings before creating the `TargetIsa` trait object with `finish`.
154 #[derive(Clone)]
155 pub struct IsaBuilder<T> {
156     triple: Triple,
157     setup: settings::Builder,
158     constructor: fn(Triple, settings::Flags, &settings::Builder) -> T,
159 }
160 
161 impl<T> IsaBuilder<T> {
162     /// Creates a new ISA-builder from its components, namely the `triple` for
163     /// the ISA, the ISA-specific settings builder, and a final constructor
164     /// function to generate the ISA from its components.
165     pub fn new(
166         triple: Triple,
167         setup: settings::Builder,
168         constructor: fn(Triple, settings::Flags, &settings::Builder) -> T,
169     ) -> Self {
170         IsaBuilder {
171             triple,
172             setup,
173             constructor,
174         }
175     }
176 
177     /// Gets the triple for the builder.
178     pub fn triple(&self) -> &Triple {
179         &self.triple
180     }
181 
182     /// Iterates the available settings in the builder.
183     pub fn iter(&self) -> impl Iterator<Item = settings::Setting> {
184         self.setup.iter()
185     }
186 
187     /// Combine the ISA-specific settings with the provided
188     /// ISA-independent settings and allocate a fully configured
189     /// `TargetIsa` trait object. May return an error if some of the
190     /// flags are inconsistent or incompatible: for example, some
191     /// platform-independent features, like general SIMD support, may
192     /// need certain ISA extensions to be enabled.
193     pub fn finish(&self, shared_flags: settings::Flags) -> T {
194         (self.constructor)(self.triple.clone(), shared_flags, &self.setup)
195     }
196 }
197 
198 impl<T> settings::Configurable for IsaBuilder<T> {
199     fn set(&mut self, name: &str, value: &str) -> SetResult<()> {
200         self.setup.set(name, value)
201     }
202 
203     fn enable(&mut self, name: &str) -> SetResult<()> {
204         self.setup.enable(name)
205     }
206 }
207 
208 /// After determining that an instruction doesn't have an encoding, how should we proceed to
209 /// legalize it?
210 ///
211 /// The `Encodings` iterator returns a legalization function to call.
212 pub type Legalize =
213     fn(ir::Inst, &mut ir::Function, &mut flowgraph::ControlFlowGraph, &dyn TargetIsa) -> bool;
214 
215 /// This struct provides information that a frontend may need to know about a target to
216 /// produce Cranelift IR for the target.
217 #[derive(Clone, Copy, Hash)]
218 pub struct TargetFrontendConfig {
219     /// The default calling convention of the target.
220     pub default_call_conv: CallConv,
221 
222     /// The pointer width of the target.
223     pub pointer_width: PointerWidth,
224 }
225 
226 impl TargetFrontendConfig {
227     /// Get the pointer type of this target.
228     pub fn pointer_type(self) -> ir::Type {
229         ir::Type::int(self.pointer_bits() as u16).unwrap()
230     }
231 
232     /// Get the width of pointers on this target, in units of bits.
233     pub fn pointer_bits(self) -> u8 {
234         self.pointer_width.bits()
235     }
236 
237     /// Get the width of pointers on this target, in units of bytes.
238     pub fn pointer_bytes(self) -> u8 {
239         self.pointer_width.bytes()
240     }
241 }
242 
243 /// Methods that are specialized to a target ISA.
244 ///
245 /// Implies a Display trait that shows the shared flags, as well as any ISA-specific flags.
246 pub trait TargetIsa: fmt::Display + Send + Sync {
247     /// Get the name of this ISA.
248     fn name(&self) -> &'static str;
249 
250     /// Get the target triple that was used to make this trait object.
251     fn triple(&self) -> &Triple;
252 
253     /// Get the ISA-independent flags that were used to make this trait object.
254     fn flags(&self) -> &settings::Flags;
255 
256     /// Get the ISA-dependent flag values that were used to make this trait object.
257     fn isa_flags(&self) -> Vec<settings::Value>;
258 
259     /// Get a flag indicating whether branch protection is enabled.
260     fn is_branch_protection_enabled(&self) -> bool {
261         false
262     }
263 
264     /// Get the ISA-dependent maximum vector register size, in bytes.
265     fn dynamic_vector_bytes(&self, dynamic_ty: ir::Type) -> u32;
266 
267     /// Compile the given function.
268     fn compile_function(
269         &self,
270         func: &Function,
271         domtree: &DominatorTree,
272         want_disasm: bool,
273         ctrl_plane: &mut ControlPlane,
274     ) -> CodegenResult<CompiledCodeStencil>;
275 
276     #[cfg(feature = "unwind")]
277     /// Map a regalloc::Reg to its corresponding DWARF register.
278     fn map_regalloc_reg_to_dwarf(
279         &self,
280         _: crate::machinst::Reg,
281     ) -> Result<u16, RegisterMappingError> {
282         Err(RegisterMappingError::UnsupportedArchitecture)
283     }
284 
285     /// Creates unwind information for the function.
286     ///
287     /// Returns `None` if there is no unwind information for the function.
288     #[cfg(feature = "unwind")]
289     fn emit_unwind_info(
290         &self,
291         result: &CompiledCode,
292         kind: UnwindInfoKind,
293     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>>;
294 
295     /// Creates a new System V Common Information Entry for the ISA.
296     ///
297     /// Returns `None` if the ISA does not support System V unwind information.
298     #[cfg(feature = "unwind")]
299     fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
300         // By default, an ISA cannot create a System V CIE
301         None
302     }
303 
304     /// Returns an object that can be used to build the text section of an
305     /// executable.
306     ///
307     /// This object will internally attempt to handle as many relocations as
308     /// possible using relative calls/jumps/etc between functions.
309     ///
310     /// The `num_labeled_funcs` argument here is the number of functions which
311     /// will be "labeled" or might have calls between them, typically the number
312     /// of defined functions in the object file.
313     fn text_section_builder(&self, num_labeled_funcs: usize) -> Box<dyn TextSectionBuilder>;
314 
315     /// Returns the minimum function alignment and the preferred function
316     /// alignment, for performance, required by this ISA.
317     fn function_alignment(&self) -> FunctionAlignment;
318 
319     /// Create a polymorphic TargetIsa from this specific implementation.
320     fn wrapped(self) -> OwnedTargetIsa
321     where
322         Self: Sized + 'static,
323     {
324         Arc::new(self)
325     }
326 
327     /// Generate a `Capstone` context for disassembling bytecode for this architecture.
328     #[cfg(feature = "disas")]
329     fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
330         Err(capstone::Error::UnsupportedArch)
331     }
332 
333     /// Returns whether this ISA has a native fused-multiply-and-add instruction
334     /// for floats.
335     ///
336     /// Currently this only returns false on x86 when some native features are
337     /// not detected.
338     fn has_native_fma(&self) -> bool;
339 
340     /// Returns whether the CLIF `x86_blendv` instruction is implemented for
341     /// this ISA for the specified type.
342     fn has_x86_blendv_lowering(&self, ty: Type) -> bool;
343 
344     /// Returns whether the CLIF `x86_pshufb` instruction is implemented for
345     /// this ISA.
346     fn has_x86_pshufb_lowering(&self) -> bool;
347 
348     /// Returns whether the CLIF `x86_pmulhrsw` instruction is implemented for
349     /// this ISA.
350     fn has_x86_pmulhrsw_lowering(&self) -> bool;
351 
352     /// Returns whether the CLIF `x86_pmaddubsw` instruction is implemented for
353     /// this ISA.
354     fn has_x86_pmaddubsw_lowering(&self) -> bool;
355 }
356 
357 /// Function alignment specifications as required by an ISA, returned by
358 /// [`TargetIsa::function_alignment`].
359 #[derive(Copy, Clone)]
360 pub struct FunctionAlignment {
361     /// The minimum alignment required by an ISA, where all functions must be
362     /// aligned to at least this amount.
363     pub minimum: u32,
364     /// A "preferred" alignment which should be used for more
365     /// performance-sensitive situations. This can involve cache-line-aligning
366     /// for example to get more of a small function into fewer cache lines.
367     pub preferred: u32,
368 }
369 
370 /// Methods implemented for free for target ISA!
371 impl<'a> dyn TargetIsa + 'a {
372     /// Get the default calling convention of this target.
373     pub fn default_call_conv(&self) -> CallConv {
374         CallConv::triple_default(self.triple())
375     }
376 
377     /// Get the endianness of this ISA.
378     pub fn endianness(&self) -> ir::Endianness {
379         match self.triple().endianness().unwrap() {
380             target_lexicon::Endianness::Little => ir::Endianness::Little,
381             target_lexicon::Endianness::Big => ir::Endianness::Big,
382         }
383     }
384 
385     /// Returns the minimum symbol alignment for this ISA.
386     pub fn symbol_alignment(&self) -> u64 {
387         match self.triple().architecture {
388             // All symbols need to be aligned to at least 2 on s390x.
389             Architecture::S390x => 2,
390             _ => 1,
391         }
392     }
393 
394     /// Get the pointer type of this ISA.
395     pub fn pointer_type(&self) -> ir::Type {
396         ir::Type::int(self.pointer_bits() as u16).unwrap()
397     }
398 
399     /// Get the width of pointers on this ISA.
400     pub(crate) fn pointer_width(&self) -> PointerWidth {
401         self.triple().pointer_width().unwrap()
402     }
403 
404     /// Get the width of pointers on this ISA, in units of bits.
405     pub fn pointer_bits(&self) -> u8 {
406         self.pointer_width().bits()
407     }
408 
409     /// Get the width of pointers on this ISA, in units of bytes.
410     pub fn pointer_bytes(&self) -> u8 {
411         self.pointer_width().bytes()
412     }
413 
414     /// Get the information needed by frontends producing Cranelift IR.
415     pub fn frontend_config(&self) -> TargetFrontendConfig {
416         TargetFrontendConfig {
417             default_call_conv: self.default_call_conv(),
418             pointer_width: self.pointer_width(),
419         }
420     }
421 }
422 
423 impl Debug for &dyn TargetIsa {
424     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
425         write!(
426             f,
427             "TargetIsa {{ triple: {:?}, pointer_width: {:?}}}",
428             self.triple(),
429             self.pointer_width()
430         )
431     }
432 }
433