1
//! Dynamically emitted HashX assembly code for x86_64 targets
2

            
3
use crate::CompilerError;
4
use crate::compiler::{Architecture, Executable, util};
5
use crate::program::{Instruction, InstructionArray, NUM_INSTRUCTIONS};
6
use crate::register::{RegisterFile, RegisterId};
7
use dynasmrt::{DynasmApi, DynasmLabelApi, x64, x64::Rq};
8
use std::mem;
9

            
10
impl Architecture for Executable {
11
8418
    fn compile(program: &InstructionArray) -> Result<Self, CompilerError> {
12
8418
        let mut asm = Assembler::new();
13
        {
14
8418
            emit_save_regs(&mut asm);
15
8418
            emit_load_input(&mut asm);
16
8418
            emit_init_locals(&mut asm);
17
8418
            debug_assert_eq!(asm.len(), PROLOGUE_SIZE);
18
        }
19
4318434
        for inst in program {
20
4310016
            let prev_len = asm.len();
21
4310016
            emit_instruction(&mut asm, inst);
22
4310016
            debug_assert!(asm.len() - prev_len <= INSTRUCTION_SIZE_LIMIT);
23
        }
24
        {
25
8418
            let prev_len = asm.len();
26
8418
            emit_store_output(&mut asm);
27
8418
            emit_restore_regs(&mut asm);
28
8418
            emit_return(&mut asm);
29
8418
            debug_assert_eq!(asm.len() - prev_len, EPILOGUE_SIZE);
30
        }
31
8418
        asm.finalize()
32
8418
    }
33

            
34
339229254
    fn invoke(&self, regs: &mut RegisterFile) {
35
        // Choose the System V ABI for x86_64. (Rust now lets us do this even on
36
        // targets that use a different default C ABI.) We aren't using the
37
        // stack red zone, and we only need one register-sized parameter.
38
        //
39
        // Parameters: rdi rsi rdx rcx r8 r9
40
        // Callee save: rbx rsp rbp r12 r13 r14 r15
41
        // Scratch: rax rdi rsi rdx rcx r8 r9 r10 r11
42

            
43
339229254
        let entry = self.buffer.ptr(Assembler::entry());
44
339229254
        let entry: extern "sysv64" fn(*mut RegisterFile) -> () = unsafe { mem::transmute(entry) };
45
339229254
        entry(regs);
46
339229254
    }
47
}
48

            
49
/// Architecture-specific fixed prologue size
50
const PROLOGUE_SIZE: usize = 0x68;
51

            
52
/// Architecture-specific fixed epilogue size
53
const EPILOGUE_SIZE: usize = 0x60;
54

            
55
/// Architecture-specific maximum size for one instruction
56
const INSTRUCTION_SIZE_LIMIT: usize = 0x11;
57

            
58
/// Capacity for the temporary output buffer, before code is copied into
59
/// a long-lived allocation that can be made executable.
60
const BUFFER_CAPACITY: usize =
61
    PROLOGUE_SIZE + EPILOGUE_SIZE + NUM_INSTRUCTIONS * INSTRUCTION_SIZE_LIMIT;
