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