1 //! This module exposes the machine-specific backend definition pieces. 2 //! 3 //! The MachInst infrastructure is the compiler backend, from CLIF 4 //! (ir::Function) to machine code. The purpose of this infrastructure is, at a 5 //! high level, to do instruction selection/lowering (to machine instructions), 6 //! register allocation, and then perform all the fixups to branches, constant 7 //! data references, etc., needed to actually generate machine code. 8 //! 9 //! The container for machine instructions, at various stages of construction, 10 //! is the `VCode` struct. We refer to a sequence of machine instructions organized 11 //! into basic blocks as "vcode". This is short for "virtual-register code". 12 //! 13 //! The compilation pipeline, from an `ir::Function` (already optimized as much as 14 //! you like by machine-independent optimization passes) onward, is as follows. 15 //! 16 //! ```plain 17 //! 18 //! ir::Function (SSA IR, machine-independent opcodes) 19 //! | 20 //! | [lower] 21 //! | 22 //! VCode<arch_backend::Inst> (machine instructions: 23 //! | - mostly virtual registers. 24 //! | - cond branches in two-target form. 25 //! | - branch targets are block indices. 26 //! | - in-memory constants held by insns, 27 //! | with unknown offsets. 28 //! | - critical edges (actually all edges) 29 //! | are split.) 30 //! | 31 //! | [regalloc --> `regalloc2::Output`; VCode is unchanged] 32 //! | 33 //! | [binary emission via MachBuffer] 34 //! | 35 //! Vec<u8> (machine code: 36 //! | - two-dest branches resolved via 37 //! | streaming branch resolution/simplification. 38 //! | - regalloc `Allocation` results used directly 39 //! | by instruction emission code. 40 //! | - prologue and epilogue(s) built and emitted 41 //! | directly during emission. 42 //! | - nominal-SP-relative offsets resolved 43 //! | by tracking EmitState.) 44 //! 45 //! ``` 46 47 use crate::binemit::{Addend, CodeInfo, CodeOffset, Reloc, StackMap}; 48 use crate::ir::function::FunctionParameters; 49 use crate::ir::{DynamicStackSlot, RelSourceLoc, StackSlot, Type}; 50 use crate::isa::FunctionAlignment; 51 use crate::result::CodegenResult; 52 use crate::settings; 53 use crate::settings::Flags; 54 use crate::value_label::ValueLabelsRanges; 55 use alloc::vec::Vec; 56 use core::fmt::Debug; 57 use cranelift_control::ControlPlane; 58 use cranelift_entity::PrimaryMap; 59 use regalloc2::{Allocation, VReg}; 60 use smallvec::{smallvec, SmallVec}; 61 use std::string::String; 62 63 #[cfg(feature = "enable-serde")] 64 use serde_derive::{Deserialize, Serialize}; 65 66 #[macro_use] 67 pub mod isle; 68 69 pub mod lower; 70 pub use lower::*; 71 pub mod vcode; 72 pub use vcode::*; 73 pub mod compile; 74 pub use compile::*; 75 pub mod blockorder; 76 pub use blockorder::*; 77 pub mod abi; 78 pub use abi::*; 79 pub mod buffer; 80 pub use buffer::*; 81 pub mod helpers; 82 pub use helpers::*; 83 pub mod inst_common; 84 #[allow(unused_imports)] // not used in all backends right now 85 pub use inst_common::*; 86 pub mod valueregs; 87 pub use reg::*; 88 pub use valueregs::*; 89 pub mod pcc; 90 pub mod reg; 91 92 /// A machine instruction. 93 pub trait MachInst: Clone + Debug { 94 /// The ABI machine spec for this `MachInst`. 95 type ABIMachineSpec: ABIMachineSpec<I = Self>; 96 97 /// Return the registers referenced by this machine instruction along with 98 /// the modes of reference (use, def, modify). 99 fn get_operands(&mut self, collector: &mut impl OperandVisitor); 100 101 /// If this is a simple move, return the (source, destination) tuple of registers. 102 fn is_move(&self) -> Option<(Writable<Reg>, Reg)>; 103 104 /// Is this a terminator (branch or ret)? If so, return its type 105 /// (ret/uncond/cond) and target if applicable. 106 fn is_term(&self) -> MachTerminator; 107 108 /// Is this an unconditional trap? 109 fn is_trap(&self) -> bool; 110 111 /// Is this an "args" pseudoinst? 112 fn is_args(&self) -> bool; 113 114 /// Should this instruction be included in the clobber-set? 115 fn is_included_in_clobbers(&self) -> bool; 116 117 /// Does this instruction access memory? 118 fn is_mem_access(&self) -> bool; 119 120 /// Generate a move. 121 fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self; 122 123 /// Generate a dummy instruction that will keep a value alive but 124 /// has no other purpose. 125 fn gen_dummy_use(reg: Reg) -> Self; 126 127 /// Determine register class(es) to store the given Cranelift type, and the 128 /// Cranelift type actually stored in the underlying register(s). May return 129 /// an error if the type isn't supported by this backend. 130 /// 131 /// If the type requires multiple registers, then the list of registers is 132 /// returned in little-endian order. 133 /// 134 /// Note that the type actually stored in the register(s) may differ in the 135 /// case that a value is split across registers: for example, on a 32-bit 136 /// target, an I64 may be stored in two registers, each of which holds an 137 /// I32. The actually-stored types are used only to inform the backend when 138 /// generating spills and reloads for individual registers. 139 fn rc_for_type(ty: Type) -> CodegenResult<(&'static [RegClass], &'static [Type])>; 140 141 /// Get an appropriate type that can fully hold a value in a given 142 /// register class. This may not be the only type that maps to 143 /// that class, but when used with `gen_move()` or the ABI trait's 144 /// load/spill constructors, it should produce instruction(s) that 145 /// move the entire register contents. 146 fn canonical_type_for_rc(rc: RegClass) -> Type; 147 148 /// Generate a jump to another target. Used during lowering of 149 /// control flow. 150 fn gen_jump(target: MachLabel) -> Self; 151 152 /// Generate a store of an immediate 64-bit integer to a register. Used by 153 /// the control plane to generate random instructions. 154 fn gen_imm_u64(_value: u64, _dst: Writable<Reg>) -> Option<Self> { 155 None 156 } 157 158 /// Generate a store of an immediate 64-bit integer to a register. Used by 159 /// the control plane to generate random instructions. The tmp register may 160 /// be used by architectures which don't support writing immediate values to 161 /// floating point registers directly. 162 fn gen_imm_f64(_value: f64, _tmp: Writable<Reg>, _dst: Writable<Reg>) -> SmallVec<[Self; 2]> { 163 SmallVec::new() 164 } 165 166 /// Generate a NOP. The `preferred_size` parameter allows the caller to 167 /// request a NOP of that size, or as close to it as possible. The machine 168 /// backend may return a NOP whose binary encoding is smaller than the 169 /// preferred size, but must not return a NOP that is larger. However, 170 /// the instruction must have a nonzero size if preferred_size is nonzero. 171 fn gen_nop(preferred_size: usize) -> Self; 172 173 /// Align a basic block offset (from start of function). By default, no 174 /// alignment occurs. 175 fn align_basic_block(offset: CodeOffset) -> CodeOffset { 176 offset 177 } 178 179 /// What is the worst-case instruction size emitted by this instruction type? 180 fn worst_case_size() -> CodeOffset; 181 182 /// What is the register class used for reference types (GC-observable pointers)? Can 183 /// be dependent on compilation flags. 184 fn ref_type_regclass(_flags: &Flags) -> RegClass; 185 186 /// Is this a safepoint? 187 fn is_safepoint(&self) -> bool; 188 189 /// Generate an instruction that must appear at the beginning of a basic 190 /// block, if any. Note that the return value must not be subject to 191 /// register allocation. 192 fn gen_block_start( 193 _is_indirect_branch_target: bool, 194 _is_forward_edge_cfi_enabled: bool, 195 ) -> Option<Self> { 196 None 197 } 198 199 /// Returns a description of the alignment required for functions for this 200 /// architecture. 201 fn function_alignment() -> FunctionAlignment; 202 203 /// A label-use kind: a type that describes the types of label references that 204 /// can occur in an instruction. 205 type LabelUse: MachInstLabelUse; 206 207 /// Byte representation of a trap opcode which is inserted by `MachBuffer` 208 /// during its `defer_trap` method. 209 const TRAP_OPCODE: &'static [u8]; 210 } 211 212 /// A descriptor of a label reference (use) in an instruction set. 213 pub trait MachInstLabelUse: Clone + Copy + Debug + Eq { 214 /// Required alignment for any veneer. Usually the required instruction 215 /// alignment (e.g., 4 for a RISC with 32-bit instructions, or 1 for x86). 216 const ALIGN: CodeOffset; 217 218 /// What is the maximum PC-relative range (positive)? E.g., if `1024`, a 219 /// label-reference fixup at offset `x` is valid if the label resolves to `x 220 /// + 1024`. 221 fn max_pos_range(self) -> CodeOffset; 222 /// What is the maximum PC-relative range (negative)? This is the absolute 223 /// value; i.e., if `1024`, then a label-reference fixup at offset `x` is 224 /// valid if the label resolves to `x - 1024`. 225 fn max_neg_range(self) -> CodeOffset; 226 /// What is the size of code-buffer slice this label-use needs to patch in 227 /// the label's value? 228 fn patch_size(self) -> CodeOffset; 229 /// Perform a code-patch, given the offset into the buffer of this label use 230 /// and the offset into the buffer of the label's definition. 231 /// It is guaranteed that, given `delta = offset - label_offset`, we will 232 /// have `offset >= -self.max_neg_range()` and `offset <= 233 /// self.max_pos_range()`. 234 fn patch(self, buffer: &mut [u8], use_offset: CodeOffset, label_offset: CodeOffset); 235 /// Can the label-use be patched to a veneer that supports a longer range? 236 /// Usually valid for jumps (a short-range jump can jump to a longer-range 237 /// jump), but not for e.g. constant pool references, because the constant 238 /// load would require different code (one more level of indirection). 239 fn supports_veneer(self) -> bool; 240 /// How many bytes are needed for a veneer? 241 fn veneer_size(self) -> CodeOffset; 242 /// What's the largest possible veneer that may be generated? 243 fn worst_case_veneer_size() -> CodeOffset; 244 /// Generate a veneer. The given code-buffer slice is `self.veneer_size()` 245 /// bytes long at offset `veneer_offset` in the buffer. The original 246 /// label-use will be patched to refer to this veneer's offset. A new 247 /// (offset, LabelUse) is returned that allows the veneer to use the actual 248 /// label. For veneers to work properly, it is expected that the new veneer 249 /// has a larger range; on most platforms this probably means either a 250 /// "long-range jump" (e.g., on ARM, the 26-bit form), or if already at that 251 /// stage, a jump that supports a full 32-bit range, for example. 252 fn generate_veneer(self, buffer: &mut [u8], veneer_offset: CodeOffset) -> (CodeOffset, Self); 253 254 /// Returns the corresponding label-use for the relocation specified. 255 /// 256 /// This returns `None` if the relocation doesn't have a corresponding 257 /// representation for the target architecture. 258 fn from_reloc(reloc: Reloc, addend: Addend) -> Option<Self>; 259 } 260 261 /// Describes a block terminator (not call) in the vcode, when its branches 262 /// have not yet been finalized (so a branch may have two targets). 263 /// 264 /// Actual targets are not included: the single-source-of-truth for 265 /// those is the VCode itself, which holds, for each block, successors 266 /// and outgoing branch args per successor. 267 #[derive(Clone, Debug, PartialEq, Eq)] 268 pub enum MachTerminator { 269 /// Not a terminator. 270 None, 271 /// A return instruction. 272 Ret, 273 /// A tail call. 274 RetCall, 275 /// An unconditional branch to another block. 276 Uncond, 277 /// A conditional branch to one of two other blocks. 278 Cond, 279 /// An indirect branch with known possible targets. 280 Indirect, 281 } 282 283 /// A trait describing the ability to encode a MachInst into binary machine code. 284 pub trait MachInstEmit: MachInst { 285 /// Persistent state carried across `emit` invocations. 286 type State: MachInstEmitState<Self>; 287 /// Constant information used in `emit` invocations. 288 type Info; 289 /// Emit the instruction. 290 fn emit( 291 &self, 292 allocs: &[Allocation], 293 code: &mut MachBuffer<Self>, 294 info: &Self::Info, 295 state: &mut Self::State, 296 ); 297 /// Pretty-print the instruction. 298 fn pretty_print_inst(&self, allocs: &[Allocation], state: &mut Self::State) -> String; 299 } 300 301 /// A trait describing the emission state carried between MachInsts when 302 /// emitting a function body. 303 pub trait MachInstEmitState<I: VCodeInst>: Default + Clone + Debug { 304 /// Create a new emission state given the ABI object. 305 fn new(abi: &Callee<I::ABIMachineSpec>, ctrl_plane: ControlPlane) -> Self; 306 /// Update the emission state before emitting an instruction that is a 307 /// safepoint. 308 fn pre_safepoint(&mut self, _stack_map: StackMap) {} 309 /// The emission state holds ownership of a control plane, so it doesn't 310 /// have to be passed around explicitly too much. `ctrl_plane_mut` may 311 /// be used if temporary access to the control plane is needed by some 312 /// other function that doesn't have access to the emission state. 313 fn ctrl_plane_mut(&mut self) -> &mut ControlPlane; 314 /// Used to continue using a control plane after the emission state is 315 /// not needed anymore. 316 fn take_ctrl_plane(self) -> ControlPlane; 317 /// A hook that triggers when first emitting a new block. 318 /// It is guaranteed to be called before any instructions are emitted. 319 fn on_new_block(&mut self) {} 320 } 321 322 /// The result of a `MachBackend::compile_function()` call. Contains machine 323 /// code (as bytes) and a disassembly, if requested. 324 #[derive(PartialEq, Debug, Clone)] 325 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] 326 pub struct CompiledCodeBase<T: CompilePhase> { 327 /// Machine code. 328 pub buffer: MachBufferFinalized<T>, 329 /// Size of stack frame, in bytes. 330 pub frame_size: u32, 331 /// Disassembly, if requested. 332 pub vcode: Option<String>, 333 /// Debug info: value labels to registers/stackslots at code offsets. 334 pub value_labels_ranges: ValueLabelsRanges, 335 /// Debug info: stackslots to stack pointer offsets. 336 pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>, 337 /// Debug info: stackslots to stack pointer offsets. 338 pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>, 339 /// Basic-block layout info: block start offsets. 340 /// 341 /// This info is generated only if the `machine_code_cfg_info` 342 /// flag is set. 343 pub bb_starts: Vec<CodeOffset>, 344 /// Basic-block layout info: block edges. Each edge is `(from, 345 /// to)`, where `from` and `to` are basic-block start offsets of 346 /// the respective blocks. 347 /// 348 /// This info is generated only if the `machine_code_cfg_info` 349 /// flag is set. 350 pub bb_edges: Vec<(CodeOffset, CodeOffset)>, 351 } 352 353 impl CompiledCodeStencil { 354 /// Apply function parameters to finalize a stencil into its final form. 355 pub fn apply_params(self, params: &FunctionParameters) -> CompiledCode { 356 CompiledCode { 357 buffer: self.buffer.apply_base_srcloc(params.base_srcloc()), 358 frame_size: self.frame_size, 359 vcode: self.vcode, 360 value_labels_ranges: self.value_labels_ranges, 361 sized_stackslot_offsets: self.sized_stackslot_offsets, 362 dynamic_stackslot_offsets: self.dynamic_stackslot_offsets, 363 bb_starts: self.bb_starts, 364 bb_edges: self.bb_edges, 365 } 366 } 367 } 368 369 impl<T: CompilePhase> CompiledCodeBase<T> { 370 /// Get a `CodeInfo` describing section sizes from this compilation result. 371 pub fn code_info(&self) -> CodeInfo { 372 CodeInfo { 373 total_size: self.buffer.total_size(), 374 } 375 } 376 377 /// Returns a reference to the machine code generated for this function compilation. 378 pub fn code_buffer(&self) -> &[u8] { 379 self.buffer.data() 380 } 381 382 /// Get the disassembly of the buffer, using the given capstone context. 383 #[cfg(feature = "disas")] 384 pub fn disassemble( 385 &self, 386 params: Option<&crate::ir::function::FunctionParameters>, 387 cs: &capstone::Capstone, 388 ) -> Result<String, anyhow::Error> { 389 use std::fmt::Write; 390 391 let mut buf = String::new(); 392 393 let relocs = self.buffer.relocs(); 394 let traps = self.buffer.traps(); 395 396 // Normalize the block starts to include an initial block of offset 0. 397 let mut block_starts = Vec::new(); 398 if self.bb_starts.first().copied() != Some(0) { 399 block_starts.push(0); 400 } 401 block_starts.extend_from_slice(&self.bb_starts); 402 block_starts.push(self.buffer.data().len() as u32); 403 404 // Iterate over block regions, to ensure that we always produce block labels 405 for (n, (&start, &end)) in block_starts 406 .iter() 407 .zip(block_starts.iter().skip(1)) 408 .enumerate() 409 { 410 writeln!(buf, "block{}: ; offset 0x{:x}", n, start)?; 411 412 let buffer = &self.buffer.data()[start as usize..end as usize]; 413 let insns = cs.disasm_all(buffer, start as u64).map_err(map_caperr)?; 414 for i in insns.iter() { 415 write!(buf, " ")?; 416 417 let op_str = i.op_str().unwrap_or(""); 418 if let Some(s) = i.mnemonic() { 419 write!(buf, "{}", s)?; 420 if !op_str.is_empty() { 421 write!(buf, " ")?; 422 } 423 } 424 425 write!(buf, "{}", op_str)?; 426 427 let end = i.address() + i.bytes().len() as u64; 428 let contains = |off| i.address() <= off && off < end; 429 430 for reloc in relocs.iter().filter(|reloc| contains(reloc.offset as u64)) { 431 write!( 432 buf, 433 " ; reloc_external {} {} {}", 434 reloc.kind, 435 reloc.target.display(params), 436 reloc.addend, 437 )?; 438 } 439 440 if let Some(trap) = traps.iter().find(|trap| contains(trap.offset as u64)) { 441 write!(buf, " ; trap: {}", trap.code)?; 442 } 443 444 writeln!(buf)?; 445 } 446 } 447 448 return Ok(buf); 449 450 fn map_caperr(err: capstone::Error) -> anyhow::Error { 451 anyhow::format_err!("{}", err) 452 } 453 } 454 } 455 456 /// Result of compiling a `FunctionStencil`, before applying `FunctionParameters` onto it. 457 /// 458 /// Only used internally, in a transient manner, for the incremental compilation cache. 459 pub type CompiledCodeStencil = CompiledCodeBase<Stencil>; 460 461 /// `CompiledCode` in its final form (i.e. after `FunctionParameters` have been applied), ready for 462 /// consumption. 463 pub type CompiledCode = CompiledCodeBase<Final>; 464 465 impl CompiledCode { 466 /// If available, return information about the code layout in the 467 /// final machine code: the offsets (in bytes) of each basic-block 468 /// start, and all basic-block edges. 469 pub fn get_code_bb_layout(&self) -> (Vec<usize>, Vec<(usize, usize)>) { 470 ( 471 self.bb_starts.iter().map(|&off| off as usize).collect(), 472 self.bb_edges 473 .iter() 474 .map(|&(from, to)| (from as usize, to as usize)) 475 .collect(), 476 ) 477 } 478 479 /// Creates unwind information for the function. 480 /// 481 /// Returns `None` if the function has no unwind information. 482 #[cfg(feature = "unwind")] 483 pub fn create_unwind_info( 484 &self, 485 isa: &dyn crate::isa::TargetIsa, 486 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> { 487 use crate::isa::unwind::UnwindInfoKind; 488 let unwind_info_kind = match isa.triple().operating_system { 489 target_lexicon::OperatingSystem::Windows => UnwindInfoKind::Windows, 490 _ => UnwindInfoKind::SystemV, 491 }; 492 self.create_unwind_info_of_kind(isa, unwind_info_kind) 493 } 494 495 /// Creates unwind information for the function using the supplied 496 /// "kind". Supports cross-OS (but not cross-arch) generation. 497 /// 498 /// Returns `None` if the function has no unwind information. 499 #[cfg(feature = "unwind")] 500 pub fn create_unwind_info_of_kind( 501 &self, 502 isa: &dyn crate::isa::TargetIsa, 503 unwind_info_kind: crate::isa::unwind::UnwindInfoKind, 504 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> { 505 isa.emit_unwind_info(self, unwind_info_kind) 506 } 507 } 508 509 /// An object that can be used to create the text section of an executable. 510 /// 511 /// This primarily handles resolving relative relocations at 512 /// text-section-assembly time rather than at load/link time. This 513 /// architecture-specific logic is sort of like a linker, but only for one 514 /// object file at a time. 515 pub trait TextSectionBuilder { 516 /// Appends `data` to the text section with the `align` specified. 517 /// 518 /// If `labeled` is `true` then this also binds the appended data to the 519 /// `n`th label for how many times this has been called with `labeled: 520 /// true`. The label target can be passed as the `target` argument to 521 /// `resolve_reloc`. 522 /// 523 /// This function returns the offset at which the data was placed in the 524 /// text section. 525 fn append( 526 &mut self, 527 labeled: bool, 528 data: &[u8], 529 align: u32, 530 ctrl_plane: &mut ControlPlane, 531 ) -> u64; 532 533 /// Attempts to resolve a relocation for this function. 534 /// 535 /// The `offset` is the offset of the relocation, within the text section. 536 /// The `reloc` is the kind of relocation. 537 /// The `addend` is the value to add to the relocation. 538 /// The `target` is the labeled function that is the target of this 539 /// relocation. 540 /// 541 /// Labeled functions are created with the `append` function above by 542 /// setting the `labeled` parameter to `true`. 543 /// 544 /// If this builder does not know how to handle `reloc` then this function 545 /// will return `false`. Otherwise this function will return `true` and this 546 /// relocation will be resolved in the final bytes returned by `finish`. 547 fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool; 548 549 /// A debug-only option which is used to for 550 fn force_veneers(&mut self); 551 552 /// Completes this text section, filling out any final details, and returns 553 /// the bytes of the text section. 554 fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8>; 555 } 556