aboutsummaryrefslogtreecommitdiffstats
path: root/scheduling/RTLpathSE_impl.v
blob: f42a34920bf03d6d6d5bd10205ae886eae2dbbd4 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
(** Implementation and refinement of the symbolic execution *)

Require Import Coqlib Maps Floats.
Require Import AST Integers Values Events Memory Globalenvs Smallstep.
Require Import Op Registers.
Require Import RTL RTLpath.
Require Import Errors.
Require Import RTLpathSE_theory RTLpathLivegenproof.
Require Import Axioms RTLpathSE_simu_specs.
Require Import Asmgen Asmgenproof1.
Require Import RTLpathSE_simplify.

Local Open Scope error_monad_scope.
Local Open Scope option_monad_scope.

Require Import Impure.ImpHCons.
Import Notations.
Import HConsing.

Local Open Scope impure.
Local Open Scope hse.

Import ListNotations.
Local Open Scope list_scope.

Definition XDEBUG {A} (x:A) (k: A -> ?? pstring): ?? unit := RET tt. (* TO REMOVE DEBUG INFO *)
(*Definition XDEBUG {A} (x:A) (k: A -> ?? pstring): ?? unit := DO s <~ k x;; println ("DEBUG simu_check:" +; s). (* TO INSERT DEBUG INFO *)*)

Definition DEBUG (s: pstring): ?? unit := XDEBUG tt (fun _ => RET s).

(** * Implementation of Data-structure use in Hash-consing *)

Definition hsval_get_hid (hsv: hsval): hashcode :=
  match hsv with
  | HSinput _ hid => hid
  | HSop _ _ hid => hid
  | HSload _ _ _ _ _ hid => hid
  end.

Definition list_hsval_get_hid (lhsv: list_hsval): hashcode :=
  match lhsv with
  | HSnil hid => hid
  | HScons _ _ hid => hid
  end.

Definition hsmem_get_hid (hsm: hsmem): hashcode :=
  match hsm with
  | HSinit hid => hid
  | HSstore _ _ _ _ _ hid => hid
  end.

Definition hsval_set_hid (hsv: hsval) (hid: hashcode): hsval :=
  match hsv with
  | HSinput r _ => HSinput r hid
  | HSop o lhsv _ => HSop o lhsv hid
  | HSload hsm trap chunk addr lhsv _ => HSload hsm trap chunk addr lhsv hid
  end.

Definition list_hsval_set_hid (lhsv: list_hsval) (hid: hashcode): list_hsval :=
  match lhsv with
  | HSnil _ => HSnil hid
  | HScons hsv lhsv _ => HScons hsv lhsv hid
  end.

Definition hsmem_set_hid (hsm: hsmem) (hid: hashcode): hsmem :=
  match hsm with
  | HSinit _ => HSinit hid
  | HSstore hsm chunk addr lhsv srce _ => HSstore hsm chunk addr lhsv srce hid
  end.


Lemma hsval_set_hid_correct x y ge sp rs0 m0:
  hsval_set_hid x unknown_hid = hsval_set_hid y unknown_hid ->
  seval_hsval ge sp x rs0 m0 = seval_hsval ge sp y rs0 m0.
Proof.
  destruct x, y; intro H; inversion H; subst; simpl; auto.
Qed.
Local Hint Resolve hsval_set_hid_correct: core.

Lemma list_hsval_set_hid_correct x y ge sp rs0 m0:
  list_hsval_set_hid x unknown_hid = list_hsval_set_hid y unknown_hid ->
  seval_list_hsval ge sp x rs0 m0 = seval_list_hsval ge sp y rs0 m0.
Proof.
  destruct x, y; intro H; inversion H; subst; simpl; auto.
Qed.
Local Hint Resolve list_hsval_set_hid_correct: core.

Lemma hsmem_set_hid_correct x y ge sp rs0 m0:
  hsmem_set_hid x unknown_hid = hsmem_set_hid y unknown_hid ->
  seval_hsmem ge sp x rs0 m0 = seval_hsmem ge sp y rs0 m0.
Proof.
  destruct x, y; intro H; inversion H; subst; simpl; auto.
Qed.
Local Hint Resolve hsmem_set_hid_correct: core.

(** Now, we build the hash-Cons value from a "hash_eq".

  Informal specification: 
    [hash_eq] must be consistent with the "hashed" constructors defined above.

  We expect that hashinfo values in the code of these "hashed" constructors verify:
    (hash_eq (hdata x) (hdata y) ~> true) <-> (hcodes x)=(hcodes y)
*)


Definition hsval_hash_eq (sv1 sv2: hsval): ?? bool :=
  match sv1, sv2 with
  | HSinput r1 _, HSinput r2 _ => struct_eq r1 r2 (* NB: really need a struct_eq here ? *)
  | HSop op1 lsv1 _, HSop op2 lsv2 _  =>
     DO b1 <~ phys_eq lsv1 lsv2;;
     if b1
     then struct_eq op1 op2 (* NB: really need a struct_eq here ? *)
     else RET false
  | HSload sm1 trap1 chk1 addr1 lsv1 _, HSload sm2 trap2 chk2 addr2 lsv2 _ =>
     DO b1 <~ phys_eq lsv1 lsv2;;
     DO b2 <~ phys_eq sm1 sm2;;
     DO b3 <~ struct_eq trap1 trap2;;
     DO b4 <~ struct_eq chk1 chk2;;
     if b1 && b2 && b3 && b4
     then struct_eq addr1 addr2
     else RET false
  | _,_ => RET false
  end.


Lemma and_true_split a b: a && b = true <-> a = true /\ b = true.
Proof.
  destruct a; simpl; intuition.
Qed.

Lemma hsval_hash_eq_correct x y:
  WHEN hsval_hash_eq x y ~> b THEN 
   b = true -> hsval_set_hid x unknown_hid = hsval_set_hid y unknown_hid.
Proof.
  destruct x, y; wlp_simplify; try (rewrite !and_true_split in *); intuition; subst; try congruence.
Qed.
Global Opaque hsval_hash_eq.
Local Hint Resolve hsval_hash_eq_correct: wlp.

Definition list_hsval_hash_eq (lsv1 lsv2: list_hsval): ?? bool :=
  match lsv1, lsv2 with
  | HSnil _, HSnil _ => RET true
  | HScons sv1 lsv1' _, HScons sv2 lsv2' _  =>
     DO b <~ phys_eq lsv1' lsv2';;
     if b 
     then phys_eq sv1 sv2
     else RET false
  | _,_ => RET false
  end.

Lemma list_hsval_hash_eq_correct x y:
  WHEN list_hsval_hash_eq x y ~> b THEN 
   b = true -> list_hsval_set_hid x unknown_hid = list_hsval_set_hid y unknown_hid.
Proof.
  destruct x, y; wlp_simplify; try (rewrite !and_true_split in *); intuition; subst; try congruence.
Qed.
Global Opaque list_hsval_hash_eq.
Local Hint Resolve list_hsval_hash_eq_correct: wlp.

Definition hsmem_hash_eq (sm1 sm2: hsmem): ?? bool :=
  match sm1, sm2 with
  | HSinit _, HSinit _ => RET true
  | HSstore sm1 chk1 addr1 lsv1 sv1 _, HSstore sm2 chk2 addr2 lsv2 sv2 _ =>
     DO b1 <~ phys_eq lsv1 lsv2;;
     DO b2 <~ phys_eq sm1 sm2;;
     DO b3 <~ phys_eq sv1 sv2;;
     DO b4 <~ struct_eq chk1 chk2;;
     if b1 && b2 && b3 && b4
     then struct_eq addr1 addr2
     else RET false
  | _,_ => RET false
  end.

Lemma hsmem_hash_eq_correct x y:
  WHEN hsmem_hash_eq x y ~> b THEN 
   b = true -> hsmem_set_hid x unknown_hid = hsmem_set_hid y unknown_hid.
Proof.
  destruct x, y; wlp_simplify; try (rewrite !and_true_split in *); intuition; subst; try congruence.
Qed.
Global Opaque hsmem_hash_eq.
Local Hint Resolve hsmem_hash_eq_correct: wlp.


Definition hSVAL: hashP hsval := {| hash_eq := hsval_hash_eq; get_hid:=hsval_get_hid; set_hid:=hsval_set_hid |}. 
Definition hLSVAL: hashP list_hsval := {| hash_eq := list_hsval_hash_eq; get_hid:= list_hsval_get_hid; set_hid:= list_hsval_set_hid |}.
Definition hSMEM: hashP hsmem := {| hash_eq := hsmem_hash_eq; get_hid:= hsmem_get_hid; set_hid:= hsmem_set_hid |}.

Program Definition mk_hash_params: Dict.hash_params hsval :=
 {|
    Dict.test_eq := phys_eq;
    Dict.hashing := fun (ht: hsval) => RET (hsval_get_hid ht);
    Dict.log := fun hv =>
         DO hv_name <~ string_of_hashcode (hsval_get_hid hv);;
         println ("unexpected undef behavior of hashcode:" +; (CamlStr hv_name)) |}.
Obligation 1.
  wlp_simplify.
Qed.

(** ** various auxiliary (trivial lemmas) *)
Lemma hsilocal_refines_sreg ge sp rs0 m0 hst st:
  hsilocal_refines ge sp rs0 m0 hst st -> hsok_local ge sp rs0 m0 hst -> forall r, hsi_sreg_eval ge sp hst r rs0 m0 = seval_sval ge sp (si_sreg st r) rs0 m0.
Proof.
  unfold hsilocal_refines; intuition.
Qed.
Local Hint Resolve hsilocal_refines_sreg: core.

Lemma hsilocal_refines_valid_pointer ge sp rs0 m0 hst st:
  hsilocal_refines ge sp rs0 m0 hst st -> forall m b ofs, seval_smem ge sp st.(si_smem) rs0 m0 = Some m -> Mem.valid_pointer m b ofs = Mem.valid_pointer m0 b ofs.
Proof.
  unfold hsilocal_refines; intuition.
Qed.
Local Hint Resolve hsilocal_refines_valid_pointer: core.

Lemma hsilocal_refines_smem_refines ge sp rs0 m0 hst st:
  hsilocal_refines ge sp rs0 m0 hst st -> hsok_local ge sp rs0 m0 hst -> smem_refines ge sp rs0 m0 (hsi_smem hst) (st.(si_smem)).
Proof.
  unfold hsilocal_refines; intuition.
Qed.
Local Hint Resolve hsilocal_refines_smem_refines: core.

Lemma hsistate_refines_dyn_exits ge sp rs0 m0 hst st:
  hsistate_refines_dyn ge sp rs0 m0 hst st -> hsiexits_refines_dyn ge sp rs0 m0 (hsi_exits hst) (si_exits st).
Proof.
  unfold hsistate_refines_dyn; intuition.
Qed.
Local Hint Resolve hsistate_refines_dyn_exits: core.

Lemma hsistate_refines_dyn_local ge sp rs0 m0 hst st:
  hsistate_refines_dyn ge sp rs0 m0 hst st -> hsilocal_refines ge sp rs0 m0 (hsi_local hst) (si_local st).
Proof.
  unfold hsistate_refines_dyn; intuition.
Qed.
Local Hint Resolve hsistate_refines_dyn_local: core.

Lemma hsistate_refines_dyn_nested ge sp rs0 m0 hst st:
  hsistate_refines_dyn ge sp rs0 m0 hst st -> nested_sok ge sp rs0 m0 (si_local st) (si_exits st).
Proof.
  unfold hsistate_refines_dyn; intuition.
Qed.
Local Hint Resolve hsistate_refines_dyn_nested: core.

(** * Implementation of symbolic execution *)
Section CanonBuilding.

Variable hC_hsval: hashinfo hsval -> ?? hsval.

Hypothesis hC_hsval_correct: forall hs,
  WHEN hC_hsval hs ~> hs' THEN forall ge sp rs0 m0,
    seval_hsval ge sp (hdata hs) rs0 m0 = seval_hsval ge sp hs' rs0 m0.

Variable hC_list_hsval: hashinfo list_hsval -> ?? list_hsval.
Hypothesis hC_list_hsval_correct: forall lh,
  WHEN hC_list_hsval lh ~> lh' THEN forall ge sp rs0 m0,
    seval_list_hsval ge sp (hdata lh) rs0 m0 = seval_list_hsval ge sp lh' rs0 m0.

Variable hC_hsmem: hashinfo hsmem -> ?? hsmem.
Hypothesis hC_hsmem_correct: forall hm,
  WHEN hC_hsmem hm ~> hm' THEN forall ge sp rs0 m0,
    seval_hsmem ge sp (hdata hm) rs0 m0 = seval_hsmem ge sp hm' rs0 m0.

(* First, we wrap constructors for hashed values !*)

Definition reg_hcode := 1.
Definition op_hcode := 2.
Definition load_hcode := 3.

Definition hSinput_hcodes (r: reg) :=
   DO hc <~ hash reg_hcode;;
   DO hv <~ hash r;;
   RET [hc;hv].
Extraction Inline hSinput_hcodes.

Definition hSinput (r:reg): ?? hsval :=
   DO hv <~ hSinput_hcodes r;;
   hC_hsval {| hdata:=HSinput r unknown_hid; hcodes :=hv; |}.

Lemma hSinput_correct r:
  WHEN hSinput r ~> hv THEN forall ge sp rs0 m0,
    sval_refines ge sp rs0 m0 hv (Sinput r).
Proof.
  wlp_simplify.
Qed.
Global Opaque hSinput.
Local Hint Resolve hSinput_correct: wlp.

Definition hSop_hcodes (op:operation) (lhsv: list_hsval) :=
   DO hc <~ hash op_hcode;;
   DO hv <~ hash op;;
   RET [hc;hv;list_hsval_get_hid lhsv].
Extraction Inline hSop_hcodes.

Definition hSop (op:operation) (lhsv: list_hsval): ?? hsval :=
   DO hv <~ hSop_hcodes op lhsv;;
   hC_hsval {| hdata:=HSop op lhsv unknown_hid; hcodes :=hv |}.

Lemma hSop_correct op lhsv:
  WHEN hSop op lhsv ~> hv THEN forall ge sp rs0 m0 lsv sm m
   (MEM: seval_smem ge sp sm rs0 m0 = Some m)
   (MVALID: forall b ofs, Mem.valid_pointer m b ofs = Mem.valid_pointer m0 b ofs)
   (LR: list_sval_refines ge sp rs0 m0 lhsv lsv),
   sval_refines ge sp rs0 m0 hv (Sop op lsv sm).
Proof.
  wlp_simplify.
  rewrite <- H, MEM, LR.
  destruct (seval_list_sval _ _ lsv _); try congruence.
  eapply op_valid_pointer_eq; eauto.
Qed.
Global Opaque hSop.
Local Hint Resolve hSop_correct: wlp.

Definition hSload_hcodes (hsm: hsmem) (trap: trapping_mode) (chunk: memory_chunk) (addr: addressing) (lhsv: list_hsval):=
   DO hc <~ hash load_hcode;;
   DO hv1 <~ hash trap;;
   DO hv2 <~ hash chunk;;
   DO hv3 <~ hash addr;;
   RET [hc; hsmem_get_hid hsm; hv1; hv2; hv3; list_hsval_get_hid lhsv].
Extraction Inline hSload_hcodes.

Definition hSload (hsm: hsmem) (trap: trapping_mode) (chunk: memory_chunk) (addr: addressing) (lhsv: list_hsval): ?? hsval :=
   DO hv <~ hSload_hcodes hsm trap chunk addr lhsv;;
   hC_hsval {| hdata := HSload hsm trap chunk addr lhsv unknown_hid; hcodes := hv |}.

Lemma hSload_correct hsm trap chunk addr lhsv:
  WHEN hSload hsm trap chunk addr lhsv ~> hv THEN forall ge sp rs0 m0 lsv sm
    (LR: list_sval_refines ge sp rs0 m0 lhsv lsv)
    (MR: smem_refines ge sp rs0 m0 hsm sm),
    sval_refines ge sp rs0 m0 hv (Sload sm trap chunk addr lsv).
Proof.
  wlp_simplify.
  rewrite <- LR, <- MR.
  auto.
Qed.
Global Opaque hSload.
Local Hint Resolve hSload_correct: wlp.

Definition hSnil (_: unit): ?? list_hsval :=
   hC_list_hsval {| hdata := HSnil unknown_hid; hcodes := nil |}.

