summaryrefslogtreecommitdiff
path: root/crates/hashx/src/compiler.rs
blob: d0f610a8d19ede7b33d39558c32792b07bb24550 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//! Architecture-specific compiled implementations for HashX
//!
//! This module provides a consistent interface across configurations and
//! targets via the [`Executable`] struct and the [`Architecture`] trait.
//! When the compiler is unavailable, an `Executable` is empty and the
//! `Architecture` is defined here as a stub implementation. Otherwise, the
//! `Executable` wraps a mmap buffer from the `dynasmrt` crate and the
//! `Architecture` is implemented in a CPU-specific way.

use crate::{program::InstructionArray, register::RegisterFile, CompilerError};

#[cfg(all(feature = "compiler", target_arch = "x86_64"))]
mod x86_64;

#[cfg(all(feature = "compiler", target_arch = "aarch64"))]
mod aarch64;

#[cfg(all(
    feature = "compiler",
    any(target_arch = "x86_64", target_arch = "aarch64")
))]
mod util;

/// Wrapper for a compiled program, empty when compiler support is disabled
pub(crate) struct Executable {
    /// Mapped memory, read-only and executable
    ///
    /// On platforms with compiler support, this item is present.
    /// If the compiler is unavailable, Executable will be empty.
    #[cfg(all(
        feature = "compiler",
        any(target_arch = "x86_64", target_arch = "aarch64")
    ))]
    buffer: util::ExecutableBuffer,
}

/// Default implementation for [`Architecture`], used
/// when the compiler is disabled or the target architecture is unsupported
#[cfg(any(
    not(feature = "compiler"),
    not(any(target_arch = "x86_64", target_arch = "aarch64"))
))]
impl Architecture for Executable {
    fn compile(_program: &InstructionArray) -> Result<Self, CompilerError> {
        Err(CompilerError::NotAvailable)
    }

    fn invoke(&self, _regs: &mut RegisterFile) {
        unreachable!();
    }
}

/// Default implementation for [`Debug`] on [`Executable`], when the compiler
/// is currently disabled or unsupported on the target
///
/// There should never be an [`Executable`] instance in these cases.
/// Always panics.
#[cfg(any(
    not(feature = "compiler"),
    not(any(target_arch = "x86_64", target_arch = "aarch64"))
))]
impl std::fmt::Debug for Executable {
    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        unreachable!()
    }
}

/// Trait that adds architecture-specific functionality to Executable
pub(crate) trait Architecture
where
    Self: Sized,
{
    /// Compile an array of instructions into an Executable
    fn compile(program: &InstructionArray) -> Result<Self, CompilerError>;

    /// Run the compiled code, with a RegisterFile for input and output
    fn invoke(&self, regs: &mut RegisterFile);
}