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 pub use crate::isa::call_conv::CallConv;
47 
48 use crate::flowgraph;
49 use crate::ir::{self, Function};
50 #[cfg(feature = "unwind")]
51 use crate::isa::unwind::systemv::RegisterMappingError;
52 use crate::machinst::{MachCompileResult, TextSectionBuilder, UnwindInfoKind};
53 use crate::settings;
54 use crate::settings::SetResult;
55 use crate::CodegenResult;
56 use alloc::{boxed::Box, vec::Vec};
57 use core::fmt;
58 use core::fmt::{Debug, Formatter};
59 use target_lexicon::{triple, Architecture, OperatingSystem, PointerWidth, Triple};
60 
61 // This module is made public here for benchmarking purposes. No guarantees are
62 // made regarding API stability.
63 #[cfg(feature = "x86")]
64 pub mod x64;
65 
66 #[cfg(feature = "arm64")]
67 pub(crate) mod aarch64;
68 
69 #[cfg(feature = "s390x")]
70 mod s390x;
71 
72 pub mod unwind;
73 
74 mod call_conv;
75 
76 /// Returns a builder that can create a corresponding `TargetIsa`
77 /// or `Err(LookupError::SupportDisabled)` if not enabled.
78 macro_rules! isa_builder {
79     ($name: ident, $cfg_terms: tt, $triple: ident) => {{
80         #[cfg $cfg_terms]
81         {
82             Ok($name::isa_builder($triple))
83         }
84         #[cfg(not $cfg_terms)]
85         {
86             Err(LookupError::SupportDisabled)
87         }
88     }};
89 }
90 
91 /// Look for an ISA for the given `triple`.
92 /// Return a builder that can create a corresponding `TargetIsa`.
93 pub fn lookup(triple: Triple) -> Result<Builder, LookupError> {
94     match triple.architecture {
95         Architecture::X86_64 => {
96             isa_builder!(x64, (feature = "x86"), triple)
97         }
98         Architecture::Aarch64 { .. } => isa_builder!(aarch64, (feature = "arm64"), triple),
99         Architecture::S390x { .. } => isa_builder!(s390x, (feature = "s390x"), triple),
100         _ => Err(LookupError::Unsupported),
101     }
102 }
103 
104 /// Look for a supported ISA with the given `name`.
105 /// Return a builder that can create a corresponding `TargetIsa`.
106 pub fn lookup_by_name(name: &str) -> Result<Builder, LookupError> {
107     use alloc::str::FromStr;
108     lookup(triple!(name))
109 }
110 
111 /// Describes reason for target lookup failure
112 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
113 pub enum LookupError {
114     /// Support for this target was disabled in the current build.
115     SupportDisabled,
116 
117     /// Support for this target has not yet been implemented.
118     Unsupported,
119 }
120 
121 // This is manually implementing Error and Display instead of using thiserror to reduce the amount
122 // of dependencies used by Cranelift.
123 impl std::error::Error for LookupError {}
124 
125 impl fmt::Display for LookupError {
126     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
127         match self {
128             LookupError::SupportDisabled => write!(f, "Support for this target is disabled"),
129             LookupError::Unsupported => {
130                 write!(f, "Support for this target has not been implemented yet")
131             }
132         }
133     }
134 }
135 
136 /// Builder for a `TargetIsa`.
137 /// Modify the ISA-specific settings before creating the `TargetIsa` trait object with `finish`.
138 #[derive(Clone)]
139 pub struct Builder {
140     triple: Triple,
141     setup: settings::Builder,
142     constructor:
143         fn(Triple, settings::Flags, settings::Builder) -> CodegenResult<Box<dyn TargetIsa>>,
144 }
145 
146 impl Builder {
147     /// Gets the triple for the builder.
148     pub fn triple(&self) -> &Triple {
149         &self.triple
150     }
151 
152     /// Iterates the available settings in the builder.
153     pub fn iter(&self) -> impl Iterator<Item = settings::Setting> {
154         self.setup.iter()
155     }
156 
157     /// Combine the ISA-specific settings with the provided
158     /// ISA-independent settings and allocate a fully configured
159     /// `TargetIsa` trait object. May return an error if some of the
160     /// flags are inconsistent or incompatible: for example, some
161     /// platform-independent features, like general SIMD support, may
162     /// need certain ISA extensions to be enabled.
163     pub fn finish(self, shared_flags: settings::Flags) -> CodegenResult<Box<dyn TargetIsa>> {
164         (self.constructor)(self.triple, shared_flags, self.setup)
165     }
166 }
167 
168 impl settings::Configurable for Builder {
169     fn set(&mut self, name: &str, value: &str) -> SetResult<()> {
170         self.setup.set(name, value)
171     }
172 
173     fn enable(&mut self, name: &str) -> SetResult<()> {
174         self.setup.enable(name)
175     }
176 }
177 
178 /// After determining that an instruction doesn't have an encoding, how should we proceed to
179 /// legalize it?
180 ///
181 /// The `Encodings` iterator returns a legalization function to call.
182 pub type Legalize =
183     fn(ir::Inst, &mut ir::Function, &mut flowgraph::ControlFlowGraph, &dyn TargetIsa) -> bool;
184 
185 /// This struct provides information that a frontend may need to know about a target to
186 /// produce Cranelift IR for the target.
187 #[derive(Clone, Copy, Hash)]
188 pub struct TargetFrontendConfig {
189     /// The default calling convention of the target.
190     pub default_call_conv: CallConv,
191 
192     /// The pointer width of the target.
193     pub pointer_width: PointerWidth,
194 }
195 
196 impl TargetFrontendConfig {
197     /// Get the pointer type of this target.
198     pub fn pointer_type(self) -> ir::Type {
199         ir::Type::int(u16::from(self.pointer_bits())).unwrap()
200     }
201 
202     /// Get the width of pointers on this target, in units of bits.
203     pub fn pointer_bits(self) -> u8 {
204         self.pointer_width.bits()
205     }
206 
207     /// Get the width of pointers on this target, in units of bytes.
208     pub fn pointer_bytes(self) -> u8 {
209         self.pointer_width.bytes()
210     }
211 }
212 
213 /// Methods that are specialized to a target ISA.
214 ///
215 /// Implies a Display trait that shows the shared flags, as well as any ISA-specific flags.
216 pub trait TargetIsa: fmt::Display + Send + Sync {
217     /// Get the name of this ISA.
218     fn name(&self) -> &'static str;
219 
220     /// Get the target triple that was used to make this trait object.
221     fn triple(&self) -> &Triple;
222 
223     /// Get the ISA-independent flags that were used to make this trait object.
224     fn flags(&self) -> &settings::Flags;
225 
226     /// Get the ISA-dependent flag values that were used to make this trait object.
227     fn isa_flags(&self) -> Vec<settings::Value>;
228 
229     /// Compile the given function.
230     fn compile_function(
231         &self,
232         func: &Function,
233         want_disasm: bool,
234     ) -> CodegenResult<MachCompileResult>;
235 
236     #[cfg(feature = "unwind")]
237     /// Map a regalloc::Reg to its corresponding DWARF register.
238     fn map_regalloc_reg_to_dwarf(&self, _: ::regalloc::Reg) -> Result<u16, RegisterMappingError> {
239         Err(RegisterMappingError::UnsupportedArchitecture)
240     }
241 
242     /// IntCC condition for Unsigned Addition Overflow (Carry).
243     fn unsigned_add_overflow_condition(&self) -> ir::condcodes::IntCC;
244 
245     /// Creates unwind information for the function.
246     ///
247     /// Returns `None` if there is no unwind information for the function.
248     #[cfg(feature = "unwind")]
249     fn emit_unwind_info(
250         &self,
251         result: &MachCompileResult,
252         kind: UnwindInfoKind,
253     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>>;
254 
255     /// Creates a new System V Common Information Entry for the ISA.
256     ///
257     /// Returns `None` if the ISA does not support System V unwind information.
258     #[cfg(feature = "unwind")]
259     fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
260         // By default, an ISA cannot create a System V CIE
261         None
262     }
263 
264     /// Returns an object that can be used to build the text section of an
265     /// executable.
266     ///
267     /// This object will internally attempt to handle as many relocations as
268     /// possible using relative calls/jumps/etc between functions.
269     ///
270     /// The `num_labeled_funcs` argument here is the number of functions which
271     /// will be "labeled" or might have calls between them, typically the number
272     /// of defined functions in the object file.
273     fn text_section_builder(&self, num_labeled_funcs: u32) -> Box<dyn TextSectionBuilder>;
274 }
275 
276 /// Methods implemented for free for target ISA!
277 impl<'a> dyn TargetIsa + 'a {
278     /// Get the default calling convention of this target.
279     pub fn default_call_conv(&self) -> CallConv {
280         CallConv::triple_default(self.triple())
281     }
282 
283     /// Get the endianness of this ISA.
284     pub fn endianness(&self) -> ir::Endianness {
285         match self.triple().endianness().unwrap() {
286             target_lexicon::Endianness::Little => ir::Endianness::Little,
287             target_lexicon::Endianness::Big => ir::Endianness::Big,
288         }
289     }
290 
291     /// Returns the code (text) section alignment for this ISA.
292     pub fn code_section_alignment(&self) -> u64 {
293         use target_lexicon::*;
294         match (self.triple().operating_system, self.triple().architecture) {
295             (
296                 OperatingSystem::MacOSX { .. }
297                 | OperatingSystem::Darwin
298                 | OperatingSystem::Ios
299                 | OperatingSystem::Tvos,
300                 Architecture::Aarch64(..),
301             ) => 0x4000,
302             // 64 KB is the maximal page size (i.e. memory translation granule size)
303             // supported by the architecture and is used on some platforms.
304             (_, Architecture::Aarch64(..)) => 0x10000,
305             _ => 0x1000,
306         }
307     }
308 
309     /// Get the pointer type of this ISA.
310     pub fn pointer_type(&self) -> ir::Type {
311         ir::Type::int(u16::from(self.pointer_bits())).unwrap()
312     }
313 
314     /// Get the width of pointers on this ISA.
315     pub(crate) fn pointer_width(&self) -> PointerWidth {
316         self.triple().pointer_width().unwrap()
317     }
318 
319     /// Get the width of pointers on this ISA, in units of bits.
320     pub fn pointer_bits(&self) -> u8 {
321         self.pointer_width().bits()
322     }
323 
324     /// Get the width of pointers on this ISA, in units of bytes.
325     pub fn pointer_bytes(&self) -> u8 {
326         self.pointer_width().bytes()
327     }
328 
329     /// Get the information needed by frontends producing Cranelift IR.
330     pub fn frontend_config(&self) -> TargetFrontendConfig {
331         TargetFrontendConfig {
332             default_call_conv: self.default_call_conv(),
333             pointer_width: self.pointer_width(),
334         }
335     }
336 
337     /// Returns the flavor of unwind information emitted for this target.
338     pub(crate) fn unwind_info_kind(&self) -> UnwindInfoKind {
339         match self.triple().operating_system {
340             #[cfg(feature = "unwind")]
341             OperatingSystem::Windows => UnwindInfoKind::Windows,
342             #[cfg(feature = "unwind")]
343             _ => UnwindInfoKind::SystemV,
344             #[cfg(not(feature = "unwind"))]
345             _ => UnwindInfoKind::None,
346         }
347     }
348 }
349 
350 impl Debug for &dyn TargetIsa {
351     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
352         write!(
353             f,
354             "TargetIsa {{ triple: {:?}, pointer_width: {:?}}}",
355             self.triple(),
356             self.pointer_width()
357         )
358     }
359 }
360