Lemma hSnil_correct:
  WHEN hSnil() ~> hv THEN forall ge sp rs0 m0,
    list_sval_refines ge sp rs0 m0 hv Snil.
Proof.
  wlp_simplify.
Qed.
Global Opaque hSnil.
Local Hint Resolve hSnil_correct: wlp.

Definition hScons (hsv: hsval) (lhsv: list_hsval): ?? list_hsval :=
   hC_list_hsval {| hdata := HScons hsv lhsv unknown_hid; hcodes := [hsval_get_hid hsv; list_hsval_get_hid lhsv] |}.

Lemma hScons_correct hsv lhsv:
  WHEN hScons hsv lhsv ~> lhsv' THEN forall ge sp rs0 m0 sv lsv
    (VR: sval_refines ge sp rs0 m0 hsv sv)
    (LR: list_sval_refines ge sp rs0 m0 lhsv lsv),
    list_sval_refines ge sp rs0 m0 lhsv' (Scons sv lsv).
Proof.
  wlp_simplify.
  rewrite <- VR, <- LR.
  auto.
Qed.
Global Opaque hScons.
Local Hint Resolve hScons_correct: wlp.

Definition hSinit (_: unit): ?? hsmem :=
   hC_hsmem {| hdata := HSinit unknown_hid; hcodes := nil |}.

Lemma hSinit_correct:
  WHEN hSinit() ~> hm THEN forall ge sp rs0 m0,
    smem_refines ge sp rs0 m0 hm Sinit.
Proof.
  wlp_simplify.
Qed.
Global Opaque hSinit.
Local Hint Resolve hSinit_correct: wlp.

Definition hSstore_hcodes (hsm: hsmem) (chunk: memory_chunk) (addr: addressing) (lhsv: list_hsval) (srce: hsval):=
   DO hv1 <~ hash chunk;;
   DO hv2 <~ hash addr;;
   RET [hsmem_get_hid hsm; hv1; hv2; list_hsval_get_hid lhsv; hsval_get_hid srce].
Extraction Inline hSstore_hcodes.

Definition hSstore (hsm: hsmem) (chunk: memory_chunk) (addr: addressing) (lhsv: list_hsval) (srce: hsval): ?? hsmem :=
   DO hv <~ hSstore_hcodes hsm chunk addr lhsv srce;;
   hC_hsmem {| hdata := HSstore hsm chunk addr lhsv srce unknown_hid; hcodes := hv |}.

Lemma hSstore_correct hsm chunk addr lhsv hsv:
  WHEN hSstore hsm chunk addr lhsv hsv ~> hsm' THEN forall ge sp rs0 m0 lsv sm sv
    (LR: list_sval_refines ge sp rs0 m0 lhsv lsv)
    (MR: smem_refines ge sp rs0 m0 hsm sm)
    (VR: sval_refines ge sp rs0 m0 hsv sv),
    smem_refines ge sp rs0 m0 hsm' (Sstore sm chunk addr lsv sv).
Proof.
  wlp_simplify.
  rewrite <- LR, <- MR, <- VR.
  auto.
Qed.
Global Opaque hSstore.
Local Hint Resolve hSstore_correct: wlp.

Definition hsi_sreg_get (hst: PTree.t hsval) r: ?? hsval :=
   match PTree.get r hst with 
   | None => hSinput r
   | Some sv => RET sv
   end.

Lemma hsi_sreg_get_correct hst r:
  WHEN hsi_sreg_get hst r ~> hsv THEN forall ge sp rs0 m0 (f: reg -> sval)
    (RR: forall r, hsi_sreg_eval ge sp hst r rs0 m0 = seval_sval ge sp (f r) rs0 m0),
    sval_refines ge sp rs0 m0 hsv (f r).
Proof.
  unfold hsi_sreg_eval, hsi_sreg_proj; wlp_simplify; rewrite <- RR; try_simplify_someHyps.
Qed.
Global Opaque hsi_sreg_get.
Local Hint Resolve hsi_sreg_get_correct: wlp.

Fixpoint hlist_args (hst: PTree.t hsval) (l: list reg): ?? list_hsval :=
  match l with
  | nil => hSnil()
  | r::l =>
    DO v <~ hsi_sreg_get hst r;;
    DO lhsv <~ hlist_args hst l;;
    hScons v lhsv
  end.

Lemma hlist_args_correct hst l:
  WHEN hlist_args hst l ~> lhsv THEN forall ge sp rs0 m0 (f: reg -> sval)
    (RR: forall r, hsi_sreg_eval ge sp hst r rs0 m0 = seval_sval ge sp (f r) rs0 m0),
    list_sval_refines ge sp rs0 m0 lhsv (list_sval_inj (List.map f l)).
Proof.
  induction l; wlp_simplify.
Qed.
Global Opaque hlist_args.
Local Hint Resolve hlist_args_correct: wlp.

(** Convert a "fake" hash-consed term into a "real" hash-consed term *)

Fixpoint fsval_proj hsv: ?? hsval :=
  match hsv with
  | HSinput r hc => 
    DO b <~ phys_eq hc unknown_hid;;
    if b 
    then hSinput r (* was not yet really hash-consed *)
    else RET hsv (* already hash-consed *)
  | HSop op hl hc => 
    DO b <~ phys_eq hc unknown_hid;;
    if b 
    then (* was not yet really hash-consed *) 
      DO hl' <~ fsval_list_proj hl;;
      hSop op hl' 
    else RET hsv (* already hash-consed *)
  | HSload hm t chk addr hl _ => RET hsv (* FIXME ? *)
  end
with fsval_list_proj hl: ?? list_hsval :=
  match hl with
  | HSnil hc => 
    DO b <~ phys_eq hc unknown_hid;;
    if b 
    then hSnil() (* was not yet really hash-consed *)
    else RET hl (* already hash-consed *)
  | HScons hv hl hc => 
    DO b <~ phys_eq hc unknown_hid;;
    if b 
    then (* was not yet really hash-consed *)
      DO hv' <~ fsval_proj hv;;
      DO hl' <~ fsval_list_proj hl;;
      hScons hv' hl' 
    else RET hl (* already hash-consed *)
  end.

Lemma fsval_proj_correct hsv:
  WHEN fsval_proj hsv ~> hsv' THEN forall ge sp rs0 m0,
  seval_hsval ge sp hsv rs0 m0 = seval_hsval ge sp hsv' rs0 m0.
Admitted.
Global Opaque fsval_proj.
Local Hint Resolve fsval_proj_correct: wlp.

Lemma fsval_list_proj_correct lhsv:
  WHEN fsval_list_proj lhsv ~> lhsv' THEN forall ge sp rs0 m0,
  seval_list_hsval ge sp lhsv rs0 m0 = seval_list_hsval ge sp lhsv' rs0 m0.
Admitted.
Global Opaque fsval_list_proj.
Local Hint Resolve fsval_list_proj_correct: wlp.


(** ** Assignment of memory *)
Definition hslocal_set_smem (hst:hsistate_local) hm :=
  {| hsi_smem := hm;
     hsi_ok_lsval := hsi_ok_lsval hst;
     hsi_sreg:= hsi_sreg hst
  |}.

Lemma sok_local_set_mem ge sp rs0 m0 st sm:
  sok_local ge sp rs0 m0 (slocal_set_smem st sm)
  <-> (sok_local ge sp rs0 m0 st /\ seval_smem ge sp sm rs0 m0 <> None).
Proof.
  unfold slocal_set_smem, sok_local; simpl; intuition (subst; eauto).
Qed.

Lemma hsok_local_set_mem ge sp rs0 m0 hst hsm:
  (seval_hsmem ge sp (hsi_smem hst) rs0 m0 = None -> seval_hsmem ge sp hsm rs0 m0 = None) ->
  hsok_local ge sp rs0 m0 (hslocal_set_smem hst hsm)
  <-> (hsok_local ge sp rs0 m0 hst /\ seval_hsmem ge sp hsm rs0 m0 <> None).
Proof.
  unfold hslocal_set_smem, hsok_local; simpl; intuition.
Qed.

Lemma hslocal_set_mem_correct ge sp rs0 m0 hst st hsm sm:
  (seval_hsmem ge sp (hsi_smem hst) rs0 m0 = None -> seval_hsmem ge sp hsm rs0 m0 = None) ->
  (forall m b ofs, seval_smem ge sp sm rs0 m0 = Some m -> Mem.valid_pointer m b ofs = Mem.valid_pointer m0 b ofs) ->
  hsilocal_refines ge sp rs0 m0 hst st ->
  (hsok_local ge sp rs0 m0 hst -> smem_refines ge sp rs0 m0 hsm sm) ->
  hsilocal_refines ge sp rs0 m0 (hslocal_set_smem hst hsm) (slocal_set_smem st sm).
