-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcongruenceClosure.ml
More file actions
1610 lines (1436 loc) · 59.6 KB
/
congruenceClosure.ml
File metadata and controls
1610 lines (1436 loc) · 59.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
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
(** OCaml implementation of a quantitative congruence closure.
It is used by the C-2PO Analysis and based on the UnionFind implementation.
*)
include UnionFind
open GoblintCil
open DuplicateVars
module M = Messages
module TUF = UnionFind
module LMap = LookupMap
(* block disequalities *)
module BlDis = struct
(** Block disequalities:
a term t1 is mapped to a set of terms that have a different block than t1.
It is allowed to contain terms that are not present in the data structure,
so we shouldn't assume that all terms in bldis are present in the union find!
*)
type t = TSet.t TMap.t [@@deriving eq, ord, hash]
let bindings = TMap.bindings
let empty = TMap.empty
let is_empty = TMap.is_empty
let to_conj bldiseq = List.fold_left
(fun list (t1, tset) ->
TSet.fold (fun t2 bldiseqs -> BlNequal(t1, t2)::bldiseqs) tset [] @ list
) [] (bindings bldiseq)
let add bldiseq t1 t2 =
match TMap.find_opt t1 bldiseq with
| None -> TMap.add t1 (TSet.singleton t2) bldiseq
| Some tset -> TMap.add t1 (TSet.add t2 tset) bldiseq
(** Add disequalities bl(t1) != bl(t2) and bl(t2) != bl(t1). *)
let add_block_diseq bldiseq (t1, t2) =
add (add bldiseq t1 t2) t2 t1
(**
params:
t1-> a term that is not necessarily present in the data structure
tlist: a list of representative terms
For each term t2 in tlist, it adds the disequality t1 != t2 to diseqs.
*)
let add_block_diseqs bldiseq uf t1 tlist =
let add_block_diseq_t1 bldiseq t2 =
add_block_diseq bldiseq (t1, t2)
in
List.fold_left add_block_diseq_t1 bldiseq tlist
(** For each block disequality bl(t1) != bl(t2) we add all disequalities
that follow from equalities. I.e., if t1 = z1 + t1' and t2 = z2 + t2',
then we add the disequality bl(t1') != bl(t2').
*)
let element_closure bldis cmap =
let comp_closure = function
| BlNequal (r1,r2) ->
let eq_class1 = LMap.comp_t_cmap_repr cmap r1 in
let eq_class2 = LMap.comp_t_cmap_repr cmap r2 in
let terms1 = List.map snd eq_class1 in
let terms2 = List.map snd eq_class2 in
BatList.cartesian_product terms1 terms2
| _ -> []
in
List.concat_map comp_closure bldis
(** Returns true if bl(v) != bl(v'). *)
let map_set_mem v v' (map:t) =
match TMap.find_opt v map with
| None -> false
| Some set -> TSet.mem v' set
let filter_map f (diseq:t) =
let filter_map_set _ s =
let set = TSet.filter_map f s in
if TSet.is_empty set then None else Some set
in
TMap.filter_map filter_map_set diseq
let map f (diseq:t) =
let map_set s =
TSet.map f s
in
TMap.map map_set diseq
let term_set bldis =
bldis |> TMap.to_seq |> Seq.map fst |> TSet.of_seq
let map_lhs =
let add_change bldis (t1,t2) =
match TMap.find_opt t1 bldis with
| None -> bldis
| Some tset -> TMap.add t2 tset (TMap.remove t1 bldis)
in
List.fold_left add_change
let filter_map_lhs f (diseq:t) =
let filter_map_lhs diseq t =
match f t with
| None -> TMap.remove t diseq
| Some t2 ->
if not (T.equal t t2) then
TMap.add t2 (TMap.find t diseq) (TMap.remove t diseq)
else
diseq
in
let keys = diseq |> TMap.to_seq |> Seq.map fst in
Seq.fold_left filter_map_lhs diseq keys
end
module Disequalities = struct
(* disequality map:
if t_1 -> z -> {t_2, t_3}
then we know that t_1 + z != t_2
and also that t_1 + z != t_3
*)
type t = TSet.t ZMap.t TMap.t [@@deriving eq, ord, hash] (* disequalitites *)
type arg_t = (T.t * Z.t) ZMap.t TMap.t (* maps each state in the automata to its predecessors *)
let empty = TMap.empty
let is_empty = TMap.is_empty
let remove = TMap.remove
(** Returns a list of tuples, which each represent a disequality *)
let bindings x =
let bindings_from_smap (t, smap) =
smap |> ZMap.to_seq |> Seq.concat_map (fun (z, tset) -> TSet.to_seq tset |> Seq.map (fun term -> (t,z,term)))
in
x |> TMap.to_seq |> Seq.concat_map bindings_from_smap |> List.of_seq
(** adds a mapping v -> r -> size -> { v' } to the map,
or if there are already elements
in v -> r -> {..} then v' is added to the previous set *)
let map_set_add (v,r) v' (map:t) =
match TMap.find_opt v map with
| None ->
let inner_map = ZMap.add r (TSet.singleton v') ZMap.empty in
TMap.add v inner_map map
| Some imap ->
let set = match ZMap.find_opt r imap with
| None -> TSet.singleton v'
| Some set -> TSet.add v' set
in
let inner_map = ZMap.add r set imap in
TMap.add v inner_map map
let map_set_mem (v,r) v' (map:t) =
let mem_inner_map inner_map =
BatOption.map_default (TSet.mem v') false (ZMap.find_opt r inner_map)
in
BatOption.map_default mem_inner_map false (TMap.find_opt v map)
(** Map of partition, transform union find to a map
of type V -> Z -> V set
with reference variable |-> offset |-> all terms that are in the union find with this ref var and offset. *)
let comp_map uf =
let f (comp,uf) (v,_) =
let t, z, uf = TUF.find uf v in
map_set_add (t,z) v comp,uf
in
List.fold_left f (TMap.empty, uf) (TMap.bindings uf)
(** Find all elements that are in the same equivalence class as t. *)
let comp_t uf t =
let (t',z',uf) = TUF.find uf t in
let f (comp,uf) (v,((p,z),_)) =
let v', z'',uf = TUF.find uf v in
if T.equal v' t' then
(v, Z.(z'-z''))::comp,uf
else
comp, uf
in
let equivs, _ = List.fold_left f ([],uf) (TMap.bindings uf) in
equivs
(** Returns: "arg" map:
maps each representative term t to a map that maps an integer Z to
a list of representatives t' of v where *(v + z') is
in the representative class of t.
It basically maps each state in the automata to its predecessors. *)
let get_args uf =
let do_term (uf,xs) el =
match el with
| Deref (v', r', _) ->
let v0, r0, uf = TUF.find uf v' in
let x = (v0, Z.(r0 + r')) in
uf, x::xs
| _ -> uf, xs
in
let do_set iarg (r,set) =
let uf,list = List.fold_left do_term (uf,[]) (TSet.elements set) in
ZMap.add r list iarg
in
let do_bindings arg (v, imap) =
let ilist = ZMap.bindings imap in
let iarg = List.fold_left do_set ZMap.empty ilist in
TMap.add v iarg arg
in
let cmap, uf = comp_map uf in
let clist = TMap.bindings cmap in
let arg = List.fold_left do_bindings TMap.empty clist in
(uf, cmap, arg)
(* TODO: GobList.cartesian_fold_left? *)
let fold_left2 f acc l1 l2 =
List.fold_left (
fun acc x -> List.fold_left (
fun acc y -> f acc x y) acc l2) acc l1
let map_find_opt (v,r) map =
let inner_map = TMap.find_opt v map in
BatOption.map_default (ZMap.find_opt r) None inner_map
let map_find_all t map =
let inner_map = TMap.find_opt t map in
let bindings = Option.map ZMap.bindings inner_map in
let concat =
(* TODO: Can one change returned order to xs@acc? *)
List.fold_left (fun acc (z, xs) -> acc@xs) []
in
BatOption.map_default concat [] (bindings)
(* Helper function for check_neq and check_neq_bl, to add a disequality, if it adds information and is not impossible *)
let add_diseq acc (v1, r1') (v2, r2') =
if T.equal v1 v2 then
if Z.equal r1' r2' then
raise Unsat
else
acc
else
(v1, v2, Z.(r2'-r1'))::acc
(** Find all disequalities of the form t1 != z2-z1 + t2
that can be inferred from equalities of the form *(z1 + t1) = *(z2 + t2).
*)
let check_neq (_,arg) acc (v,zmap) =
let f acc (r1,_) (r2,_) =
if Z.equal r1 r2 then
acc
else (* r1 <> r2 *)
let l1 = BatOption.default [] (map_find_opt (v,r1) arg) in
let l2 = BatOption.default [] (map_find_opt (v,r2) arg) in
fold_left2 add_diseq acc l1 l2
in
let zlist = ZMap.bindings zmap in
fold_left2 f acc zlist zlist
(** Find all disequalities of the form t1 != z2-z1 + t2
that can be inferred from block equalities of the form bl( *(z1 + t1) ) = bl( *(z2 + t2) ).
*)
let check_neq_bl (uf,arg) acc (t1, tset) =
let l1 = map_find_all t1 arg in
let f t2 acc =
(* We know that r1 <> r2, otherwise it would be Unsat. *)
let l2 = map_find_all t2 arg in
fold_left2 add_diseq acc l1 l2
in
TSet.fold f tset acc
(** Initialize the list of disequalities taking only implicit dis-equalities into account.
Returns: List of dis-equalities implied by the equalities. *)
let init_neq (uf,cmap,arg) =
List.fold_left (check_neq (uf,arg)) [] (TMap.bindings cmap)
(** Initialize the list of disequalities taking only implicit dis-equalities into account.
Returns: List of dis-equalities implied by the block disequalities. *)
let init_neg_block_diseq (uf, bldis, cmap, arg) =
List.fold_left (check_neq_bl (uf,arg)) [] (TMap.bindings bldis)
(** Initialize the list of disequalities taking explicit dis-equalities into account.
Parameters: union-find partition, explicit disequalities.
Returns: list of normalized provided dis-equalities *)
let init_list_neq uf neg =
let add_diseq (uf, list) (v1,v2,r) =
let v1, r1, uf = TUF.find uf v1 in
let v2, r2, uf = TUF.find uf v2 in
if T.equal v1 v2 then
if Z.(equal r1 (r2+r)) then
raise Unsat
else
uf, list
else
uf, (v1, v2, Z.(r2-r1+r))::list
in
List.fold_left add_diseq (uf,[]) neg
(** Parameter: list of disequalities (t1, t2, z), where t1 and t2 are roots.
Returns: map `neq` where each representative is mapped to a set of representatives it is not equal to.
*)
let rec propagate_neq (uf,(cmap: TSet.t ZMap.t TMap.t),arg,neq) bldis = function (* v1, v2 are distinct roots with v1 != v2+r *)
| [] -> neq (* uf need not be returned: has been flattened during constr. of cmap *)
| (v1,v2,r) :: rest ->
(* we don't want to explicitly store disequalities of the kind &x != &y *)
if T.is_addr v1 && T.is_addr v2 || BlDis.map_set_mem v1 v2 bldis then
propagate_neq (uf,cmap,arg,neq) bldis rest
else (* v1, v2 are roots; v2 -> r,v1 not yet contained in neq *)
if T.equal v1 v2 then
if Z.equal r Z.zero then
raise Unsat
else
propagate_neq (uf,cmap,arg,neq) bldis rest
else (* check whether it is already in neq *)
if map_set_mem (v1,Z.(-r)) v2 neq then
propagate_neq (uf,cmap,arg,neq) bldis rest
else
let neq = map_set_add (v1,Z.(-r)) v2 neq |> map_set_add (v2,r) v1 in
(*
search components of v1, v2 for elements at distance r to obtain inferred equalities
at the same level (not recorded) and then compare their predecessors
*)
match TMap.find_opt v1 (cmap:t), TMap.find_opt v2 cmap with
| None,_
| _,None -> (*should not happen*)
propagate_neq (uf,cmap,arg,neq) bldis rest
| Some imap1, Some imap2 ->
let f rest (r1,_) =
match ZMap.find_opt Z.(r1+r) imap2 with
| None -> rest
| Some _ ->
let l1 = BatOption.default [] (map_find_opt (v1,r1) arg) in
let l2 = BatOption.default [] (map_find_opt (v2,Z.(r1+r)) arg) in
fold_left2 add_diseq rest l1 l2
in
let ilist1 = ZMap.bindings imap1 in
let rest = List.fold_left f rest ilist1 in
propagate_neq (uf,cmap,arg,neq) bldis rest
(*
collection of disequalities:
* disequalities originating from different offsets of same root
* disequalities originating from block disequalities
* stated disequalities
* closure by collecting appropriate args
for a disequality v1 != v2 +r for distinct roots v1,v2
check whether there is some r1, r2 such that r1 = r2 +r
then dis-equate the sets at v1,r1 with v2,r2.
*)
(** Produces a string for the number used as offset; helper function for show* functions below.*)
let show_number r =
if Z.equal r Z.zero then
""
else if Z.leq r Z.zero then
Z.to_string r
else
" + " ^ Z.to_string r
let show_neq neq =
let clist = bindings neq in
let do_neq =
(fun s (v,r,v') ->
s ^ "\t" ^ T.show v ^ show_number r ^ " != " ^ T.show v' ^ "\n")
in
List.fold_left do_neq "" clist
let get_disequalities x =
let to_disequality (t1, z, t2) =
Nequal (t1, t2, Z.(-z))
in
List.map to_disequality @@ bindings x
(** For each disequality t1 != z + t2 we add all disequalities
that follow from equalities. I.e., if t1 = z1 + t1' and t2 = z2 + t2',
then we add the disequaity t1' != z + z2 - z1 + t2'.
*)
let element_closure diseqs cmap uf =
let comp_closure (r1,r2,z) =
let eq_class1 = LMap.comp_t_cmap_repr cmap r1 in
let eq_class2 = LMap.comp_t_cmap_repr cmap r2 in
let to_diseq (z1, nt1) (z2, nt2) =
(nt1, nt2, Z.(-z2+z+z1))
in
GobList.cartesian_map to_diseq eq_class1 eq_class2
in
List.concat_map comp_closure diseqs
end
(** Set of subterms which are present in the current data structure. *)
module SSet = struct
type t = TSet.t [@@deriving eq, ord, hash]
let elements = TSet.elements
let mem = TSet.mem
let add = TSet.add
let fold = TSet.fold
let empty = TSet.empty
let to_list = TSet.elements
let inter = TSet.inter
let find_opt = TSet.find_opt
let union = TSet.union
let show_set set =
let show_element v s =
s ^ "\t" ^ T.show v ^ ";\n"
in
TSet.fold show_element set "" ^ "\n"
(** Adds all subterms of t to the SSet and the LookupMap*)
let rec subterms_of_term (set,map) t =
match t with
| Addr _
| Aux _ -> (add t set, map)
| Deref (t',z,_) ->
let set = add t set in
let map = LMap.map_add (t',z) t map in
subterms_of_term (set, map) t'
let subterms_of_conj list =
(** Adds all subterms of the proposition to the SSet and the LookupMap*)
let subterms_of_prop (set, map) (t1, t2, _) =
let subterms' = subterms_of_term (set, map) t1 in
subterms_of_term subterms' t2
in
List.fold_left subterms_of_prop (TSet.empty, LMap.empty) list
let fold_atoms f (acc: 'a) set:'a =
let exception AtomsDone in
let res = ref acc in
let do_atom (v: T.t) acc =
match v with
| Addr _
| Aux _ ->
f acc v
| _ ->
res := acc;
raise AtomsDone
in
try
TSet.fold do_atom set acc
with AtomsDone -> !res
let get_atoms set =
(* `elements set` returns a sorted list of the elements. The atoms are always smaller that other terms,
according to our comparison function. Therefore take_while is enough. *)
let is_atom = function
| Addr _
| Aux _ -> true
| _ -> false
in
BatList.take_while is_atom (elements set)
(** We try to find the dereferenced term between the already existing terms, in order to remember the information about the exp. *)
let deref_term t z set =
let exp = T.to_cil t in
match find_opt (Deref (t, z, exp)) set with
| None -> Deref (t, z, T.dereference_exp exp z)
| Some t -> t
(** Sometimes it's important to keep the dereferenced term,
even if it's not technically possible to dereference it from a point of view of the C types.
We still need the dereferenced term for the correctness of some algorithms,
and the resulting expression will never be used, so it doesn't need to be a
C expression that makes sense. *)
let deref_term_even_if_its_not_possible min_term z set =
try
deref_term min_term z set
with (T.UnsupportedCilExpression _) ->
let random_type = (TPtr (TPtr (TInt (ILong,[]),[]),[])) in (*the type is not so important for min_repr and get_normal_form*)
let cil_offset =
(* TODO: Is there a "valid" reason for to throw an exception? If not, just propagate exception here. *)
try T.to_cil_constant z (Some random_type)
with (T.UnsupportedCilExpression _) ->
Const (CInt (Z.zero, T.default_int_type, Some (Z.to_string z)))
in
Deref (min_term, z, Lval (Mem (BinOp (PlusPI, T.to_cil(min_term), cil_offset, random_type)), NoOffset))
end
(** Minimal representatives map.
It maps each representative term of an equivalence class to the minimal term of this representative class.
rep -> (t, z) means that t = rep + z *)
module MRMap = struct
type t = (T.t * Z.t) TMap.t [@@deriving eq, ord, hash]
let bindings = TMap.bindings
let find = TMap.find
let find_opt = TMap.find_opt
let add = TMap.add
let remove = TMap.remove
let mem = TMap.mem
let empty = TMap.empty
let show_min_rep min_representatives =
let show_one_rep s (state, (rep, z)) =
s ^ "\tState: " ^ T.show state ^
"\n\tMin: (" ^ T.show rep ^ ", " ^ Z.to_string z ^ ")--\n\n"
in
List.fold_left show_one_rep "" (bindings min_representatives)
let rec update_min_repr (uf, set, map) min_representatives = function
| [] -> min_representatives
| state::queue -> (* process all outgoing edges in order of ascending edge labels *)
match LMap.successors state map with
| edges ->
let process_edge (min_representatives, queue, uf) (edge_z, next_term) =
let next_state, next_z = TUF.find_no_pc uf next_term in
let (min_term, min_z) = find state min_representatives in
let next_min =
(SSet.deref_term_even_if_its_not_possible min_term Z.(edge_z - min_z) set, next_z) in
match TMap.find_opt next_state min_representatives
with
| None ->
(add next_state next_min min_representatives, queue @ [next_state], uf)
| Some current_min when T.compare (fst next_min) (fst current_min) < 0 ->
(add next_state next_min min_representatives, queue @ [next_state], uf)
| _ -> (min_representatives, queue, uf)
in
let (min_representatives, queue, uf) = List.fold_left process_edge (min_representatives, queue, uf) edges
in update_min_repr (uf, set, map) min_representatives queue
(** Uses dijkstra algorithm to update the minimal representatives of
the successor nodes of all edges in the queue
and if necessary it recursively updates the minimal representatives of the successor nodes.
The states in the queue must already have an updated min_repr.
This function visits only the successor nodes of the nodes in queue, not the nodes themselves.
Before visiting the nodes, it sorts the queue by the size of the current mininmal representative.
parameters:
- `(uf, set, map)` represent the union find data structure and the corresponding term set and lookup map.
- `min_representatives` maps each representative of the union find data structure to the minimal representative of the equivalence class.
- `queue` contains the states that need to be processed.
The states of the automata are the equivalence classes and each state of the automata is represented by the representative term.
Therefore the queue is a list of representative terms.
Returns:
- The updated `min_representatives` map with the minimal representatives*)
let update_min_repr (uf, set, map) min_representatives queue =
(* order queue by size of the current min representative *)
let compare el1 el2 =
let compare_repr = TUF.compare_repr (find el1 min_representatives) (find el2 min_representatives) in
if compare_repr = 0 then
T.compare el1 el2
else
compare_repr
in
let roots = List.filter (TUF.is_root uf) queue in
let sorted_roots = BatList.sort_unique compare roots in
update_min_repr (uf, set, map) min_representatives sorted_roots
(**
Computes a map that maps each representative of an equivalence class to the minimal representative of the equivalence class.
Returns:
- The map with the minimal representatives.
*)
let compute_minimal_representatives (uf, set, map) =
if M.tracing then M.trace "c2po-normal-form" "compute_minimal_representatives\n";
let atoms = SSet.get_atoms set in
(* process all atoms in increasing order *)
let compare el1 el2 =
let v1, z1 = TUF.find_no_pc uf el1 in
let v2, z2 = TUF.find_no_pc uf el2 in
let repr_compare = TUF.compare_repr (v1, z1) (v2, z2) in
if repr_compare = 0 then
T.compare el1 el2
else
repr_compare
in
let atoms = List.sort compare atoms in
let add_atom_to_map (min_representatives, queue, uf) a =
let rep, offs = TUF.find_no_pc uf a in
if mem rep min_representatives then
(min_representatives, queue, uf)
else
(add rep (a, offs) min_representatives, queue @ [rep], uf)
in
let (min_representatives, queue, uf) = List.fold_left add_atom_to_map (empty, [], uf) atoms
(* compute the minimal representative of all remaining edges *)
in update_min_repr (uf, set, map) min_representatives queue
let compute_minimal_representatives a =
Timing.wrap "c2po-compute-min-repr" compute_minimal_representatives a
(** Computes the initial map of minimal representatives.
It maps each element `e` in the set to `(e, 0)`. *)
let initial_minimal_representatives set =
let add_element map element =
add element (element, Z.zero) map
in
List.fold_left add_element empty (SSet.elements set)
end
(** Returns a list of all the transition that are present in the automata. *)
let get_transitions (uf, map) =
let do_binding t (edge_z, res_t) =
(edge_z, t, TUF.find_no_pc uf res_t)
in
let do_bindings ((t : term), zmap) =
let bindings = LMap.zmap_bindings zmap in
List.map (do_binding t) bindings
in
List.concat_map do_bindings (LMap.bindings map)
let show_conj list =
match list with
| [] -> "top"
| list ->
let show_prop s d =
s ^ "\t" ^ T.show_prop d ^ ";\n"
in
List.fold_left show_prop "" list
type data = {
uf: TUF.t;
set: SSet.t;
map: LMap.t;
diseq: Disequalities.t;
bldis: BlDis.t
} [@@deriving eq, ord, hash]
(** Converts the domain representation to a conjunction, using
the function `get_normal_repr` to compute the representatives that need to be used in the conjunction.*)
let get_normal_conjunction cc get_normal_repr =
let is_non_trivial_equality (t1, t2, z) =
not (T.equal t1 t2 && Z.(equal z zero))
in
let to_equality (t1, t2, z) =
Equal (t1, t2, z)
in
let conjunctions_of prop_of xs =
List.to_seq xs
|> Seq.map prop_of
|> Seq.filter is_non_trivial_equality
|> Seq.map to_equality
|> List.of_seq
in
let conjunctions_of_atoms =
let eq_of_atom atom =
let rep_state, rep_z = TUF.find_no_pc cc.uf atom in
let min_state, min_z = get_normal_repr rep_state in
(atom, min_state, Z.(rep_z - min_z))
in
let atoms = SSet.get_atoms cc.set in
conjunctions_of eq_of_atom atoms
in
let conjunctions_of_transitions =
let transitions = get_transitions (cc.uf, cc.map) in
let eq_of_transition (z, s, (s', z')) =
let min_state, min_z = get_normal_repr s in
let min_state', min_z' = get_normal_repr s' in
(SSet.deref_term_even_if_its_not_possible min_state Z.(z - min_z) cc.set, min_state', Z.(z' - min_z'))
in
conjunctions_of eq_of_transition transitions
in
(* disequalities *)
let disequalities = Disequalities.get_disequalities cc.diseq in
(* find disequalities between min_repr *)
let normalize_disequality (t1, t2, z) =
let min_state1, min_z1 = get_normal_repr t1 in
let min_state2, min_z2 = get_normal_repr t2 in
let new_offset = Z.(-min_z2 + min_z1 + z) in
if T.compare min_state1 min_state2 < 0 then
Nequal (min_state1, min_state2, new_offset)
else
Nequal (min_state2, min_state1, Z.(-new_offset))
in
let normalize_disequality = function
| Nequal (t1,t2,z) -> normalize_disequality (t1, t2, z)
| Equal (t1,t2,z) -> failwith "No equality expected."
| BlNequal (t1,t2) -> failwith "No block disequality expected."
in
if M.tracing then M.trace "c2po-diseq" "DISEQUALITIES: %s;\nUnion find: %s\nMap: %s\n" (show_conj disequalities) (TUF.show_uf cc.uf) (LMap.show_map cc.map);
let disequalities = List.map normalize_disequality disequalities in
(* block disequalities *)
let normalize_bldis t = match t with
| BlNequal (t1,t2) ->
let min_state1, _ = get_normal_repr t1 in
let min_state2, _ = get_normal_repr t2 in
if T.compare min_state1 min_state2 < 0 then
BlNequal (min_state1, min_state2)
else
BlNequal (min_state2, min_state1)
| _ -> failwith "Expected a block disequality, but received something different."
in
let conjunctions_of_bl_diseqs = List.map normalize_bldis @@ BlDis.to_conj cc.bldis in
(* all propositions *)
let all_props = conjunctions_of_atoms @ conjunctions_of_transitions @ disequalities @ conjunctions_of_bl_diseqs in
BatList.sort_unique T.compare_v_prop all_props
module NormalFormEval =
struct
type t = data
type result = T.v_prop list
let eval (cc: t) : result =
let f min_repr t =
match MRMap.find_opt t min_repr with
| None -> t, Z.zero
| Some minr -> minr
in
let min_repr = MRMap.compute_minimal_representatives (cc.uf, cc.set, cc.map) in
let conj = get_normal_conjunction cc (f min_repr) in
conj
end
module LazyNormalFormEval = struct
include LazyEval.Make(NormalFormEval)
(* For usage in mo*)
let equal _ _ = true
end
(**
This is the type for the abstract domain.
- `uf` is the union find tree
- `set` is the set of terms that are currently considered.
It is the set of terms that have a mapping in the `uf` tree.
- `map` maps reference variables v to a map that maps integers z to terms that are equivalent to *(v + z).
It represents the transitions of the quantitative finite automata.
- `normal_form` is the unique normal form of the domain element, it is a lazily computed when needed and stored such that it can be used again later.
- `diseq` represents the disequalities. It is a map from a term t1 to a map from an integer z to a set of terms T, which represents the disequality t1 != z + t2 for each t2 in T.
- `bldis` represents the block disequalities. It is a map that maps each term to a set of terms that are definitely in a different block.
*)
type t = {data: data;
normal_form: (LazyNormalFormEval.t [@compare fun _ _ -> 0][@eq fun _ _ -> true][@hash fun _ -> 0]);
}
[@@deriving eq, ord, hash]
let exactly_equal cc1 cc2 =
cc1.uf == cc2.uf &&
cc1.map == cc2.map &&
cc1.diseq == cc2.diseq &&
cc1.bldis == cc2.bldis
(** Returns the canonical normal form of the data structure in form of a sorted list of conjunctions. *)
let get_normal_form cc =
if M.tracing && not (LazyNormalFormEval.is_val cc.normal_form) then M.trace "c2po-normal-form" "Computing normal form";
LazyNormalFormEval.force cc.normal_form
(** Converts the normal form to string, but only if it was already computed. *)
let show_normal_form normal_form =
if LazyNormalFormEval.is_val normal_form then
show_conj (LazyNormalFormEval.force normal_form)
else
"not computed"
let get_conjunction_from_data data =
get_normal_conjunction data (fun t -> t, Z.zero)
(** Returns a list of conjunctions that follow from the data structure in form of a sorted list of conjunctions.
This is not a normal form, but it is useful to print information
about the current state of the analysis. *)
let get_conjunction cc =
get_conjunction_from_data cc.data
(** Sets the normal_form to an uncomputed value,
that will be lazily computed when it is needed. *)
let reset_normal_form cc =
{cc with normal_form = LazyNormalFormEval.make cc.data}
let data_to_t (cc : data) : t =
{data = cc;
normal_form = LazyNormalFormEval.make cc}
let show_all (x: t) =
"Normal form:\n" ^
show_conj((get_conjunction x)) ^
"Union Find partition:\n" ^
TUF.show_uf x.data.uf
^ "\nSubterm set:\n"
^ SSet.show_set x.data.set
^ "\nLookup map/transitions:\n"
^ LMap.show_map x.data.map
^ "\nNeq:\n"
^ Disequalities.show_neq x.data.diseq
^ "\nBlock diseqs:\n"
^ show_conj (BlDis.to_conj x.data.bldis)
^ "\nMin repr:\n"
^ show_normal_form x.normal_form
(** Splits the conjunction into three groups: the first one contains all equality propositions,
the second one contains all inequality propositions
and the third one contains all block disequality propositions. *)
let split conj =
let group (eqs, neqs, blds) = function
| Equal eq -> (eq::eqs, neqs, blds)
| Nequal neq -> (eqs, neq::neqs, blds)
| BlNequal bld -> (eqs, neqs, bld::blds)
in
List.fold_left group ([],[],[]) conj
(**
Returns \{uf, set, map, normal_form, bldis, diseq\},
where all data structures are initialized with an empty map/set.
*)
let init_cc () =
{uf = TUF.empty;
set = SSet.empty;
map = LMap.empty;
diseq = Disequalities.empty;
bldis = BlDis.empty}
(** Computes the closure of disequalities. *)
let congruence_neq cc neg' =
let _, neg, _ = split (Disequalities.get_disequalities cc.diseq) in
let neg = neg @ neg' in
(* get args of dereferences *)
let uf, cmap, arg = Disequalities.get_args cc.uf in
(* take implicit dis-equalities into account *)
let neq_list = Disequalities.init_neq (uf, cmap, arg) in
let neq_list_from_bldis = Disequalities.init_neg_block_diseq (uf, cc.bldis, cmap, arg) in
let neq_list = neq_list @ neq_list_from_bldis in
let neq = Disequalities.propagate_neq (uf, cmap, arg, Disequalities.empty) cc.bldis neq_list in
(* take explicit dis-equalities into account *)
let uf, neq_list = Disequalities.init_list_neq uf neg in
let neq = Disequalities.propagate_neq (uf, cmap, arg, neq) cc.bldis neq_list in
if M.tracing then M.trace "c2po-neq" "congruence_neq: %s\nUnion find: %s\n" (Disequalities.show_neq neq) (TUF.show_uf uf);
{cc with uf; diseq = neq}
(**
parameters: (uf, map, new_repr) equalities.
returns updated (uf, map, new_repr), where:
`uf` is the new union find data structure after having added all equalities.
`map` maps reference variables v to a map that maps integers z to terms that are equivalent to *(v + z).
`new_repr` maps each term that changed its representative term to the new representative.
It can be given as a parameter to `update_bldis` in order to update the representatives in the block disequalities.
Throws "Unsat" if a contradiction is found.
*)
let rec closure (uf, map, new_repr) = function
| [] -> (uf, map, new_repr)
| (t1, t2, r)::rest ->
let v1, r1, uf = TUF.find uf t1 in
let v2, r2, uf = TUF.find uf t2 in
let sizet1, sizet2 = T.get_size t1, T.get_size t2 in
if not (Z.equal sizet1 sizet2) then (
if M.tracing then M.trace "c2po" "ignoring equality because the sizes are not the same: %s = %s + %s" (T.show t1) (Z.to_string r) (T.show t2);
closure (uf, map, new_repr) rest
)
else if T.equal v1 v2 then
(* t1 and t2 are in the same equivalence class *)
if Z.equal r1 Z.(r2 + r) then
closure (uf, map, new_repr) rest
else
raise Unsat
else
let diff_r = Z.(r2 - r1 + r) in
let v, uf, b = TUF.union uf v1 v2 diff_r in (* union *)
(* update new_representative *)
let new_repr =
if T.equal v v1 then
TMap.add v2 v new_repr
else
TMap.add v1 v new_repr
in
let f (zmap, rest) (r', v') =
let rest = match LMap.zmap_find_opt r' zmap with
| None -> rest
| Some v'' -> (v', v'',Z.zero) ::rest
in
let zmap = LMap.zmap_add r' v' zmap in
zmap, rest
in
(* update map *)
let map, rest =
match LMap.find_opt v1 map, LMap.find_opt v2 map, b with
| None, _, false
| _, None, true -> (* either v1 or v2 does not occur inside Deref *)
map, rest
| None, Some _, true ->
LMap.shift v1 Z.(r1 - r2 - r) v2 map, rest
| Some _, None, false ->
LMap.shift v2 Z.(r2 - r1 + r) v1 map, rest
| Some imap1, Some imap2, true -> (* v1 is new root *)
(* zmap describes args of Deref *)
let r0 = Z.(r2 - r1 + r) in (* difference between roots *)
(* we move all entries of imap2 to imap1 *)
let infl2 = List.map (fun (r', v') -> Z.(-r0 + r'), v') (LMap.zmap_bindings imap2) in
let zmap, rest = List.fold_left f (imap1, rest) infl2 in
let map = LMap.add v zmap map in
let map = LMap.remove v2 map in
map, rest
| Some imap1, Some imap2, false -> (* v2 is new root *)
let r0 = Z.(r1 - r2 - r) in
let infl1 = List.map (fun (r', v') -> Z.(-r0 + r'),v') (LMap.zmap_bindings imap1) in
let zmap, rest = List.fold_left f (imap2, rest) infl1 in
let map = LMap.add v zmap map in
let map = LMap.remove v1 map in
map, rest
in
closure (uf, map, new_repr) rest
(** Update block disequalities with the new representatives. *)
let update_bldis new_repr bldis =
let bldis = BlDis.map_lhs bldis (TMap.bindings new_repr) in
(* update block disequalities with the new representatives *)
let find_new_root t1 = BatOption.default t1 (TMap.find_opt t1 new_repr) in
BlDis.map find_new_root bldis
(**
Parameters: cc conjunctions.
returns updated cc, where:
- `uf` is the new union find data structure after having added all equalities.
- `set` doesn't change
- `map` maps reference variables v to a map that maps integers z to terms that are equivalent to *(v + z).
- `diseq` doesn't change (it must be updated later to the new representatives).
- `bldis` are the block disequalities between the new representatives.
Throws "Unsat" if a contradiction is found.
This does NOT update the disequalities.
They need to be updated with `congruence_neq`.
*)
let closure cc conjs =
let (uf, map, new_repr) = closure (cc.uf, cc.map, TMap.empty) conjs in
let bldis = update_bldis new_repr cc.bldis in
{cc with uf; map; bldis}
(** Adds the block disequalities to the cc, but first rewrites them such that
they are disequalities between representatives. The cc should already contain
all the terms that are present in those block disequalities.
*)
let rec add_normalized_bl_diseqs cc = function
| [] -> cc
| (t1,t2)::bl_conjs ->
let t1',_,uf = TUF.find cc.uf t1 in
let t2',_,uf = TUF.find uf t2 in
if T.equal t1' t2' then
raise Unsat (*unsatisfiable*)
else
let bldis = BlDis.add_block_diseq cc.bldis (t1',t2') in
add_normalized_bl_diseqs {cc with bldis; uf} bl_conjs
(** Add a term to the data structure.
Returns (reference variable, offset), updated congruence closure *)
let rec insert cc t =
if SSet.mem t cc.set then
let v, z, uf = TUF.find cc.uf t in
(v,z), {cc with uf}
else
match t with
| Addr _
| Aux _ ->
let uf = TUF.ValMap.add t ((t, Z.zero), 1) cc.uf in
let set = SSet.add t cc.set in
(t, Z.zero), {cc with uf; set}
| Deref (t', z, exp) ->
let (v, r), cc = insert cc t' in
let set = SSet.add t cc.set in
match LMap.map_find_opt (v, Z.(r + z)) cc.map with
| Some v' ->
let v2, z2, uf = TUF.find cc.uf v' in
let uf = LMap.add t ((t, Z.zero),1) uf in
let cc = closure {cc with uf; set} [(t, v', Z.zero)] in
(v2, z2), cc
| None ->
let map = LMap.map_add (v, Z.(r + z)) t cc.map in
let uf = LMap.add t ((t, Z.zero),1) cc.uf in
(t, Z.zero), {cc with uf; set; map}
(** Add all terms in a specific set to the data structure.
Returns updated cc. *)
let insert_set cc t_set =
let insert_term t cc =
let _, cc = insert cc t in
cc
in
SSet.fold insert_term t_set cc
(** Returns true if t1 and t2 are equivalent. *)
let rec eq_query cc (t1,t2,r) =
let (v1, r1), cc = insert cc t1 in
let (v2, r2), cc = insert cc t2 in
if T.equal v1 v2 && Z.equal r1 Z.(r2 + r) then