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::result::CodegenResult;
51 use crate::settings::Flags;
52 use crate::value_label::ValueLabelsRanges;
53 use alloc::vec::Vec;
54 use core::fmt::Debug;
55 use cranelift_entity::PrimaryMap;
56 use regalloc2::{Allocation, VReg};
57 use smallvec::{smallvec, SmallVec};
58 use std::string::String;
59 
60 #[cfg(feature = "enable-serde")]
61 use serde::{Deserialize, Serialize};
62 
63 #[macro_use]
64 pub mod isle;
65 
66 pub mod lower;
67 pub use lower::*;
68 pub mod vcode;
69 pub use vcode::*;
70 pub mod compile;
71 pub use compile::*;
72 pub mod blockorder;
73 pub use blockorder::*;
74 pub mod abi;
75 pub use abi::*;
76 pub mod buffer;
77 pub use buffer::*;
78 pub mod helpers;
79 pub use helpers::*;
80 pub mod inst_common;
81 pub use inst_common::*;
82 pub mod valueregs;
83 pub use reg::*;
84 pub use valueregs::*;
85 pub mod reg;
86 
87 /// A machine instruction.
88 pub trait MachInst: Clone + Debug {
89     /// The ABI machine spec for this `MachInst`.
90     type ABIMachineSpec: ABIMachineSpec<I = Self>;
91 
92     /// Return the registers referenced by this machine instruction along with
93     /// the modes of reference (use, def, modify).
94     fn get_operands<F: Fn(VReg) -> VReg>(&self, collector: &mut OperandCollector<'_, F>);
95 
96     /// If this is a simple move, return the (source, destination) tuple of registers.
97     fn is_move(&self) -> Option<(Writable<Reg>, Reg)>;
98 
99     /// Is this a terminator (branch or ret)? If so, return its type
100     /// (ret/uncond/cond) and target if applicable.
101     fn is_term(&self) -> MachTerminator;
102 
103     /// Should this instruction be included in the clobber-set?
104     fn is_included_in_clobbers(&self) -> bool {
105         true
106     }
107 
108     /// Generate a move.
109     fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self;
110 
111     /// Generate a constant into a reg.
112     fn gen_constant<F: FnMut(Type) -> Writable<Reg>>(
113         to_regs: ValueRegs<Writable<Reg>>,
114         value: u128,
115         ty: Type,
116         alloc_tmp: F,
117     ) -> SmallVec<[Self; 4]>;
118 
119     /// Generate a dummy instruction that will keep a value alive but
120     /// has no other purpose.
121     fn gen_dummy_use(reg: Reg) -> Self;
122 
123     /// Determine register class(es) to store the given Cranelift type, and the
124     /// Cranelift type actually stored in the underlying register(s).  May return
125     /// an error if the type isn't supported by this backend.
126     ///
127     /// If the type requires multiple registers, then the list of registers is
128     /// returned in little-endian order.
129     ///
130     /// Note that the type actually stored in the register(s) may differ in the
131     /// case that a value is split across registers: for example, on a 32-bit
132     /// target, an I64 may be stored in two registers, each of which holds an
133     /// I32. The actually-stored types are used only to inform the backend when
134     /// generating spills and reloads for individual registers.
135     fn rc_for_type(ty: Type) -> CodegenResult<(&'static [RegClass], &'static [Type])>;
136 
137     /// Get an appropriate type that can fully hold a value in a given
138     /// register class. This may not be the only type that maps to
139     /// that class, but when used with `gen_move()` or the ABI trait's
140     /// load/spill constructors, it should produce instruction(s) that
141     /// move the entire register contents.
142     fn canonical_type_for_rc(rc: RegClass) -> Type;
143 
144     /// Generate a jump to another target. Used during lowering of
145     /// control flow.
146     fn gen_jump(target: MachLabel) -> Self;
147 
148     /// Generate a NOP. The `preferred_size` parameter allows the caller to
149     /// request a NOP of that size, or as close to it as possible. The machine
150     /// backend may return a NOP whose binary encoding is smaller than the
151     /// preferred size, but must not return a NOP that is larger. However,
152     /// the instruction must have a nonzero size if preferred_size is nonzero.
153     fn gen_nop(preferred_size: usize) -> Self;
154 
155     /// Align a basic block offset (from start of function).  By default, no
156     /// alignment occurs.
157     fn align_basic_block(offset: CodeOffset) -> CodeOffset {
158         offset
159     }
160 
161     /// What is the worst-case instruction size emitted by this instruction type?
162     fn worst_case_size() -> CodeOffset;
163 
164     /// What is the register class used for reference types (GC-observable pointers)? Can
165     /// be dependent on compilation flags.
166     fn ref_type_regclass(_flags: &Flags) -> RegClass;
167 
168     /// Is this a safepoint?
169     fn is_safepoint(&self) -> bool;
170 
171     /// A label-use kind: a type that describes the types of label references that
172     /// can occur in an instruction.
173     type LabelUse: MachInstLabelUse;
174 }
175 
176 /// A descriptor of a label reference (use) in an instruction set.
177 pub trait MachInstLabelUse: Clone + Copy + Debug + Eq {
178     /// Required alignment for any veneer. Usually the required instruction
179     /// alignment (e.g., 4 for a RISC with 32-bit instructions, or 1 for x86).
180     const ALIGN: CodeOffset;
181 
182     /// What is the maximum PC-relative range (positive)? E.g., if `1024`, a
183     /// label-reference fixup at offset `x` is valid if the label resolves to `x
184     /// + 1024`.
185     fn max_pos_range(self) -> CodeOffset;
186     /// What is the maximum PC-relative range (negative)? This is the absolute
187     /// value; i.e., if `1024`, then a label-reference fixup at offset `x` is
188     /// valid if the label resolves to `x - 1024`.
189     fn max_neg_range(self) -> CodeOffset;
190     /// What is the size of code-buffer slice this label-use needs to patch in
191     /// the label's value?
192     fn patch_size(self) -> CodeOffset;
193     /// Perform a code-patch, given the offset into the buffer of this label use
194     /// and the offset into the buffer of the label's definition.
195     /// It is guaranteed that, given `delta = offset - label_offset`, we will
196     /// have `offset >= -self.max_neg_range()` and `offset <=
197     /// self.max_pos_range()`.
198     fn patch(self, buffer: &mut [u8], use_offset: CodeOffset, label_offset: CodeOffset);
199     /// Can the label-use be patched to a veneer that supports a longer range?
200     /// Usually valid for jumps (a short-range jump can jump to a longer-range
201     /// jump), but not for e.g. constant pool references, because the constant
202     /// load would require different code (one more level of indirection).
203     fn supports_veneer(self) -> bool;
204     /// How many bytes are needed for a veneer?
205     fn veneer_size(self) -> CodeOffset;
206     /// Generate a veneer. The given code-buffer slice is `self.veneer_size()`
207     /// bytes long at offset `veneer_offset` in the buffer. The original
208     /// label-use will be patched to refer to this veneer's offset.  A new
209     /// (offset, LabelUse) is returned that allows the veneer to use the actual
210     /// label. For veneers to work properly, it is expected that the new veneer
211     /// has a larger range; on most platforms this probably means either a
212     /// "long-range jump" (e.g., on ARM, the 26-bit form), or if already at that
213     /// stage, a jump that supports a full 32-bit range, for example.
214     fn generate_veneer(self, buffer: &mut [u8], veneer_offset: CodeOffset) -> (CodeOffset, Self);
215 
216     /// Returns the corresponding label-use for the relocation specified.
217     ///
218     /// This returns `None` if the relocation doesn't have a corresponding
219     /// representation for the target architecture.
220     fn from_reloc(reloc: Reloc, addend: Addend) -> Option<Self>;
221 }
222 
223 /// Describes a block terminator (not call) in the vcode, when its branches
224 /// have not yet been finalized (so a branch may have two targets).
225 ///
226 /// Actual targets are not included: the single-source-of-truth for
227 /// those is the VCode itself, which holds, for each block, successors
228 /// and outgoing branch args per successor.
229 #[derive(Clone, Debug, PartialEq, Eq)]
230 pub enum MachTerminator {
231     /// Not a terminator.
232     None,
233     /// A return instruction.
234     Ret,
235     /// An unconditional branch to another block.
236     Uncond,
237     /// A conditional branch to one of two other blocks.
238     Cond,
239     /// An indirect branch with known possible targets.
240     Indirect,
241 }
242 
243 /// A trait describing the ability to encode a MachInst into binary machine code.
244 pub trait MachInstEmit: MachInst {
245     /// Persistent state carried across `emit` invocations.
246     type State: MachInstEmitState<Self>;
247     /// Constant information used in `emit` invocations.
248     type Info;
249     /// Emit the instruction.
250     fn emit(
251         &self,
252         allocs: &[Allocation],
253         code: &mut MachBuffer<Self>,
254         info: &Self::Info,
255         state: &mut Self::State,
256     );
257     /// Pretty-print the instruction.
258     fn pretty_print_inst(&self, allocs: &[Allocation], state: &mut Self::State) -> String;
259 }
260 
261 /// A trait describing the emission state carried between MachInsts when
262 /// emitting a function body.
263 pub trait MachInstEmitState<I: VCodeInst>: Default + Clone + Debug {
264     /// Create a new emission state given the ABI object.
265     fn new(abi: &Callee<I::ABIMachineSpec>) -> Self;
266     /// Update the emission state before emitting an instruction that is a
267     /// safepoint.
268     fn pre_safepoint(&mut self, _stack_map: StackMap) {}
269     /// Update the emission state to indicate instructions are associated with a
270     /// particular RelSourceLoc.
271     fn pre_sourceloc(&mut self, _srcloc: RelSourceLoc) {}
272 }
273 
274 /// The result of a `MachBackend::compile_function()` call. Contains machine
275 /// code (as bytes) and a disassembly, if requested.
276 #[derive(PartialEq, Debug, Clone)]
277 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
278 pub struct CompiledCodeBase<T: CompilePhase> {
279     /// Machine code.
280     pub buffer: MachBufferFinalized<T>,
281     /// Size of stack frame, in bytes.
282     pub frame_size: u32,
283     /// Disassembly, if requested.
284     pub disasm: Option<String>,
285     /// Debug info: value labels to registers/stackslots at code offsets.
286     pub value_labels_ranges: ValueLabelsRanges,
287     /// Debug info: stackslots to stack pointer offsets.
288     pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>,
289     /// Debug info: stackslots to stack pointer offsets.
290     pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>,
291     /// Basic-block layout info: block start offsets.
292     ///
293     /// This info is generated only if the `machine_code_cfg_info`
294     /// flag is set.
295     pub bb_starts: Vec<CodeOffset>,
296     /// Basic-block layout info: block edges. Each edge is `(from,
297     /// to)`, where `from` and `to` are basic-block start offsets of
298     /// the respective blocks.
299     ///
300     /// This info is generated only if the `machine_code_cfg_info`
301     /// flag is set.
302     pub bb_edges: Vec<(CodeOffset, CodeOffset)>,
303 }
304 
305 impl CompiledCodeStencil {
306     /// Apply function parameters to finalize a stencil into its final form.
307     pub fn apply_params(self, params: &FunctionParameters) -> CompiledCode {
308         CompiledCode {
309             buffer: self.buffer.apply_params(params),
310             frame_size: self.frame_size,
311             disasm: self.disasm,
312             value_labels_ranges: self.value_labels_ranges,
313             sized_stackslot_offsets: self.sized_stackslot_offsets,
314             dynamic_stackslot_offsets: self.dynamic_stackslot_offsets,
315             bb_starts: self.bb_starts,
316             bb_edges: self.bb_edges,
317         }
318     }
319 }
320 
321 impl<T: CompilePhase> CompiledCodeBase<T> {
322     /// Get a `CodeInfo` describing section sizes from this compilation result.
323     pub fn code_info(&self) -> CodeInfo {
324         CodeInfo {
325             total_size: self.buffer.total_size(),
326         }
327     }
328 
329     /// Returns a reference to the machine code generated for this function compilation.
330     pub fn code_buffer(&self) -> &[u8] {
331         self.buffer.data()
332     }
333 }
334 
335 /// Result of compiling a `FunctionStencil`, before applying `FunctionParameters` onto it.
336 ///
337 /// Only used internally, in a transient manner, for the incremental compilation cache.
338 pub type CompiledCodeStencil = CompiledCodeBase<Stencil>;
339 
340 /// `CompiledCode` in its final form (i.e. after `FunctionParameters` have been applied), ready for
341 /// consumption.
342 pub type CompiledCode = CompiledCodeBase<Final>;
343 
344 /// An object that can be used to create the text section of an executable.
345 ///
346 /// This primarily handles resolving relative relocations at
347 /// text-section-assembly time rather than at load/link time. This
348 /// architecture-specific logic is sort of like a linker, but only for one
349 /// object file at a time.
350 pub trait TextSectionBuilder {
351     /// Appends `data` to the text section with the `align` specified.
352     ///
353     /// If `labeled` is `true` then the offset of the final data is used to
354     /// resolve relocations in `resolve_reloc` in the future.
355     ///
356     /// This function returns the offset at which the data was placed in the
357     /// text section.
358     fn append(&mut self, labeled: bool, data: &[u8], align: Option<u32>) -> u64;
359 
360     /// Attempts to resolve a relocation for this function.
361     ///
362     /// The `offset` is the offset of the relocation, within the text section.
363     /// The `reloc` is the kind of relocation.
364     /// The `addend` is the value to add to the relocation.
365     /// The `target` is the labeled function that is the target of this
366     /// relocation.
367     ///
368     /// Labeled functions are created with the `append` function above by
369     /// setting the `labeled` parameter to `true`.
370     ///
371     /// If this builder does not know how to handle `reloc` then this function
372     /// will return `false`. Otherwise this function will return `true` and this
373     /// relocation will be resolved in the final bytes returned by `finish`.
374     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: u32) -> bool;
375 
376     /// A debug-only option which is used to for
377     fn force_veneers(&mut self);
378 
379     /// Completes this text section, filling out any final details, and returns
380     /// the bytes of the text section.
381     fn finish(&mut self) -> Vec<u8>;
382 }
383 
384 /// Expected unwind info type.
385 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
386 #[non_exhaustive]
387 pub enum UnwindInfoKind {
388     /// No unwind info.
389     None,
390     /// SystemV CIE/FDE unwind info.
391     #[cfg(feature = "unwind")]
392     SystemV,
393     /// Windows X64 Unwind info
394     #[cfg(feature = "unwind")]
395     Windows,
396 }
397