Proof.
  intros PRESERV SMVALID (OKEQ & SMEMEQ' & REGEQ & MVALID) SMEMEQ.
  split; rewrite! hsok_local_set_mem; simpl; eauto; try tauto.
  rewrite sok_local_set_mem.
  intuition congruence.
Qed.

Definition hslocal_store (hst: hsistate_local) chunk addr args src: ?? hsistate_local :=
   let pt := hst.(hsi_sreg) in
   DO hargs <~ hlist_args pt args;;
   DO hsrc <~ hsi_sreg_get pt src;;
   DO hm <~ hSstore hst chunk addr hargs hsrc;;
   RET (hslocal_set_smem hst hm).

Lemma hslocal_store_correct hst chunk addr args src:
  WHEN hslocal_store hst chunk addr args src ~> hst' THEN forall ge sp rs0 m0 st
    (REF: hsilocal_refines ge sp rs0 m0 hst st),
    hsilocal_refines ge sp rs0 m0 hst' (slocal_store st chunk addr args src).
Proof.
  wlp_simplify.
  eapply hslocal_set_mem_correct; simpl; eauto.
  + intros X; erewrite H1; eauto.
    rewrite X. simplify_SOME z.
  + unfold hsilocal_refines in *; 
    simplify_SOME z; intuition. 
    erewrite <- Mem.storev_preserv_valid; [| eauto].
    eauto.
  + unfold hsilocal_refines in *; intuition eauto.
Qed.
Global Opaque hslocal_store.
Local Hint Resolve hslocal_store_correct: wlp.

(** ** Assignment of local state *)

Definition hsist_set_local (hst: hsistate) (pc: node) (hnxt: hsistate_local): hsistate :=
   {| hsi_pc := pc; hsi_exits := hst.(hsi_exits); hsi_local:= hnxt |}.

Lemma hsist_set_local_correct_stat hst st pc hnxt nxt:
  hsistate_refines_stat hst st ->
  hsistate_refines_stat (hsist_set_local hst pc hnxt) (sist_set_local st pc nxt).
Proof.
  unfold hsistate_refines_stat; simpl; intuition.
Qed.

Lemma hsist_set_local_correct_dyn ge sp rs0 m0 hst st pc hnxt nxt:
  hsistate_refines_dyn ge sp rs0 m0 hst st ->
  hsilocal_refines ge sp rs0 m0 hnxt nxt ->
  (sok_local ge sp rs0 m0 nxt -> sok_local ge sp rs0 m0 (si_local st)) ->
  hsistate_refines_dyn ge sp rs0 m0 (hsist_set_local hst pc hnxt) (sist_set_local st pc nxt).
Proof.
  unfold hsistate_refines_dyn; simpl.
  intros (EREF & LREF & NESTED) LREFN SOK; intuition.
  destruct NESTED as [|st0 se lse TOP NEST]; econstructor; simpl; auto.
Qed.

(** ** Assignment of registers *)

(** locally new symbolic values during symbolic execution *)
Inductive root_sval: Type :=
| Rop (op: operation)
| Rload (trap: trapping_mode) (chunk: memory_chunk) (addr: addressing)
.

Definition root_apply (rsv: root_sval) (lr: list reg) (st: sistate_local): sval :=
  let lsv := list_sval_inj (List.map (si_sreg st) lr) in
  let sm := si_smem st in
  match rsv with
  | Rop op => Sop op lsv sm
  | Rload trap chunk addr => Sload sm trap chunk addr lsv
  end.
Coercion root_apply: root_sval >-> Funclass.

Definition root_happly (rsv: root_sval) (lr: list reg) (hst: hsistate_local) : ?? hsval :=
  DO lhsv <~ hlist_args hst lr;;
  match rsv with
  | Rop op => hSop op lhsv
  | Rload trap chunk addr => hSload hst trap chunk addr lhsv
  end.

Lemma root_happly_correct (rsv: root_sval) lr hst:
  WHEN root_happly rsv lr hst ~> hv' THEN forall ge sp rs0 m0 st
    (REF:hsilocal_refines ge sp rs0 m0 hst st)
    (OK:hsok_local ge sp rs0 m0 hst),
    sval_refines ge sp rs0 m0 hv' (rsv lr st).
Proof.
   unfold hsilocal_refines, root_apply, root_happly; destruct rsv; wlp_simplify.
   unfold sok_local in *.
   generalize (H0 ge sp rs0 m0 (list_sval_inj (map (si_sreg st) lr)) (si_smem st)); clear H0.
   destruct (seval_smem ge sp (si_smem st) rs0 m0) as [m|] eqn:X; eauto.
   intuition congruence.
Qed.
Global Opaque root_happly.
Hint Resolve root_happly_correct: wlp.

Local Open Scope lazy_bool_scope.

(* NB: return [false] if the rsv cannot fail *)
Definition may_trap (rsv: root_sval) (lr: list reg): bool :=
  match rsv with 
  | Rop op => is_trapping_op op ||| negb (Nat.eqb (length lr) (args_of_operation op))  (* cf. lemma is_trapping_op_sound *)
  | Rload TRAP _ _  => true
  | _ => false
  end.

Lemma lazy_orb_negb_false (b1 b2:bool):
  (b1 ||| negb b2) = false <-> (b1 = false /\ b2 = true).
Proof.
  unfold negb; explore; simpl; intuition (try congruence).
Qed.

Lemma seval_list_sval_length ge sp rs0 m0 (f: reg -> sval) (l:list reg):
  forall l', seval_list_sval ge sp (list_sval_inj (List.map f l)) rs0 m0 = Some l' ->
  Datatypes.length l = Datatypes.length l'.
Proof.
  induction l.
  - simpl. intros. inv H. reflexivity.
  - simpl. intros. destruct (seval_sval _ _ _ _ _); [|discriminate].
    destruct (seval_list_sval _ _ _ _ _) eqn:SLS; [|discriminate]. inv H. simpl.
    erewrite IHl; eauto.
Qed.

Lemma may_trap_correct (ge: RTL.genv) (sp:val) (rsv: root_sval) (rs0: regset) (m0: mem) (lr: list reg) st:
  may_trap rsv lr = false -> 
  seval_list_sval ge sp (list_sval_inj (List.map (si_sreg st) lr)) rs0 m0 <> None ->
  seval_smem ge sp (si_smem st) rs0 m0 <> None ->
  seval_sval ge sp (rsv lr st) rs0 m0 <> None.
Proof.
  destruct rsv; simpl; try congruence.
  - rewrite lazy_orb_negb_false. intros (TRAP1 & TRAP2) OK1 OK2.
    explore; try congruence.
    eapply is_trapping_op_sound; eauto.
    erewrite <- seval_list_sval_length; eauto.
    apply Nat.eqb_eq in TRAP2.
    assumption.
  - intros X OK1 OK2.
    explore; try congruence.
Qed.

(* TODO gourdinl MOVE EXPANSIONS BELOW ELSEWHERE *)

(* TODO gourdinl IF NEEDED LATER Fixpoint hlist_sval (l: list hsval): ?? list_hsval :=
  match l with
  | nil => hSnil()
  | r::l =>
    DO lhsv <~ hlist_sval l;;
    hScons r lhsv
   end.*)

(*
Definition load_hilo32 (hi lo: int) :=
  DO hnil <~ hSnil();;
  if Int.eq lo Int.zero then
    hSop (OEluiw hi) hnil
  else
    DO hvs <~ hSop (OEluiw hi) hnil;;
    DO hl <~ make_lhsv_single hvs;;
    hSop (Oaddimm lo) hl.

Definition load_hilo64 (hi lo: int64) :=
  DO hnil <~ hSnil();;
  if Int64.eq lo Int64.zero then
    hSop (OEluil hi) hnil
  else
    DO hvs <~ hSop (OEluil hi) hnil;;
    DO hl <~ make_lhsv_single hvs;;
    hSop (Oaddlimm lo) hl.

Definition loadimm32 (n: int) :=
  match make_immed32 n with
  | Imm32_single imm =>
      DO hnil <~ hSnil();;
      hSop (OEaddiwr0 imm) hnil
  | Imm32_pair hi lo => load_hilo32 hi lo
  end.

Definition loadimm64 (n: int64) :=
  DO hnil <~ hSnil();;
  match make_immed64 n with
  | Imm64_single imm =>
      hSop (OEaddilr0 imm) hnil
  | Imm64_pair hi lo => load_hilo64 hi lo
  | Imm64_large imm => hSop (OEloadli imm) hnil
  end.

Definition opimm32 (hv1: hsval) (n: int) (op: operation) (opimm: int -> operation) :=
  match make_immed32 n with
  | Imm32_single imm =>
      DO hl <~ make_lhsv_single hv1;;
      hSop (opimm imm) hl
  | Imm32_pair hi lo =>
      DO hvs <~ load_hilo32 hi lo;;
      DO hl <~ make_lhsv_cmp false hv1 hvs;;
      hSop op hl
  end.

Definition opimm64 (hv1: hsval) (n: int64) (op: operation) (opimm: int64 -> operation) :=
  match make_immed64 n with
  | Imm64_single imm =>
      DO hl <~ make_lhsv_single hv1;;
      hSop (opimm imm) hl
  | Imm64_pair hi lo =>
      DO hvs <~ load_hilo64 hi lo;;
      DO hl <~ make_lhsv_cmp false hv1 hvs;;
      hSop op hl
  | Imm64_large imm =>
      DO hnil <~ hSnil();;
      DO hvs <~ hSop (OEloadli imm) hnil;;
      DO hl <~ make_lhsv_cmp false hv1 hvs;;
      hSop op hl
  end.

Definition xorimm32 (hv1: hsval) (n: int) := opimm32 hv1 n Oxor OExoriw.
Definition sltimm32 (hv1: hsval) (n: int) := opimm32 hv1 n (OEsltw None) OEsltiw.
Definition sltuimm32 (hv1: hsval) (n: int) := opimm32 hv1 n (OEsltuw None) OEsltiuw.
Definition xorimm64 (hv1: hsval) (n: int64) := opimm64 hv1 n Oxorl OExoril.
Definition sltimm64 (hv1: hsval) (n: int64) := opimm64 hv1 n (OEsltl None) OEsltil.
Definition sltuimm64 (hv1: hsval) (n: int64) := opimm64 hv1 n (OEsltul None) OEsltiul.


Definition cond_int32u (cmp: comparison) (lhsv: list_hsval) (optR0: option bool) :=
  match cmp with
  | Ceq => hSop (OEsequw optR0) lhsv
  | Cne => hSop (OEsneuw optR0) lhsv
  | Clt | Cgt => hSop (OEsltuw optR0) lhsv
  | Cle | Cge =>
      DO hvs <~ (hSop (OEsltuw optR0) lhsv);;
      DO hl <~ make_lhsv_single hvs;;
      hSop (OExoriw Int.one) hl
  end.

Definition cond_int64s (cmp: comparison) (lhsv: list_hsval) (optR0: option bool) :=
  match cmp with
  | Ceq => hSop (OEseql optR0) lhsv
  | Cne => hSop (OEsnel optR0) lhsv
  | Clt | Cgt => hSop (OEsltl optR0) lhsv
  | Cle | Cge =>
      DO hvs <~ (hSop (OEsltl optR0) lhsv);;
      DO hl <~ make_lhsv_single hvs;;
      hSop (OExoriw Int.one) hl
  end.

Definition cond_int64u (cmp: comparison) (lhsv: list_hsval) (optR0: option bool) :=
  match cmp with
  | Ceq => hSop (OEsequl optR0) lhsv
  | Cne => hSop (OEsneul optR0) lhsv
  | Clt | Cgt => hSop (OEsltul optR0) lhsv
  | Cle | Cge =>
      DO hvs <~ (hSop (OEsltul optR0) lhsv);;
      DO hl <~ make_lhsv_single hvs;;
      hSop (OExoriw Int.one) hl
  end.

Definition cond_float (cmp: comparison) (lhsv: list_hsval) :=
  match cmp with
  | Ceq | Cne => hSop OEfeqd lhsv
  | Clt | Cgt => hSop OEfltd lhsv
  | Cle | Cge => hSop OEfled lhsv
  end.

Definition cond_single (cmp: comparison) (lhsv: list_hsval) :=
  match cmp with
  | Ceq | Cne => hSop OEfeqs lhsv
  | Clt | Cgt => hSop OEflts lhsv
  | Cle | Cge => hSop OEfles lhsv
  end.

Definition is_normal_cmp cmp :=
  match cmp with | Cne => false | _ => true end.

Definition expanse_cond_fp (cnot: bool) fn_cond cmp (lhsv: list_hsval) :=
  let normal := is_normal_cmp cmp in
  let normal' := if cnot then negb normal else normal in
  DO hvs <~ fn_cond cmp lhsv;;
  DO hl <~ make_lhsv_single hvs;;
  if normal' then RET hvs else hSop (OExoriw Int.one) hl.

Definition expanse_condimm_int32s (cmp: comparison) (hv1: hsval) (n: int) :=
  let is_inv := is_inv_cmp_int cmp in
  if Int.eq n Int.zero then
    let optR0 := make_optR0 true is_inv in
    DO hl <~ make_lhsv_cmp is_inv hv1 hv1;;
    cond_int32s cmp hl optR0
  else
    match cmp with
    | Ceq | Cne =>
        let optR0 := make_optR0 true is_inv in
        DO hvs <~ xorimm32 hv1 n;;
        DO hl <~ make_lhsv_cmp false hvs hvs;;
        cond_int32s cmp hl optR0
    | Clt => sltimm32 hv1 n
    | Cle =>
        if Int.eq n (Int.repr Int.max_signed) then
          loadimm32 Int.one
        else sltimm32 hv1 (Int.add n Int.one)
    | _ =>
        let optR0 := make_optR0 false is_inv in
        DO hvs <~ loadimm32 n;;
        DO hl <~ make_lhsv_cmp is_inv hv1 hvs;;
        cond_int32s cmp hl optR0
    end.

Definition expanse_condimm_int32u (cmp: comparison) (hv1: hsval) (n: int) :=
  let is_inv := is_inv_cmp_int cmp in
  if Int.eq n Int.zero then
    let optR0 := make_optR0 true is_inv in
    DO hl <~ make_lhsv_cmp is_inv hv1 hv1;;
    cond_int32u cmp hl optR0
  else
    match cmp with
    | Clt => sltuimm32 hv1 n
    | _ =>
        let optR0 := make_optR0 false is_inv in
        DO hvs <~ loadimm32 n;;
        DO hl <~ make_lhsv_cmp is_inv hv1 hvs;;
        cond_int32u cmp hl optR0
    end.

Definition expanse_condimm_int64s (cmp: comparison) (hv1: hsval) (n: int64) :=
  let is_inv := is_inv_cmp_int cmp in
  if Int64.eq n Int64.zero then
    let optR0 := make_optR0 true is_inv in
    DO hl <~ make_lhsv_cmp is_inv hv1 hv1;;
    cond_int64s cmp hl optR0
  else
    match cmp with
    | Ceq | Cne =>
        let optR0 := make_optR0 true is_inv in
        DO hvs <~ xorimm64 hv1 n;;
        DO hl <~ make_lhsv_cmp false hvs hvs;;
        cond_int64s cmp hl optR0
    | Clt => sltimm64 hv1 n
    | Cle =>
        if Int64.eq n (Int64.repr Int64.max_signed) then
          loadimm32 Int.one
        else sltimm64 hv1 (Int64.add n Int64.one)
    | _ =>
        let optR0 := make_optR0 false is_inv in
        DO hvs <~ loadimm64 n;;
        DO hl <~ make_lhsv_cmp is_inv hv1 hvs;;
        cond_int64s cmp hl optR0
    end.

Definition expanse_condimm_int64u (cmp: comparison) (hv1: hsval) (n: int64) :=
  let is_inv := is_inv_cmp_int cmp in
  if Int64.eq n Int64.zero then
    let optR0 := make_optR0 true is_inv in
    DO hl <~ make_lhsv_cmp is_inv hv1 hv1;;
    cond_int64u cmp hl optR0
  else
    match cmp with
    | Clt => sltuimm64 hv1 n
    | _ =>
        let optR0 := make_optR0 false is_inv in
        DO hvs <~ loadimm64 n;;
        DO hl <~ make_lhsv_cmp is_inv hv1 hvs;;
        cond_int64u cmp hl optR0
    end.
 *)

(** simplify a symbolic value before assignment to a register *)
Definition simplify (rsv: root_sval) (lr: list reg) (hst: hsistate_local): ?? hsval :=
  match rsv with
  | Rop op =>
     match is_move_operation op lr with
     | Some arg => hsi_sreg_get hst arg (* optimization of Omove *)
     | None =>
       match target_op_simplify op lr hst with
       | Some fhv => fsval_proj fhv
       | None =>
         DO lhsv <~ hlist_args hst lr;;
         hSop op lhsv
       end
     end
  | Rload _ chunk addr => 
       DO lhsv <~ hlist_args hst lr;;
       hSload hst NOTRAP chunk addr lhsv
  end.

(*
Lemma simplify_nothing lr (hst: hsistate_local) op:
  WHEN DO lhsv <~ hlist_args hst lr;; hSop op lhsv ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) lr)) rs0 m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp op args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) lr)) rs0 m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp op args m)).
Proof.
  wlp_simplify.
  generalize (H0 ge sp rs0 m0 (list_sval_inj (map (si_sreg st) lr)) (si_smem st)); clear H0.
  destruct (seval_smem ge sp (si_smem st) rs0 m0) as [m|] eqn:X; eauto.
  intro H0; clear H0; simplify_SOME z; congruence. 
Qed.

