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