forked from hyperledger-solang/solang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdead_storage.rs
More file actions
855 lines (762 loc) · 27.6 KB
/
dead_storage.rs
File metadata and controls
855 lines (762 loc) · 27.6 KB
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
// SPDX-License-Identifier: Apache-2.0
use super::cfg::{BasicBlock, ControlFlowGraph, Instr};
use crate::codegen::Expression;
use crate::sema::ast::{Namespace, RetrieveType, Type};
use solang_parser::pt::Loc;
use std::collections::{HashMap, HashSet};
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
enum Definition {
Undefined,
Instr {
block_no: usize,
instr_no: usize,
assignment_no: usize,
},
}
impl fmt::Display for Definition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Definition::Undefined => {
write!(f, "undef")
}
Definition::Instr {
block_no,
instr_no,
assignment_no,
} => {
write!(f, "({block_no}, {instr_no}, {assignment_no})")
}
}
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Clone, PartialEq, Eq)]
enum Transfer {
Gen {
def: Definition,
var_no: usize,
},
Copy {
var_no: usize,
src: usize,
},
Kill {
var_no: usize,
},
Store {
def: Definition,
expr: Option<Expression>,
},
}
impl fmt::Display for Transfer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Transfer::Gen { def, var_no } => {
write!(f, "Gen %{var_no} = {def}")
}
Transfer::Copy { var_no, src } => {
write!(f, "Copy %{var_no} from %{src}")
}
Transfer::Kill { var_no } => {
write!(f, "Kill %{var_no}")
}
Transfer::Store { def, expr } => {
write!(f, "Storage: {expr:?} at {def}")
}
}
}
}
#[derive(Clone, PartialEq, Eq)]
struct ReachingDefs {
vars: HashMap<usize, HashMap<Definition, Option<Expression>>>,
stores: Vec<(Definition, Expression)>,
}
type BlockVars = HashMap<usize, Vec<ReachingDefs>>;
/// Calculate all the reaching definitions for the contract. This is a flow
/// analysis which is used for further optimizations
#[allow(clippy::map_entry)]
fn reaching_definitions(cfg: &mut ControlFlowGraph) -> (Vec<Vec<Vec<Transfer>>>, BlockVars) {
// the transfers
let mut block_transfers: Vec<Vec<Vec<Transfer>>> = Vec::new();
let mut block_vars: BlockVars = HashMap::new();
// calculate the per-instruction reaching defs
for (block_no, block) in cfg.blocks.iter().enumerate() {
let transfer = instr_transfers(block_no, block);
debug_assert_eq!(block_no, block_transfers.len());
block_transfers.push(transfer);
debug_assert_eq!(
cfg.blocks[block_no].instr.len(),
block_transfers[block_no].len()
);
}
let mut blocks_todo: HashSet<usize> = HashSet::new();
blocks_todo.insert(0);
while let Some(block_no) = blocks_todo.iter().next() {
let block_no = *block_no;
blocks_todo.remove(&block_no);
let mut vars = if let Some(vars) = block_vars.get(&block_no) {
vars[0].clone()
} else {
debug_assert_eq!(block_no, 0);
// On entry all variables should be undefined
let mut vars: HashMap<usize, HashMap<Definition, Option<Expression>>> = HashMap::new();
for var_no in cfg.vars.keys() {
let mut defs = HashMap::new();
defs.insert(Definition::Undefined, None);
vars.insert(*var_no, defs);
}
ReachingDefs {
vars,
stores: Vec::new(),
}
};
apply_transfers(
&block_transfers[block_no],
&mut vars,
cfg,
block_no,
&mut block_vars,
);
for edge in cfg.blocks[block_no].successors() {
let mut changed = false;
if !block_vars.contains_key(&edge) {
changed |= block_vars.insert(edge, vec![vars.clone()]).is_none();
} else if block_vars[&edge][0] != vars {
let block_vars = block_vars
.get_mut(&edge)
.expect("block vars must contain edge");
// merge incoming vars
for (var_no, defs) in &vars.vars {
if let Some(entry) = block_vars[0].vars.get_mut(var_no) {
for (incoming_def, storage) in defs {
if !entry.contains_key(incoming_def) {
entry.insert(*incoming_def, storage.clone());
changed = true;
}
}
} else {
changed |= block_vars[0].vars.insert(*var_no, defs.clone()).is_none();
}
}
// merge storage stores
for store in &vars.stores {
if !block_vars[0].stores.iter().any(|(def, _)| *def == store.0) {
block_vars[0].stores.push(store.clone());
changed = true;
}
}
}
if changed {
blocks_todo.insert(edge);
}
}
}
(block_transfers, block_vars)
}
/// Instruction defs
fn instr_transfers(block_no: usize, block: &BasicBlock) -> Vec<Vec<Transfer>> {
let mut transfers = Vec::new();
for (instr_no, instr) in block.instr.iter().enumerate() {
let def = Definition::Instr {
block_no,
instr_no,
assignment_no: 0,
};
let set_var = |var_nos: &[usize]| {
let mut transfer = Vec::new();
for (assignment_no, var_no) in var_nos.iter().enumerate() {
transfer.insert(0, Transfer::Kill { var_no: *var_no });
transfer.push(Transfer::Gen {
def: Definition::Instr {
block_no,
instr_no,
assignment_no,
},
var_no: *var_no,
});
}
transfer
};
transfers.push(match instr {
Instr::Set {
res,
expr: Expression::Variable { var_no: src, .. },
..
} => {
vec![
Transfer::Kill { var_no: *res },
Transfer::Copy {
var_no: *res,
src: *src,
},
]
}
Instr::Set { res, .. } => set_var(&[*res]),
Instr::Call { res, .. } => {
// We don't know what this function does to storage, so clear all storage
// possibly we should check if the function is pure/view and not clear storage references
let mut v = set_var(res);
v.push(Transfer::Store { def, expr: None });
v
}
Instr::LoadStorage { res, .. } => set_var(&[*res]),
Instr::PushMemory { array, res, .. } => {
let mut v = set_var(&[*res]);
v.push(Transfer::Kill { var_no: *array });
v
}
Instr::PopMemory { array, .. } => {
vec![Transfer::Kill { var_no: *array }]
}
Instr::ExternalCall {
success: Some(res), ..
}
| Instr::Constructor {
success: None, res, ..
}
| Instr::ValueTransfer {
success: Some(res), ..
} => {
// A constructor/external call can call us back and modify storage
vec![
Transfer::Kill { var_no: *res },
Transfer::Store { def, expr: None },
]
}
Instr::Store { dest, .. } => {
let mut v = Vec::new();
if let Some(var_no) = array_var(dest) {
v.push(Transfer::Kill { var_no });
}
v
}
Instr::Constructor {
success: Some(success),
res,
..
} => {
// A constructor can call us back and modify storage
vec![
Transfer::Kill { var_no: *res },
Transfer::Kill { var_no: *success },
Transfer::Store { def, expr: None },
]
}
Instr::SetStorageBytes { storage, .. }
| Instr::ClearStorage { storage, .. }
| Instr::SetStorage { storage, .. } => {
vec![Transfer::Store {
def,
expr: Some(storage.clone()),
}]
}
Instr::PopStorage {
res: Some(res),
storage,
..
}
| Instr::PushStorage { res, storage, .. } => {
vec![
Transfer::Kill { var_no: *res },
Transfer::Gen { def, var_no: *res },
Transfer::Store {
def,
expr: Some(storage.clone()),
},
]
}
Instr::Return { .. } => {
vec![Transfer::Store { def, expr: None }]
}
_ => Vec::new(),
});
}
debug_assert_eq!(transfers.len(), block.instr.len());
transfers
}
fn array_var(expr: &Expression) -> Option<usize> {
match expr {
Expression::Variable { var_no, .. } => Some(*var_no),
Expression::Subscript { expr, .. } | Expression::StructMember { expr, .. } => {
array_var(expr)
}
_ => None,
}
}
fn apply_transfers(
transfers: &[Vec<Transfer>],
vars: &mut ReachingDefs,
cfg: &ControlFlowGraph,
block_no: usize,
block_vars: &mut BlockVars,
) {
let mut res = Vec::new();
debug_assert_eq!(transfers.len(), cfg.blocks[block_no].instr.len());
// this is done in two passes. The first pass just deals with variables.
// The second pass deals with storage stores
// for each instruction
for transfers in transfers {
res.push(vars.clone());
// each instruction has a list of transfers
for transfer in transfers {
match transfer {
Transfer::Kill { var_no } => {
vars.vars.remove(var_no);
}
Transfer::Copy { var_no, src } => {
if let Some(defs) = vars.vars.get(src) {
let defs = defs.clone();
vars.vars.insert(*var_no, defs);
}
}
Transfer::Gen { var_no, def } => {
if let Some(entry) = vars.vars.get_mut(var_no) {
entry.insert(*def, None);
} else {
let mut v = HashMap::new();
v.insert(*def, None);
vars.vars.insert(*var_no, v);
}
}
// For the second pass
Transfer::Store { .. } => (),
}
}
}
block_vars.insert(block_no, res.clone());
*vars = res[0].clone();
let mut res = Vec::new();
// 2nd pass
for transfers in transfers {
res.push(vars.clone());
// each instruction has a list of transfers
for transfer in transfers {
match transfer {
Transfer::Kill { var_no } => {
vars.vars.remove(var_no);
}
Transfer::Copy { var_no, src } => {
if let Some(defs) = vars.vars.get(src) {
let defs = defs.clone();
vars.vars.insert(*var_no, defs);
}
}
Transfer::Gen { var_no, def } => {
if let Some(entry) = vars.vars.get_mut(var_no) {
entry.insert(*def, None);
} else {
let mut v = HashMap::new();
v.insert(*def, None);
vars.vars.insert(*var_no, v);
}
}
Transfer::Store { def, expr } => {
// store to contract storage. This should kill any equal
let mut eliminated_vars = Vec::new();
for (var_no, def) in vars.vars.iter() {
for def in def.keys() {
if let Some(storage_def) = get_storage_definition(def, cfg) {
if let Some(expr) = expr {
let storage_vars = get_vars_at(def, block_vars);
if expression_compare(
expr,
vars,
storage_def.slot,
&storage_vars,
cfg,
block_vars,
) != ExpressionCmp::NotEqual
{
eliminated_vars.push(*var_no);
}
} else {
// all storage references must be killed
eliminated_vars.push(*var_no);
}
}
}
}
for var_no in eliminated_vars {
vars.vars.remove(&var_no);
}
// Now handle the reaching storage stores
if let Some(expr) = expr {
// all stores should are no longer reaching if they are clobbered by this store
let mut eliminated_stores = Vec::new();
for (no, (def, storage)) in vars.stores.iter().enumerate() {
let storage_vars = get_vars_at(def, block_vars);
if expression_compare(
expr,
vars,
storage,
&storage_vars,
cfg,
block_vars,
) == ExpressionCmp::Equal
{
eliminated_stores.push(no);
}
}
for no in eliminated_stores.into_iter().rev() {
vars.stores.remove(no);
}
vars.stores.push((*def, expr.clone()));
} else {
// flush all reaching stores
vars.stores.truncate(0);
}
}
}
}
}
assert_eq!(res.len(), transfers.len());
assert_eq!(res.len(), cfg.blocks[block_no].instr.len());
block_vars.insert(block_no, res);
}
/// Eliminate dead storage load/store.
pub fn dead_storage(cfg: &mut ControlFlowGraph, _ns: &mut Namespace) {
// first calculate reaching definitions. We use a special case reaching definitions, which we track
let (blocktransfers, block_vars) = reaching_definitions(cfg);
let mut redundant_stores = HashMap::new();
// for each block, instruction
for block_no in 0..cfg.blocks.len() {
for instr_no in 0..cfg.blocks[block_no].instr.len() {
if !block_vars.contains_key(&block_no) {
// do not consider unreachable blocks
continue;
}
let vars = &block_vars[&block_no][instr_no];
match &cfg.blocks[block_no].instr[instr_no] {
Instr::LoadStorage {
res, ty, storage, ..
} => {
// is there a definition which has the same storage expression
let mut found = None;
for var_no in vars.vars.keys() {
let defs = &vars.vars[var_no];
if defs.len() == 1 {
let (def, _) = defs.iter().next().unwrap();
if let Some(storage_def) = get_storage_definition(def, cfg) {
let def_vars = get_vars_at(def, &block_vars);
if expression_compare(
storage,
vars,
storage_def.slot,
&def_vars,
cfg,
&block_vars,
) == ExpressionCmp::Equal
&& storage_def.var_no != *res
&& ty == storage_def.ty
{
found = Some(var_no);
break;
}
}
}
}
if let Some(var_no) = found {
cfg.blocks[block_no].instr[instr_no] = Instr::Set {
loc: Loc::Codegen,
res: *res,
expr: Expression::Variable {
loc: Loc::Codegen,
ty: ty.clone(),
var_no: *var_no,
},
};
} else {
for (def, expr) in &vars.stores {
let def_vars = get_vars_at(def, &block_vars);
if expression_compare(storage, vars, expr, &def_vars, cfg, &block_vars)
!= ExpressionCmp::NotEqual
{
if let Some(entry) = redundant_stores.get_mut(def) {
*entry = false;
}
}
}
}
}
Instr::PushStorage { storage, .. } | Instr::PopStorage { storage, .. } => {
for (def, expr) in &vars.stores {
let def_vars = get_vars_at(def, &block_vars);
if expression_compare(storage, vars, expr, &def_vars, cfg, &block_vars)
!= ExpressionCmp::NotEqual
{
if let Some(entry) = redundant_stores.get_mut(def) {
*entry = false;
}
}
}
}
Instr::SetStorage { .. }
| Instr::SetStorageBytes { .. }
| Instr::ClearStorage { .. } => {
let def = Definition::Instr {
block_no,
instr_no,
assignment_no: 0,
};
// add an entry if there is not one there already
redundant_stores.entry(def).or_insert(true);
}
_ => (),
}
let transfers = &blocktransfers[block_no][instr_no];
if transfers
.iter()
.any(|t| matches!(t, Transfer::Store { expr: None, .. }))
{
for (def, _) in &vars.stores {
// insert new entry or override existing one
redundant_stores.insert(*def, false);
}
}
}
}
// remove all stores which are marked as still redundant
for (def, redundant) in &redundant_stores {
if *redundant {
if let Definition::Instr {
block_no, instr_no, ..
} = def
{
// Function calls should never be eliminated from the CFG, as they might have side effects
if !matches!(cfg.blocks[*block_no].instr[*instr_no], Instr::Call { .. }) {
cfg.blocks[*block_no].instr[*instr_no] = Instr::Nop;
}
}
}
}
}
struct StorageDef<'a> {
var_no: usize,
slot: &'a Expression,
ty: &'a Type,
}
fn get_storage_definition<'a>(
def: &Definition,
cfg: &'a ControlFlowGraph,
) -> Option<StorageDef<'a>> {
if let Definition::Instr {
block_no, instr_no, ..
} = def
{
match &cfg.blocks[*block_no].instr[*instr_no] {
Instr::LoadStorage {
storage, res, ty, ..
} => Some(StorageDef {
var_no: *res,
slot: storage,
ty,
}),
_ => None,
}
} else {
None
}
}
fn get_definition<'a>(
def: &Definition,
cfg: &'a ControlFlowGraph,
) -> Option<(&'a Expression, Type)> {
if let Definition::Instr {
block_no, instr_no, ..
} = def
{
match &cfg.blocks[*block_no].instr[*instr_no] {
Instr::LoadStorage { storage, ty, .. } => Some((storage, ty.clone())),
Instr::Set { expr, .. } => Some((expr, expr.ty())),
_ => None,
}
} else {
None
}
}
fn get_vars_at(def: &Definition, block_vars: &BlockVars) -> ReachingDefs {
match def {
Definition::Instr {
block_no, instr_no, ..
} => {
let vars = if let Some(vars) = block_vars.get(block_no) {
vars[*instr_no].clone()
} else {
ReachingDefs {
vars: HashMap::new(),
stores: Vec::new(),
}
};
vars
}
Definition::Undefined => {
unreachable!("cannot get reaching definitions for undefined");
}
}
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
enum ExpressionCmp {
Equal,
NotEqual,
Unknown,
}
/// Compare two expressions that express storage locations. There are a limited amount of expressions needed here
fn expression_compare(
left: &Expression,
left_vars: &ReachingDefs,
right: &Expression,
right_vars: &ReachingDefs,
cfg: &ControlFlowGraph,
block_vars: &BlockVars,
) -> ExpressionCmp {
let v = match (left, right) {
(
Expression::NumberLiteral { value: left, .. },
Expression::NumberLiteral { value: right, .. },
) => {
if left == right {
ExpressionCmp::Equal
} else {
ExpressionCmp::NotEqual
}
}
(Expression::Keccak256 { exprs: left, .. }, Expression::Keccak256 { exprs: right, .. }) => {
// This could be written with fold_first() rather than collect(), but that is an unstable feature.
// Also fold first does not short circuit
let cmps: Vec<ExpressionCmp> = left
.iter()
.zip(right.iter())
.map(|(left, right)| {
expression_compare(left, left_vars, right, right_vars, cfg, block_vars)
})
.collect();
let first = cmps[0];
if cmps.into_iter().any(|c| c != first) {
ExpressionCmp::Unknown
} else {
first
}
}
(Expression::ZeroExt { expr: left, .. }, Expression::ZeroExt { expr: right, .. })
| (Expression::Trunc { expr: left, .. }, Expression::Trunc { expr: right, .. }) => {
expression_compare(left, left_vars, right, right_vars, cfg, block_vars)
}
(
Expression::FunctionArg { arg_no: left, .. },
Expression::FunctionArg { arg_no: right, .. },
) => {
if left == right {
ExpressionCmp::Equal
} else {
// two function arguments can have the same value
ExpressionCmp::Unknown
}
}
(
Expression::Add {
left: l1,
right: r1,
..
},
Expression::Add {
left: l2,
right: r2,
..
},
)
| (
Expression::Multiply {
left: l1,
right: r1,
..
},
Expression::Multiply {
left: l2,
right: r2,
..
},
)
| (
Expression::Subtract {
left: l1,
right: r1,
..
},
Expression::Subtract {
left: l2,
right: r2,
..
},
)
| (
Expression::Subscript {
expr: l1,
index: r1,
..
},
Expression::Subscript {
expr: l2,
index: r2,
..
},
) => {
let l = expression_compare(l1, left_vars, l2, right_vars, cfg, block_vars);
let r = expression_compare(r1, left_vars, r2, right_vars, cfg, block_vars);
if l == r {
l
} else if (l == ExpressionCmp::Equal && r == ExpressionCmp::NotEqual)
|| (l == ExpressionCmp::NotEqual && r == ExpressionCmp::Equal)
{
ExpressionCmp::NotEqual
} else {
ExpressionCmp::Unknown
}
}
(Expression::Variable { var_no: left, .. }, Expression::Variable { var_no: right, .. }) => {
// let's check that the variable left has the same reaching definitions as right
let left = match left_vars.vars.get(left) {
Some(left) => left,
None => {
return ExpressionCmp::Unknown;
}
};
let right = match right_vars.vars.get(right) {
Some(right) => right,
None => {
return ExpressionCmp::Unknown;
}
};
if left == right {
ExpressionCmp::Equal
} else if left.len() == 1 && right.len() == 1 {
let left = left.iter().next().unwrap();
let right = right.iter().next().unwrap();
match (get_definition(left.0, cfg), get_definition(right.0, cfg)) {
(Some((left_expr, left_ty)), Some((right_expr, right_ty))) => {
let left_vars = get_vars_at(left.0, block_vars);
let right_vars = get_vars_at(right.0, block_vars);
let cmp = expression_compare(
left_expr,
&left_vars,
right_expr,
&right_vars,
cfg,
block_vars,
);
if cmp == ExpressionCmp::Equal && left_ty != right_ty {
ExpressionCmp::Unknown
} else {
cmp
}
}
_ => ExpressionCmp::Unknown,
}
} else {
ExpressionCmp::Unknown
}
}
_ => ExpressionCmp::Unknown,
};
v
}