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