cranelift_codegen/machinst/
mod.rs

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