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::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(&self, code: &mut MachBuffer<Self>, info: &Self::Info, state: &mut Self::State);
291     /// Pretty-print the instruction.
292     fn pretty_print_inst(&self, state: &mut Self::State) -> String;
293 }
294 
295 /// A trait describing the emission state carried between MachInsts when
296 /// emitting a function body.
297 pub trait MachInstEmitState<I: VCodeInst>: Default + Clone + Debug {
298     /// Create a new emission state given the ABI object.
299     fn new(abi: &Callee<I::ABIMachineSpec>, ctrl_plane: ControlPlane) -> Self;
300     /// Update the emission state before emitting an instruction that is a
301     /// safepoint.
302     fn pre_safepoint(&mut self, _stack_map: StackMap) {}
303     /// The emission state holds ownership of a control plane, so it doesn't
304     /// have to be passed around explicitly too much. `ctrl_plane_mut` may
305     /// be used if temporary access to the control plane is needed by some
306     /// other function that doesn't have access to the emission state.
307     fn ctrl_plane_mut(&mut self) -> &mut ControlPlane;
308     /// Used to continue using a control plane after the emission state is
309     /// not needed anymore.
310     fn take_ctrl_plane(self) -> ControlPlane;
311     /// A hook that triggers when first emitting a new block.
312     /// It is guaranteed to be called before any instructions are emitted.
313     fn on_new_block(&mut self) {}
314 }
315 
316 /// The result of a `MachBackend::compile_function()` call. Contains machine
317 /// code (as bytes) and a disassembly, if requested.
318 #[derive(PartialEq, Debug, Clone)]
319 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
320 pub struct CompiledCodeBase<T: CompilePhase> {
321     /// Machine code.
322     pub buffer: MachBufferFinalized<T>,
323     /// Size of stack frame, in bytes.
324     pub frame_size: u32,
325     /// Disassembly, if requested.
326     pub vcode: Option<String>,
327     /// Debug info: value labels to registers/stackslots at code offsets.
328     pub value_labels_ranges: ValueLabelsRanges,
329     /// Debug info: stackslots to stack pointer offsets.
330     pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>,
331     /// Debug info: stackslots to stack pointer offsets.
332     pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>,
333     /// Basic-block layout info: block start offsets.
334     ///
335     /// This info is generated only if the `machine_code_cfg_info`
336     /// flag is set.
337     pub bb_starts: Vec<CodeOffset>,
338     /// Basic-block layout info: block edges. Each edge is `(from,
339     /// to)`, where `from` and `to` are basic-block start offsets of
340     /// the respective blocks.
341     ///
342     /// This info is generated only if the `machine_code_cfg_info`
343     /// flag is set.
344     pub bb_edges: Vec<(CodeOffset, CodeOffset)>,
345 }
346 
347 impl CompiledCodeStencil {
348     /// Apply function parameters to finalize a stencil into its final form.
349     pub fn apply_params(self, params: &FunctionParameters) -> CompiledCode {
350         CompiledCode {
351             buffer: self.buffer.apply_base_srcloc(params.base_srcloc()),
352             frame_size: self.frame_size,
353             vcode: self.vcode,
354             value_labels_ranges: self.value_labels_ranges,
355             sized_stackslot_offsets: self.sized_stackslot_offsets,
356             dynamic_stackslot_offsets: self.dynamic_stackslot_offsets,
357             bb_starts: self.bb_starts,
358             bb_edges: self.bb_edges,
359         }
360     }
361 }
362 
363 impl<T: CompilePhase> CompiledCodeBase<T> {
364     /// Get a `CodeInfo` describing section sizes from this compilation result.
365     pub fn code_info(&self) -> CodeInfo {
366         CodeInfo {
367             total_size: self.buffer.total_size(),
368         }
369     }
370 
371     /// Returns a reference to the machine code generated for this function compilation.
372     pub fn code_buffer(&self) -> &[u8] {
373         self.buffer.data()
374     }
375 
376     /// Get the disassembly of the buffer, using the given capstone context.
377     #[cfg(feature = "disas")]
378     pub fn disassemble(
379         &self,
380         params: Option<&crate::ir::function::FunctionParameters>,
381         cs: &capstone::Capstone,
382     ) -> Result<String, anyhow::Error> {
383         use std::fmt::Write;
384 
385         let mut buf = String::new();
386 
387         let relocs = self.buffer.relocs();
388         let traps = self.buffer.traps();
389 
390         // Normalize the block starts to include an initial block of offset 0.
391         let mut block_starts = Vec::new();
392         if self.bb_starts.first().copied() != Some(0) {
393             block_starts.push(0);
394         }
395         block_starts.extend_from_slice(&self.bb_starts);
396         block_starts.push(self.buffer.data().len() as u32);
397 
398         // Iterate over block regions, to ensure that we always produce block labels
399         for (n, (&start, &end)) in block_starts
400             .iter()
401             .zip(block_starts.iter().skip(1))
402             .enumerate()
403         {
404             writeln!(buf, "block{}: ; offset 0x{:x}", n, start)?;
405 
406             let buffer = &self.buffer.data()[start as usize..end as usize];
407             let insns = cs.disasm_all(buffer, start as u64).map_err(map_caperr)?;
408             for i in insns.iter() {
409                 write!(buf, "  ")?;
410 
411                 let op_str = i.op_str().unwrap_or("");
412                 if let Some(s) = i.mnemonic() {
413                     write!(buf, "{}", s)?;
414                     if !op_str.is_empty() {
415                         write!(buf, " ")?;
416                     }
417                 }
418 
419                 write!(buf, "{}", op_str)?;
420 
421                 let end = i.address() + i.bytes().len() as u64;
422                 let contains = |off| i.address() <= off && off < end;
423 
424                 for reloc in relocs.iter().filter(|reloc| contains(reloc.offset as u64)) {
425                     write!(
426                         buf,
427                         " ; reloc_external {} {} {}",
428                         reloc.kind,
429                         reloc.target.display(params),
430                         reloc.addend,
431                     )?;
432                 }
433 
434                 if let Some(trap) = traps.iter().find(|trap| contains(trap.offset as u64)) {
435                     write!(buf, " ; trap: {}", trap.code)?;
436                 }
437 
438                 writeln!(buf)?;
439             }
440         }
441 
442         return Ok(buf);
443 
444         fn map_caperr(err: capstone::Error) -> anyhow::Error {
445             anyhow::format_err!("{}", err)
446         }
447     }
448 }
449 
450 /// Result of compiling a `FunctionStencil`, before applying `FunctionParameters` onto it.
451 ///
452 /// Only used internally, in a transient manner, for the incremental compilation cache.
453 pub type CompiledCodeStencil = CompiledCodeBase<Stencil>;
454 
455 /// `CompiledCode` in its final form (i.e. after `FunctionParameters` have been applied), ready for
456 /// consumption.
457 pub type CompiledCode = CompiledCodeBase<Final>;
458 
459 impl CompiledCode {
460     /// If available, return information about the code layout in the
461     /// final machine code: the offsets (in bytes) of each basic-block
462     /// start, and all basic-block edges.
463     pub fn get_code_bb_layout(&self) -> (Vec<usize>, Vec<(usize, usize)>) {
464         (
465             self.bb_starts.iter().map(|&off| off as usize).collect(),
466             self.bb_edges
467                 .iter()
468                 .map(|&(from, to)| (from as usize, to as usize))
469                 .collect(),
470         )
471     }
472 
473     /// Creates unwind information for the function.
474     ///
475     /// Returns `None` if the function has no unwind information.
476     #[cfg(feature = "unwind")]
477     pub fn create_unwind_info(
478         &self,
479         isa: &dyn crate::isa::TargetIsa,
480     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
481         use crate::isa::unwind::UnwindInfoKind;
482         let unwind_info_kind = match isa.triple().operating_system {
483             target_lexicon::OperatingSystem::Windows => UnwindInfoKind::Windows,
484             _ => UnwindInfoKind::SystemV,
485         };
486         self.create_unwind_info_of_kind(isa, unwind_info_kind)
487     }
488 
489     /// Creates unwind information for the function using the supplied
490     /// "kind". Supports cross-OS (but not cross-arch) generation.
491     ///
492     /// Returns `None` if the function has no unwind information.
493     #[cfg(feature = "unwind")]
494     pub fn create_unwind_info_of_kind(
495         &self,
496         isa: &dyn crate::isa::TargetIsa,
497         unwind_info_kind: crate::isa::unwind::UnwindInfoKind,
498     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
499         isa.emit_unwind_info(self, unwind_info_kind)
500     }
501 }
502 
503 /// An object that can be used to create the text section of an executable.
504 ///
505 /// This primarily handles resolving relative relocations at
506 /// text-section-assembly time rather than at load/link time. This
507 /// architecture-specific logic is sort of like a linker, but only for one
508 /// object file at a time.
509 pub trait TextSectionBuilder {
510     /// Appends `data` to the text section with the `align` specified.
511     ///
512     /// If `labeled` is `true` then this also binds the appended data to the
513     /// `n`th label for how many times this has been called with `labeled:
514     /// true`. The label target can be passed as the `target` argument to
515     /// `resolve_reloc`.
516     ///
517     /// This function returns the offset at which the data was placed in the
518     /// text section.
519     fn append(
520         &mut self,
521         labeled: bool,
522         data: &[u8],
523         align: u32,
524         ctrl_plane: &mut ControlPlane,
525     ) -> u64;
526 
527     /// Attempts to resolve a relocation for this function.
528     ///
529     /// The `offset` is the offset of the relocation, within the text section.
530     /// The `reloc` is the kind of relocation.
531     /// The `addend` is the value to add to the relocation.
532     /// The `target` is the labeled function that is the target of this
533     /// relocation.
534     ///
535     /// Labeled functions are created with the `append` function above by
536     /// setting the `labeled` parameter to `true`.
537     ///
538     /// If this builder does not know how to handle `reloc` then this function
539     /// will return `false`. Otherwise this function will return `true` and this
540     /// relocation will be resolved in the final bytes returned by `finish`.
541     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool;
542 
543     /// A debug-only option which is used to for
544     fn force_veneers(&mut self);
545 
546     /// Completes this text section, filling out any final details, and returns
547     /// the bytes of the text section.
548     fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8>;
549 }
550