1use std::collections::{BTreeMap, HashMap};
4use std::hash::BuildHasher;
5
6use super::{Context, Expr, Node, OpCode};
7use crate::error::Error;
8use crate::hash::IdMap;
9use crate::value::narrow;
10use crate::{BitVec, SymbolKey, Width};
11
12#[derive(Default)]
15pub(super) struct Plan {
16 roots: Vec<u32>,
17 outputs: Vec<u32>,
18 instructions: Vec<Instruction>,
19 narrow: bool,
20 has_native: bool,
21 routes: Vec<Route>,
23 words: Vec<u128>,
24 values: Vec<BitVec>,
25}
26
27struct Route {
28 native: bool,
29 word: bool,
31 value: u32,
33}
34
35struct Instruction {
36 id: u32,
37 node: Node,
39}
40
41impl Plan {
42 pub(super) fn clear(&mut self) {
43 self.roots.clear();
44 self.outputs.clear();
45 self.instructions.clear();
46 self.routes.clear();
47 self.words.clear();
48 self.values.clear();
49 }
50
51 fn native_supported(node: Node, width: impl Fn(u32) -> u16) -> bool {
52 node.width <= 128
53 && !node.op.is_fp()
54 && node.op.as_ext().is_none()
55 && node
56 .op
57 .as_bin()
58 .is_none_or(|op| narrow::bin_supported(op, node.width))
59 && node.children().all(|child| width(child) <= 128)
60 }
61
62 fn prepare(&mut self, cx: &mut Context, roots: &[u32]) {
63 self.clear();
64 let order = cx.post_order_ids(roots);
65 let mut slots = IdMap::default();
66 slots.reserve(order.len());
67 self.instructions.reserve(order.len());
68 self.narrow = true;
69 self.has_native = false;
70 for id in order {
71 let mut node = cx.node(id);
72 let native = Self::native_supported(node, |child| cx.wid(child));
73 self.narrow &= native;
74 self.has_native |= native;
75 let arity = node.op.arity();
76 if arity > 0 {
77 node.a = slots[&node.a];
78 }
79 if arity > 1 {
80 node.b = slots[&node.b];
81 }
82 if arity > 2 {
83 node.c = slots[&node.c];
84 }
85 slots.insert(id, self.instructions.len() as u32);
86 self.instructions.push(Instruction { id, node });
87 }
88 self.outputs.extend(roots.iter().map(|r| slots[r]));
89 self.roots.extend_from_slice(roots);
90 if self.narrow {
91 self.words.resize(self.instructions.len(), 0);
92 } else if !self.has_native {
93 self.values
94 .resize(self.instructions.len(), BitVec::zero(Width::W1));
95 } else {
96 self.routes.reserve(self.instructions.len());
97 for inst in &self.instructions {
98 let native =
99 Self::native_supported(inst.node, |r| self.instructions[r as usize].node.width);
100 self.routes.push(Route {
101 native,
102 word: native,
103 value: if native { u32::MAX } else { 0 },
104 });
105 }
106 for (slot, inst) in self.instructions.iter().enumerate() {
107 let native = self.routes[slot].native;
108 for child in inst.node.children() {
109 let route = &mut self.routes[child as usize];
110 if native {
111 route.word = true;
112 } else {
113 route.value = 0;
114 }
115 }
116 }
117 let mut values = 0;
118 for route in &mut self.routes {
119 if route.value != u32::MAX {
120 route.value = values;
121 values += 1;
122 }
123 }
124 self.values.resize(values as usize, BitVec::zero(Width::W1));
125 let words = self
126 .routes
127 .iter()
128 .rposition(|r| r.word)
129 .map_or(0, |i| i + 1);
130 self.words.resize(words, 0);
131 }
132 }
133
134 #[inline(always)]
136 fn eval_word(
137 &self,
138 cx: &Context,
139 inst: &Instruction,
140 env: &(impl Env + ?Sized),
141 ) -> Result<u128, Error> {
142 let n = inst.node;
143 let get = |r: u32| self.words[r as usize];
144 let width = |r: u32| self.instructions[r as usize].node.width;
145 Ok(match n.op {
146 OpCode::Const => cx.const_val(inst.id).unwrap().to_u128().unwrap(),
147 OpCode::Sym => cx.eval_symbol(n.a, env)?.to_u128().unwrap(),
148 OpCode::Zext => get(n.a),
149 OpCode::Sext => narrow::signed(get(n.a), width(n.a)) as u128 & narrow::mask(n.width),
150 OpCode::Extract => (get(n.a) >> n.b) & narrow::mask(n.width),
151 OpCode::Concat => (get(n.a) << width(n.b)) | get(n.b),
152 OpCode::Select => {
153 if get(n.a) != 0 {
154 get(n.b)
155 } else {
156 get(n.c)
157 }
158 }
159 op => {
160 if let Some(u) = op.as_un() {
161 narrow::un(u, n.width, get(n.a))
162 } else if let Some(b) = op.as_bin() {
163 narrow::bin(b, n.width, get(n.a), get(n.b))
164 } else {
165 u128::from(narrow::cmp(
166 op.as_cmp().unwrap(),
167 width(n.a),
168 get(n.a),
169 get(n.b),
170 ))
171 }
172 }
173 })
174 }
175
176 #[inline(never)]
178 fn run_narrow(
179 &mut self,
180 cx: &Context,
181 env: &(impl Env + ?Sized),
182 ) -> Result<Vec<BitVec>, Error> {
183 for (slot, inst) in self.instructions.iter().enumerate() {
184 self.words[slot] = self.eval_word(cx, inst, env)?;
185 }
186 Ok(self
187 .outputs
188 .iter()
189 .map(|&r| {
190 BitVec::wrapping_from_u128(
191 cx.width_of(self.instructions[r as usize].id),
192 self.words[r as usize],
193 )
194 })
195 .collect())
196 }
197
198 fn run(&mut self, cx: &Context, env: &(impl Env + ?Sized)) -> Result<Vec<BitVec>, Error> {
199 if self.narrow {
200 return self.run_narrow(cx, env);
201 }
202 if !self.has_native {
203 for (slot, inst) in self.instructions.iter().enumerate() {
204 let v = cx.eval_node_mapped(
205 inst.id,
206 inst.node,
207 |r| self.values[r as usize],
208 |key, width| env.value(key, width),
209 )?;
210 self.values[slot] = v;
211 }
212 Ok(self
213 .outputs
214 .iter()
215 .map(|&r| self.values[r as usize])
216 .collect())
217 } else {
218 for (slot, inst) in self.instructions.iter().enumerate() {
219 let route = &self.routes[slot];
220 if route.native {
221 let v = self.eval_word(cx, inst, env)?;
222 self.words[slot] = v;
223 if route.value != u32::MAX {
224 self.values[route.value as usize] =
225 BitVec::wrapping_from_u128(cx.width_of(inst.id), v);
226 }
227 } else {
228 let v = cx.eval_node_mapped(
229 inst.id,
230 inst.node,
231 |r| self.values[self.routes[r as usize].value as usize],
232 |key, width| env.value(key, width),
233 )?;
234 self.values[route.value as usize] = v;
235 if route.word {
236 self.words[slot] = v.to_u128().unwrap();
237 }
238 }
239 }
240 Ok(self
241 .outputs
242 .iter()
243 .map(|&r| {
244 let slot = r as usize;
245 let value = self.routes[slot].value;
246 if value != u32::MAX {
247 self.values[value as usize]
248 } else {
249 BitVec::wrapping_from_u128(
250 cx.width_of(self.instructions[slot].id),
251 self.words[slot],
252 )
253 }
254 })
255 .collect())
256 }
257 }
258}
259
260#[cfg(test)]
261mod plan_tests {
262 use super::*;
263 use crate::{BinOp, UnOp};
264
265 fn interpreted(cx: &mut Context, roots: &[Expr], env: &(impl Env + ?Sized)) -> Vec<BitVec> {
266 let ids = cx.ids(roots).unwrap();
267 let mut values = IdMap::default();
268 for id in cx.post_order_ids(&ids) {
269 let v = cx
270 .eval_node(id, |i| values[&i], |k, w| env.value(k, w))
271 .unwrap();
272 values.insert(id, v);
273 }
274 ids.iter().map(|i| values[i]).collect()
275 }
276
277 #[test]
278 fn evaluation_plans_agree_with_interpretation_at_width_boundaries() {
279 for bits in [1, 7, 8, 31, 63, 64, 65, 127, 128, 129, 512] {
280 let w = Width::new(bits).unwrap();
281 let mut cx = Context::new();
282 let a = cx.symbol("a", w).unwrap();
283 let b = cx.symbol("b", w).unwrap();
284 let c = cx.symbol("c", Width::W1).unwrap();
285 let mut roots = vec![a, cx.select(c, a, b).unwrap()];
286 let mut fallback = Vec::new();
287 for op in OpCode::ALL {
288 if let Some(u) = op.as_un() {
289 if u != UnOp::Bswap || bits % 8 == 0 {
290 roots.push(cx.un(u, a).unwrap());
291 }
292 } else if let Some(bin) = op.as_bin() {
293 let e = cx.bin(bin, a, b).unwrap();
294 if bits > 64 && matches!(bin, BinOp::UMulHi | BinOp::SMulHi) {
295 fallback.push(e);
296 } else {
297 roots.push(e);
298 }
299 } else if let Some(cmp) = op.as_cmp() {
300 roots.push(cx.cmp(cmp, a, b).unwrap());
301 }
302 }
303 if bits > 1 {
304 let half = Width::new(bits / 2).unwrap();
305 let low = cx.extract(a, 0, half).unwrap();
306 let high = cx
307 .extract(b, bits / 2, Width::new(bits - bits / 2).unwrap())
308 .unwrap();
309 roots.extend([
310 low,
311 high,
312 cx.concat(high, low).unwrap(),
313 cx.zext(low, w).unwrap(),
314 cx.sext(low, w).unwrap(),
315 ]);
316 }
317 let wide = cx.zero(Width::W512).unwrap();
318 let mut mixed = roots.clone();
319 mixed.push(wide);
320 let points = [
321 BitVec::zero(w),
322 BitVec::one(w),
323 BitVec::ones(w),
324 BitVec::smin(w),
325 BitVec::wrapping_from_limbs(w, &[0xaaaa_aaaa_aaaa_aaaa; 8]),
326 ];
327 for (i, &av) in points.iter().enumerate() {
328 for (j, &bv) in points.iter().enumerate() {
329 let env: HashMap<_, _> = [
330 (SymbolKey::from("a"), av),
331 (SymbolKey::from("b"), bv),
332 (SymbolKey::from("c"), BitVec::from_bool((i + j) % 2 == 0)),
333 ]
334 .into_iter()
335 .collect();
336 let want = interpreted(&mut cx, &roots, &env);
337 assert_eq!(cx.eval(&roots, &env).unwrap(), want, "width {bits}");
338 assert_eq!(cx.eval(&roots, &env).unwrap(), want, "warm width {bits}");
339 assert_eq!(cx.eval_plan.as_ref().unwrap().narrow, bits <= 128);
340 let mut mixed_want = want.clone();
341 mixed_want.push(BitVec::zero(Width::W512));
342 assert_eq!(
343 cx.eval(&mixed, &env).unwrap(),
344 mixed_want,
345 "mixed width {bits}"
346 );
347 assert_eq!(
348 cx.eval(&mixed, &env).unwrap(),
349 mixed_want,
350 "warm mixed width {bits}"
351 );
352 if !fallback.is_empty() {
353 let want = interpreted(&mut cx, &fallback, &env);
354 assert_eq!(cx.eval(&fallback, &env).unwrap(), want);
355 assert!(!cx.eval_plan.as_ref().unwrap().narrow);
356 }
357 }
358 }
359 }
360 }
361
362 #[test]
363 fn evaluation_plans_refresh_inputs_roots_and_context_generations() {
364 let mut cx = Context::new();
365 let x = cx.symbol("x", Width::W8).unwrap();
366 let y = cx.symbol("y", Width::W8).unwrap();
367 let sum = cx.add(x, y).unwrap();
368 let env = |a, b| {
369 FnEnv(move |k: &SymbolKey, w| {
370 Some(BitVec::wrapping_from_u64(
371 w,
372 if k == &SymbolKey::from("x") { a } else { b },
373 ))
374 })
375 };
376 assert_eq!(
377 cx.eval(&[sum, x, sum], &env(2, 3))
378 .unwrap()
379 .iter()
380 .map(BitVec::to_u64)
381 .collect::<Vec<_>>(),
382 vec![Some(5), Some(2), Some(5)]
383 );
384 assert_eq!(
385 cx.eval(&[sum, x, sum], &env(7, 9)).unwrap()[0].to_u64(),
386 Some(16)
387 );
388 assert!(
389 cx.eval(&[sum, x, sum], &FnEnv(|_: &SymbolKey, _| None))
390 .is_err()
391 );
392 assert!(matches!(
393 cx.eval(
394 &[sum, x, sum],
395 &FnEnv(|_: &SymbolKey, _| Some(BitVec::zero(Width::W16)))
396 ),
397 Err(Error::EnvWidth { .. })
398 ));
399 assert_eq!(
400 cx.eval(&[sum, x, sum], &env(1, 4)).unwrap()[0].to_u64(),
401 Some(5)
402 );
403 assert_eq!(cx.eval(&[y, sum], &env(1, 4)).unwrap()[0].to_u64(), Some(4));
404 assert!(cx.eval(&[], &env(1, 4)).unwrap().is_empty());
405 cx.clear();
406 let x2 = cx.symbol("x", Width::W8).unwrap();
407 let y2 = cx.symbol("y", Width::W8).unwrap();
408 let product = cx.bin(BinOp::Mul, x2, y2).unwrap();
409 assert_eq!(product.index(), sum.index());
410 assert!(matches!(cx.eval(&[sum], &env(2, 3)), Err(Error::StaleExpr)));
411 assert_eq!(
412 cx.eval(&[product], &env(2, 3)).unwrap()[0].to_u64(),
413 Some(6)
414 );
415 }
416
417 #[test]
418 fn sparse_evaluation_plans_only_store_reachable_values_and_read_shared_symbols_once() {
419 let mut cx = Context::new();
420 let x = cx.symbol("x", Width::W64).unwrap();
421 let y = cx.symbol("y", Width::W64).unwrap();
422 let sum = cx.add(x, y).unwrap();
423 for i in 0..10_000 {
424 cx.symbol(SymbolKey::U64(i), Width::W512).unwrap();
425 }
426 let reads = std::cell::RefCell::new(Vec::new());
427 let env = FnEnv(|key: &SymbolKey, w| {
428 reads.borrow_mut().push(key.clone());
429 Some(BitVec::one(w))
430 });
431 let want_order = cx
432 .post_order(&[sum, x, sum])
433 .unwrap()
434 .into_iter()
435 .filter_map(|e| cx.symbol_id(e).unwrap())
436 .map(|s| cx.symbol_key(s).unwrap().clone())
437 .collect::<Vec<_>>();
438 for _ in 0..2 {
439 reads.borrow_mut().clear();
440 cx.eval(&[sum, x, sum], &env).unwrap();
441 assert_eq!(*reads.borrow(), want_order);
442 let plan = cx.eval_plan.as_ref().unwrap();
443 assert_eq!(plan.instructions.len(), 3);
444 assert_eq!(plan.words.len(), 3);
445 assert!(plan.values.is_empty());
446 }
447 }
448
449 #[test]
450 fn mixed_evaluation_plans_only_materialize_values_needed_by_fallbacks() {
451 let mut cx = Context::new();
452 let x = cx.symbol("x", Width::W64).unwrap();
453 let one = cx.one(Width::W64).unwrap();
454 let mut root = x;
455 for _ in 0..1000 {
456 root = cx.add(root, one).unwrap();
457 }
458 let wide = cx.zero(Width::W512).unwrap();
459 let reads = std::cell::Cell::new(0);
460 let env = FnEnv(|_: &SymbolKey, w| {
461 reads.set(reads.get() + 1);
462 Some(BitVec::one(w))
463 });
464 let expected = BitVec::from_u64(Width::W64, 1001).unwrap();
465 for _ in 0..2 {
466 let values = cx.eval(&[root, wide, root], &env).unwrap();
467 assert_eq!(values, [expected, BitVec::zero(Width::W512), expected]);
468 let plan = cx.eval_plan.as_ref().unwrap();
469 assert_eq!(plan.values.len(), 1);
471 }
472 assert_eq!(reads.get(), 2);
473 assert!(matches!(
474 cx.eval(&[root, wide, root], &FnEnv(|_: &SymbolKey, _| None)),
475 Err(Error::UnboundSymbol { .. })
476 ));
477 assert!(matches!(
478 cx.eval(
479 &[root, wide, root],
480 &FnEnv(|_: &SymbolKey, _| Some(BitVec::one(Width::W128)))
481 ),
482 Err(Error::EnvWidth { .. })
483 ));
484 assert_eq!(
485 cx.eval(&[root, wide, root], &env).unwrap()[0].to_u64(),
486 Some(1001)
487 );
488 assert_eq!(cx.eval(&[root], &env).unwrap()[0].to_u64(), Some(1001));
489 assert!(cx.eval_plan.as_ref().unwrap().narrow);
490 }
491
492 #[test]
493 fn mixed_evaluation_plans_cross_width_and_kernel_boundaries() {
494 for bits in [129, 192, 255, 256, 511, 512] {
495 let w = Width::new(bits).unwrap();
496 let mut cx = Context::new();
497 let x = cx.symbol("x", w).unwrap();
498 let y = cx.symbol("y", Width::W64).unwrap();
499 let lo = cx.extract(x, 0, Width::W64).unwrap();
500 let hi = cx.extract(x, bits - 64, Width::W64).unwrap();
501 let sum = cx.add(lo, y).unwrap();
502 let extended = cx.sext(sum, w).unwrap();
503 let wide = cx.add(x, extended).unwrap();
504 let predicate = cx.cmp(crate::CmpOpExt::Slt, x, wide).unwrap();
505 let selected = cx.select(predicate, sum, hi).unwrap();
506 let wide_selected = cx.select(predicate, wide, extended).unwrap();
507 let truncated = cx.extract(wide_selected, bits - 64, Width::W64).unwrap();
508 let round_trip = cx.add(truncated, selected).unwrap();
509 let lhs = cx.concat(hi, lo).unwrap();
510 let rhs = cx.sext(sum, Width::W128).unwrap();
511 let mut roots = vec![sum, wide, predicate, selected, wide_selected, round_trip];
512 for op in [BinOp::UMulHi, BinOp::SMulHi] {
513 let product = cx.bin(op, lhs, rhs).unwrap();
514 let resumed = cx.add(product, lhs).unwrap();
515 roots.extend([product, resumed]);
516 }
517 let roots2 = roots
518 .iter()
519 .rev()
520 .copied()
521 .chain([round_trip, sum])
522 .collect::<Vec<_>>();
523 for value in [
524 BitVec::zero(w),
525 BitVec::one(w),
526 BitVec::ones(w),
527 BitVec::smin(w),
528 BitVec::wrapping_from_limbs(w, &[0x0123_4567_89ab_cdef; 8]),
529 ] {
530 let env = [
531 (SymbolKey::from("x"), value),
532 (
533 SymbolKey::from("y"),
534 BitVec::wrapping_from_u64(Width::W64, value.limbs()[0]),
535 ),
536 ];
537 for roots in [&roots, &roots, &roots2, &roots2] {
538 let want = interpreted(&mut cx, roots, &env[..]);
539 assert_eq!(cx.eval(roots, &env[..]).unwrap(), want, "width {bits}");
540 }
541 }
542 }
543 }
544
545 #[test]
546 fn mixed_evaluation_plans_cross_floating_point_boundaries() {
547 use crate::fp::{FpCmpOp, FpFormat, FpOp, RoundingMode};
548 for format in [FpFormat::F32, FpFormat::F64, FpFormat::F128] {
549 let mut cx = Context::new();
550 let x = cx.symbol("x", Width::W64).unwrap();
551 let y = cx.symbol("y", format.width()).unwrap();
552 let one = cx.one(Width::W64).unwrap();
553 let incremented = cx.add(x, one).unwrap();
554 let f = cx
555 .fp(FpOp::FromUInt(RoundingMode::Rne), format, &[incremented])
556 .unwrap();
557 let fsum = cx
558 .fp(FpOp::Add(RoundingMode::Rne), format, &[f, y])
559 .unwrap();
560 let fma = cx
561 .fp(FpOp::Fma(RoundingMode::Rne), format, &[f, y, fsum])
562 .unwrap();
563 let converted = cx
564 .fp(
565 FpOp::Convert {
566 to: FpFormat::F32,
567 rm: RoundingMode::Rne,
568 },
569 format,
570 &[fma],
571 )
572 .unwrap();
573 let raw_bits = cx.extract(converted, 0, Width::W8).unwrap();
574 let resumed = cx.add(raw_bits, raw_bits).unwrap();
575 let integer = cx
576 .fp(FpOp::ToUInt(RoundingMode::Rtz, Width::W64), format, &[fsum])
577 .unwrap();
578 let predicate = cx.fp_cmp(format, FpCmpOp::Lt, y, f).unwrap();
579 let selected = cx.select(predicate, integer, incremented).unwrap();
580 let result = cx.add(selected, one).unwrap();
581 let roots = [
582 incremented,
583 fsum,
584 fma,
585 converted,
586 resumed,
587 integer,
588 predicate,
589 result,
590 ];
591 for fv in [
592 format.zero(false),
593 format.zero(true),
594 format.inf(false),
595 format.nan(),
596 format.from_uint(
597 RoundingMode::Rne,
598 &BitVec::from_u64(Width::W64, 17).unwrap(),
599 ),
600 ] {
601 let env = [
602 (
603 SymbolKey::from("x"),
604 BitVec::from_u64(Width::W64, 42).unwrap(),
605 ),
606 (SymbolKey::from("y"), fv),
607 ];
608 let want = interpreted(&mut cx, &roots, &env[..]);
609 for _ in 0..2 {
610 assert_eq!(cx.eval(&roots, &env[..]).unwrap(), want, "{format:?}");
611 }
612 }
613 }
614 }
615
616 #[test]
617 fn mixed_evaluation_plans_cross_extension_boundaries() {
618 use crate::ext::{ExtOp, ExtSig, Registry};
619 struct WidePair;
620 impl ExtOp for WidePair {
621 fn name(&self) -> &str {
622 "test.widepair"
623 }
624 fn signature(&self, args: &[Width]) -> Result<ExtSig, String> {
625 match args {
626 [w] => Ok(ExtSig::new(&[("wide", Width::W512), ("inverted", *w)])),
627 _ => Err("one argument".into()),
628 }
629 }
630 fn eval(&self, args: &[BitVec], out: &mut [BitVec]) {
631 out[0] = args[0].zext(Width::W512).unwrap();
632 out[1] = BitVec::apply_un(UnOp::Not, &args[0]).unwrap();
633 }
634 }
635 let registry = std::sync::Arc::new(Registry::builder().register(WidePair).unwrap().build());
636 let op = registry.id("test.widepair").unwrap();
637 let mut cx = Context::with_registry(crate::ContextConfig::default(), registry);
638 let x = cx.symbol("x", Width::W64).unwrap();
639 let one = cx.one(Width::W64).unwrap();
640 let incremented = cx.add(x, one).unwrap();
641 let outputs = cx.ext(op, &[incremented]).unwrap();
642 let low = cx.extract(outputs[0], 0, Width::W64).unwrap();
643 let sum = cx.add(low, outputs[1]).unwrap();
644 let again = cx.ext(op, &[sum]).unwrap();
645 let roots = [incremented, outputs[0], outputs[1], sum, again[0], again[1]];
646 for value in [0, 1, u64::MAX, 0x0123_4567_89ab_cdef] {
647 let env = [(
648 SymbolKey::from("x"),
649 BitVec::from_u64(Width::W64, value).unwrap(),
650 )];
651 let want = interpreted(&mut cx, &roots, &env[..]);
652 for _ in 0..2 {
653 assert_eq!(cx.eval(&roots, &env[..]).unwrap(), want);
654 }
655 }
656 }
657}
658
659pub trait Env {
661 fn value(&self, key: &SymbolKey, width: Width) -> Option<BitVec>;
663}
664
665impl<S: BuildHasher> Env for HashMap<SymbolKey, BitVec, S> {
666 fn value(&self, key: &SymbolKey, _width: Width) -> Option<BitVec> {
667 self.get(key).copied()
668 }
669}
670
671impl Env for BTreeMap<SymbolKey, BitVec> {
672 fn value(&self, key: &SymbolKey, _width: Width) -> Option<BitVec> {
673 self.get(key).copied()
674 }
675}
676
677impl Env for [(SymbolKey, BitVec)] {
678 fn value(&self, key: &SymbolKey, _width: Width) -> Option<BitVec> {
679 self.iter().find(|(k, _)| k == key).map(|(_, v)| *v)
680 }
681}
682
683#[derive(Clone, Copy, Debug)]
685pub struct FnEnv<F>(pub F);
686
687impl<F: Fn(&SymbolKey, Width) -> Option<BitVec>> Env for FnEnv<F> {
688 fn value(&self, key: &SymbolKey, width: Width) -> Option<BitVec> {
689 (self.0)(key, width)
690 }
691}
692
693impl Context {
694 pub fn eval(
698 &mut self,
699 roots: &[Expr],
700 env: &(impl Env + ?Sized),
701 ) -> Result<Vec<BitVec>, Error> {
702 let ids = self.ids(roots)?;
703 self.eval_ids(&ids, env)
704 }
705
706 pub(crate) fn eval_ids(
707 &mut self,
708 roots: &[u32],
709 env: &(impl Env + ?Sized),
710 ) -> Result<Vec<BitVec>, Error> {
711 if roots.is_empty() {
712 return Ok(Vec::new());
713 }
714 let mut plan = self.eval_plan.take().unwrap_or_default();
715 if plan.roots != roots {
716 plan.prepare(self, roots);
717 }
718 let result = plan.run(self, env);
719 self.eval_plan = Some(plan);
720 result
721 }
722
723 fn eval_symbol(&self, symbol: u32, env: &(impl Env + ?Sized)) -> Result<BitVec, Error> {
724 let entry = &self.symbols.entries[symbol as usize];
725 let v = env
726 .value(&entry.key, entry.width)
727 .ok_or_else(|| Error::UnboundSymbol {
728 key: entry.key.clone(),
729 })?;
730 if v.width() != entry.width {
731 return Err(Error::EnvWidth {
732 key: entry.key.clone(),
733 expected: entry.width,
734 got: v.width(),
735 });
736 }
737 Ok(v)
738 }
739
740 pub(crate) fn eval_node(
742 &self,
743 i: u32,
744 get: impl Fn(u32) -> BitVec,
745 sym: impl Fn(&SymbolKey, Width) -> Option<BitVec>,
746 ) -> Result<BitVec, Error> {
747 self.eval_node_mapped(i, self.node(i), get, sym)
748 }
749
750 fn eval_node_mapped(
751 &self,
752 i: u32,
753 n: Node,
754 get: impl Fn(u32) -> BitVec,
755 sym: impl Fn(&SymbolKey, Width) -> Option<BitVec>,
756 ) -> Result<BitVec, Error> {
757 Ok(match n.op {
758 OpCode::Const => self.const_val(i).unwrap_or(BitVec::zero(Width::W1)),
759 OpCode::Sym => {
760 let entry = &self.symbols.entries[n.a as usize];
761 let v = sym(&entry.key, entry.width).ok_or_else(|| Error::UnboundSymbol {
762 key: entry.key.clone(),
763 })?;
764 if v.width() != entry.width {
765 return Err(Error::EnvWidth {
766 key: entry.key.clone(),
767 expected: entry.width,
768 got: v.width(),
769 });
770 }
771 v
772 }
773 OpCode::Zext => get(n.a).zext(self.width_of(i))?,
774 OpCode::Sext => get(n.a).sext(self.width_of(i))?,
775 OpCode::Extract => get(n.a).extract(n.b as u16, self.width_of(i))?,
776 OpCode::Concat => BitVec::concat(&get(n.a), &get(n.b))?,
777 OpCode::Select => BitVec::select(&get(n.a), &get(n.b), &get(n.c))?,
778 op if op.as_ext().is_some() => {
779 let args: Vec<BitVec> = n.children().map(&get).collect();
780 self.eval_ext(i, &args)?
781 }
782 op => {
783 if let Some(u) = op.as_un() {
784 BitVec::apply_un(u, &get(n.a))?
785 } else if let Some(b) = op.as_bin() {
786 BitVec::bin_unchecked(b, &get(n.a), &get(n.b))
787 } else if let Some(c) = op.as_cmp() {
788 BitVec::from_bool(BitVec::cmp_unchecked(c, &get(n.a), &get(n.b)))
789 } else if let Some(d) = self.fp_desc(i) {
790 let args: Vec<BitVec> = n.children().map(&get).collect();
791 crate::fp::eval(&d, &args)
792 } else {
793 unreachable!("every opcode is covered")
794 }
795 }
796 })
797 }
798
799 pub(crate) fn eval_ext(&self, i: u32, args: &[BitVec]) -> Result<BitVec, Error> {
802 let n = self.node(i);
803 let (_, k) = n.op.as_ext().unwrap_or((1, 0));
804 let op = self
805 .registry
806 .as_deref()
807 .and_then(|r| r.op_at(n.aux))
808 .ok_or_else(|| Error::Contract("an extension node without its operation".into()))?;
809 let out = crate::ext::run_eval(op, args)
810 .map_err(|why| Error::Contract(format!("`{}`: {why}", op.name())))?;
811 out.get(k)
812 .copied()
813 .ok_or_else(|| Error::Contract(format!("`{}` has no output {k}", op.name())))
814 }
815
816 pub fn substitute(&mut self, roots: &[Expr], map: &[(Expr, Expr)]) -> Result<Vec<Expr>, Error> {
820 let ids = self.ids(roots)?;
821 let mut repl: IdMap<u32, u32> = IdMap::default();
822 for &(from, to) in map {
823 let (f, t) = (self.id(from)?, self.id(to)?);
824 let (wf, wt) = (self.wid(f), self.wid(t));
825 if wf != wt {
826 return Err(crate::WidthError::Mismatch {
827 left: wf,
828 right: wt,
829 }
830 .into());
831 }
832 if repl.insert(f, t).is_some() {
833 return Err(Error::DuplicateSubstitution);
834 }
835 }
836 let out = self.substitute_ids(&ids, &repl)?;
837 Ok(out.into_iter().map(|i| self.handle(i)).collect())
838 }
839
840 pub fn substitute_bounded(
845 &mut self,
846 roots: &[Expr],
847 s: &mut Substitution,
848 max_visits: u64,
849 ) -> Result<Option<Vec<Expr>>, Error> {
850 let ids = self.ids(roots)?;
851 s.check_context(self)?;
852 let mut visits = 0u64;
853 let (mut next_root, mut stack) = match s.pending.take() {
855 Some(p) if p.roots == ids => (p.next_root, p.stack),
856 _ => (0, Vec::new()),
857 };
858 loop {
859 if stack.is_empty() {
860 let Some(&root) = ids.get(next_root) else {
861 break;
862 };
863 next_root += 1;
864 if !s.done.contains_key(&root) {
865 stack.push((root, false));
866 }
867 continue;
868 }
869 let Some(&(i, expanded)) = stack.last() else {
870 break;
871 };
872 if s.done.contains_key(&i) {
873 stack.pop();
874 continue;
875 }
876 if let Some(&t) = s.repl.get(&i) {
877 stack.pop();
878 s.done.insert(i, t);
879 continue;
880 }
881 let n = self.node(i);
882 if !expanded {
883 if visits >= max_visits {
884 s.pending = Some(Pending {
885 roots: ids,
886 next_root,
887 stack,
888 });
889 return Ok(None);
890 }
891 visits += 1;
892 if let Some(top) = stack.last_mut() {
893 top.1 = true;
894 }
895 for c in n.children() {
896 if !s.done.contains_key(&c) {
897 stack.push((c, false));
898 }
899 }
900 continue;
901 }
902 stack.pop();
903 let mut kids = [n.a, n.b, n.c];
904 let mut changed = false;
905 for (k, c) in n.children().enumerate() {
906 let nc = s.done[&c];
907 changed |= nc != c;
908 kids[k] = nc;
909 }
910 let r = if changed { self.rebuild(i, kids)? } else { i };
911 s.done.insert(i, r);
912 }
913 Ok(Some(ids.iter().map(|r| self.handle(s.done[r])).collect()))
914 }
915
916 pub(crate) fn substitute_ids(
917 &mut self,
918 roots: &[u32],
919 repl: &IdMap<u32, u32>,
920 ) -> Result<Vec<u32>, Error> {
921 if repl.is_empty() {
922 return Ok(roots.to_vec());
923 }
924 let order = self.post_order_ids_pruned(roots, |e| repl.contains_key(&e.index()));
925 let mut new = crate::engine::pass::Lease::new(self.len());
930 let became = |new: &crate::engine::pass::Lease, c: u32| match new.get(c) {
931 Some(r) => r,
932 None => repl[&c],
933 };
934 for i in order {
935 let n = self.node(i);
936 let mut kids = [n.a, n.b, n.c];
937 let mut changed = false;
938 for (k, c) in n.children().enumerate() {
939 let nc = became(&new, c);
940 changed |= nc != c;
941 kids[k] = nc;
942 }
943 let r = if changed { self.rebuild(i, kids)? } else { i };
944 new.insert(i, r);
945 }
946 Ok(roots.iter().map(|&r| became(&new, r)).collect())
947 }
948}
949
950#[derive(Clone, Debug)]
952struct Pending {
953 roots: Vec<u32>,
954 next_root: usize,
955 stack: Vec<(u32, bool)>,
956}
957
958#[derive(Clone, Debug, Default)]
962pub struct Substitution {
963 repl: IdMap<u32, u32>,
964 done: IdMap<u32, u32>,
965 pending: Option<Pending>,
967 probe: Option<Expr>,
969}
970
971impl Substitution {
972 pub fn new() -> Self {
974 Self::default()
975 }
976
977 pub fn replace(&mut self, cx: &Context, from: Expr, to: Expr) -> Result<&mut Self, Error> {
980 let (f, t) = (cx.id(from)?, cx.id(to)?);
981 self.check_context(cx)?;
982 let (wf, wt) = (cx.wid(f), cx.wid(t));
983 if wf != wt {
984 return Err(crate::WidthError::Mismatch {
985 left: wf,
986 right: wt,
987 }
988 .into());
989 }
990 if !self.done.is_empty() {
991 return Err(Error::Unsupported(
992 "a replacement added after the substitution was applied".into(),
993 ));
994 }
995 if self.repl.insert(f, t).is_some() {
996 return Err(Error::DuplicateSubstitution);
997 }
998 self.probe.get_or_insert(from);
999 Ok(self)
1000 }
1001
1002 pub fn image(&self, cx: &Context, e: Expr) -> Result<Option<Expr>, Error> {
1004 let i = cx.id(e)?;
1005 Ok(self.done.get(&i).map(|&r| cx.handle(r)))
1006 }
1007
1008 pub fn changed(&self, cx: &Context) -> Vec<(Expr, Expr)> {
1010 let mut v: Vec<(u32, u32)> = self
1011 .done
1012 .iter()
1013 .filter(|(a, b)| a != b)
1014 .map(|(&a, &b)| (a, b))
1015 .collect();
1016 v.sort_unstable();
1017 v.into_iter()
1018 .map(|(a, b)| (cx.handle(a), cx.handle(b)))
1019 .collect()
1020 }
1021
1022 fn check_context(&self, cx: &Context) -> Result<(), Error> {
1023 if let Some(p) = self.probe {
1024 cx.id(p)?;
1025 }
1026 Ok(())
1027 }
1028}