cranelift_codegen/isa/x64/inst/
external.rs

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//! Interface with the external assembler crate.

use super::{
    regs, Amode, Gpr, Inst, LabelUse, MachBuffer, MachLabel, OperandVisitor, OperandVisitorImpl,
    SyntheticAmode, VCodeConstant, WritableGpr, WritableXmm, Xmm,
};
use crate::ir::TrapCode;
use cranelift_assembler_x64 as asm;

/// Define the types of registers Cranelift will use.
#[derive(Clone, Debug)]
pub struct CraneliftRegisters;
impl asm::Registers for CraneliftRegisters {
    type ReadGpr = Gpr;
    type ReadWriteGpr = PairedGpr;
    type ReadXmm = Xmm;
    type ReadWriteXmm = PairedXmm;
}

/// A pair of registers, one for reading and one for writing.
///
/// Due to how Cranelift's SSA form, we must track the read and write registers
/// separately prior to register allocation. Once register allocation is
/// complete, we expect the hardware encoding for both `read` and `write` to be
/// the same.
#[derive(Clone, Copy, Debug)]
pub struct PairedGpr {
    pub(crate) read: Gpr,
    pub(crate) write: WritableGpr,
}

impl asm::AsReg for PairedGpr {
    fn enc(&self) -> u8 {
        let PairedGpr { read, write } = self;
        let read = enc_gpr(read);
        let write = enc_gpr(&write.to_reg());
        assert_eq!(read, write);
        write
    }

    fn new(_: u8) -> Self {
        panic!("disallow creation of new assembler registers")
    }
}

/// A pair of XMM registers, one for reading and one for writing.
#[derive(Clone, Copy, Debug)]
pub struct PairedXmm {
    pub(crate) read: Xmm,
    pub(crate) write: WritableXmm,
}

impl asm::AsReg for PairedXmm {
    fn enc(&self) -> u8 {
        let PairedXmm { read, write } = self;
        let read = enc_xmm(read);
        let write = enc_xmm(&write.to_reg());
        assert_eq!(read, write);
        write
    }

    fn new(_: u8) -> Self {
        panic!("disallow creation of new assembler registers")
    }
}

/// This bridges the gap between codegen and assembler for general purpose register types.
impl asm::AsReg for Gpr {
    fn enc(&self) -> u8 {
        enc_gpr(self)
    }

    fn new(_: u8) -> Self {
        panic!("disallow creation of new assembler registers")
    }
}

/// This bridges the gap between codegen and assembler for xmm register types.
impl asm::AsReg for Xmm {
    fn enc(&self) -> u8 {
        enc_xmm(self)
    }

    fn new(_: u8) -> Self {
        panic!("disallow creation of new assembler registers")
    }
}

/// A helper method for extracting the hardware encoding of a general purpose register.
#[inline]
fn enc_gpr(gpr: &Gpr) -> u8 {
    if let Some(real) = gpr.to_reg().to_real_reg() {
        real.hw_enc()
    } else {
        unreachable!()
    }
}

/// A helper method for extracting the hardware encoding of an xmm register.
#[inline]
fn enc_xmm(xmm: &Xmm) -> u8 {
    if let Some(real) = xmm.to_reg().to_real_reg() {
        real.hw_enc()
    } else {
        unreachable!()
    }
}

/// A wrapper to implement the `cranelift-assembler-x64` register allocation trait,
/// `RegallocVisitor`, in terms of the trait used in Cranelift,
/// `OperandVisitor`.
pub(crate) struct RegallocVisitor<'a, T>
where
    T: OperandVisitorImpl,
{
    pub collector: &'a mut T,
}

impl<'a, T: OperandVisitor> asm::RegisterVisitor<CraneliftRegisters> for RegallocVisitor<'a, T> {
    fn read(&mut self, reg: &mut Gpr) {
        self.collector.reg_use(reg);
    }

    fn read_write(&mut self, reg: &mut PairedGpr) {
        let PairedGpr { read, write } = reg;
        self.collector.reg_use(read);
        self.collector.reg_reuse_def(write, 0);
    }

    fn fixed_read(&mut self, _reg: &Gpr) {
        todo!()
    }

    fn fixed_read_write(&mut self, _reg: &PairedGpr) {
        todo!()
    }

    fn read_xmm(&mut self, reg: &mut Xmm) {
        self.collector.reg_use(reg);
    }

