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
//! What a lifter implements and the block it writes into.
use std::collections::HashSet;
use vlk_base::target::Isa;
use vlk_ir::ir::visit::{expr_reads, reads_memory};
use vlk_ir::ir::{Block, Expr, FLAG_OPERANDS, RegRef, Stmt};
use super::{constants, flags};
pub(super) struct Decoded<I> {
pub(super) pc: u64,
pub(super) next: u64,
pub(super) instruction: I,
}
pub(super) trait Machine {
type Instruction;
fn branch_target(&self, instruction: &Self::Instruction, pc: u64) -> Option<u64>;
/// Appends the instruction's statements and reports whether it ends the block.
fn step(&mut self, instruction: &Self::Instruction, pc: u64) -> bool;
/// The block the lifter writes into.
fn out(&mut self) -> &mut Emitter;
/// The address of the instruction a step's statements come from.
fn origin(&self, _: &Self::Instruction, pc: u64) -> u64 {
pc
}
/// The instruction's name, for the note on one whose operands the
/// lifter cannot express.
fn name(&self, _: &Self::Instruction) -> String {
String::new()
}
/// The registers the instruction may write, for a statement that
/// leaves it unsupported without saying which.
fn written(&mut self, _: &Self::Instruction) -> Option<Vec<u16>> {
None
}
/// Whether the instruction may change the flags.
fn sets_flags(&self, _: &Self::Instruction) -> bool {
false
}
/// Whether the instruction only reads the flags, so that leaving it
/// unsupported leaves them as they were.
fn reads_flags(&self, _: &Self::Instruction) -> bool {
false
}
/// A block begins: what the lifter remembers of the instructions before
/// it no longer holds.
fn enter_block(&mut self) {}
/// How the driver follows constants while it completes the calls.
fn rules(&self) -> constants::Rules {
constants::Rules::default()
}
/// Blocks an instruction that loops by itself adds after the one it ends
/// (an x86 `rep` string instruction's body).
fn take_extra_blocks(&mut self) -> Vec<(Block, Option<flags::Flags>)> {
Vec::new()
}
}
/// What an instruction is about to overwrite.
pub(super) enum Write<'a> {
/// A register and, when the register then holds exactly it, the value it receives.
Register(u16, Option<&'a Expr>),
Memory,
}
/// The block a lifter writes an instruction's statements into, with the
/// flags its code leaves pending.
#[derive(Default)]
pub(super) struct Emitter {
pub(super) stmts: Vec<Stmt>,
pub(super) flags: flags::State,
/// Whether an operand of the instruction being lifted was one the
/// lifter cannot express, so that its effect would be lost.
pub(super) incomplete: std::cell::Cell<bool>,
}
impl Emitter {
/// A block whose flags are pending as given.
#[cfg(test)]
pub(super) fn pending(flags: Option<flags::Flags>) -> Self {
Self {
stmts: Vec::new(),
flags: flags::State {
pending: flags,
touched: false,
written: false,
},
incomplete: std::cell::Cell::new(false),
}
}
/// The instruction being lifted leaves the flags as `flags` says, or
/// in a way not known.
pub(super) fn set_flags(&mut self, flags: Option<flags::Flags>) {
self.flags.pending = flags;
self.flags.written = true;
}
/// `cond` under the pending flags; flags set in another block are
/// unknown.
pub(super) fn test(&self, cond: vlk_ir::ir::Cond, isa: Isa) -> flags::Test {
self.flags
.pending
.as_ref()
.map_or(flags::Test::Unknown, |flags| flags.test(cond, isa))
}
/// Copies `value` into a register of its own and reads it from there.
pub(super) fn hold(&mut self, value: Expr) -> Expr {
self.preserve(Write::Register(vlk_ir::ir::EXCHANGE, None));
self.stmts.push(Stmt::Assign {
dest: RegRef {
index: vlk_ir::ir::EXCHANGE,
width: 64,
},
value,
at: None,
});
Expr::reg(vlk_ir::ir::EXCHANGE, 64)
}
/// Before a write, keeps the pending compare testing the values its flags
/// were set from: an operand equal to the value written reads the register
/// afterwards, the operand of a written sum or difference is recovered from
/// the register, and any other operand reading what is overwritten moves into
/// a register of its own.
pub(super) fn preserve(&mut self, write: Write<'_>) {
let Some(flags) = &mut self.flags.pending else {
return;
};
let clobbered = |expr: &Expr| match write {
Write::Register(index, _) => {
let mut reads = HashSet::new();
expr_reads(expr, &mut reads);
reads.contains(&index)
}
Write::Memory => reads_memory(expr),
};
for (slot, operand) in FLAG_OPERANDS.into_iter().zip(flags.operands_mut()) {
if !clobbered(operand) {
continue;
}
let width = match vlk_ir::ir::semantics::width(operand) {
0 => 64,
bits => bits as u8,
};
if let Write::Register(index, Some(value)) = write {
if operand == value {
*operand = Expr::reg(index, width);
continue;
}
if let Some(recovered) = recover_operand(operand, value, index, width) {
*operand = recovered;
continue;
}
}
self.stmts.push(Stmt::Assign {
dest: RegRef {
index: slot,
width: 64,
},
value: operand.clone(),
at: None,
});
*operand = Expr::reg(slot, width);
}
}
}
/// `a` from the register that receives `a - b`, `a + b` or `0 - a`, when
/// `b` does not read that register.
pub(super) fn recover_operand(operand: &Expr, value: &Expr, index: u16, width: u8) -> Option<Expr> {
let Expr::Bin { op, lhs, rhs } = value else {
return None;
};
// A negation is undone by negating the register.
if *op == vlk_ir::ir::BinOp::Sub && matches!(lhs.as_ref(), Expr::Const(0)) && **rhs == *operand
{
return Some(Expr::bin(
vlk_ir::ir::BinOp::Sub,
Expr::constant(0),
Expr::reg(index, width),
));
}
let inverse = match op {
vlk_ir::ir::BinOp::Sub => vlk_ir::ir::BinOp::Add,
vlk_ir::ir::BinOp::Add => vlk_ir::ir::BinOp::Sub,
_ => return None,
};
let mut reads = HashSet::new();
expr_reads(rhs, &mut reads);
(**lhs == *operand && !reads.contains(&index))
.then(|| Expr::bin(inverse, Expr::reg(index, width), rhs.as_ref().clone()))
}
#[cfg(test)]
mod tests;