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