    fn read_write_xmm(&mut self, reg: &mut PairedXmm) {
        let PairedXmm { read, write } = reg;
        self.collector.reg_use(read);
        self.collector.reg_reuse_def(write, 0);
    }

    fn fixed_read_xmm(&mut self, _reg: &Xmm) {
        todo!()
    }

    fn fixed_read_write_xmm(&mut self, _reg: &PairedXmm) {
        todo!()
    }
}

impl Into<asm::Amode<Gpr>> for SyntheticAmode {
    fn into(self) -> asm::Amode<Gpr> {
        match self {
            SyntheticAmode::Real(amode) => match amode {
                Amode::ImmReg {
                    simm32,
                    base,
                    flags,
                } => asm::Amode::ImmReg {
                    simm32: asm::AmodeOffsetPlusKnownOffset {
                        simm32: simm32.into(),
                        offset: None,
                    },
                    base: Gpr::unwrap_new(base),
                    trap: flags.trap_code().map(Into::into),
                },
                Amode::ImmRegRegShift {
                    simm32,
                    base,
                    index,
                    shift,
                    flags,
                } => asm::Amode::ImmRegRegShift {
                    base,
                    index: asm::NonRspGpr::new(index),
                    scale: asm::Scale::new(shift),
                    simm32: simm32.into(),
                    trap: flags.trap_code().map(Into::into),
                },
                Amode::RipRelative { target } => asm::Amode::RipRelative {
                    target: asm::DeferredTarget::Label(asm::Label(target.as_u32())),
                },
            },
            SyntheticAmode::IncomingArg { offset } => asm::Amode::ImmReg {
                base: Gpr::unwrap_new(regs::rbp()),
                simm32: asm::AmodeOffsetPlusKnownOffset {
                    simm32: (-i32::try_from(offset).unwrap()).into(),
                    offset: Some(offsets::KEY_INCOMING_ARG),
                },
                trap: None,
            },
            SyntheticAmode::SlotOffset { simm32 } => asm::Amode::ImmReg {
                base: Gpr::unwrap_new(regs::rbp()),
                simm32: asm::AmodeOffsetPlusKnownOffset {
                    simm32: simm32.into(),
                    offset: Some(offsets::KEY_SLOT_OFFSET),
                },
                trap: None,
            },
            SyntheticAmode::ConstantOffset(vcode_constant) => asm::Amode::RipRelative {
                target: asm::DeferredTarget::Constant(asm::Constant(vcode_constant.as_u32())),
            },
        }
    }
}

/// Keep track of the offset slots to fill in during emission; see
/// `KnownOffsetTable`.
pub mod offsets {
    pub const KEY_INCOMING_ARG: usize = 0;
    pub const KEY_SLOT_OFFSET: usize = 1;
}

impl asm::CodeSink for MachBuffer<Inst> {
    fn put1(&mut self, value: u8) {
        self.put1(value)
    }

    fn put2(&mut self, value: u16) {
        self.put2(value)
    }

    fn put4(&mut self, value: u32) {
        self.put4(value)
    }

    fn put8(&mut self, value: u64) {
        self.put8(value)
    }

    fn current_offset(&self) -> u32 {
        self.cur_offset()
    }

    fn use_label_at_offset(&mut self, offset: u32, label: asm::Label) {
        self.use_label_at_offset(offset, label.into(), LabelUse::JmpRel32);
    }

    fn add_trap(&mut self, code: asm::TrapCode) {
        self.add_trap(code.into());
    }

    fn get_label_for_constant(&mut self, c: asm::Constant) -> asm::Label {
        self.get_label_for_constant(c.into()).into()
    }
}

impl From<asm::TrapCode> for TrapCode {
    fn from(value: asm::TrapCode) -> Self {
        Self::from_raw(value.0)
    }
}

impl From<TrapCode> for asm::TrapCode {
    fn from(value: TrapCode) -> Self {
        Self(value.as_raw())
    }
}

impl From<asm::Label> for MachLabel {
    fn from(value: asm::Label) -> Self {
        Self::from_u32(value.0)
    }
}

impl From<MachLabel> for asm::Label {
    fn from(value: MachLabel) -> Self {
        Self(value.as_u32())
    }
}

impl From<asm::Constant> for VCodeConstant {
    fn from(value: asm::Constant) -> Self {
        Self::from_u32(value.0)
    }
}