Lemma xor_neg_ltle_cmp: forall v1 v2,
  Some (Val.xor (Val.cmp Clt v1 v2) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmp_bool Cle v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  unfold Val.cmp; simpl;
  try rewrite Int.eq_sym;
  try destruct (Int.eq _ _); try destruct (Int.lt _ _) eqn:ELT ; simpl;
  try rewrite Int.xor_one_one; try rewrite Int.xor_zero_one;
  auto.
Qed.

Lemma xor_neg_optb: forall v,
  Some (Val.xor (Val.of_optbool (option_map negb v))
    (Vint Int.one)) = Some (Val.of_optbool v).
Proof.
  intros.
  destruct v; simpl; trivial.
  destruct b; simpl; auto.
Qed.

Lemma xor_ceq_zero: forall v n cmp,
  cmp = Ceq \/ cmp = Cne ->
  Some
    (Val.of_optbool (Val.cmp_bool cmp (Val.xor v (Vint n)) (Vint Int.zero))) =
  Some (Val.of_optbool (Val.cmp_bool cmp v (Vint n))).
Proof.
  intros; destruct v; unfold Val.xor; simpl; auto.
  destruct cmp, H; try discriminate; simpl;
  destruct (Int.eq (Int.xor i n) Int.zero) eqn:EQ;
  rewrite Int.xor_is_zero in EQ; rewrite EQ; trivial.
Qed.

(* TODO gourdinl Lemma xor_neg_ltge_cmp: forall v1 v2,
  Some (Val.xor (Val.cmp Clt v1 v2) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmp_bool Cge v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  unfold Val.cmp; simpl;
  try rewrite Int.eq_sym;
  try destruct (Int.eq _ _); try destruct (Int.lt _ _) eqn:ELT ; simpl;
  try rewrite Int.xor_one_one; try rewrite Int.xor_zero_one;
  auto.
   Qed.*)

(* TODO gourdinl useless? Lemma cmp_neg_ltgt_cmp: forall v1 v2,
  Some (Val.cmp Clt v1 v2) = Some (Val.of_optbool (Val.cmp_bool Cgt v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmp; simpl; auto.
   Qed.*)

Lemma xor_neg_ltle_cmpu: forall mptr v1 v2,
  Some (Val.xor (Val.cmpu (Mem.valid_pointer mptr) Clt v1 v2) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmpu_bool (Mem.valid_pointer mptr) Cle v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  unfold Val.cmpu; simpl;
  try rewrite Int.eq_sym;
  try destruct (Int.eq _ _); try destruct (Int.ltu _ _) eqn:ELT ; simpl;
  try rewrite Int.xor_one_one; try rewrite Int.xor_zero_one;
  auto.
  1,2:
    unfold Val.cmpu, Val.cmpu_bool;
    destruct Archi.ptr64; try destruct (_ && _); try destruct (_ || _);
    try destruct (eq_block _ _); auto.
  unfold Val.cmpu, Val.cmpu_bool; simpl;
  destruct Archi.ptr64; try destruct (_ || _); simpl; auto;
  destruct (eq_block b b0); destruct (eq_block b0 b);
  try congruence;
  try destruct (_ || _); simpl; try destruct (Ptrofs.ltu _ _);
  simpl; auto;
  repeat destruct (_ && _); simpl; auto.
Qed.

(* TODO gourdinl Lemma xor_neg_ltge_cmpu: forall mptr v1 v2,
  Some (Val.xor (Val.cmpu (Mem.valid_pointer mptr) Clt v1 v2) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmpu_bool (Mem.valid_pointer mptr) Cge v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  unfold Val.cmpu; simpl;
  try rewrite Int.eq_sym;
  try destruct (Int.eq _ _); try destruct (Int.ltu _ _) eqn:ELT ; simpl;
  try rewrite Int.xor_one_one; try rewrite Int.xor_zero_one;
  auto.
  1,2:
    unfold Val.cmpu, Val.cmpu_bool;
    destruct Archi.ptr64; try destruct (_ && _); try destruct (_ || _);
    try destruct (eq_block _ _); auto.
  unfold Val.cmpu, Val.cmpu_bool; simpl;
  destruct Archi.ptr64; try destruct (_ || _); simpl; auto;
  destruct (eq_block b b0); destruct (eq_block b0 b);
  try congruence;
  try destruct (_ || _); simpl; try destruct (Ptrofs.ltu _ _);
  simpl; auto;
  repeat destruct (_ && _); simpl; auto.
   Qed.*)

(* TODO gourdinl Lemma cmp_neg_ltgt_cmpu: forall mptr v1 v2,
  Some (Val.cmpu (Mem.valid_pointer mptr) Clt v1 v2) =
  Some (Val.of_optbool (Val.cmpu_bool (Mem.valid_pointer mptr) Cgt v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmpu; simpl; auto.
  destruct (Archi.ptr64);
  destruct (eq_block b b0); destruct (eq_block b0 b);
  try congruence.
  - repeat destruct (_ || _); simpl; auto.
  - repeat destruct (_ && _); simpl; auto.
   Qed.*)

Lemma optbool_mktotal: forall v,
  Some (Val.maketotal (option_map Val.of_bool v)) =
  Some (Val.of_optbool v).
Proof.
  intros. eapply f_equal.
  destruct v; simpl; auto.
Qed.

Lemma cmplu_optbool_mktotal: forall mptr cmp v1 v2,
  Some (Val.maketotal (Val.cmplu (Mem.valid_pointer mptr) cmp v1 v2)) =
  Some (Val.of_optbool (Val.cmplu_bool (Mem.valid_pointer mptr) cmp v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmplu; simpl; auto;
  destruct (Archi.ptr64); simpl;
  try destruct (eq_block _ _); simpl;
  try destruct (_ && _); simpl;
  try destruct (Ptrofs.cmpu _ _);
  try destruct cmp; simpl; auto.
Qed.

Lemma xor_neg_ltle_cmpl: forall v1 v2,
  Some (Val.xor (Val.maketotal (Val.cmpl Clt v1 v2)) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmpl_bool Cle v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  destruct (Int64.lt _ _); auto.
Qed.

Lemma cmp_neg_ltgt_cmpl: forall v1 v2,
  Some (Val.maketotal (Val.cmpl Clt v1 v2)) =
  Some (Val.of_optbool (Val.cmpl_bool Cgt v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  destruct (Int64.lt _ _); auto.
Qed.

Lemma xor_neg_ltge_cmpl: forall v1 v2,
  Some (Val.xor (Val.maketotal (Val.cmpl Clt v1 v2)) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmpl_bool Cge v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  destruct (Int64.lt _ _); auto.
Qed.

Lemma xor_neg_ltle_cmplu: forall mptr v1 v2,
  Some (Val.xor (Val.maketotal (Val.cmplu (Mem.valid_pointer mptr) Clt v1 v2)) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmplu_bool (Mem.valid_pointer mptr) Cle v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  destruct (Int64.ltu _ _); auto.
  1,2: unfold Val.cmplu; simpl; auto;
  destruct (Archi.ptr64); simpl;
  try destruct (eq_block _ _); simpl;
  try destruct (_ && _); simpl;
  try destruct (Ptrofs.cmpu _ _);
  try destruct cmp; simpl; auto.
  unfold Val.cmplu; simpl;
  destruct Archi.ptr64; try destruct (_ || _); simpl; auto;
  destruct (eq_block b b0); destruct (eq_block b0 b);
  try congruence;
  try destruct (_ || _); simpl; try destruct (Ptrofs.ltu _ _);
  simpl; auto;
  repeat destruct (_ && _); simpl; auto.
Qed.

Lemma cmp_neg_ltgt_cmplu: forall mptr v1 v2,
  Some (Val.maketotal (Val.cmplu (Mem.valid_pointer mptr) Clt v1 v2)) =
  Some (Val.of_optbool (Val.cmplu_bool (Mem.valid_pointer mptr) Cgt v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  destruct (Int64.ltu _ _); auto.
  1,2: unfold Val.cmplu; simpl; auto;
  destruct (Archi.ptr64); simpl;
  try destruct (eq_block _ _); simpl;
  try destruct (_ && _); simpl;
  try destruct (Ptrofs.cmpu _ _);
  try destruct cmp; simpl; auto.
  unfold Val.cmplu; simpl;
  destruct Archi.ptr64; try destruct (_ || _); simpl; auto;
  destruct (eq_block b b0); destruct (eq_block b0 b);
  try congruence;
  try destruct (_ || _); simpl; try destruct (Ptrofs.ltu _ _);
  simpl; auto;
  repeat destruct (_ && _); simpl; auto.
Qed.

Lemma xor_neg_ltge_cmplu: forall mptr v1 v2,
  Some (Val.xor (Val.maketotal (Val.cmplu (Mem.valid_pointer mptr) Clt v1 v2)) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmplu_bool (Mem.valid_pointer mptr) Cge v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence.
  destruct (Int64.ltu _ _); auto.
  1,2: unfold Val.cmplu; simpl; auto;
  destruct (Archi.ptr64); simpl;
  try destruct (eq_block _ _); simpl;
  try destruct (_ && _); simpl;
  try destruct (Ptrofs.cmpu _ _);
  try destruct cmp; simpl; auto.
  unfold Val.cmplu; simpl;
  destruct Archi.ptr64; try destruct (_ || _); simpl; auto;
  destruct (eq_block b b0); destruct (eq_block b0 b);
  try congruence;
  try destruct (_ || _); simpl; try destruct (Ptrofs.ltu _ _);
  simpl; auto;
  repeat destruct (_ && _); simpl; auto.
Qed.

Lemma xor_neg_eqne_cmpf: forall v1 v2,
  Some (Val.xor (Val.cmpf Ceq v1 v2) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmpf_bool Cne v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmpf; simpl.
  rewrite Float.cmp_ne_eq.
  destruct (Float.cmp _ _ _); simpl; auto.
Qed.

Lemma xor_neg_eqne_cmpfs: forall v1 v2,
  Some (Val.xor (Val.cmpfs Ceq v1 v2) (Vint Int.one)) =
  Some (Val.of_optbool (Val.cmpfs_bool Cne v1 v2)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmpfs; simpl.
  rewrite Float32.cmp_ne_eq.
  destruct (Float32.cmp _ _ _); simpl; auto.
Qed.

Lemma cmp_neg_ltgt_cmpf: forall v1 v2,
  Some (Val.cmpf Clt v1 v2) = Some (Val.of_optbool (Val.cmpf_bool Cgt v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmpf; simpl; auto.
  replace Cgt with (swap_comparison Clt) by auto.
  rewrite Float.cmp_swap.
  destruct (Float.cmp _ _ _); simpl; auto.
Qed.

Lemma cmp_neg_lege_cmpf: forall v1 v2,
  Some (Val.cmpf Cle v1 v2) = Some (Val.of_optbool (Val.cmpf_bool Cge v2 v1)).
Proof.
  intros. eapply f_equal.
  destruct v1, v2; simpl; try congruence;
  unfold Val.cmpf; simpl; auto.
  replace Cle with (swap_comparison Cge) by auto.
  rewrite Float.cmp_swap.
  destruct (Float.cmp _ _ _); simpl; auto.
Qed.

Lemma cmp_ltle_add_one: forall v n,
  Int.eq n (Int.repr Int.max_signed) = false ->
  Some (Val.of_optbool (Val.cmp_bool Clt v (Vint (Int.add n Int.one)))) =
  Some (Val.of_optbool (Val.cmp_bool Cle v (Vint n))).
Proof.
  intros v n EQMAX. unfold Val.cmp_bool; destruct v; simpl; auto.
  unfold Int.lt. replace (Int.signed (Int.add n Int.one)) with (Int.signed n + 1).
  destruct (zlt (Int.signed n) (Int.signed i)).
  rewrite zlt_false by omega. auto.
  rewrite zlt_true by omega. auto.
  rewrite Int.add_signed. symmetry; apply Int.signed_repr. 
  specialize (Int.eq_spec n (Int.repr Int.max_signed)).
  rewrite EQMAX; simpl; intros.
  assert (Int.signed n <> Int.max_signed).
  { red; intros E. elim H. rewrite <- (Int.repr_signed n). rewrite E. auto. }
  generalize (Int.signed_range n); omega.
Qed.

(* TODO gourdinl Lemma cmp_le_max: forall v*)
  (*(CONTRA: Some*)
       (*(Val.of_optbool (Val.cmp_bool Cle v (Vint (Int.repr Int.max_signed)))) =*)
     (*None -> False),*)
  (*Some (Vint Int.one) =*)
  (*Some (Val.of_optbool (Val.cmp_bool Cle v (Vint (Int.repr Int.max_signed)))).*)
(*Proof.*)
  (*intros; destruct v. simpl in *; try discriminate CONTRA; auto.*)

Lemma simplify_ccomp_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_int c) hv1 hv2;;
       cond_int32s c lhsv None ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccomp c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccomp c)) args m)).
Proof.
  unfold cond_int32s in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmp.
    - intros; apply xor_neg_ltle_cmp.
    - intros; replace (Clt) with (swap_comparison Cgt) by auto;
      rewrite Val.swap_cmp_bool; trivial.
    - intros; replace (Clt) with (negate_comparison Cge) by auto;
      rewrite Val.negate_cmp_bool.
      rewrite xor_neg_optb; trivial.
Qed.

Lemma simplify_ccompu_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_int c) hv1 hv2;;
       cond_int32u c lhsv None ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompu c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompu c)) args m)).
Proof.
  unfold cond_int32u in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpu.
    - intros; apply xor_neg_ltle_cmpu.
    - intros; replace (Clt) with (swap_comparison Cgt) by auto;
      rewrite Val.swap_cmpu_bool; trivial.
    - intros; replace (Clt) with (negate_comparison Cge) by auto;
      rewrite Val.negate_cmpu_bool.
      rewrite xor_neg_optb; trivial.
Qed.

Lemma mkimm_single_equal: forall n imm,
  make_immed32 n = Imm32_single imm ->
  n = imm.
Proof.
  intros. unfold make_immed32 in H.
  destruct (Int.eq _ _); inv H; auto.
Qed.

Lemma mkimm_pair_equal: forall n hi lo,
  make_immed32 n = Imm32_pair hi lo ->
  hi = (Int.shru (Int.sub n (Int.sign_ext 12 n)) (Int.repr 12)) /\
  lo = (Int.sign_ext 12 n).
Proof.
  intros. unfold make_immed32 in H.
  destruct (Int.eq _ _) in H; try congruence.
  inv H. auto.
Qed.

(* TODO gourdinl Lemma mkimm_pair_lo_zero_equal: forall n hi lo,
  make_immed32 n = Imm32_pair hi lo ->
  Int.eq n Int.zero = false ->
  Int.eq lo Int.zero = true ->
  n = Int.shl hi (Int.repr 12).
Proof.
  intros. unfold make_immed32 in H.
  destruct (Int.eq _ _) in H; try discriminate.
  inv H. apply Int.same_if_eq in H1. rewrite H1.
  rewrite Int.sub_zero_l. unfold Int.shru, Int.shl.
 *)

Lemma simplify_ccompimm_correct: forall c n r (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;; expanse_condimm_int32s c hv1 n ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r])) rs0 m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompimm c n)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r])) rs0 m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompimm c n)) args m)).
Proof.
  unfold expanse_condimm_int32s, cond_int32s in *; destruct c;
  intros; destruct (Int.eq n Int.zero) eqn:EQIMM; simpl;
  unfold loadimm32, sltimm32, xorimm32, opimm32, load_hilo32.
  1,3,5,7,9,11: 
    wlp_simplify;
    destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence;
    try (simplify_SOME z; contradiction; fail);
    try erewrite H9; eauto; try erewrite H8; eauto;
    try erewrite H7; eauto; try erewrite H6; eauto; try erewrite H5; eauto;
    try erewrite H4; eauto; try erewrite H3; eauto; try erewrite H2; eauto;
    try erewrite H1; eauto; try erewrite H0; eauto; try erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpu, zero32; intros; try contradiction.
  4: rewrite <- xor_neg_ltle_cmp; unfold Val.cmp.
  5: intros; replace (Clt) with (swap_comparison Cgt) by auto;
     unfold Val.cmp; rewrite Val.swap_cmp_bool; trivial.
  6: intros; replace (Clt) with (negate_comparison Cge) by auto;
     unfold Val.cmp; rewrite Val.negate_cmp_bool; rewrite xor_neg_optb.
  1,2,3,4,5,6: apply Int.same_if_eq in EQIMM; subst; trivial.
  all:
    specialize make_immed32_sound with n;
    destruct (make_immed32 n) eqn:EQMKI;
    try destruct (Int.eq n (Int.repr Int.max_signed)) eqn:EQMAX;
    try destruct (Int.eq lo Int.zero) eqn:EQLO.
  19,21,22:
    specialize make_immed32_sound with (Int.one);
    destruct (make_immed32 Int.one) eqn:EQMKI_A1.
  25,26,27:
    specialize make_immed32_sound with (Int.add n Int.one);
    destruct (make_immed32 (Int.add n Int.one)) eqn:EQMKI_A2.
  all:
    wlp_simplify;
    destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try erewrite H12; eauto; try erewrite H11; eauto;
    try erewrite H10; eauto; try erewrite H9; eauto; try erewrite H8; eauto;
    try erewrite H7; eauto; try erewrite H6; eauto; try erewrite H5; eauto;
    try erewrite H4; eauto; try erewrite H3; eauto; try erewrite H2; eauto;
    try erewrite H1; eauto; try erewrite H0; eauto; try erewrite H; eauto;
    simplify_SOME z; unfold Val.cmp, zero32; intros; try contradiction.
  all: try apply Int.same_if_eq in H1; subst.
  all: try apply Int.same_if_eq in EQLO; subst.
  all: try apply Int.same_if_eq in EQMAX; subst.
  all: try rewrite Int.add_commut, Int.add_zero_l; trivial.
  all: try apply xor_ceq_zero; auto.
  (* Problème d'implémentation lié au addiwr0 ?
     --> On dirait que comme l'instruction n'a pas d'argument une fois expansée,
     un cas spécial se produit si l'argument de départ n'est pas un entier :
     L'instruction addiwr0 est configurée pour toujours renvoyer Int.one,
     mais si le premier argument de la comparaison originelle n'est pas un
     Vint, alors on se retrouve avec :
      Some (Vint Int.one) = Some (Val.of_optbool None)
      <-> Some (Vint Int.zero) = Some (Vundef)
     Il faudrait peut-être modifier la sémantique dans Op pour éliminer ce cas. *)
  admit.
  admit.
  admit.
  admit.
  admit.
  admit.
  admit.
  admit.
  admit.
  { apply cmp_ltle_add_one; auto. }
  { apply Int.same_if_eq in H2; subst.
    rewrite (Int.add_commut (Int.shl hi (Int.repr 12)) Int.zero) in H.
    rewrite Int.add_zero_l in H. rewrite <- H.
    apply cmp_ltle_add_one; auto. }
  { rewrite <- H. apply cmp_ltle_add_one; auto. }
  { rewrite (Int.add_commut (Int.shl hi (Int.repr 12))). rewrite Int.add_zero_l.
    apply cmp_ltle_add_one. rewrite Int.add_commut, Int.add_zero_l in EQMAX.
    auto. }
  { apply Int.same_if_eq in H2; subst.
    rewrite (Int.add_commut (Int.shl hi0 (Int.repr 12)) Int.zero) in H.
    rewrite Int.add_zero_l in H. rewrite <- H.
    rewrite (Int.add_commut (Int.shl hi (Int.repr 12)) Int.zero) in *.
    rewrite Int.add_zero_l in *. apply cmp_ltle_add_one; auto. }
  { rewrite <- H.
    rewrite (Int.add_commut (Int.shl hi (Int.repr 12)) Int.zero) in *.
    rewrite Int.add_zero_l in *. apply cmp_ltle_add_one; auto. }
  { apply cmp_ltle_add_one; auto. }
  { apply Int.same_if_eq in H2; subst.
    rewrite (Int.add_commut (Int.shl hi0 (Int.repr 12)) Int.zero) in H.
    rewrite Int.add_zero_l in H. rewrite <- H.
     apply cmp_ltle_add_one; auto. }
  { rewrite <- H. apply cmp_ltle_add_one; auto. }
  { intros; replace (Clt) with (negate_comparison Cge) by auto;
    rewrite Val.negate_cmp_bool.
    rewrite xor_neg_optb; trivial. }
  { intros; replace (Clt) with (negate_comparison Cge) by auto;
    rewrite Val.negate_cmp_bool.
    rewrite xor_neg_optb; trivial. }
  { intros; replace (Clt) with (negate_comparison Cge) by auto;
    rewrite Val.negate_cmp_bool.
    rewrite xor_neg_optb; trivial. }
  { intros; replace (Clt) with (negate_comparison Cge) by auto;
    rewrite Val.negate_cmp_bool.
    rewrite xor_neg_optb; trivial. }
  { intros; replace (Clt) with (negate_comparison Cge) by auto;
    rewrite Val.negate_cmp_bool.
    rewrite xor_neg_optb; trivial. }
  { intros; replace (Clt) with (negate_comparison Cge) by auto;
    rewrite Val.negate_cmp_bool.
    rewrite xor_neg_optb; trivial. }
Admitted.
(*Qed.*)

Lemma simplify_ccompuimm_correct: forall c n r (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;; expanse_condimm_int32u c hv1 n ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r])) rs0 m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompuimm c n)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r])) rs0 m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompuimm c n)) args m)).
Proof.
  unfold expanse_condimm_int32u, cond_int32u in *; destruct c;
  intros; destruct (Int.eq n Int.zero) eqn:EQIMM; simpl;
  unfold loadimm32, sltuimm32, opimm32, load_hilo32.
  1,3,5,7,9,11: 
    wlp_simplify;
    destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence;
    try (simplify_SOME z; contradiction; fail);
    try erewrite H9; eauto; try erewrite H8; eauto;
    try erewrite H7; eauto; try erewrite H6; eauto; try erewrite H5; eauto;
    try erewrite H4; eauto; try erewrite H3; eauto; try erewrite H2; eauto;
    try erewrite H1; eauto; try erewrite H0; eauto; try erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpu, zero32; intros; try contradiction.
  4: rewrite <- xor_neg_ltle_cmpu; unfold Val.cmpu.
  5: intros; replace (Clt) with (swap_comparison Cgt) by auto;
     rewrite Val.swap_cmpu_bool; trivial.
  6: intros; replace (Clt) with (negate_comparison Cge) by auto;
     rewrite Val.negate_cmpu_bool; rewrite xor_neg_optb.
  1,2,3,4,5,6: apply Int.same_if_eq in EQIMM; subst; trivial.
  all:
    specialize make_immed32_sound with n;
    destruct (make_immed32 n) eqn:EQMKI;
    try destruct (Int.eq lo Int.zero) eqn:EQLO.
  all:
    wlp_simplify;
    destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try erewrite H11; eauto;
    try erewrite H10; eauto; try erewrite H9; eauto; try erewrite H8; eauto;
    try erewrite H7; eauto; try erewrite H6; eauto; try erewrite H5; eauto;
    try erewrite H4; eauto; try erewrite H3; eauto; try erewrite H2; eauto;
    try erewrite H1; eauto; try erewrite H0; eauto; try erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpu, zero32; intros; try contradiction.
  all: try apply Int.same_if_eq in H1; subst.
  all: try apply Int.same_if_eq in EQLO; subst.
  all: try rewrite Int.add_commut, Int.add_zero_l; trivial.
  all: try rewrite <- xor_neg_ltle_cmpu; unfold Val.cmpu; trivial.
  all: intros; replace (Clt) with (negate_comparison Cge) by auto;
     rewrite Val.negate_cmpu_bool; rewrite xor_neg_optb; trivial.
