1use crate::simd::{
15 and_words, andnot_words, is_all_zero_words, not_words, or_and_assign_words, or_assign_words,
16 or_words,
17};
18use elinvar_logic::{
19 Against, BinaryOp, Bounds, Decl, Error, Expr, ExprKind, Formula, FormulaKind, Multiplicity,
20 Quantifier, Relation, UnaryOp, Variable, check_formula, count as plain_count,
21};
22use std::collections::BTreeMap;
23
24const WORDS: usize = 64;
26const LANES: u64 = (WORDS * 64) as u64;
27
28#[derive(Clone, PartialEq, Eq)]
29struct Mask(Vec<u64>);
30
31impl Mask {
32 fn zeros() -> Mask {
33 Mask(vec![0; WORDS])
34 }
35
36 fn ones() -> Mask {
37 Mask(vec![u64::MAX; WORDS])
38 }
39
40 fn and(&self, o: &Mask) -> Mask {
41 let mut d = Mask::zeros();
42 and_words(&mut d.0, &self.0, &o.0);
43 d
44 }
45
46 fn or(&self, o: &Mask) -> Mask {
47 let mut d = Mask::zeros();
48 or_words(&mut d.0, &self.0, &o.0);
49 d
50 }
51
52 fn or_assign(&mut self, o: &Mask) {
53 or_assign_words(&mut self.0, &o.0);
54 }
55
56 fn or_and_assign(&mut self, a: &Mask, b: &Mask) {
57 or_and_assign_words(&mut self.0, &a.0, &b.0);
58 }
59
60 fn andnot(&self, o: &Mask) -> Mask {
62 let mut d = Mask::zeros();
63 andnot_words(&mut d.0, &self.0, &o.0);
64 d
65 }
66
67 fn not(&self) -> Mask {
68 let mut d = Mask::zeros();
69 not_words(&mut d.0, &self.0);
70 d
71 }
72
73 fn is_zero(&self) -> bool {
74 is_all_zero_words(&self.0)
75 }
76
77 fn count(&self) -> u64 {
78 self.0.iter().map(|w| u64::from(w.count_ones())).sum()
79 }
80}
81
82type Table = BTreeMap<u64, Mask>;
84
85fn get(t: &Table, i: u64) -> Mask {
86 t.get(&i).cloned().unwrap_or_else(Mask::zeros)
87}
88
89fn put(t: &mut Table, i: u64, m: Mask) {
90 if !m.is_zero() {
91 t.insert(i, m);
92 }
93}
94
95fn supported(f: &Formula) -> bool {
98 fn expr(e: &Expr) -> bool {
99 match e.kind() {
100 ExprKind::Binary(_, a, b) => expr(a) && expr(b),
101 ExprKind::Unary(_, a) => expr(a),
102 ExprKind::Comprehension(decls, body) => decls_ok(decls) && formula(body),
103 ExprKind::IfThenElse(c, a, b) => formula(c) && expr(a) && expr(b),
104 ExprKind::Prime(_) | ExprKind::IntToSet(_) => false,
105 ExprKind::Relation(r) => !r.is_changing(),
106 ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => true,
107 }
108 }
109 fn decls_ok(decls: &[Decl]) -> bool {
110 decls.iter().all(|d| d.is_first_order() && expr(&d.expr))
111 }
112 fn formula(f: &Formula) -> bool {
113 match f.kind() {
114 FormulaKind::Constant(_) => true,
115 FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr(a) && expr(b),
116 FormulaKind::Multiplicity(_, a) => expr(a),
117 FormulaKind::Not(g) => formula(g),
118 FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(formula),
119 FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => formula(a) && formula(b),
120 FormulaKind::Quantified(_, decls, body) => decls_ok(decls) && formula(body),
121 FormulaKind::Temporal(..)
122 | FormulaKind::TemporalBinary(..)
123 | FormulaKind::IntCompare(..) => false,
124 }
125 }
126 formula(f)
127}
128
129struct Block<'a> {
130 n: u64,
131 relations: &'a [(Relation, Table)],
132 env: Vec<(Variable, u64)>,
133}
134
135impl Block<'_> {
136 fn pow(&self, k: usize) -> u64 {
137 self.n.pow(k as u32)
138 }
139
140 fn arity(e: &Expr) -> usize {
141 e.arity().expect("checked before counting")
142 }
143
144 fn expr(&mut self, e: &Expr) -> Table {
145 let n = self.n;
146 let mut out = Table::new();
147 match e.kind() {
148 ExprKind::Relation(r) => {
149 return self
150 .relations
151 .iter()
152 .find(|(s, _)| s == r)
153 .map(|(_, t)| t.clone())
154 .expect("checked before counting");
155 }
156 ExprKind::Variable(v) => {
157 let a = self
158 .env
159 .iter()
160 .rev()
161 .find(|(w, _)| w == v)
162 .map(|(_, a)| *a)
163 .expect("checked before counting");
164 out.insert(a, Mask::ones());
165 }
166 ExprKind::None => {}
167 ExprKind::Univ => {
168 for a in 0..n {
169 out.insert(a, Mask::ones());
170 }
171 }
172 ExprKind::Iden => {
173 for a in 0..n {
174 out.insert(a * n + a, Mask::ones());
175 }
176 }
177 ExprKind::Binary(op, a, b) => {
178 let (ta, tb) = (self.expr(a), self.expr(b));
179 return self.binary(*op, &ta, &tb, Self::arity(a), Self::arity(b));
180 }
181 ExprKind::Unary(op, a) => {
182 let ta = self.expr(a);
183 return match op {
184 UnaryOp::Transpose => ta
185 .into_iter()
186 .map(|(i, m)| ((i % n) * n + i / n, m))
187 .collect(),
188 UnaryOp::Closure => self.closure(&ta),
189 UnaryOp::ReflexiveClosure => {
190 let mut t = self.closure(&ta);
191 for x in 0..n {
192 t.insert(x * n + x, Mask::ones());
193 }
194 t
195 }
196 };
197 }
198 ExprKind::Comprehension(decls, body) => {
199 let mut values: Table = Table::new();
200 let mut chosen = Vec::new();
201 self.bindings(decls, &mut chosen, Mask::ones(), &mut |b, atoms, guard| {
202 let v = guard.and(&b.formula(body));
203 if !v.is_zero() {
204 let idx = atoms.iter().fold(0u64, |acc, &x| acc * n + x);
205 values.entry(idx).or_insert_with(Mask::zeros).or_assign(&v);
206 }
207 });
208 return values;
209 }
210 ExprKind::IfThenElse(c, a, b) => {
211 let cv = self.formula(c);
212 let (ta, tb) = (self.expr(a), self.expr(b));
213 let keys: std::collections::BTreeSet<u64> =
214 ta.keys().chain(tb.keys()).copied().collect();
215 for i in keys {
216 let v = get(&ta, i).and(&cv).or(&get(&tb, i).andnot(&cv));
217 put(&mut out, i, v);
218 }
219 }
220 ExprKind::Prime(_) | ExprKind::IntToSet(_) => {
221 unreachable!("not supported, so not counted here")
222 }
223 }
224 out
225 }
226
227 fn join(&self, a: &Table, b: &Table, bk: usize) -> Table {
228 let n = self.n;
229 let tail = self.pow(bk - 1);
230 let mut out = Table::new();
231 for (&x, ma) in a {
232 for (&y, mb) in b {
233 if y / tail == x % n {
234 let i = (x / n) * tail + y % tail;
235 out.entry(i)
236 .or_insert_with(Mask::zeros)
237 .or_and_assign(ma, mb);
238 }
239 }
240 }
241 out.retain(|_, m| !m.is_zero());
242 out
243 }
244
245 fn binary(&self, op: BinaryOp, a: &Table, b: &Table, ak: usize, bk: usize) -> Table {
246 let n = self.n;
247 let mut out = Table::new();
248 match op {
249 BinaryOp::Union => {
250 let keys: std::collections::BTreeSet<u64> =
251 a.keys().chain(b.keys()).copied().collect();
252 for i in keys {
253 put(&mut out, i, get(a, i).or(&get(b, i)));
254 }
255 }
256 BinaryOp::Intersection => {
257 for (&i, m) in a {
258 put(&mut out, i, m.and(&get(b, i)));
259 }
260 }
261 BinaryOp::Difference => {
262 for (&i, m) in a {
263 put(&mut out, i, m.andnot(&get(b, i)));
264 }
265 }
266 BinaryOp::Join => return self.join(a, b, bk),
267 BinaryOp::Product => {
268 let shift = self.pow(bk);
269 for (&x, ma) in a {
270 for (&y, mb) in b {
271 put(&mut out, x * shift + y, ma.and(mb));
272 }
273 }
274 }
275 BinaryOp::Override => {
276 let row = self.pow(ak - 1);
279 let mut rows: BTreeMap<u64, Mask> = BTreeMap::new();
280 for (&y, m) in b {
281 let cur = rows.get(&(y / row)).cloned().unwrap_or_else(Mask::zeros);
282 rows.insert(y / row, cur.or(m));
283 }
284 let keys: std::collections::BTreeSet<u64> =
285 a.keys().chain(b.keys()).copied().collect();
286 for i in keys {
287 let blocked = rows.get(&(i / row)).cloned().unwrap_or_else(Mask::zeros);
288 put(&mut out, i, get(a, i).andnot(&blocked).or(&get(b, i)));
289 }
290 }
291 BinaryOp::DomainRestriction => {
292 let row = self.pow(bk - 1);
293 for (&y, m) in b {
294 put(&mut out, y, m.and(&get(a, y / row)));
295 }
296 }
297 BinaryOp::RangeRestriction => {
298 for (&x, m) in a {
299 put(&mut out, x, m.and(&get(b, x % n)));
300 }
301 }
302 }
303 out
304 }
305
306 fn closure(&self, a: &Table) -> Table {
309 let mut t = a.clone();
310 loop {
311 let step = self.join(&t, a, 2);
312 let next = self.binary(BinaryOp::Union, &t, &step, 2, 2);
313 if next == t {
314 return t;
315 }
316 t = next;
317 }
318 }
319
320 fn bindings(
321 &mut self,
322 decls: &[Decl],
323 chosen: &mut Vec<u64>,
324 guard: Mask,
325 visit: &mut dyn FnMut(&mut Self, &[u64], &Mask),
326 ) {
327 let k = chosen.len();
328 if k == decls.len() {
329 visit(self, chosen, &guard);
330 return;
331 }
332 let range = self.expr(&decls[k].expr);
333 for (atom, m) in range {
334 let g = guard.and(&m);
335 if g.is_zero() {
336 continue;
337 }
338 self.env.push((decls[k].var.clone(), atom));
339 chosen.push(atom);
340 self.bindings(decls, chosen, g, visit);
341 chosen.pop();
342 self.env.pop();
343 }
344 }
345
346 fn count(m: Multiplicity, values: &[Mask]) -> Mask {
348 let mut seen = Mask::zeros();
349 let mut two = Mask::zeros();
350 for v in values {
351 two = two.or(&seen.and(v));
352 seen = seen.or(v);
353 }
354 match m {
355 Multiplicity::Some => seen,
356 Multiplicity::No => seen.not(),
357 Multiplicity::Lone => two.not(),
358 Multiplicity::One => seen.andnot(&two),
359 }
360 }
361
362 fn formula(&mut self, f: &Formula) -> Mask {
363 match f.kind() {
364 FormulaKind::Constant(true) => Mask::ones(),
365 FormulaKind::Constant(false) => Mask::zeros(),
366 FormulaKind::Subset(a, b) => {
367 let (ta, tb) = (self.expr(a), self.expr(b));
368 let mut all = Mask::ones();
369 for (&i, m) in &ta {
370 all = all.andnot(&m.andnot(&get(&tb, i)));
371 }
372 all
373 }
374 FormulaKind::Equal(a, b) => {
375 let (ta, tb) = (self.expr(a), self.expr(b));
376 let keys: std::collections::BTreeSet<u64> =
377 ta.keys().chain(tb.keys()).copied().collect();
378 let mut all = Mask::ones();
379 for i in keys {
380 let (x, y) = (get(&ta, i), get(&tb, i));
381 all = all.andnot(&x.andnot(&y)).andnot(&y.andnot(&x));
382 }
383 all
384 }
385 FormulaKind::Multiplicity(m, a) => {
386 let values: Vec<Mask> = self.expr(a).into_values().collect();
387 Self::count(*m, &values)
388 }
389 FormulaKind::Not(g) => self.formula(g).not(),
390 FormulaKind::And(fs) => fs
391 .iter()
392 .fold(Mask::ones(), |acc, g| acc.and(&self.formula(g))),
393 FormulaKind::Or(fs) => fs
394 .iter()
395 .fold(Mask::zeros(), |acc, g| acc.or(&self.formula(g))),
396 FormulaKind::Implies(a, b) => {
397 let (x, y) = (self.formula(a), self.formula(b));
398 x.not().or(&y)
399 }
400 FormulaKind::Iff(a, b) => {
401 let (x, y) = (self.formula(a), self.formula(b));
402 x.and(&y).or(&x.not().and(&y.not()))
403 }
404 FormulaKind::Quantified(q, decls, body) => {
405 let mut cases: Vec<(Mask, Mask)> = Vec::new();
406 let mut chosen = Vec::new();
407 self.bindings(decls, &mut chosen, Mask::ones(), &mut |b, _, guard| {
408 let v = b.formula(body);
409 cases.push((guard.clone(), v));
410 });
411 match q {
412 Quantifier::All => cases
413 .iter()
414 .fold(Mask::ones(), |acc, (g, v)| acc.andnot(&g.andnot(v))),
415 _ => {
416 let values: Vec<Mask> = cases.iter().map(|(g, v)| g.and(v)).collect();
417 let m = match q {
418 Quantifier::Some => Multiplicity::Some,
419 Quantifier::No => Multiplicity::No,
420 Quantifier::One => Multiplicity::One,
421 Quantifier::Lone | Quantifier::All => Multiplicity::Lone,
422 };
423 Self::count(m, &values)
424 }
425 }
426 }
427 FormulaKind::Temporal(..)
428 | FormulaKind::TemporalBinary(..)
429 | FormulaKind::IntCompare(..) => {
430 unreachable!("not supported, so not counted here")
431 }
432 }
433 }
434}
435
436pub fn count_bitsliced(bounds: &Bounds, formula: &Formula, cap: usize) -> Result<u64, Vec<Error>> {
440 let errors = check_formula(formula, Against::Bounds(bounds));
441 if !errors.is_empty() {
442 return Err(errors);
443 }
444 if !supported(formula) || bounds.relations().any(Relation::is_changing) {
445 return plain_count(bounds, formula, cap);
446 }
447 let mut free = Vec::new();
449 for (pos, (_, lower, upper)) in bounds.entries().enumerate() {
450 for i in upper.indices() {
451 if !lower.contains_index(i) {
452 free.push((pos, i));
453 }
454 }
455 }
456 let m = free.len();
457 if m > cap || m > 63 {
458 return Err(vec![Error::new(
459 "enumerate.too_large",
460 format!("{m} free tuples, and the cap is {}", cap.min(63)),
461 )]);
462 }
463 let total = 1u64 << m;
464 let lane_bits = LANES.trailing_zeros() as usize;
465 let pattern = |b: usize| -> Mask {
467 Mask(
468 (0..WORDS)
469 .map(|w| {
470 (0..64u64).fold(0u64, |acc, k| {
471 let lane = (w as u64) * 64 + k;
472 acc | (((lane >> b) & 1) << k)
473 })
474 })
475 .collect(),
476 )
477 };
478 let patterns: Vec<Mask> = (0..lane_bits.min(m)).map(pattern).collect();
479 let mut counted = 0u64;
480 let mut base = 0u64;
481 while base < total {
482 let relations: Vec<(Relation, Table)> = bounds
483 .entries()
484 .enumerate()
485 .map(|(pos, (r, lower, _))| {
486 let mut t = Table::new();
487 for i in lower.indices() {
488 t.insert(i, Mask::ones());
489 }
490 for (bit, &(p, i)) in free.iter().enumerate() {
491 if p != pos {
492 continue;
493 }
494 let mask = if bit < lane_bits {
495 patterns[bit].clone()
496 } else if (base >> bit) & 1 == 1 {
497 Mask::ones()
498 } else {
499 Mask::zeros()
500 };
501 put(&mut t, i, mask);
502 }
503 (r.clone(), t)
504 })
505 .collect();
506 let mut block = Block {
507 n: bounds.universe().size() as u64,
508 relations: &relations,
509 env: Vec::new(),
510 };
511 let mut holds = block.formula(formula);
512 let valid = (total - base).min(LANES);
514 if valid < LANES {
515 let mut keep = Mask::zeros();
516 for lane in 0..valid {
517 keep.0[(lane / 64) as usize] |= 1 << (lane % 64);
518 }
519 holds = holds.and(&keep);
520 }
521 counted += holds.count();
522 base += LANES;
523 }
524 Ok(counted)
525}