-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathlib.rs
1700 lines (1522 loc) · 58.1 KB
/
lib.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use itertools::Itertools;
use powdr::collect_cols_algebraic;
use powdr_ast::analyzed::BusInteractionKind as AnalyzedBusInteractionKind;
use powdr_ast::parsed::asm::Part;
use powdr_ast::{
analyzed::{
AlgebraicBinaryOperation, AlgebraicBinaryOperator, AlgebraicExpression, AlgebraicReference,
AlgebraicUnaryOperator, Analyzed, BusInteractionIdentity, Identity, PolynomialIdentity,
},
parsed::{
asm::SymbolPath, visitor::AllChildren, ArrayLiteral, BinaryOperation, BinaryOperator,
Expression, FunctionCall, NamespacedPolynomialReference, Number, PILFile, PilStatement,
UnaryOperation, UnaryOperator,
},
};
use powdr_executor::witgen::evaluators::symbolic_evaluator::SymbolicEvaluator;
use powdr_executor::witgen::{AlgebraicVariable, PartialExpressionEvaluator};
use powdr_parser_util::SourceRef;
use powdr_pil_analyzer::analyze_ast;
use powdr_pilopt::optimize;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use powdr_number::{BigUint, FieldElement, LargeInt};
use powdr_pilopt::simplify_expression;
pub mod powdr;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SymbolicInstructionStatement<T> {
pub name: String,
pub opcode: usize,
pub args: Vec<T>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolicInstructionDefinition {
pub name: String,
pub inputs: Vec<String>,
pub outputs: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolicConstraint<T> {
pub expr: AlgebraicExpression<T>,
}
impl<T> From<AlgebraicExpression<T>> for SymbolicConstraint<T> {
fn from(expr: AlgebraicExpression<T>) -> Self {
SymbolicConstraint { expr }
}
}
impl<T: Clone + Ord + std::fmt::Display> SymbolicConstraint<T> {
pub fn columns(&self) -> BTreeSet<String> {
let mut cols = BTreeSet::new();
cols.extend(powdr::collect_cols_names_algebraic(&self.expr));
cols
}
pub fn column_ids(&self) -> BTreeSet<u64> {
let mut cols = BTreeSet::new();
cols.extend(powdr::collect_cols_ids_algebraic(&self.expr));
cols
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub struct SymbolicBusInteraction<T> {
pub kind: BusInteractionKind,
pub id: u64,
pub mult: AlgebraicExpression<T>,
pub args: Vec<AlgebraicExpression<T>>,
}
impl<T: Clone + Ord + std::fmt::Display> SymbolicBusInteraction<T> {
pub fn columns(&self) -> BTreeSet<String> {
let mut cols = BTreeSet::new();
cols.extend(powdr::collect_cols_names_algebraic(&self.mult));
for a in &self.args {
cols.extend(powdr::collect_cols_names_algebraic(&a));
}
cols
}
pub fn column_ids(&self) -> BTreeSet<u64> {
let mut cols = BTreeSet::new();
cols.extend(powdr::collect_cols_ids_algebraic(&self.mult));
for a in &self.args {
cols.extend(powdr::collect_cols_ids_algebraic(&a));
}
cols
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum BusInteractionKind {
Send,
Receive,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolicMachine<T> {
pub constraints: Vec<SymbolicConstraint<T>>,
pub bus_interactions: Vec<SymbolicBusInteraction<T>>,
}
impl<T> SymbolicMachine<T> {
pub fn algebraic_expressions(&self) -> impl Iterator<Item = &AlgebraicExpression<T>> {
let constraints_exprs = self.constraints.iter().map(|constraint| &constraint.expr);
let bus_mult_exprs = self
.bus_interactions
.iter()
.map(|interaction| &interaction.mult);
let bus_args_exprs = self
.bus_interactions
.iter()
.flat_map(|interaction| interaction.args.iter());
constraints_exprs
.chain(bus_mult_exprs)
.chain(bus_args_exprs)
}
}
impl<T: Clone + Ord + std::fmt::Display> SymbolicMachine<T> {
pub fn columns(&self) -> BTreeSet<String> {
let mut cols = BTreeSet::new();
for c in &self.constraints {
cols.extend(c.columns());
}
for b in &self.bus_interactions {
cols.extend(b.columns());
}
cols
}
pub fn constraint_columns(&self) -> BTreeSet<String> {
let mut cols = BTreeSet::new();
for c in &self.constraints {
cols.extend(c.columns());
}
cols
}
pub fn column_ids(&self) -> BTreeSet<u64> {
let mut cols = BTreeSet::new();
for c in &self.constraints {
cols.extend(c.column_ids());
}
for b in &self.bus_interactions {
cols.extend(b.column_ids());
}
cols
}
}
#[derive(Debug, Clone)]
pub enum InstructionKind {
Normal,
ConditionalBranch,
UnconditionalBranch,
Terminal,
}
#[derive(Debug, Clone)]
pub struct Autoprecompiles<T> {
pub program: Vec<SymbolicInstructionStatement<T>>,
pub instruction_kind: BTreeMap<String, InstructionKind>,
pub instruction_machines: BTreeMap<String, (SymbolicInstructionDefinition, SymbolicMachine<T>)>,
}
#[derive(Debug, Clone)]
pub struct BasicBlock<T> {
pub start_idx: u64,
pub statements: Vec<SymbolicInstructionStatement<T>>,
}
#[derive(Clone, Debug)]
pub enum MemoryType {
Constant,
Register,
Memory,
}
impl<T: FieldElement> From<AlgebraicExpression<T>> for MemoryType {
fn from(expr: AlgebraicExpression<T>) -> Self {
match expr {
AlgebraicExpression::Number(n) => {
let n_u32 = n.to_integer().try_into_u32().unwrap();
match n_u32 {
0 => MemoryType::Constant,
1 => MemoryType::Register,
2 => MemoryType::Memory,
_ => unreachable!("Expected 0, 1 or 2 but got {n}"),
}
}
_ => unreachable!("Expected number"),
}
}
}
impl<T: FieldElement> From<MemoryType> for AlgebraicExpression<T> {
fn from(ty: MemoryType) -> Self {
match ty {
MemoryType::Constant => AlgebraicExpression::Number(T::from(0u32)),
MemoryType::Register => AlgebraicExpression::Number(T::from(1u32)),
MemoryType::Memory => AlgebraicExpression::Number(T::from(2u32)),
}
}
}
#[derive(Clone, Debug)]
pub enum MemoryOp {
Read,
Write,
}
impl From<BusInteractionKind> for MemoryOp {
fn from(kind: BusInteractionKind) -> Self {
match kind {
BusInteractionKind::Receive => MemoryOp::Read,
BusInteractionKind::Send => MemoryOp::Write,
}
}
}
impl From<MemoryOp> for BusInteractionKind {
fn from(op: MemoryOp) -> Self {
match op {
MemoryOp::Read => BusInteractionKind::Receive,
MemoryOp::Write => BusInteractionKind::Send,
}
}
}
#[derive(Clone, Debug)]
pub struct MemoryBusInteraction<T> {
pub ty: MemoryType,
pub op: MemoryOp,
pub addr: AlgebraicExpression<T>,
pub data: Vec<AlgebraicExpression<T>>,
pub bus_interaction: SymbolicBusInteraction<T>,
}
impl<T: FieldElement> MemoryBusInteraction<T> {
pub fn try_addr_u32(&self) -> Option<u32> {
match self.addr {
AlgebraicExpression::Number(n) => n.to_integer().try_into_u32(),
_ => None,
}
}
}
impl<T: FieldElement> From<SymbolicBusInteraction<T>> for MemoryBusInteraction<T> {
fn from(bus_interaction: SymbolicBusInteraction<T>) -> Self {
//println!("\n\nBus interaction is {bus_interaction:?}\n\n");
//println!("\n\nAS = {}\n\n", bus_interaction.args[0]);
let ty = bus_interaction.args[0].clone().into();
let op = bus_interaction.kind.clone().into();
let addr = bus_interaction.args[1].clone();
let data = bus_interaction.args[2..bus_interaction.args.len() - 2].to_vec();
MemoryBusInteraction {
ty,
op,
addr,
data,
bus_interaction,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct PcLookupBusInteraction<T> {
pub from_pc: AlgebraicExpression<T>,
pub op: AlgebraicExpression<T>,
pub args: Vec<AlgebraicExpression<T>>,
pub bus_interaction: SymbolicBusInteraction<T>,
}
impl<T: FieldElement> From<SymbolicBusInteraction<T>> for PcLookupBusInteraction<T> {
fn from(bus_interaction: SymbolicBusInteraction<T>) -> Self {
let from_pc = bus_interaction.args[0].clone();
let op = bus_interaction.args[1].clone();
let args = bus_interaction.args[2..].to_vec();
PcLookupBusInteraction {
from_pc,
op,
args,
bus_interaction,
}
}
}
pub enum VMBusInteraction<T> {
Memory(MemoryBusInteraction<T>),
}
const EXECUTION_BUS_ID: u64 = 0;
const MEMORY_BUS_ID: u64 = 1;
const PC_LOOKUP_BUS_ID: u64 = 2;
const RANGE_CHECK_BUS_ID: u64 = 3;
impl<T: FieldElement> Autoprecompiles<T> {
pub fn run(
&self,
) -> (
Vec<SymbolicInstructionStatement<T>>,
Vec<(String, SymbolicMachine<T>)>,
Vec<BTreeMap<String, String>>,
) {
let blocks = self.collect_basic_blocks();
let new_instr_name = "new_instr".to_string();
let new_instr = SymbolicInstructionStatement {
name: new_instr_name.clone(),
opcode: 0,
args: Vec::new(),
};
let selected = [(0, new_instr)].into();
let new_program = replace_autoprecompile_basic_blocks(&blocks, &selected);
let (machine, col_subs) = generate_precompile(
&blocks[0].statements,
&self.instruction_kind,
&self.instruction_machines,
false,
);
let machine = optimize_precompile(machine);
(new_program, vec![(new_instr_name, machine)], col_subs)
}
pub fn build(&self, optimize: bool) -> (SymbolicMachine<T>, Vec<BTreeMap<String, String>>) {
let (mut machine, subs) = generate_precompile(
&self.program,
&self.instruction_kind,
&self.instruction_machines,
optimize,
);
println!("\nMachine after autoprecompile");
for c in &machine.constraints {
println!("Constraint: {}", c.expr);
}
for b in &machine.bus_interactions {
println!(
"\nBus interaction id = {}, kind = {:?}, mult = {}",
b.id, b.kind, b.mult
);
for a in &b.args {
println!("arg = {a}");
}
println!("\n");
}
let c = machine.columns();
let i = machine.column_ids();
// println!("\n\nCollecting info");
// println!("\nC:\n{c:?}");
// println!("\nI:\n{i:?}");
// for c in &machine.constraints {
// println!("Constraint: {}", c.expr);
// }
// for i in &machine.bus_interactions {
// println!(
// "\nBus interaction id = {}, kind = {:?}, mult = {}",
// i.id, i.kind, i.mult
// );
// for a in &i.args {
// println!("arg = {a}");
// }
// println!("\n");
// }
assert_eq!(c.len(), i.len());
assert_eq!(machine.columns().len(), machine.column_ids().len());
if optimize {
machine = optimize_pc_lookup(machine);
machine = optimize_exec_bus(machine);
machine = optimize_precompile(machine);
}
let mut bus: BTreeMap<u64, Vec<&SymbolicBusInteraction<T>>> = BTreeMap::new();
for b in &machine.bus_interactions {
match bus.get_mut(&b.id) {
Some(v) => {
v.push(&b);
}
None => {
bus.insert(b.id, vec![&b]);
}
}
}
for (b, v) in &bus {
println!("Bus id {b} has {} interactions", v.len());
}
println!("\nMachine after autoprecompile optimization");
for c in &machine.constraints {
println!("Constraint: {}", c.expr);
}
for b in &machine.bus_interactions {
println!(
"\nBus interaction id = {}, kind = {:?}, mult = {}",
b.id, b.kind, b.mult
);
for a in &b.args {
println!("arg = {a}");
}
println!("\n");
}
if optimize {
machine = powdr_optimize(machine);
machine = remove_zero_mult(machine);
machine = remove_zero_constraint(machine);
}
println!("\nMachine after powdr optimization");
for c in &machine.constraints {
println!("Constraint: {}", c.expr);
}
for b in &machine.bus_interactions {
println!(
"\nBus interaction id = {}, kind = {:?}, mult = {}",
b.id, b.kind, b.mult
);
for a in &b.args {
println!("arg = {a}");
}
println!("\n");
}
//let machine = remove_range_checks(machine);
(machine, subs)
}
pub fn collect_basic_blocks(&self) -> Vec<BasicBlock<T>> {
let mut blocks = Vec::new();
let mut curr_block = BasicBlock {
start_idx: 0,
statements: Vec::new(),
};
for (i, instr) in self.program.iter().enumerate() {
match self.instruction_kind.get(&instr.name).unwrap() {
InstructionKind::Normal => {
curr_block.statements.push(instr.clone());
}
InstructionKind::ConditionalBranch
| InstructionKind::UnconditionalBranch
| InstructionKind::Terminal => {
curr_block.statements.push(instr.clone());
blocks.push(curr_block);
curr_block = BasicBlock {
start_idx: i as u64,
statements: Vec::new(),
};
}
}
}
if !curr_block.statements.is_empty() {
blocks.push(curr_block);
}
blocks
}
}
pub fn replace_autoprecompile_basic_blocks<T: Clone>(
blocks: &Vec<BasicBlock<T>>,
selected: &BTreeMap<u64, SymbolicInstructionStatement<T>>,
) -> Vec<SymbolicInstructionStatement<T>> {
let mut new_program = Vec::new();
for (i, block) in blocks.iter().enumerate() {
if let Some(instr) = selected.get(&(i as u64)) {
new_program.push(instr.clone());
} else {
new_program.extend(block.statements.clone());
}
}
new_program
}
pub fn remove_zero_mult<T: FieldElement>(mut machine: SymbolicMachine<T>) -> SymbolicMachine<T> {
println!(
"Before zero mult optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
.bus_interactions
.retain(|bus_int| !powdr::is_zero(&bus_int.mult));
println!(
"After zero mult optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
}
pub fn remove_zero_constraint<T: FieldElement>(
mut machine: SymbolicMachine<T>,
) -> SymbolicMachine<T> {
println!(
"Before zero constraint optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine.constraints.retain(|c| !powdr::is_zero(&c.expr));
println!(
"After zero constraint optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
}
pub fn remove_range_checks<T: FieldElement>(mut machine: SymbolicMachine<T>) -> SymbolicMachine<T> {
println!(
"Before range check optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
let cols = machine.constraint_columns();
machine.bus_interactions.retain(|bus_int| {
if bus_int.id != RANGE_CHECK_BUS_ID {
return true;
}
bus_int.args.iter().any(|a| {
let a_cols = powdr::collect_cols_names_algebraic(a);
a_cols.iter().any(|c| cols.contains(c))
})
});
println!(
"After range check optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
}
pub fn exec_receive<T: FieldElement>(machine: &SymbolicMachine<T>) -> SymbolicBusInteraction<T> {
machine
.bus_interactions
.iter()
.filter_map(|bus_int| match (bus_int.id, &bus_int.kind) {
(EXECUTION_BUS_ID, BusInteractionKind::Receive) => Some(bus_int.clone()),
_ => None,
})
.exactly_one()
.expect("Expected single execution receive")
}
pub fn optimize_precompile<T: FieldElement>(mut machine: SymbolicMachine<T>) -> SymbolicMachine<T> {
println!(
"Before autoprecompile optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
/*
for c in &machine.constraints {
println!("Constraint: {}", c.expr);
}
*/
let mut local_reg_mem: BTreeMap<u32, Vec<AlgebraicExpression<T>>> = BTreeMap::new();
let mut new_constraints: Vec<SymbolicConstraint<T>> = Vec::new();
let mut prev_tss: Vec<AlgebraicExpression<T>> = Vec::new();
machine.bus_interactions.retain(|bus_int| {
if bus_int.id != MEMORY_BUS_ID {
return true;
}
let mem_int: MemoryBusInteraction<T> = bus_int.clone().into();
if matches!(mem_int.ty, MemoryType::Constant | MemoryType::Memory) {
return true;
}
let addr = match mem_int.try_addr_u32() {
None => {
panic!("Register memory access must have constant address");
}
Some(addr) => addr,
};
match mem_int.op {
MemoryOp::Read => match local_reg_mem.get(&addr) {
Some(data) => {
assert_eq!(data.len(), mem_int.data.len());
/*
println!(
"Replacing bus interaction of addr {} by local constraints:",
mem_int.addr
);
println!("Data: {data:?}");
println!("Mem int data: {:?}", mem_int.data);
*/
mem_int
.data
.iter()
.zip(data.iter())
.for_each(|(new_data, old_data)| {
let eq_expr = AlgebraicExpression::new_binary(
new_data.clone(),
AlgebraicBinaryOperator::Sub,
old_data.clone(),
);
//let eq_expr = bus_int.mult.clone() * eq_expr;
//println!("New constraint: {eq_expr}");
new_constraints.push(eq_expr.into());
});
// If this receive's ts is a prev_ts, we can remove the constraint that
// decomposes this prev_ts and range checks on the limbs.
let prev_ts = mem_int.bus_interaction.args[6].clone();
assert!(powdr::is_ref(&prev_ts));
//println!("Adding {prev_ts} to prev_tss");
prev_tss.push(prev_ts);
false
}
None => {
local_reg_mem.insert(addr, mem_int.data.clone());
true
}
},
MemoryOp::Write => {
local_reg_mem.insert(addr, mem_int.data.clone());
true
}
}
});
let mut last_store: BTreeMap<u32, usize> = BTreeMap::new();
machine
.bus_interactions
.iter()
.enumerate()
.for_each(|(i, bus_int)| {
if bus_int.id != MEMORY_BUS_ID {
return;
}
let mem_int: MemoryBusInteraction<T> = bus_int.clone().into();
if matches!(mem_int.ty, MemoryType::Constant | MemoryType::Memory) {
return;
}
let addr = match mem_int.try_addr_u32() {
None => {
panic!("Register memory access must have constant address");
}
Some(addr) => addr,
};
match mem_int.op {
MemoryOp::Read => {}
MemoryOp::Write => {
last_store.insert(addr, i);
}
}
});
machine.bus_interactions = machine
.bus_interactions
.into_iter()
.enumerate()
.filter_map(|(i, bus_int)| {
if bus_int.id != MEMORY_BUS_ID {
return Some(bus_int);
}
let mem_int: MemoryBusInteraction<T> = bus_int.clone().into();
if matches!(mem_int.ty, MemoryType::Constant | MemoryType::Memory) {
return Some(bus_int);
}
let addr = match mem_int.try_addr_u32() {
None => {
panic!("Register memory access must have constant address");
}
Some(addr) => addr,
};
match mem_int.op {
MemoryOp::Read => {
return Some(bus_int);
}
MemoryOp::Write => {
if last_store
.get(&addr)
.is_some_and(|&last_index| last_index == i)
{
Some(bus_int)
} else {
//println!("Removing redundant register write");
//println!("Bus interaction: {:?}", bus_int);
None
}
}
}
})
.collect();
let mut to_remove: BTreeSet<AlgebraicExpression<T>> = Default::default();
machine.constraints.retain(|c| {
for prev_ts in &prev_tss {
if powdr::has_ref(&c.expr, prev_ts) {
// println!(
// "Removing constraint: {} because of prev_ts {prev_ts}",
// c.expr
// );
let (col1, col2) = powdr::find_byte_decomp(&c.expr);
//println!("Decomp cols are {col1} and {col2}");
to_remove.insert(col1);
to_remove.insert(col2);
return false;
}
}
true
});
machine.bus_interactions.retain(|bus_int| {
if bus_int.id != RANGE_CHECK_BUS_ID {
return true;
}
assert_eq!(bus_int.args.len(), 2);
let col = bus_int.args[0].clone();
if to_remove.contains(&col) {
//println!("Removing range check bus interaction for col {col}");
return false;
}
true
});
machine.constraints.extend(new_constraints);
println!(
"After autoprecompile optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
}
pub fn optimize_pc_lookup<T: FieldElement>(mut machine: SymbolicMachine<T>) -> SymbolicMachine<T> {
println!(
"Before autoprecompile pc lookup optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
let mut first_pc = None;
machine.bus_interactions.retain(|bus_int| {
if bus_int.id == PC_LOOKUP_BUS_ID {
if first_pc.is_none() {
first_pc = Some(bus_int.clone());
}
return false;
}
true
});
let mut first_pc = first_pc.unwrap();
assert_eq!(first_pc.args.len(), 9);
first_pc.args[1] = AlgebraicExpression::Number(T::from(4351u32));
first_pc.args[2] = AlgebraicExpression::Number(T::from(0u32));
first_pc.args[3] = AlgebraicExpression::Number(T::from(0u32));
first_pc.args[4] = AlgebraicExpression::Number(T::from(0u32));
first_pc.args[5] = AlgebraicExpression::Number(T::from(0u32));
first_pc.args[6] = AlgebraicExpression::Number(T::from(0u32));
first_pc.args[7] = AlgebraicExpression::Number(T::from(0u32));
first_pc.args[8] = AlgebraicExpression::Number(T::from(0u32));
machine.bus_interactions.push(first_pc);
println!(
"After autoprecompile pc lookup optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
}
pub fn optimize_exec_bus<T: FieldElement>(mut machine: SymbolicMachine<T>) -> SymbolicMachine<T> {
println!(
"Before autoprecompile exec optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
let mut first_seen = false;
let mut latest_send = None;
let mut subs_pc: BTreeMap<AlgebraicExpression<T>, AlgebraicExpression<T>> = Default::default();
let mut subs_ts: BTreeMap<AlgebraicExpression<T>, AlgebraicExpression<T>> = Default::default();
machine.bus_interactions.retain(|bus_int| {
if bus_int.id != EXECUTION_BUS_ID {
return true;
}
// Keep the first receive
if !first_seen {
assert_eq!(bus_int.kind, BusInteractionKind::Receive);
first_seen = true;
true
} else if bus_int.kind == BusInteractionKind::Send {
// Save the latest send and remove the bus interaction
let mut pc_expr = bus_int.args[0].clone();
powdr::substitute_algebraic_algebraic(&mut pc_expr, &subs_pc);
pc_expr = simplify_expression(pc_expr);
let mut ts_expr = bus_int.args[1].clone();
powdr::substitute_algebraic_algebraic(&mut ts_expr, &subs_ts);
ts_expr = simplify_expression(ts_expr);
let mut send = bus_int.clone();
send.args[0] = pc_expr;
send.args[1] = ts_expr;
latest_send = Some(send);
false
} else {
// Equate the latest send to the new receive and remove the bus interaction
subs_pc.insert(
bus_int.args[0].clone(),
latest_send.clone().unwrap().args[0].clone(),
);
subs_ts.insert(
bus_int.args[1].clone(),
latest_send.clone().unwrap().args[1].clone(),
);
false
}
});
// Re-add the last send
machine.bus_interactions.push(latest_send.unwrap());
for c in &mut machine.constraints {
powdr::substitute_algebraic_algebraic(&mut c.expr, &subs_pc);
powdr::substitute_algebraic_algebraic(&mut c.expr, &subs_ts);
c.expr = simplify_expression(c.expr.clone());
}
for b in &mut machine.bus_interactions {
powdr::substitute_algebraic_algebraic(&mut b.mult, &subs_pc);
powdr::substitute_algebraic_algebraic(&mut b.mult, &subs_ts);
b.mult = simplify_expression(b.mult.clone());
for a in &mut b.args {
powdr::substitute_algebraic_algebraic(a, &subs_pc);
powdr::substitute_algebraic_algebraic(a, &subs_ts);
*a = simplify_expression(a.clone());
}
}
println!(
"After autoprecompile exec optimizations, columns: {}, constraints: {}, bus_interactions: {}",
machine.columns().len(),
machine.constraints.len(),
machine.bus_interactions.len()
);
machine
}
pub fn generate_precompile<T: FieldElement>(
statements: &Vec<SymbolicInstructionStatement<T>>,
instruction_kinds: &BTreeMap<String, InstructionKind>,
instruction_machines: &BTreeMap<String, (SymbolicInstructionDefinition, SymbolicMachine<T>)>,
optimize: bool,
) -> (SymbolicMachine<T>, Vec<BTreeMap<String, String>>) {
println!("Generating autoprecompile inside powdr");
let mut constraints: Vec<SymbolicConstraint<T>> = Vec::new();
let mut bus_interactions: Vec<SymbolicBusInteraction<T>> = Vec::new();
let mut col_subs: Vec<BTreeMap<String, String>> = Vec::new();
let mut global_idx: usize = 3;
let mut global_idx_subs: BTreeMap<String, usize> = BTreeMap::new();
let mut global_idx_subs_rev: BTreeMap<usize, String> = BTreeMap::new();
for (i, instr) in statements.iter().enumerate() {
//println!("\n\nVisiting instruction {i}\n\n");
//println!("Inlining instruction {} index {i}", &instr.name);
match instruction_kinds.get(&instr.name).unwrap() {
InstructionKind::Normal
| InstructionKind::UnconditionalBranch
| InstructionKind::ConditionalBranch => {
let (instr_def, mut machine) =
instruction_machines.get(&instr.name).unwrap().clone();
println!(
"Machine before autoprecompile for instruction {} at index {i}",
instr.name
);
for c in &machine.constraints {
println!("Constraint: {}", c.expr);
}
for b in &machine.bus_interactions {
println!(
"\nBus interaction id = {}, kind = {:?}, mult = {}",
b.id, b.kind, b.mult
);
for a in &b.args {
println!("arg = {a}");
}
println!("\n");
}
let pc_lookup: PcLookupBusInteraction<T> = machine
.bus_interactions
.iter()
.filter_map(|bus_int| match bus_int.id {
PC_LOOKUP_BUS_ID => Some(bus_int.clone().into()),
_ => None,
})
.exactly_one()
.expect("Expected single pc lookup");
let mut sub_map: BTreeMap<String, AlgebraicExpression<T>> = Default::default();
let mut local_constraints: Vec<SymbolicConstraint<T>> = Vec::new();
let is_valid: AlgebraicExpression<T> = exec_receive(&machine).mult.clone();
let one = AlgebraicExpression::Number(1u64.into());
local_constraints.push((is_valid.clone() - one).into());
let mut sub_map_loadstore: BTreeMap<String, AlgebraicExpression<T>> =
Default::default();
if is_loadstore(instr.opcode) {
sub_map_loadstore.extend(loadstore_chip_info(&machine, instr.opcode));
}
add_opcode_constraints(&mut local_constraints, instr.opcode, &pc_lookup.op);
assert_eq!(instr.args.len(), pc_lookup.args.len());
if optimize {
instr
.args
.iter()
.zip(pc_lookup.args.iter())
.for_each(|(instr_arg, pc_arg)| {
let arg = AlgebraicExpression::Number(instr_arg.clone());
match pc_arg {
AlgebraicExpression::Reference(ref arg_ref) => {
sub_map.insert(arg_ref.name.clone(), arg);
}
AlgebraicExpression::BinaryOperation(_expr) => {
local_constraints.push((arg - pc_arg.clone()).into());
}
AlgebraicExpression::UnaryOperation(_expr) => {
local_constraints.push((arg - pc_arg.clone()).into());
}
_ => {}
}
});
}
// for l in &local_constraints {
// println!("Local constraint: {}", l.expr);
// }
// println!("\nSubmap = {sub_map:?}\n");
let mut local_subs = BTreeMap::new();
/*
for l in &machine.constraints {
println!("\nMachine constraint: {}", l.expr);
}
for i in &machine.bus_interactions {
println!(