Qed.

Lemma simplify_ccompl_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_int c) hv1 hv2;;
       cond_int64s c lhsv None ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompl c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompl c)) args m)).
Proof.
  unfold cond_int64s in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpl.
    1,2,3: intros; apply optbool_mktotal.
    - intros; apply xor_neg_ltle_cmpl.
    - intros; replace (Clt) with (swap_comparison Cgt) by auto;
      rewrite Val.swap_cmpl_bool; trivial.
      apply optbool_mktotal.
    - intros; apply xor_neg_ltge_cmpl.
Qed.

Lemma simplify_ccomplu_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_int c) hv1 hv2;;
       cond_int64u c lhsv None ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccomplu c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccomplu c)) args m)).
Proof.
  unfold cond_int64u in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmplu.
    1,2,3: intros; apply optbool_mktotal.
    - intros; apply xor_neg_ltle_cmplu.
    - intros; replace (Clt) with (swap_comparison Cgt) by auto;
      rewrite Val.swap_cmplu_bool; trivial.
      apply optbool_mktotal.
    - intros; apply xor_neg_ltge_cmplu.
Qed.

(* TODO gourdinl move to common/Values ? *)
Theorem swap_cmpf_bool:
  forall c x y,
  Val.cmpf_bool (swap_comparison c) x y = Val.cmpf_bool c y x.
Proof.
  destruct x; destruct y; simpl; auto. rewrite Float.cmp_swap. auto.
Qed.

Theorem swap_cmpfs_bool:
  forall c x y,
  Val.cmpfs_bool (swap_comparison c) x y = Val.cmpfs_bool c y x.
Proof.
  destruct x; destruct y; simpl; auto. rewrite Float32.cmp_swap. auto.
Qed.

Lemma simplify_ccompf_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_float c) hv1 hv2;;
       expanse_cond_fp false cond_float c lhsv ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompf c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompf c)) args m)).
Proof.
  unfold expanse_cond_fp in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H9; eauto; erewrite H8; eauto);
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpf.
    - intros; apply xor_neg_eqne_cmpf.
    - intros; replace (Clt) with (swap_comparison Cgt) by auto;
      rewrite swap_cmpf_bool; trivial.
    - intros; replace (Cle) with (swap_comparison Cge) by auto;
      rewrite swap_cmpf_bool; trivial.
Qed.

Lemma simplify_cnotcompf_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_float c) hv1 hv2;;
       expanse_cond_fp true cond_float c lhsv ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Cnotcompf c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Cnotcompf c)) args m)).
Proof.
  unfold expanse_cond_fp in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H9; eauto; erewrite H8; eauto);
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpf.
    all: intros; apply f_equal;
    try destruct z0, z2; try destruct z2, z4;
    try destruct z8, z10;
    simpl; trivial.
    2: rewrite Float.cmp_ne_eq; rewrite negb_involutive; trivial.
    4: replace (Clt) with (swap_comparison Cgt) by auto; rewrite <- Float.cmp_swap; simpl.
    5: replace (Cle) with (swap_comparison Cge) by auto; rewrite <- Float.cmp_swap; simpl.
    all: destruct (Float.cmp _ _ _); trivial.
Qed.

Lemma simplify_ccompfs_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_float c) hv1 hv2;;
       expanse_cond_fp false cond_single c lhsv ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompfs c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Ccompfs c)) args m)).
Proof.
  unfold expanse_cond_fp in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H9; eauto; erewrite H8; eauto);
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpfs.
    - intros; apply xor_neg_eqne_cmpfs.
    - intros; replace (Clt) with (swap_comparison Cgt) by auto;
      rewrite swap_cmpfs_bool; trivial.
    - intros; replace (Cle) with (swap_comparison Cge) by auto;
      rewrite swap_cmpfs_bool; trivial.
Qed.

Lemma simplify_cnotcompfs_correct: forall c r r0 (hst: hsistate_local),
  WHEN DO hv1 <~ hsi_sreg_get hst r;;
       DO hv2 <~ hsi_sreg_get hst r0;;
       DO lhsv <~ make_lhsv_cmp (is_inv_cmp_float c) hv1 hv2;;
       expanse_cond_fp true cond_single c lhsv ~> hv
  THEN (forall (ge : RTL.genv) (sp : val) (rs0 : regset) 
          (m0 : mem) (st : sistate_local),
        hsilocal_refines ge sp rs0 m0 hst st ->
        hsok_local ge sp rs0 m0 hst ->
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Cnotcompfs c)) args m) <> None ->
        seval_sval ge sp (hsval_proj hv) rs0 m0 =
        (SOME args <-
         seval_list_sval ge sp (list_sval_inj (map (si_sreg st) [r; r0])) rs0
           m0
         IN SOME m <- seval_smem ge sp (si_smem st) rs0 m0
            IN eval_operation ge sp (Ocmp (Cnotcompfs c)) args m)).
Proof.
  unfold expanse_cond_fp in *; destruct c;
  wlp_simplify;
  destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
  all: try (simplify_SOME z; contradiction; fail).
  all:
    try (erewrite H9; eauto; erewrite H8; eauto);
    try (erewrite H7; eauto; erewrite H6; eauto; erewrite H5; eauto);
    erewrite H4; eauto; erewrite H3; eauto; erewrite H2; eauto;
    erewrite H1; eauto; erewrite H0; eauto; erewrite H; eauto;
    simplify_SOME z; unfold Val.cmpfs.
    all: intros; apply f_equal;
    try destruct z0, z2; try destruct z2, z4;
    try destruct z8, z10;
    simpl; trivial.
    2: rewrite Float32.cmp_ne_eq; rewrite negb_involutive; trivial.
    4: replace (Clt) with (swap_comparison Cgt) by auto; rewrite <- Float32.cmp_swap; simpl.
    5: replace (Cle) with (swap_comparison Cge) by auto; rewrite <- Float32.cmp_swap; simpl.
    all: destruct (Float32.cmp _ _ _); trivial.
   Qed.*)

Lemma simplify_correct rsv lr hst:
  WHEN simplify rsv lr hst ~> hv THEN forall ge sp rs0 m0 st
    (REF: hsilocal_refines ge sp rs0 m0 hst st)
    (OK0: hsok_local ge sp rs0 m0 hst)
    (OK1: seval_sval ge sp (rsv lr st) rs0 m0 <> None),
    sval_refines ge sp rs0 m0 hv (rsv lr st).
Proof.
  destruct rsv; simpl; auto.
  - (* Rop *)
    destruct (is_move_operation _ _) eqn: Hmove.
    { wlp_simplify; exploit is_move_operation_correct; eauto.
      intros (Hop & Hlsv); subst; simpl in *.
      simplify_SOME z.
      * erewrite H; eauto.
      * try_simplify_someHyps; congruence.
      * congruence. }
    destruct (target_op_simplify _ _ _) eqn: Htarget_op_simp; wlp_simplify.
    { destruct (seval_list_sval _ _ _) eqn: OKlist; try congruence.
      destruct (seval_smem _ _ _ _ _) eqn: OKmem; try congruence.
      rewrite <- H; exploit target_op_simplify_correct; eauto. }
    clear Htarget_op_simp.
    generalize (H0 ge sp rs0 m0 (list_sval_inj (map (si_sreg st) lr)) (si_smem st)); clear H0.
    destruct (seval_smem ge sp (si_smem st) rs0 m0) as [m|] eqn:X; eauto.
    intro H0; clear H0; simplify_SOME z; congruence. (* absurd case *)
  - (* Rload *)
    destruct trap; wlp_simplify.
    erewrite H0; eauto.
    erewrite H; eauto.
    erewrite hsilocal_refines_smem_refines; eauto.
    destruct (seval_list_sval _ _ _ _) as [args|] eqn: Hargs; try congruence.
    destruct (eval_addressing _ _ _ _) as [a|] eqn: Ha; try congruence.
    destruct (seval_smem _ _ _ _) as [m|] eqn: Hm; try congruence.
    destruct (Mem.loadv _ _ _); try congruence.
(*Qed.*)
Admitted.
Global Opaque simplify.
Local Hint Resolve simplify_correct: wlp.

Definition red_PTree_set (r: reg) (hsv: hsval) (hst: PTree.t hsval): PTree.t hsval :=
  match hsv with
  | HSinput r' _ =>
     if Pos.eq_dec r r' 
     then PTree.remove r' hst
     else PTree.set r hsv hst
  | _ => PTree.set r hsv hst
  end.

Lemma red_PTree_set_correct (r r0:reg) hsv hst ge sp rs0 m0:
  hsi_sreg_eval ge sp (red_PTree_set r hsv hst) r0 rs0 m0 = hsi_sreg_eval ge sp (PTree.set r hsv hst) r0 rs0 m0.
Proof.
  destruct hsv; simpl; auto.
  destruct (Pos.eq_dec r r1); auto.
  subst; unfold hsi_sreg_eval, hsi_sreg_proj.
  destruct (Pos.eq_dec r0 r1); auto.
  - subst; rewrite PTree.grs, PTree.gss; simpl; auto.
  - rewrite PTree.gro, PTree.gso; simpl; auto.
Qed.

Lemma red_PTree_set_refines (r r0:reg) hsv hst sv st ge sp rs0 m0:
 hsilocal_refines ge sp rs0 m0 hst st ->
 sval_refines ge sp rs0 m0 hsv sv ->
 hsok_local ge sp rs0 m0 hst ->
 hsi_sreg_eval ge sp (red_PTree_set r hsv hst) r0 rs0 m0 = seval_sval ge sp (if Pos.eq_dec r r0 then sv else si_sreg st r0) rs0 m0.
Proof.
  intros; rewrite red_PTree_set_correct.
  exploit hsilocal_refines_sreg; eauto.
  unfold hsi_sreg_eval, hsi_sreg_proj.
  destruct (Pos.eq_dec r r0); auto.
  - subst. rewrite PTree.gss; simpl; auto.
  - rewrite PTree.gso; simpl; eauto.
Qed.

Lemma sok_local_set_sreg (rsv:root_sval) ge sp rs0 m0 st r lr:
  sok_local ge sp rs0 m0 (slocal_set_sreg st r (rsv lr st))
  <-> (sok_local ge sp rs0 m0 st /\ seval_sval ge sp (rsv lr st) rs0 m0 <> None).
Proof.
  unfold slocal_set_sreg, sok_local; simpl; split.
  + intros ((SVAL0 & PRE) & SMEM & SVAL).
    repeat (split; try tauto).
    - intros r0; generalize (SVAL r0); clear SVAL; destruct (Pos.eq_dec r r0); try congruence.
    - generalize (SVAL r); clear SVAL; destruct (Pos.eq_dec r r); try congruence.
  + intros ((PRE & SMEM & SVAL0) & SVAL).
    repeat (split; try tauto; eauto).
    intros r0;  destruct (Pos.eq_dec r r0); try congruence.
Qed.

Definition hslocal_set_sreg (hst: hsistate_local) (r: reg) (rsv: root_sval) (lr: list reg): ?? hsistate_local :=
  DO ok_lhsv <~
   (if may_trap rsv lr
    then DO hv <~ root_happly rsv lr hst;;
         XDEBUG hv (fun hv => DO hv_name <~ string_of_hashcode (hsval_get_hid hv);; RET ("-- insert undef behavior of hashcode:" +; (CamlStr hv_name))%string);;
         RET (hv::(hsi_ok_lsval hst))
    else RET (hsi_ok_lsval hst));;
  DO simp <~ simplify rsv lr hst;;
  RET {| hsi_smem := hst;
         hsi_ok_lsval := ok_lhsv;
         hsi_sreg := red_PTree_set r simp (hsi_sreg hst) |}.

Lemma hslocal_set_sreg_correct hst r rsv lr:
  WHEN hslocal_set_sreg hst r rsv lr ~> hst' THEN forall ge sp rs0 m0 st
    (REF: hsilocal_refines ge sp rs0 m0 hst st),
    hsilocal_refines ge sp rs0 m0 hst' (slocal_set_sreg st r (rsv lr st)).
Proof.
  wlp_simplify.
  + (* may_trap ~> true *)
    assert (X: sok_local ge sp rs0 m0 (slocal_set_sreg st r (rsv lr st)) <->
               hsok_local ge sp rs0 m0 {| hsi_smem := hst; hsi_ok_lsval := exta :: hsi_ok_lsval hst; hsi_sreg := red_PTree_set r exta0 hst |}).
    { rewrite sok_local_set_sreg; generalize REF.
      intros (OKeq & MEM & REG & MVALID); rewrite OKeq; clear OKeq.
      unfold hsok_local; simpl; intuition (subst; eauto);
      erewrite <- H0 in *; eauto; unfold hsok_local; simpl; intuition eauto.
    }
    unfold hsilocal_refines; simpl; split; auto.
    rewrite <- X, sok_local_set_sreg. intuition eauto.
    - destruct REF; intuition eauto.
    - generalize REF; intros (OKEQ & _). rewrite OKEQ in * |-; erewrite red_PTree_set_refines; eauto.
  + (* may_trap ~> false *)
    assert (X: sok_local ge sp rs0 m0 (slocal_set_sreg st r (rsv lr st)) <->
               hsok_local ge sp rs0 m0 {| hsi_smem := hst; hsi_ok_lsval := hsi_ok_lsval hst; hsi_sreg := red_PTree_set r exta hst |}).
    { 
      rewrite sok_local_set_sreg; generalize REF.
      intros (OKeq & MEM & REG & MVALID); rewrite OKeq.
      unfold hsok_local; simpl; intuition (subst; eauto).
      assert (X0:hsok_local ge sp rs0 m0 hst). { unfold hsok_local; intuition. }
      exploit may_trap_correct; eauto.
      * intro X1; eapply seval_list_sval_inj_not_none; eauto.
        assert (X2: sok_local ge sp rs0 m0 st). { intuition. }
        unfold sok_local in X2; intuition eauto.
      * rewrite <- MEM; eauto.
    }
    unfold hsilocal_refines; simpl; split; auto.
    rewrite <- X, sok_local_set_sreg. intuition eauto.
    - destruct REF; intuition eauto.
    - generalize REF; intros (OKEQ & _). rewrite OKEQ in * |-; erewrite red_PTree_set_refines; eauto.
     Qed.
Global Opaque hslocal_set_sreg.
Local Hint Resolve hslocal_set_sreg_correct: wlp.

(* TODO gourdinl MOVE ELSEWHERE Branch expansion *)

(* TODO gourdinl NOT SURE IF THIS DEF IS NEEDED
 * SHOULD WE TAKE THE PREV STATE INTO ACCOUNT HERE?
Definition make_lr_prev_cmp (is_inv: bool) (a1 a2: reg) (prev: hsistate_local) : ?? list_hsval :=
  if is_inv then
   hlist_args prev*)

