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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
mod concat;
mod cost;
mod count_idioms;
mod loops;
mod mux;
mod or_scan;
mod slices;
mod types;
use super::*;
use crate::SLTNodeArena;
use celox_design::BitAccess;
use celox_sir::{BlockId, ExecutionUnit};
fn input(arena: &mut SLTNodeArena<u32>, variable: u32, width: usize) -> NodeId {
arena
.alloc(SLTNode::Input {
variable,
signed: false,
index: vec![],
access: BitAccess::new(0, width - 1),
})
.unwrap()
}
fn input_bit(arena: &mut SLTNodeArena<u32>, variable: u32, bit: usize) -> NodeId {
arena
.alloc(SLTNode::Input {
variable,
signed: false,
index: vec![],
access: BitAccess::new(bit, bit),
})
.unwrap()
}
fn constant(arena: &mut SLTNodeArena<u32>, value: u64, width: usize) -> NodeId {
arena
.alloc(SLTNode::Constant(value.into(), 0u8.into(), width, false))
.unwrap()
}
fn operation_chain(
arena: &mut SLTNodeArena<u32>,
mut value: NodeId,
op: BinaryOp,
operations: usize,
constant_base: u64,
width: usize,
) -> NodeId {
for index in 0..operations {
let rhs = constant(arena, constant_base + index as u64, width);
value = arena.alloc(SLTNode::Binary(value, op, rhs)).unwrap();
}
value
}
fn finish_lowering(mut builder: SIRBuilder<u32>) -> ExecutionUnit<u32> {
builder.seal_block(SIRTerminator::Return);
let (blocks, register_map, _) = builder.drain();
let eu = ExecutionUnit {
entry_block_id: BlockId(0),
blocks,
register_map,
};
eu.verify_result()
.unwrap_or_else(|error| panic!("{error}\n{eu}"));
eu
}
fn instruction_count(
eu: &ExecutionUnit<u32>,
predicate: impl Fn(&SIRInstruction<u32>) -> bool,
) -> usize {
eu.blocks
.values()
.flat_map(|block| &block.instructions)
.filter(|instruction| predicate(instruction))
.count()
}
fn branch_count(eu: &ExecutionUnit<u32>) -> usize {
eu.blocks
.values()
.filter(|block| matches!(block.terminator, SIRTerminator::Branch { .. }))
.count()
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct TestSIRValue {
payload: BigUint,
mask: BigUint,
}
fn width_mask(width: usize) -> BigUint {
(BigUint::from(1u8) << width) - BigUint::from(1u8)
}
/// Execute the small, value-only SIR subset emitted by ForFoldGroup.
/// Keeping this interpreter local to the lowering tests lets the tests pin
/// exact iteration and four-state merge semantics without adding a second
/// production execution path.
fn execute_fold_group_sir(eu: &ExecutionUnit<u32>) -> crate::HashMap<RegisterId, TestSIRValue> {
execute_fold_group_sir_with_memory(eu, &crate::HashMap::default())
}
fn execute_fold_group_sir_with_memory(
eu: &ExecutionUnit<u32>,
memory: &crate::HashMap<u32, TestSIRValue>,
) -> crate::HashMap<RegisterId, TestSIRValue> {
let mut values = crate::HashMap::default();
let mut current = eu.entry_block_id;
for _ in 0..100 {
let block = &eu.blocks[¤t];
for instruction in &block.instructions {
match instruction {
SIRInstruction::Imm(dst, value) => {
values.insert(
*dst,
TestSIRValue {
payload: value.payload.clone(),
mask: value.mask.clone(),
},
);
}
SIRInstruction::Binary(dst, lhs, op, rhs) => {
let lhs_reg = *lhs;
let rhs_reg = *rhs;
let lhs = &values[&lhs_reg];
let rhs = &values[&rhs_reg];
let width = eu.register_map[dst].width();
let modulus = BigUint::from(1u8) << width;
let (payload, mask) = match op {
BinaryOp::LogicAnd | BinaryOp::LogicOr => {
let truth = |reg: RegisterId, value: &TestSIRValue| {
let known = width_mask(eu.register_map[®].width()) ^ &value.mask;
if (&value.payload & known) != BigUint::from(0u8) {
Some(true)
} else if value.mask.is_zero() {
Some(false)
} else {
None
}
};
let lhs_truth = truth(lhs_reg, lhs);
let rhs_truth = truth(rhs_reg, rhs);
let known = match op {
BinaryOp::LogicAnd => {
if lhs_truth == Some(false) || rhs_truth == Some(false) {
Some(false)
} else if lhs_truth == Some(true) && rhs_truth == Some(true) {
Some(true)
} else {
None
}
}
BinaryOp::LogicOr => {
if lhs_truth == Some(true) || rhs_truth == Some(true) {
Some(true)
} else if lhs_truth == Some(false) && rhs_truth == Some(false) {
Some(false)
} else {
None
}
}
_ => unreachable!(),
};
match known {
Some(value) => (BigUint::from(value), BigUint::from(0u8)),
None => (BigUint::from(0u8), BigUint::from(1u8)),
}
}
_ => {
assert_eq!(lhs.mask, BigUint::from(0u8));
assert_eq!(rhs.mask, BigUint::from(0u8));
let payload = match op {
BinaryOp::Add => (&lhs.payload + &rhs.payload) % &modulus,
BinaryOp::Mul => (&lhs.payload * &rhs.payload) % &modulus,
BinaryOp::Sub => {
(&lhs.payload + &modulus - &rhs.payload) % &modulus
}
BinaryOp::And => &lhs.payload & &rhs.payload,
BinaryOp::Or => &lhs.payload | &rhs.payload,
BinaryOp::Shl => {
let shift =
rhs.payload.to_u64_digits().first().copied().unwrap_or(0);
if shift > usize::MAX as u64 {
BigUint::from(0u8)
} else {
(&lhs.payload << shift as usize) % &modulus
}
}
BinaryOp::Shr => {
let shift =
rhs.payload.to_u64_digits().first().copied().unwrap_or(0);
if shift > usize::MAX as u64 {
BigUint::from(0u8)
} else {
&lhs.payload >> shift as usize
}
}
BinaryOp::Eq | BinaryOp::EqWildcard => {
BigUint::from(lhs.payload == rhs.payload)
}
BinaryOp::Ne => BigUint::from(lhs.payload != rhs.payload),
BinaryOp::GtU => BigUint::from(lhs.payload > rhs.payload),
BinaryOp::GeU => BigUint::from(lhs.payload >= rhs.payload),
other => {
panic!("unexpected grouped-fold binary op {other:?}")
}
};
(payload, BigUint::from(0u8))
}
};
values.insert(*dst, TestSIRValue { payload, mask });
}
SIRInstruction::Unary(dst, op, src) => {
let width = eu.register_map[dst].width();
let value = &values[src];
let (payload, mask) = match op {
UnaryOp::Ident => (value.payload.clone(), value.mask.clone()),
UnaryOp::ToTwoState => {
let known = width_mask(width) ^ &value.mask;
(&value.payload & known, BigUint::from(0u8))
}
UnaryOp::BitNot => {
(&width_mask(width) ^ &value.payload, value.mask.clone())
}
UnaryOp::LogicNot => (
BigUint::from(value.payload == BigUint::from(0u8)),
value.mask.clone(),
),
UnaryOp::Or => (
BigUint::from(value.payload != BigUint::from(0u8)),
value.mask.clone(),
),
UnaryOp::PopCount => (
BigUint::from(
value
.payload
.to_u64_digits()
.iter()
.map(|word| word.count_ones() as u64)
.sum::<u64>(),
),
value.mask.clone(),
),
other => panic!("unexpected grouped-fold unary op {other:?}"),
};
values.insert(*dst, TestSIRValue { payload, mask });
}
SIRInstruction::Load(dst, address, offset, width) => {
let offset = match offset {
SIROffset::Static(offset)
| SIROffset::PackedElements {
bit_offset: offset, ..
} => *offset,
SIROffset::Dynamic(offset) => values[offset]
.payload
.to_u64_digits()
.first()
.copied()
.unwrap_or(0)
as usize,
SIROffset::Element {
index,
element_width,
bit_offset,
dynamic_bit_offset,
} => {
let element = values[index]
.payload
.to_u64_digits()
.first()
.copied()
.unwrap_or(0) as usize;
let dynamic_bit_offset = dynamic_bit_offset
.map(|register| {
values[®ister]
.payload
.to_u64_digits()
.first()
.copied()
.unwrap_or(0) as usize
})
.unwrap_or(0);
element * element_width + bit_offset + dynamic_bit_offset
}
};
let source = memory
.get(address)
.unwrap_or_else(|| panic!("missing test memory value at {address}"));
let mask = width_mask(*width);
values.insert(
*dst,
TestSIRValue {
payload: (&source.payload >> offset) & &mask,
mask: (&source.mask >> offset) & mask,
},
);
}
SIRInstruction::Concat(dst, args) => {
let mut payload = BigUint::from(0u8);
let mut mask = BigUint::from(0u8);
for arg in args {
let width = eu.register_map[arg].width();
payload = (payload << width) | &values[arg].payload;
mask = (mask << width) | &values[arg].mask;
}
values.insert(*dst, TestSIRValue { payload, mask });
}
SIRInstruction::Slice(dst, src, bit_offset, width) => {
let mask = width_mask(*width);
values.insert(
*dst,
TestSIRValue {
payload: (&values[src].payload >> *bit_offset) & &mask,
mask: (&values[src].mask >> *bit_offset) & mask,
},
);
}
SIRInstruction::Mux(dst, cond, then_value, else_value) => {
let cond = &values[cond];
let selected = if cond.payload == BigUint::from(0u8) {
&values[else_value]
} else {
&values[then_value]
};
let width = eu.register_map[dst].width();
values.insert(
*dst,
TestSIRValue {
payload: &selected.payload & width_mask(width),
mask: if cond.mask == BigUint::from(0u8) {
&selected.mask & width_mask(width)
} else {
width_mask(width)
},
},
);
}
other => panic!("unexpected grouped-fold instruction {other:?}"),
}
}
let (next, args) = match &block.terminator {
SIRTerminator::Jump(target, args) => (*target, args),
SIRTerminator::Branch {
cond,
true_block,
false_block,
} => {
if values[cond].payload == BigUint::from(0u8) {
(false_block.0, &false_block.1)
} else {
(true_block.0, &true_block.1)
}
}
SIRTerminator::Switch { .. } => {
panic!("unexpected Switch in grouped-fold lowering test")
}
SIRTerminator::Return => return values,
SIRTerminator::Error(code) => panic!("unexpected Error({code})"),
};
let arguments = args
.iter()
.map(|argument| values[argument].clone())
.collect::<Vec<_>>();
for (¶meter, argument) in eu.blocks[&next].params.iter().zip(arguments) {
values.insert(parameter, argument);
}
current = next;
}
panic!("grouped fold did not terminate at its exact trip count")
}