62

            
63
/// Architecture-specific specialization of the Assembler
64
type Assembler = util::Assembler<x64::X64Relocation, BUFFER_CAPACITY>;
65

            
66
/// Map RegisterId in our abstract program to concrete registers and addresses.
67
trait RegisterMapper {
68
    /// Map RegisterId(0) to R8, and so on
69
    fn rq(&self) -> u8;
70
    /// Byte offset in a raw RegisterFile
71
    fn offset(&self) -> i32;
72
}
73

            
74
impl RegisterMapper for RegisterId {
75
    #[inline(always)]
76
14538852
    fn rq(&self) -> u8 {
77
14538852
        8 + self.as_u8()
78
14538852
    }
79

            
80
    #[inline(always)]
81
134688
    fn offset(&self) -> i32 {
82
134688
        (self.as_usize() * mem::size_of::<u64>()) as i32
83
134688
    }
84
}
85

            
86
/// Wrapper for `dynasm!`, sets the architecture and defines register aliases
87
macro_rules! dynasm {
88
    ($asm:ident $($t:tt)*) => {
89
        dynasmrt::dynasm!($asm
90
            ; .arch x64
91
            ; .alias mulh_in, rax
92
            ; .alias mulh_result64, rdx
93
            ; .alias mulh_result32, edx
94
            ; .alias branch_prohibit_flag, esi
95
            ; .alias const_ones, ecx
96
            ; .alias register_file_ptr, rdi
97
            $($t)*
98
        )
99
    }
100
}
101

            
102
/// Emit code to initialize our local variables to default values.
103
#[inline(always)]
104
8418
fn emit_init_locals<A: DynasmApi>(asm: &mut A) {
105
8418
    dynasm!(asm
106
    ; xor mulh_result64, mulh_result64
107
    ; xor branch_prohibit_flag, branch_prohibit_flag
108
    ; lea const_ones, [branch_prohibit_flag - 1]
109
    );
110
8418
}
111

            
112
/// List of registers to save on the stack, in address order
113
const REGS_TO_SAVE: [Rq; 4] = [Rq::R12, Rq::R13, Rq::R14, Rq::R15];
114

            
115
/// Calculate the amount of stack space to reserve, in bytes.
116
///
117
/// This is enough to hold REGS_TO_SAVE, and to keep the platform's
118
/// 16-byte stack alignment.
119
16836
const fn stack_size() -> i32 {
120
16836
    let size = REGS_TO_SAVE.len() * mem::size_of::<u64>();
121
16836
    let alignment = 0x10;
122
16836
    let offset = size % alignment;
123
16836
    let size = if offset == 0 {
124
16836
        size
125
    } else {
126
        size + alignment - offset
127
    };
128
16836
    size as i32
129
16836
}
130

            
131
/// Emit code to allocate stack space and store REGS_TO_SAVE.
132
#[inline(always)]
133
8418
fn emit_save_regs<A: DynasmApi>(asm: &mut A) {
134
8418
    dynasm!(asm; sub rsp, stack_size());
135
33672
    for (i, reg) in REGS_TO_SAVE.as_ref().iter().enumerate() {
136
33672
        let offset = (i * mem::size_of::<u64>()) as i32;
137
33672
        dynasm!(asm; mov [rsp + offset], Rq(*reg));
138
33672
    }
139
8418
}
140

            
141
/// Emit code to restore REGS_TO_SAVE and deallocate stack space.
142
#[inline(always)]
143
8418
fn emit_restore_regs<A: DynasmApi>(asm: &mut A) {
144
33672
    for (i, reg) in REGS_TO_SAVE.as_ref().iter().enumerate() {
145
33672
        let offset = (i * mem::size_of::<u64>()) as i32;
146
33672
        dynasm!(asm; mov Rq(*reg), [rsp + offset]);
147
33672
    }
148
8418
    dynasm!(asm; add rsp, stack_size());
149
8418
}
150

            
151
/// Emit code to move all input values from the RegisterFile into their
152
/// actual hardware registers.
153
#[inline(always)]
154
#[allow(clippy::useless_conversion)]
155
8418
fn emit_load_input<A: DynasmApi>(asm: &mut A) {
156
67344
    for reg in RegisterId::all() {
157
67344
        dynasm!(asm; mov Rq(reg.rq()), [register_file_ptr + reg.offset()]);
158
67344
    }
159
8418
}
160

            
161
/// Emit code to move all output values from machine registers back into
162
/// their RegisterFile slots.
163
#[inline(always)]
164
#[allow(clippy::useless_conversion)]
165
8418
fn emit_store_output<A: DynasmApi>(asm: &mut A) {
166
67344
    for reg in RegisterId::all() {
167
67344
        dynasm!(asm; mov [register_file_ptr + reg.offset()], Rq(reg.rq()));
168
67344
    }
169
8418
}
170

            
171
/// Emit a return instruction.
172
#[inline(always)]
173
8418
fn emit_return<A: DynasmApi>(asm: &mut A) {
174
8418
    dynasm!(asm; ret);
175
8418
}
176

            
177
/// Emit code for a single [`Instruction`] in the hash program.
178
#[inline(always)]
179
#[allow(clippy::useless_conversion)]
180
4310016
fn emit_instruction(asm: &mut Assembler, inst: &Instruction) {
181
    /// Common implementation for binary operations on registers
182
    macro_rules! reg_op {
183
        ($op:tt, $dst:ident, $src:ident) => {
184
            dynasm!(asm; $op Rq($dst.rq()), Rq($src.rq()))
185
        }
186
    }
187

            
188
    /// Common implementation for binary operations with a const operand
189
    macro_rules! const_op {
190
        ($op:tt, $dst:ident, $src:expr) => {
191
            dynasm!(asm; $op Rq($dst.rq()), $src)
192
        }
193
    }
194

            
195
    /// Common implementation for wide multiply operations.
196
    /// These use the one-argument form of `mul` (one register plus RDX:RAX)
197
    macro_rules! mulh_op {
198
        ($op:tt, $dst:ident, $src:ident) => {
199
            dynasm!(asm
200
                ; mov mulh_in, Rq($dst.rq())
201
                ; $op Rq($src.rq())
202
                ; mov Rq($dst.rq()), mulh_result64
203
            )
204
        }
205
    }
206

            
207
    /// Common implementation for scaled add using `lea`.
208
    /// Currently dynasm can only parse literal scale parameters.
209
    macro_rules! add_scaled_op {
210
        ($scale:tt, $dst:ident, $src:ident) => {
211
            dynasm!(asm
212
                ; lea Rq($dst.rq()), [ Rq($dst.rq()) + $scale * Rq($src.rq()) ]
213
            )
214
        }
215
    }
216

            
217
4310016
    match inst {
218
134688
        Instruction::Target => {
219
134688
            dynasm!(asm; target: );
220
134688
        }
221
134688
        Instruction::Branch { mask } => {
222
134688
            // Only one branch is allowed, `branch_prohibit_flag` keeps the test
223
134688
            // from passing. We get mul result tracking for free by assigning
224
134688
            // mulh_result32 to the corresponding output register used by the
225
134688
            // x86 mul instruction.
226
134688
            dynasm!(asm
227
134688
                ; or mulh_result32, branch_prohibit_flag
228
134688
                ; test mulh_result32, *mask as i32
229
134688
                ; cmovz branch_prohibit_flag, const_ones
230
134688
                ; jz <target
231
134688
            );
232
134688
        }
233
        Instruction::AddShift {
234
290559
            dst,
235
290559
            src,
236
290559
            left_shift,
237
290559
        } => match left_shift {
238
71139
            0 => add_scaled_op!(1, dst, src),
239
74106
            1 => add_scaled_op!(2, dst, src),
240
71829
            2 => add_scaled_op!(4, dst, src),
241
73485
            3 => add_scaled_op!(8, dst, src),
242
            _ => unreachable!(),
243
        },
244
136758
        Instruction::UMulH { dst, src } => {
245
136758
            mulh_op!(mul, dst, src);
246
136758
        }
247
132618
        Instruction::SMulH { dst, src } => {
248
132618
            mulh_op!(imul, dst, src);
249
132618
        }
250
1346880
        Instruction::Mul { dst, src } => {
251
1346880
            reg_op!(imul, dst, src);
252
1346880
        }
253
328509
        Instruction::Xor { dst, src } => {
254
328509
            reg_op!(xor, dst, src);
255
328509
        }
256
298839
        Instruction::Sub { dst, src } => {
257
298839
            reg_op!(sub, dst, src);
258
298839
        }
259
584154
        Instruction::AddConst { dst, src } => {
260
584154
            const_op!(add, dst, *src);
261
584154
        }
262
593193
        Instruction::XorConst { dst, src } => {
263
593193
            const_op!(xor, dst, *src);
264
593193
        }
265
329130
        Instruction::Rotate { dst, right_rotate } => {
266
329130
            const_op!(ror, dst, *right_rotate as i8);
267
329130
        }
268
    }
269
4310016
}