(*
Definition transl_cbranch_int32s (cmp: comparison) (optR0: option bool) :=
  match cmp with
  | Ceq => CEbeqw optR0
  | Cne => CEbnew optR0
  | Clt => CEbltw optR0
  | Cle => CEbgew optR0
  | Cgt => CEbltw optR0
  | Cge => CEbgew optR0
  end.

Definition transl_cbranch_int32u (cmp: comparison) (optR0: option bool) :=
  match cmp with
  | Ceq => CEbequw optR0
  | Cne => CEbneuw optR0
  | Clt => CEbltuw optR0
  | Cle => CEbgeuw optR0
  | Cgt => CEbltuw optR0
  | Cge => CEbgeuw optR0
  end.

Definition transl_cbranch_int64s (cmp: comparison) (optR0: option bool) :=
  match cmp with
  | Ceq => CEbeql optR0
  | Cne => CEbnel optR0
  | Clt => CEbltl optR0
  | Cle => CEbgel optR0
  | Cgt => CEbltl optR0
  | Cge => CEbgel optR0
  end.

Definition transl_cbranch_int64u (cmp: comparison) (optR0: option bool) :=
  match cmp with
  | Ceq => CEbequl optR0
  | Cne => CEbneul optR0
  | Clt => CEbltul optR0
  | Cle => CEbgeul optR0
  | Cgt => CEbltul optR0
  | Cge => CEbgeul optR0
  end.

Definition expanse_cbranch_fp (cnot: bool) fn_cond cmp (lhsv: list_hsval) : ?? (condition * list_hsval) :=
  let normal := is_normal_cmp cmp in
  let normal' := if cnot then negb normal else normal in
  DO hvs <~ fn_cond cmp lhsv;;
  DO hl <~ make_lhsv_cmp false hvs hvs;;
  if normal' then RET ((CEbnew (Some false)), hl) else RET ((CEbeqw (Some false)), hl).
  
Definition cbranch_expanse (prev: hsistate_local) (cond: condition) (args: list reg) : ?? (condition * list_hsval) :=
  match cond, args with
  | (Ccomp c), (a1 :: a2 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      let cond := transl_cbranch_int32s c (make_optR0 false is_inv) in
      DO hv1 <~ hsi_sreg_get prev a1;;
      DO hv2 <~ hsi_sreg_get prev a2;;
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      RET (cond, lhsv)
  | (Ccompu c), (a1 :: a2 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      let cond := transl_cbranch_int32u c (make_optR0 false is_inv) in
      DO hv1 <~ hsi_sreg_get prev a1;;
      DO hv2 <~ hsi_sreg_get prev a2;;
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      RET (cond, lhsv)
  | (Ccompimm c n), (a1 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      DO hv1 <~ hsi_sreg_get prev a1;;
      (if Int.eq n Int.zero then
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hv1;;
        let cond := transl_cbranch_int32s c (make_optR0 true is_inv) in
        RET (cond, lhsv)
      else
        DO hvs <~ loadimm32 n;;
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hvs;;
        let cond := transl_cbranch_int32s c (make_optR0 false is_inv) in
        RET (cond, lhsv))
  | (Ccompuimm c n), (a1 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      DO hv1 <~ hsi_sreg_get prev a1;;
      (if Int.eq n Int.zero then
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hv1;;
        let cond := transl_cbranch_int32u c (make_optR0 true is_inv) in
        RET (cond, lhsv)
      else
        DO hvs <~ loadimm32 n;;
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hvs;;
        let cond := transl_cbranch_int32u c (make_optR0 false is_inv) in
        RET (cond, lhsv))
  | (Ccompl c), (a1 :: a2 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      let cond := transl_cbranch_int64s c (make_optR0 false is_inv) in
      DO hv1 <~ hsi_sreg_get prev a1;;
      DO hv2 <~ hsi_sreg_get prev a2;;
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      RET (cond, lhsv)
  | (Ccomplu c), (a1 :: a2 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      let cond := transl_cbranch_int64u c (make_optR0 false is_inv) in
      DO hv1 <~ hsi_sreg_get prev a1;;
      DO hv2 <~ hsi_sreg_get prev a2;;
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      RET (cond, lhsv)
  | (Ccomplimm c n), (a1 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      DO hv1 <~ hsi_sreg_get prev a1;;
      (if Int64.eq n Int64.zero then
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hv1;;
        let cond := transl_cbranch_int64s c (make_optR0 true is_inv) in
        RET (cond, lhsv)
      else
        DO hvs <~ loadimm64 n;;
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hvs;;
        let cond := transl_cbranch_int64s c (make_optR0 false is_inv) in
        RET (cond, lhsv))
  | (Ccompluimm c n), (a1 :: nil) =>
      let is_inv := is_inv_cmp_int c in
      DO hv1 <~ hsi_sreg_get prev a1;;
      (if Int64.eq n Int64.zero then
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hv1;;
        let cond := transl_cbranch_int64u c (make_optR0 true is_inv) in
        RET (cond, lhsv)
      else
        DO hvs <~ loadimm64 n;;
        DO lhsv <~ make_lhsv_cmp is_inv hv1 hvs;;
        let cond := transl_cbranch_int64u c (make_optR0 false is_inv) in
        RET (cond, lhsv))
  | (Ccompf c), (f1 :: f2 :: nil) =>
      DO hv1 <~ hsi_sreg_get prev f1;;
      DO hv2 <~ hsi_sreg_get prev f2;;
      let is_inv := is_inv_cmp_float c in
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      expanse_cbranch_fp false cond_float c lhsv
  | (Cnotcompf c), (f1 :: f2 :: nil) =>
      DO hv1 <~ hsi_sreg_get prev f1;;
      DO hv2 <~ hsi_sreg_get prev f2;;
      let is_inv := is_inv_cmp_float c in
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      expanse_cbranch_fp true cond_float c lhsv
  | (Ccompfs c), (f1 :: f2 :: nil) =>
      DO hv1 <~ hsi_sreg_get prev f1;;
      DO hv2 <~ hsi_sreg_get prev f2;;
      let is_inv := is_inv_cmp_float c in
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      expanse_cbranch_fp false cond_single c lhsv
  | (Cnotcompfs c), (f1 :: f2 :: nil) =>
      DO hv1 <~ hsi_sreg_get prev f1;;
      DO hv2 <~ hsi_sreg_get prev f2;;
      let is_inv := is_inv_cmp_float c in
      DO lhsv <~ make_lhsv_cmp is_inv hv1 hv2;;
      expanse_cbranch_fp true cond_single c lhsv
  | _, _ =>
      DO vargs <~ hlist_args prev args;;
         RET (cond, vargs)
   end.*)

(** ** Execution of one instruction *)


(* TODO: This function could be defined in a specific file for each target *)
Definition target_cbranch_expanse (prev: hsistate_local) (cond: condition) (args: list reg) : option (condition * list_hsval) :=
  None.

Lemma target_cbranch_expanse_correct hst c l ge sp rs0 m0 st c' l': forall
  (TARGET: target_cbranch_expanse hst c l = Some (c', l'))
  (LREF : hsilocal_refines ge sp rs0 m0 hst st)
  (OK: hsok_local ge sp rs0 m0 hst),
  seval_condition ge sp c' (hsval_list_proj l') (si_smem st) rs0 m0 =
  seval_condition ge sp c (list_sval_inj (map (si_sreg st) l)) (si_smem st) rs0 m0.
Proof.
  unfold target_cbranch_expanse; simpl; intros; try congruence.
Qed.
Global Opaque target_cbranch_expanse.

Definition cbranch_expanse (prev: hsistate_local) (cond: condition) (args: list reg): ?? (condition * list_hsval) :=
    match  target_cbranch_expanse prev cond args with
    | Some (cond', vargs) => 
      DO vargs' <~ fsval_list_proj vargs;;
      RET (cond', vargs)
    | None =>
      DO vargs <~ hlist_args prev args ;;
      RET (cond, vargs)
    end.

Lemma cbranch_expanse_correct hst c l:
 WHEN cbranch_expanse hst c l ~> r THEN forall ge sp rs0 m0 st
  (LREF : hsilocal_refines ge sp rs0 m0 hst st)
  (OK: hsok_local ge sp rs0 m0 hst),
  seval_condition ge sp (fst r) (hsval_list_proj (snd r)) (si_smem st) rs0 m0 =
  seval_condition ge sp c (list_sval_inj (map (si_sreg st) l)) (si_smem st) rs0 m0.
Proof.
  unfold cbranch_expanse.
  destruct (target_cbranch_expanse _ _ _) eqn: TARGET; wlp_simplify.
  + destruct p as [c' l']; simpl.
    exploit target_cbranch_expanse_correct; eauto.
  + unfold seval_condition; erewrite H; eauto.
Qed.
Local Hint Resolve cbranch_expanse_correct: wlp.
Global Opaque cbranch_expanse.

Definition hsiexec_inst (i: instruction) (hst: hsistate): ?? (option hsistate) := 
  match i with
  | Inop pc' => 
      RET (Some (hsist_set_local hst pc' hst.(hsi_local)))
  | Iop op args dst pc' =>
      DO next <~ hslocal_set_sreg hst.(hsi_local) dst (Rop op) args;;
      RET (Some (hsist_set_local hst pc' next))
  | Iload trap chunk addr args dst pc' =>
      DO next <~ hslocal_set_sreg hst.(hsi_local) dst (Rload trap chunk addr) args;;
      RET (Some (hsist_set_local hst pc' next))
  | Istore chunk addr args src pc' =>
      DO next <~ hslocal_store hst.(hsi_local) chunk addr args src;;
      RET (Some (hsist_set_local hst pc' next))
  | Icond cond args ifso ifnot _ =>
      let prev := hst.(hsi_local) in
      DO res <~ cbranch_expanse prev cond args;;
      let (cond, vargs) := res in
      let ex := {| hsi_cond:=cond; hsi_scondargs:=vargs; hsi_elocal := prev; hsi_ifso := ifso |} in
      RET (Some {| hsi_pc := ifnot; hsi_exits := ex::hst.(hsi_exits); hsi_local := prev |})
  | _ => RET None
  end.

Remark hsiexec_inst_None_correct i hst:
  WHEN hsiexec_inst i hst ~> o THEN forall st, o = None -> siexec_inst i st = None.
Proof.
  destruct i; wlp_simplify; congruence.
Qed.

Lemma seval_condition_refines hst st ge sp cond hargs args rs m:
  hsok_local ge sp rs m hst -> 
  hsilocal_refines ge sp rs m hst st ->
  list_sval_refines ge sp rs m hargs args ->
  hseval_condition ge sp cond hargs (hsi_smem hst) rs m
  = seval_condition ge sp cond args (si_smem st) rs m.
 Proof.
  intros HOK (_ & MEMEQ & _) LR. unfold hseval_condition, seval_condition.
  rewrite LR, <- MEMEQ; auto.
Qed.

Lemma sok_local_set_sreg_simp (rsv:root_sval) ge sp rs0 m0 st r lr:
  sok_local ge sp rs0 m0 (slocal_set_sreg st r (rsv lr st))
  -> sok_local ge sp rs0 m0 st.
Proof.
  rewrite sok_local_set_sreg; intuition.
Qed.

Local Hint Resolve hsist_set_local_correct_stat: core.

Lemma hsiexec_cond_noexp (hst: hsistate): forall l c0 n n0,
  WHEN DO res <~
       (DO vargs <~ hlist_args (hsi_local hst) l;; RET ((c0, vargs)));;
       (let (cond, vargs) := res in
        RET (Some
               {|
               hsi_pc := n0;
               hsi_exits := {|
                            hsi_cond := cond;
                            hsi_scondargs := vargs;
                            hsi_elocal := hsi_local hst;
                            hsi_ifso := n |} :: hsi_exits hst;
               hsi_local := hsi_local hst |})) ~> o0
  THEN (forall (hst' : hsistate) (st : sistate),
        o0 = Some hst' ->
        exists st' : sistate,
          Some
            {|
            si_pc := n0;
            si_exits := {|
                        si_cond := c0;
                        si_scondargs := list_sval_inj
                                          (map (si_sreg (si_local st)) l);
                        si_elocal := si_local st;
                        si_ifso := n |} :: si_exits st;
            si_local := si_local st |} = Some st' /\
          (hsistate_refines_stat hst st -> hsistate_refines_stat hst' st') /\
          (forall (ge : RTL.genv) (sp : val) (rs0 : regset) (m0 : mem),
           hsistate_refines_dyn ge sp rs0 m0 hst st ->
           hsistate_refines_dyn ge sp rs0 m0 hst' st')).
Proof.
  intros.
  wlp_simplify; try_simplify_someHyps; eexists; intuition eauto.
  - unfold hsistate_refines_stat, hsiexits_refines_stat in *; simpl; intuition.
    constructor; simpl; eauto.
    constructor.
  - destruct H0 as (EXREF & LREF & NEST).
    split.
    + constructor; simpl; auto.
      constructor; simpl; auto.
      intros; erewrite seval_condition_refines; eauto.
    + split; simpl; auto.
      destruct NEST as [|st0 se lse TOP NEST];
      econstructor; simpl; auto; constructor; auto.
Qed.

Lemma hsiexec_inst_correct i hst:
  WHEN hsiexec_inst i hst ~> o THEN forall hst' st,
   o = Some hst' ->
   exists st', siexec_inst i st = Some st'
    /\ (forall (REF:hsistate_refines_stat hst st), hsistate_refines_stat hst' st')
    /\ (forall ge sp rs0 m0 (REF:hsistate_refines_dyn ge sp rs0 m0 hst st), hsistate_refines_dyn ge sp rs0 m0 hst' st').
Proof. Admitted. (*
  destruct i; simpl;
  try (wlp_simplify; try_simplify_someHyps; eexists; intuition eauto; fail).
  - (* refines_dyn Iop *)
    wlp_simplify; try_simplify_someHyps; eexists; intuition eauto.
    eapply hsist_set_local_correct_dyn; eauto.
    generalize (sok_local_set_sreg_simp (Rop o)); simpl; eauto.
  - (* refines_dyn Iload *)
    wlp_simplify; try_simplify_someHyps; eexists; intuition eauto.
    eapply hsist_set_local_correct_dyn; eauto.
    generalize (sok_local_set_sreg_simp (Rload t0 m a)); simpl; eauto.
  - (* refines_dyn Istore *)
    wlp_simplify; try_simplify_someHyps; eexists; intuition eauto.
    eapply hsist_set_local_correct_dyn; eauto.
    unfold sok_local; simpl; intuition.
  - (* refines_stat Icond *)
    unfold cbranch_expanse; destruct c eqn:EQC;
    try apply hsiexec_cond_noexp.
    + repeat (destruct l; try apply hsiexec_cond_noexp).
      wlp_simplify; try_simplify_someHyps; eexists; intuition eauto.
      * unfold hsistate_refines_stat, hsiexits_refines_stat in *; simpl; intuition.
        constructor; simpl; eauto.
        constructor.
      * destruct REF as (EXREF & LREF & NEST).
        split.
        -- do 2 (constructor; simpl; auto).
           intros; erewrite seval_condition_refines; eauto.
           destruct c0; simpl; unfold seval_condition;
           erewrite H3; eauto; erewrite H2; eauto;
           erewrite H1; eauto; erewrite H0; eauto;
           erewrite H; eauto; simplify_SOME z.
           all: intros; destruct z0, z2; auto.
        -- split; simpl; auto.
           destruct NEST as [|st0 se lse TOP NEST];
           econstructor; simpl; auto; constructor; auto.
    + admit.
    + repeat (destruct l; try apply hsiexec_cond_noexp).
      destruct (Int.eq _ _) eqn:EQIMM; simpl.
      1: admit.
      
      unfold loadimm32; destruct make_immed32 eqn:EQMKI.
      {
      wlp_simplify; try_simplify_someHyps; eexists; intuition eauto.
      * unfold hsistate_refines_stat, hsiexits_refines_stat in *; simpl; intuition.
        constructor; simpl; eauto.
        constructor.
      * destruct REF as (EXREF & LREF & NEST).
        split.
        -- do 2 (constructor; simpl; auto).
           intros; erewrite seval_condition_refines; eauto.
           destruct c0; simpl; unfold seval_condition.

           { simpl in *. apply mkimm_single_equal in EQMKI; subst.
             destruct (seval_smem _ _ _ _ _) eqn:EQSM; try congruence.
             - erewrite H4; eauto; erewrite H3; eauto;
               erewrite H2; eauto; erewrite H1; eauto;
               try erewrite H0; eauto; try erewrite H; eauto;
               simplify_SOME z. rewrite Int.add_zero. trivial.
             - simplify_SOME x.
           }
           2: {
    generalize (sok_local_set_sreg_simp (Rop (OEaddiwr0 imm))); simpl; eauto.
    intros.j
           apply hsilocal_refines_smem_refines in LREF; auto.

           rewrite <- LREF. auto.
           2: { eauto.
           all: intros; destruct z0, z2; auto.
        -- split; simpl; auto.
           destruct NEST as [|st0 se lse TOP NEST];
           econstructor; simpl; auto; constructor; auto.

    + admit.
    + admit.
                  *)
(*Qed.*)
Global Opaque hsiexec_inst.
Local Hint Resolve hsiexec_inst_correct: wlp.


Definition some_or_fail {A} (o: option A) (msg: pstring): ?? A :=
  match o with
  | Some x => RET x
  | None => FAILWITH msg
  end.

Fixpoint hsiexec_path (path:nat) (f: function) (hst: hsistate): ?? hsistate :=
  match path with
  | O => RET hst
  | S p =>
    let pc := hst.(hsi_pc) in
    XDEBUG pc (fun pc => DO name_pc <~ string_of_Z (Zpos pc);; RET ("- sym exec node: " +; name_pc)%string);;
    DO i <~ some_or_fail ((fn_code f)!pc) "hsiexec_path.internal_error.1";;
    DO ohst1 <~ hsiexec_inst i hst;;
    DO hst1 <~ some_or_fail ohst1 "hsiexec_path.internal_error.2";;
    hsiexec_path p f hst1
  end.

Lemma hsiexec_path_correct path f: forall hst,
  WHEN hsiexec_path path f hst ~> hst' THEN forall st
  (RSTAT:hsistate_refines_stat hst st),
  exists st', siexec_path path f st = Some st'
    /\ hsistate_refines_stat hst' st'
    /\ (forall ge sp rs0 m0 (REF:hsistate_refines_dyn ge sp rs0 m0 hst st), hsistate_refines_dyn ge sp rs0 m0 hst' st').
Proof.
  induction path; wlp_simplify; try_simplify_someHyps. clear IHpath.
  generalize RSTAT; intros (PCEQ & _) INSTEQ.
  rewrite <- PCEQ, INSTEQ; simpl.
  exploit H0; eauto. clear H0.
  intros (st0 & SINST & ISTAT & IDYN); erewrite SINST.
  exploit H1; eauto. clear H1.
  intros (st' & SPATH & PSTAT & PDYN).
  eexists; intuition eauto.
Qed.
Global Opaque hsiexec_path.
Local Hint Resolve hsiexec_path_correct: wlp.

Fixpoint hbuiltin_arg (hst: PTree.t hsval) (arg : builtin_arg reg): ?? builtin_arg hsval := 
  match arg with
  | BA r => 
         DO v <~ hsi_sreg_get hst r;;
         RET (BA v)
  | BA_int n => RET (BA_int n)
  | BA_long n => RET (BA_long n)
  | BA_float f0 => RET (BA_float f0)
  | BA_single s => RET (BA_single s)
  | BA_loadstack chunk ptr => RET (BA_loadstack chunk ptr)
  | BA_addrstack ptr => RET (BA_addrstack ptr)
  | BA_loadglobal chunk id ptr => RET (BA_loadglobal chunk id ptr)
  | BA_addrglobal id ptr => RET (BA_addrglobal id ptr)
  | BA_splitlong ba1 ba2 => 
    DO v1 <~ hbuiltin_arg hst ba1;;
    DO v2 <~ hbuiltin_arg hst ba2;;
    RET (BA_splitlong v1 v2)
  | BA_addptr ba1 ba2 => 
    DO v1 <~ hbuiltin_arg hst ba1;;
    DO v2 <~ hbuiltin_arg hst ba2;;
    RET (BA_addptr v1 v2)
  end.

Lemma hbuiltin_arg_correct hst arg:
  WHEN hbuiltin_arg hst arg ~> hargs THEN forall ge sp rs0 m0 (f: reg -> sval)
    (RR: forall r, hsi_sreg_eval ge sp hst r rs0 m0 = seval_sval ge sp (f r) rs0 m0),
    seval_builtin_sval ge sp (builtin_arg_map hsval_proj hargs) rs0 m0 = seval_builtin_sval ge sp (builtin_arg_map f arg) rs0 m0.
Proof.
  induction arg; wlp_simplify.
  + erewrite H; eauto.
  + erewrite H; eauto.
    erewrite H0; eauto.
  + erewrite H; eauto.
    erewrite H0; eauto.
Qed.
Global Opaque hbuiltin_arg.
Local Hint Resolve hbuiltin_arg_correct: wlp.

Fixpoint hbuiltin_args (hst: PTree.t hsval) (args: list (builtin_arg reg)): ?? list (builtin_arg hsval) :=
  match args with
  | nil => RET nil
  | a::l =>
    DO ha <~ hbuiltin_arg hst a;;
    DO hl <~ hbuiltin_args hst l;;
    RET (ha::hl)
    end.

Lemma hbuiltin_args_correct hst args:
  WHEN hbuiltin_args hst args ~> hargs THEN forall ge sp rs0 m0 (f: reg -> sval)
    (RR: forall r, hsi_sreg_eval ge sp hst r rs0 m0 = seval_sval ge sp (f r) rs0 m0),
    bargs_refines ge sp rs0 m0 hargs (List.map (builtin_arg_map f) args).
Proof.
  unfold bargs_refines, seval_builtin_args; induction args; wlp_simplify.
  erewrite H; eauto.
  erewrite H0; eauto.
Qed.
Global Opaque hbuiltin_args.
Local Hint Resolve hbuiltin_args_correct: wlp.

Definition hsum_left (hst: PTree.t hsval) (ros: reg + ident): ?? (hsval + ident) :=
  match ros with
  | inl r => DO hr <~ hsi_sreg_get hst r;; RET (inl hr) 
  | inr s => RET (inr s)
  end.

Lemma hsum_left_correct hst ros:
  WHEN hsum_left hst ros ~> hsi THEN forall ge sp rs0 m0 (f: reg -> sval)
    (RR: forall r, hsi_sreg_eval ge sp hst r rs0 m0 = seval_sval ge sp (f r) rs0 m0),
    sum_refines ge sp rs0 m0 hsi (sum_left_map f ros).
Proof.
  unfold sum_refines; destruct ros; wlp_simplify.
Qed.
Global Opaque hsum_left.
Local Hint Resolve hsum_left_correct: wlp.

Definition hsexec_final (i: instruction) (hst: PTree.t hsval): ?? hsfval :=
  match i with
  | Icall sig ros args res pc =>
    DO svos <~ hsum_left hst ros;;
    DO sargs <~ hlist_args hst args;;
    RET (HScall sig svos sargs res pc)
  | Itailcall sig ros args =>
    DO svos <~ hsum_left hst ros;;
    DO sargs <~ hlist_args hst args;;
    RET (HStailcall sig svos sargs)
  | Ibuiltin ef args res pc =>
    DO sargs <~ hbuiltin_args hst args;;
    RET (HSbuiltin ef sargs res pc)
  | Ijumptable reg tbl =>
    DO sv <~ hsi_sreg_get hst reg;;
    RET (HSjumptable sv tbl)
  | Ireturn or =>
    match or with
    | Some r => DO hr <~ hsi_sreg_get hst r;; RET (HSreturn (Some hr))
    | None => RET (HSreturn None)
    end
  | _ => RET (HSnone)
  end.

Lemma hsexec_final_correct (hsl: hsistate_local) i:
  WHEN hsexec_final i hsl ~> hsf THEN forall ge sp rs0 m0 sl
   (OK:  hsok_local ge sp rs0 m0 hsl)
   (REF: hsilocal_refines ge sp rs0 m0 hsl sl),
   hfinal_refines ge sp rs0 m0 hsf (sexec_final i sl).
Proof.
  destruct i; wlp_simplify; try econstructor; simpl; eauto.
Qed.
Global Opaque hsexec_final.
Local Hint Resolve hsexec_final_correct: wlp.

Definition init_hsistate_local (_:unit): ?? hsistate_local
  := DO hm <~ hSinit ();;
     RET {| hsi_smem := hm; hsi_ok_lsval := nil; hsi_sreg := PTree.empty hsval |}.

Lemma init_hsistate_local_correct:
  WHEN init_hsistate_local () ~> hsl THEN forall ge sp rs0 m0,
  hsilocal_refines ge sp rs0 m0 hsl init_sistate_local.
Proof.
  unfold hsilocal_refines; wlp_simplify.
  - unfold hsok_local; simpl; intuition. erewrite H in *; congruence.
  - unfold hsok_local, sok_local; simpl in *; intuition; try congruence.
  - unfold hsi_sreg_eval, hsi_sreg_proj. rewrite PTree.gempty. reflexivity.
  - try_simplify_someHyps.
Qed.
Global Opaque init_hsistate_local.
Local Hint Resolve init_hsistate_local_correct: wlp.

Definition init_hsistate pc: ?? hsistate
  := DO hst <~ init_hsistate_local ();;
     RET {| hsi_pc := pc; hsi_exits := nil; hsi_local := hst |}.

Lemma init_hsistate_correct pc:
  WHEN init_hsistate pc ~> hst THEN
      hsistate_refines_stat hst (init_sistate pc)
   /\ forall ge sp rs0 m0, hsistate_refines_dyn ge sp rs0 m0 hst (init_sistate pc).
Proof.
  unfold hsistate_refines_stat, hsistate_refines_dyn, hsiexits_refines_dyn; wlp_simplify; constructor.
Qed.
Global Opaque init_hsistate.
Local Hint Resolve init_hsistate_correct: wlp.

Definition hsexec (f: function) (pc:node): ?? hsstate :=
  DO path <~ some_or_fail ((fn_path f)!pc) "hsexec.internal_error.1";;
  DO hinit <~ init_hsistate pc;;
  DO hst <~ hsiexec_path path.(psize) f hinit;;
  DO i <~ some_or_fail ((fn_code f)!(hst.(hsi_pc))) "hsexec.internal_error.2";;
  DO ohst <~ hsiexec_inst i hst;;
  match ohst with
  | Some hst' => RET {| hinternal := hst'; hfinal := HSnone |}
  | None => DO hsvf <~ hsexec_final i hst.(hsi_local);;
            RET {| hinternal := hst; hfinal := hsvf |}
  end.

Lemma hsexec_correct_aux f pc:
  WHEN hsexec f pc ~> hst THEN
  exists st, sexec f pc = Some st /\ hsstate_refines hst st.
Proof.
  unfold hsstate_refines, sexec; wlp_simplify.
  - (* Some *)
   rewrite H; clear H.
   exploit H0; clear H0; eauto.
   intros (st0 & EXECPATH & SREF & DREF).
   rewrite EXECPATH; clear EXECPATH.
   generalize SREF. intros (EQPC & _).
   rewrite <- EQPC, H3; clear H3.
   exploit H4; clear H4; eauto.
   intros (st' & EXECL & SREF' & DREF').
   try_simplify_someHyps.
   eexists; intuition (simpl; eauto).
   constructor.
  - (* None *)
   rewrite H; clear H H4.
   exploit H0; clear H0; eauto.
   intros (st0 & EXECPATH & SREF & DREF).
   rewrite EXECPATH; clear EXECPATH.
   generalize SREF. intros (EQPC & _).
   rewrite <- EQPC, H3; clear H3.
   erewrite hsiexec_inst_None_correct; eauto.
   eexists; intuition (simpl; eauto).
Qed.

Global Opaque hsexec.

End CanonBuilding.

(** Correction of concrete symbolic execution wrt abstract symbolic execution *)
Theorem hsexec_correct
  (hC_hsval : hashinfo hsval -> ?? hsval)
  (hC_list_hsval : hashinfo list_hsval -> ?? list_hsval)
  (hC_hsmem : hashinfo hsmem -> ?? hsmem)
  (f : function) 
  (pc : node):
       WHEN hsexec hC_hsval hC_list_hsval hC_hsmem f pc ~> hst THEN forall
        (hC_hsval_correct: forall hs,
            WHEN hC_hsval hs ~> hs' THEN forall ge sp rs0 m0,
                seval_sval ge sp (hsval_proj (hdata hs)) rs0 m0 =
                seval_sval ge sp (hsval_proj hs') rs0 m0)
        (hC_list_hsval_correct: forall lh,
            WHEN hC_list_hsval lh ~> lh' THEN forall ge sp rs0 m0,
              seval_list_sval ge sp (hsval_list_proj (hdata lh)) rs0 m0 =
              seval_list_sval ge sp (hsval_list_proj lh') rs0 m0)
         (hC_hsmem_correct: forall hm,
            WHEN hC_hsmem hm ~> hm' THEN forall ge sp rs0 m0,
              seval_smem ge sp (hsmem_proj (hdata hm)) rs0 m0 =
              seval_smem ge sp (hsmem_proj hm') rs0 m0),
         exists st : sstate, sexec f pc = Some st /\ hsstate_refines hst st.
Proof.
  wlp_simplify.
  eapply hsexec_correct_aux; eauto.
Qed.
Local Hint Resolve hsexec_correct: wlp.

(** * Implementing the simulation test with concrete hash-consed symbolic execution *)

Definition phys_check {A} (x y:A) (msg: pstring): ?? unit :=
  DO b <~ phys_eq x y;;
  assert_b b msg;;
  RET tt.

Definition struct_check {A} (x y: A) (msg: pstring): ?? unit :=
  DO b <~ struct_eq x y;;
  assert_b b msg;;
  RET tt.

Lemma struct_check_correct {A} (a b: A) msg:
  WHEN struct_check a b msg ~> _ THEN
  a = b.
Proof. wlp_simplify. Qed.
Global Opaque struct_check.
Hint Resolve struct_check_correct: wlp.

Definition option_eq_check {A} (o1 o2: option A): ?? unit :=
  match o1, o2 with
  | Some x1, Some x2 => phys_check x1 x2 "option_eq_check: data physically differ"
  | None, None => RET tt
  | _, _ => FAILWITH "option_eq_check: structure differs"
  end.

Lemma option_eq_check_correct A (o1 o2: option A): WHEN option_eq_check o1 o2 ~> _ THEN o1=o2.
Proof.
  wlp_simplify.
Qed.
Global Opaque option_eq_check.
Hint Resolve option_eq_check_correct:wlp.

Import PTree.

Fixpoint PTree_eq_check {A} (d1 d2: PTree.t A): ?? unit :=
  match d1, d2 with
  | Leaf, Leaf => RET tt
  | Node l1 o1 r1, Node l2 o2 r2 =>
      option_eq_check o1 o2;;
      PTree_eq_check l1 l2;;
      PTree_eq_check r1 r2
  | _, _ => FAILWITH "PTree_eq_check: some key is absent"
  end.

Lemma PTree_eq_check_correct A d1: forall (d2: t A),
 WHEN PTree_eq_check d1 d2 ~> _ THEN forall x, PTree.get x d1 = PTree.get x d2.
Proof.
  induction d1 as [|l1 Hl1 o1 r1 Hr1]; destruct d2 as [|l2 o2 r2]; simpl; 
  wlp_simplify. destruct x; simpl; auto.
Qed.
Global Opaque PTree_eq_check.
Local Hint Resolve PTree_eq_check_correct: wlp.

Fixpoint PTree_frame_eq_check {A} (frame: list positive) (d1 d2: PTree.t A): ?? unit :=
  match frame with
  | nil => RET tt
  | k::l => 
    option_eq_check (PTree.get k d1) (PTree.get k d2);;
    PTree_frame_eq_check l d1 d2
  end.

Lemma PTree_frame_eq_check_correct A l (d1 d2: t A):
 WHEN PTree_frame_eq_check l d1 d2 ~> _ THEN forall x, List.In x l -> PTree.get x d1 = PTree.get x d2.
Proof.
  induction l as [|k l]; simpl; wlp_simplify.
  subst; auto.
Qed.
Global Opaque PTree_frame_eq_check.
Local Hint Resolve PTree_frame_eq_check_correct: wlp.

Definition hsilocal_frame_simu_check frame hst1 hst2 : ?? unit :=
  DEBUG("? frame check");;
  phys_check (hsi_smem hst2) (hsi_smem hst1) "hsilocal_frame_simu_check: hsi_smem sets aren't equiv";;
  PTree_frame_eq_check frame (hsi_sreg hst1) (hsi_sreg hst2);;
  Sets.assert_list_incl mk_hash_params (hsi_ok_lsval hst2) (hsi_ok_lsval hst1);;
  DEBUG("=> frame check: OK").

Lemma setoid_in {A: Type} (a: A): forall l,
  SetoidList.InA (fun x y => x = y) a l ->
  In a l.
Proof.
  induction l; intros; inv H.
  - constructor. reflexivity.
  - right. auto.
Qed.

Lemma regset_elements_in r rs:
  Regset.In r rs ->
  In r (Regset.elements rs).
Proof.
  intros. exploit Regset.elements_1; eauto. intro SIN.
  apply setoid_in. assumption.
Qed.
Local Hint Resolve regset_elements_in: core.

Lemma hsilocal_frame_simu_check_correct hst1 hst2 alive:
  WHEN hsilocal_frame_simu_check (Regset.elements alive) hst1 hst2 ~> _ THEN
  hsilocal_simu_spec alive hst1 hst2.
Proof.
  unfold hsilocal_simu_spec; wlp_simplify. symmetry; eauto.
Qed.
Hint Resolve hsilocal_frame_simu_check_correct: wlp.
Global Opaque hsilocal_frame_simu_check.

Definition revmap_check_single (dm: PTree.t node) (n tn: node) : ?? unit :=
  DO res <~ some_or_fail (dm ! tn) "revmap_check_single: no mapping for tn";;
  struct_check n res "revmap_check_single: n and res are physically different".

Lemma revmap_check_single_correct dm pc1 pc2:
  WHEN revmap_check_single dm pc1 pc2 ~> _ THEN
  dm ! pc2 = Some pc1.
Proof.
  wlp_simplify. congruence.
Qed.
Hint Resolve revmap_check_single_correct: wlp.
Global Opaque revmap_check_single.

Definition hsiexit_simu_check (dm: PTree.t node) (f: RTLpath.function) (hse1 hse2: hsistate_exit): ?? unit :=
  struct_check (hsi_cond hse1) (hsi_cond hse2) "hsiexit_simu_check: conditions do not match";;
  phys_check (hsi_scondargs hse1) (hsi_scondargs hse2) "hsiexit_simu_check: args do not match";;
  revmap_check_single dm (hsi_ifso hse1) (hsi_ifso hse2);;
  DO path <~ some_or_fail ((fn_path f) ! (hsi_ifso hse1)) "hsiexit_simu_check: internal error";;
  hsilocal_frame_simu_check (Regset.elements path.(input_regs)) (hsi_elocal hse1) (hsi_elocal hse2).

Lemma hsiexit_simu_check_correct dm f hse1 hse2:
  WHEN hsiexit_simu_check dm f hse1 hse2 ~> _ THEN
  hsiexit_simu_spec dm f hse1 hse2.
Proof.
  unfold hsiexit_simu_spec; wlp_simplify.
Qed.
Hint Resolve hsiexit_simu_check_correct: wlp.
Global Opaque hsiexit_simu_check.

Fixpoint hsiexits_simu_check (dm: PTree.t node) (f: RTLpath.function) (lhse1 lhse2: list hsistate_exit) :=
  match lhse1,lhse2 with
  | nil, nil => RET tt
  | hse1 :: lhse1, hse2 :: lhse2 =>
    hsiexit_simu_check dm f hse1 hse2;;
    hsiexits_simu_check dm f lhse1 lhse2
  | _, _ => FAILWITH "siexists_simu_check:  lengths do not match"
  end.

Lemma hsiexits_simu_check_correct dm f: forall le1 le2,
  WHEN hsiexits_simu_check dm f le1 le2 ~> _ THEN
  hsiexits_simu_spec dm f le1 le2.
Proof.
  unfold hsiexits_simu_spec; induction le1; simpl; destruct le2; wlp_simplify; constructor; eauto.
Qed.
Hint Resolve hsiexits_simu_check_correct: wlp.
Global Opaque hsiexits_simu_check.

Definition hsistate_simu_check (dm: PTree.t node) (f: RTLpath.function) outframe (hst1 hst2: hsistate) :=
  hsiexits_simu_check dm f (hsi_exits hst1) (hsi_exits hst2);;
  hsilocal_frame_simu_check (Regset.elements outframe) (hsi_local hst1) (hsi_local hst2).

Lemma hsistate_simu_check_correct dm f outframe hst1 hst2:
  WHEN hsistate_simu_check dm f outframe hst1 hst2 ~> _ THEN
  hsistate_simu_spec dm f outframe hst1 hst2.
Proof.
  unfold hsistate_simu_spec; wlp_simplify.
Qed.
Hint Resolve hsistate_simu_check_correct: wlp.
Global Opaque hsistate_simu_check.


Fixpoint revmap_check_list (dm: PTree.t node) (ln ln': list node): ?? unit :=
  match ln, ln' with
  | nil, nil => RET tt
  | n::ln, n'::ln' => 
      revmap_check_single dm n n';;
      revmap_check_list dm ln ln'
  | _, _ => FAILWITH "revmap_check_list: lists have different lengths"
  end.

Lemma revmap_check_list_correct dm: forall lpc lpc',
  WHEN revmap_check_list dm lpc lpc' ~> _ THEN
  ptree_get_list dm lpc' = Some lpc.
Proof.
  induction lpc.
  - destruct lpc'; wlp_simplify.
  - destruct lpc'; wlp_simplify. try_simplify_someHyps.
Qed.
Global Opaque revmap_check_list.
Hint Resolve revmap_check_list_correct: wlp.


Definition svos_simu_check (svos1 svos2: hsval + ident) :=
  match svos1, svos2 with
  | inl sv1, inl sv2 => phys_check sv1 sv2 "svos_simu_check: sval mismatch"
  | inr id1, inr id2 => phys_check id1 id2 "svos_simu_check: symbol mismatch"
  | _, _ => FAILWITH "svos_simu_check: type mismatch"
  end.

Lemma svos_simu_check_correct svos1 svos2:
  WHEN svos_simu_check svos1 svos2 ~> _ THEN
  svos1 = svos2.
Proof.
  destruct svos1; destruct svos2; wlp_simplify.
Qed.
Global Opaque svos_simu_check.
Hint Resolve svos_simu_check_correct: wlp.


Fixpoint builtin_arg_simu_check (bs bs': builtin_arg hsval) :=
  match bs with
  | BA sv =>
    match bs' with
    | BA sv' => phys_check sv sv' "builtin_arg_simu_check: sval mismatch"
    | _ => FAILWITH "builtin_arg_simu_check: BA mismatch"
    end
  | BA_splitlong lo hi =>
    match bs' with
    | BA_splitlong lo' hi' =>
        builtin_arg_simu_check lo lo';;
        builtin_arg_simu_check hi hi'
    | _ => FAILWITH "builtin_arg_simu_check: BA_splitlong mismatch"
    end
  | BA_addptr b1 b2 =>
    match bs' with
    | BA_addptr b1' b2' =>
        builtin_arg_simu_check b1 b1';;
        builtin_arg_simu_check b2 b2'
    | _ => FAILWITH "builtin_arg_simu_check: BA_addptr mismatch"
    end
  | bs => struct_check bs bs' "builtin_arg_simu_check: basic mismatch"
  end.

Lemma builtin_arg_simu_check_correct: forall bs1 bs2,
  WHEN builtin_arg_simu_check bs1 bs2 ~> _ THEN
  builtin_arg_map hsval_proj bs1 = builtin_arg_map hsval_proj bs2.
Proof.
  induction bs1.
  all: try (wlp_simplify; subst; reflexivity).
  all: destruct bs2; wlp_simplify; congruence.
Qed.
Global Opaque builtin_arg_simu_check.
Hint Resolve builtin_arg_simu_check_correct: wlp.

Fixpoint list_builtin_arg_simu_check lbs1 lbs2 :=
  match lbs1, lbs2 with
  | nil, nil => RET tt
  | bs1::lbs1, bs2::lbs2 =>
    builtin_arg_simu_check bs1 bs2;;
    list_builtin_arg_simu_check lbs1 lbs2
  | _, _ => FAILWITH "list_builtin_arg_simu_check: length mismatch"
  end.

Lemma list_builtin_arg_simu_check_correct: forall lbs1 lbs2,
  WHEN list_builtin_arg_simu_check lbs1 lbs2 ~> _ THEN
  List.map (builtin_arg_map hsval_proj) lbs1 = List.map (builtin_arg_map hsval_proj) lbs2.
Proof.
  induction lbs1; destruct lbs2; wlp_simplify. congruence.
Qed.
Global Opaque list_builtin_arg_simu_check.
Hint Resolve list_builtin_arg_simu_check_correct: wlp.

Definition sfval_simu_check (dm: PTree.t node) (f: RTLpath.function) (pc1 pc2: node) (fv1 fv2: hsfval) :=
  match fv1, fv2 with
  | HSnone, HSnone => revmap_check_single dm pc1 pc2
  | HScall sig1 svos1 lsv1 res1 pc1, HScall sig2 svos2 lsv2 res2 pc2 =>
      revmap_check_single dm pc1 pc2;;
      phys_check sig1 sig2 "sfval_simu_check: Scall different signatures";;
      phys_check res1 res2 "sfval_simu_check: Scall res do not match";;
      svos_simu_check svos1 svos2;;
      phys_check lsv1 lsv2 "sfval_simu_check: Scall args do not match"
  | HStailcall sig1 svos1 lsv1, HStailcall sig2 svos2 lsv2 =>
      phys_check sig1 sig2 "sfval_simu_check: Stailcall different signatures";;
      svos_simu_check svos1 svos2;;
      phys_check lsv1 lsv2 "sfval_simu_check: Stailcall args do not match"
  | HSbuiltin ef1 lbs1 br1 pc1, HSbuiltin ef2 lbs2 br2 pc2 =>
      revmap_check_single dm pc1 pc2;;
      phys_check ef1 ef2 "sfval_simu_check: builtin ef do not match";;
      phys_check br1 br2 "sfval_simu_check: builtin br do not match";;
      list_builtin_arg_simu_check lbs1 lbs2
  | HSjumptable sv ln, HSjumptable sv' ln' =>
      revmap_check_list dm ln ln';;
      phys_check sv sv' "sfval_simu_check: Sjumptable sval do not match"
  | HSreturn osv1, HSreturn osv2 =>
      option_eq_check osv1 osv2
  | _, _ => FAILWITH "sfval_simu_check: structure mismatch"
  end.

Lemma sfval_simu_check_correct dm f opc1 opc2 fv1 fv2:
  WHEN sfval_simu_check dm f opc1 opc2 fv1 fv2 ~> _ THEN
  hfinal_simu_spec dm f opc1 opc2 fv1 fv2.
Proof.
  unfold hfinal_simu_spec; destruct fv1; destruct fv2; wlp_simplify; try congruence.
Qed.
Hint Resolve sfval_simu_check_correct: wlp.
Global Opaque sfval_simu_check.

Definition hsstate_simu_check (dm: PTree.t node) (f: RTLpath.function) outframe (hst1 hst2: hsstate) :=
  hsistate_simu_check dm f outframe (hinternal hst1) (hinternal hst2);;
  sfval_simu_check dm f (hsi_pc hst1) (hsi_pc hst2) (hfinal hst1) (hfinal hst2).

Lemma hsstate_simu_check_correct dm f outframe hst1 hst2:
  WHEN hsstate_simu_check dm f outframe hst1 hst2 ~> _ THEN
  hsstate_simu_spec dm f outframe hst1 hst2.
Proof.
  unfold hsstate_simu_spec; wlp_simplify.
Qed.
Hint Resolve hsstate_simu_check_correct: wlp.
Global Opaque hsstate_simu_check.

Definition simu_check_single (dm: PTree.t node) (f: RTLpath.function) (tf: RTLpath.function) (m: node * node): ?? unit :=
  let (pc2, pc1) := m in
  (* creating the hash-consing tables *)
  DO hC_sval <~ hCons hSVAL;;
  DO hC_list_hsval <~ hCons hLSVAL;;
  DO hC_hsmem <~ hCons hSMEM;;
  let hsexec := hsexec hC_sval.(hC) hC_list_hsval.(hC) hC_hsmem.(hC) in
  (* performing the hash-consed executions *)
  XDEBUG pc1 (fun pc => DO name_pc <~ string_of_Z (Zpos pc);; RET ("entry-point of input superblock: " +; name_pc)%string);;
  DO hst1 <~ hsexec f pc1;;
  XDEBUG pc2 (fun pc => DO name_pc <~ string_of_Z (Zpos pc);; RET ("entry-point of output superblock: " +; name_pc)%string);;
  DO hst2 <~ hsexec tf pc2;;
  DO path <~ some_or_fail ((fn_path f)!pc1) "simu_check_single.internal_error.1";;
  let outframe := path.(pre_output_regs) in
  (* comparing the executions *)
  hsstate_simu_check dm f outframe hst1 hst2.

Lemma simu_check_single_correct dm tf f pc1 pc2:
  WHEN simu_check_single dm f tf (pc2, pc1) ~> _ THEN
  sexec_simu dm f tf pc1 pc2.
Proof.
  unfold sexec_simu; wlp_simplify.
  exploit H2; clear H2. 1-3: wlp_simplify.
  intros (st2 & SEXEC2 & REF2). try_simplify_someHyps.
  exploit H3; clear H3. 1-3: wlp_simplify.
  intros (st3 & SEXEC3 & REF3). try_simplify_someHyps.
  eexists. eexists. split; eauto. split; eauto.
  intros ctx.
  eapply hsstate_simu_spec_correct; eauto.
Qed.
Global Opaque simu_check_single.
Global Hint Resolve simu_check_single_correct: wlp.

Fixpoint simu_check_rec (dm: PTree.t node) (f: RTLpath.function) (tf: RTLpath.function) lm : ?? unit :=
  match lm with
  | nil => RET tt
  | m :: lm => 
    simu_check_single dm f tf m;;
    simu_check_rec dm f tf lm
  end.

Lemma simu_check_rec_correct dm f tf lm:
  WHEN simu_check_rec dm f tf lm ~> _ THEN
  forall pc1 pc2, In (pc2, pc1) lm -> sexec_simu dm f tf pc1 pc2.
Proof.
  induction lm; wlp_simplify.
  match goal with
  | X: (_,_) = (_,_) |- _ => inversion X; subst
  end.
  subst; eauto.
Qed.
Global Opaque simu_check_rec.
Global Hint Resolve simu_check_rec_correct: wlp.

Definition imp_simu_check (dm: PTree.t node) (f: RTLpath.function) (tf: RTLpath.function): ?? unit :=
   simu_check_rec dm f tf (PTree.elements dm);;
   DEBUG("simu_check OK!").

Local Hint Resolve PTree.elements_correct: core.
Lemma imp_simu_check_correct dm f tf:
  WHEN imp_simu_check dm f tf ~> _ THEN
  forall pc1 pc2, dm ! pc2 = Some pc1 -> sexec_simu dm f tf pc1 pc2.
Proof.
  wlp_simplify.
Qed.
Global Opaque imp_simu_check.
Global Hint Resolve imp_simu_check_correct: wlp.

Program Definition aux_simu_check (dm: PTree.t node) (f: RTLpath.function) (tf: RTLpath.function): ?? bool :=
   DO r <~ 
     (TRY 
       imp_simu_check dm f tf;; 
       RET true
      CATCH_FAIL s, _ =>
       println ("simu_check_failure:" +; s);;
       RET false
      ENSURE (fun b => b=true -> forall pc1 pc2, dm ! pc2 = Some pc1 -> sexec_simu dm f tf pc1 pc2));;
   RET (`r).
Obligation 1.
  split; wlp_simplify. discriminate.
Qed.

Lemma aux_simu_check_correct dm f tf:
  WHEN aux_simu_check dm f tf ~> b THEN
  b=true -> forall pc1 pc2, dm ! pc2 = Some pc1 -> sexec_simu dm f tf pc1 pc2.
Proof.
  unfold aux_simu_check; wlp_simplify.
  destruct exta; simpl; auto.
Qed.

(* Coerce aux_simu_check into a pure function (this is a little unsafe like all oracles in CompCert). *)

Import UnsafeImpure.

Definition simu_check (dm: PTree.t node) (f: RTLpath.function) (tf: RTLpath.function) : res unit := 
  match unsafe_coerce (aux_simu_check dm f tf) with
  | Some true => OK tt
  | _ => Error (msg "simu_check has failed")
  end.

Lemma simu_check_correct dm f tf:
  simu_check dm f tf = OK tt ->
  forall pc1 pc2, dm ! pc2 = Some pc1 ->
  sexec_simu dm f tf pc1 pc2.
Proof.
  unfold simu_check.
  destruct (unsafe_coerce (aux_simu_check dm f tf)) as [[|]|] eqn:Hres; simpl; try discriminate.
  intros; eapply aux_simu_check_correct; eauto.
  eapply unsafe_coerce_not_really_correct; eauto.
Qed.