z3-src 416.0.2

Source distribution of the Z3 SMT solver, for use as a build dependency
Documentation
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
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
/*++
Copyright (c) 2017 Microsoft Corporation

Module Name:

    pb_solver.cpp

Abstract:

    Extension for cardinality reasoning.

Author:

    Nikolaj Bjorner (nbjorner) 2017-01-30

--*/

#include <cmath>
#include "util/mpz.h"
#include "sat/sat_types.h"
#include "sat/smt/pb_solver.h"
#include "sat/smt/euf_solver.h"
#include "sat/sat_simplifier_params.hpp"
#include "sat/sat_scc.h"

namespace pb {

    static unsigned _bad_id = 11111111; // 2759; //
#define BADLOG(_cmd_) if (p.id() == _bad_id) { _cmd_; }


    // -----------------------
    // constraint

    void solver::set_conflict(constraint& c, literal lit) {
        m_stats.m_num_conflicts++;
        TRACE(pb, display(tout, c, true); );
        if (!validate_conflict(c)) {
            IF_VERBOSE(0, display(verbose_stream(), c, true));
            UNREACHABLE();
        }
        SASSERT(validate_conflict(c));
        SASSERT(value(lit) == l_false);
        set_conflict(sat::justification::mk_ext_justification(s().scope_lvl(), c.cindex()), ~lit);
        SASSERT(inconsistent());
    }

    void solver::assign(constraint& c, literal lit) {
        if (inconsistent()) return;
        switch (value(lit)) {
        case l_true: 
            break;
        case l_false: 
            set_conflict(c, lit); 
            break;
        default:
            m_stats.m_num_propagations++;
            m_num_propagations_since_pop++;
            //TRACE(pb, tout << "#prop: " << m_stats.m_num_propagations << " - " << c.lit() << " => " << lit << "\n";);
            SASSERT(validate_unit_propagation(c, lit));
            assign(lit, sat::justification::mk_ext_justification(s().scope_lvl(), c.cindex()));
            break;
        }
    }

    // -------------------
    // pb_base

    void solver::simplify(constraint& p) {
        SASSERT(s().at_base_lvl());
        if (p.lit() != sat::null_literal && value(p.lit()) == l_false) {
            TRACE(pb, tout << "pb: flip sign " << p << "\n";);
            IF_VERBOSE(2, verbose_stream() << "sign is flipped " << p << "\n";);
            return;
        }
        bool nullify = p.lit() != sat::null_literal && value(p.lit()) == l_true;
        if (nullify) {
            IF_VERBOSE(100, display(verbose_stream() << "nullify tracking literal\n", p, true););
            SASSERT(lvl(p.lit()) == 0);
            p.nullify_tracking_literal(*this);
            init_watch(p);
        }

        SASSERT(p.lit() == sat::null_literal || value(p.lit()) != l_false);

        unsigned true_val = 0, slack = 0, num_false = 0;
        for (unsigned i = 0; i < p.size(); ++i) {
            literal l = p.get_lit(i);
            bool_var v = l.var();
            if (s().was_eliminated(v)) {
                VERIFY(p.learned());
                remove_constraint(p, "contains eliminated");
                return;
            }
            switch (value(l)) {
            case l_true: true_val += p.get_coeff(i); break;
            case l_false: ++num_false; break;
            default: slack += p.get_coeff(i); break;
            }
        }
        if (p.k() == 1 && p.lit() == sat::null_literal) {
            literal_vector lits(p.literals());
            s().mk_clause(lits.size(), lits.data(), sat::status::th(p.learned(), get_id()));
            IF_VERBOSE(100, display(verbose_stream() << "add clause: " << lits << "\n", p, true););
            remove_constraint(p, "implies clause");
        }
        else if (true_val == 0 && num_false == 0) {
            if (p.lit() == sat::null_literal || value(p.lit()) == l_true) {
                init_watch(p);
            }
        }
        else if (true_val >= p.k()) {
            IF_VERBOSE(100, display(verbose_stream() << "assign true literal ", p, true););
            if (p.lit() != sat::null_literal) 
                s().assign_scoped(p.lit());
            else 
                remove_constraint(p, "is true");
        }
        else if (slack + true_val < p.k()) {
            if (p.lit() != sat::null_literal) {
                IF_VERBOSE(3, display(verbose_stream() << "assign false literal ", p, true););
                s().assign_scoped(~p.lit());
            }
            else {
                IF_VERBOSE(1, verbose_stream() << "unsat during simplification\n");
                s().set_conflict(sat::justification(0));
            }
        }
        else if (slack + true_val == p.k()) {
            literal_vector lits(p.literals());    
            assert_unconstrained(p.lit(), lits);
            remove_constraint(p, "is tight");
        }
        else {

            unsigned sz = p.size();
            clear_watch(p);
            unsigned j = 0;
            for (unsigned i = 0; i < sz; ++i) {
                literal l = p.get_lit(i);
                if (value(l) == l_undef) {
                    if (i != j)
                        p.swap(i, j);
                    ++j;                    
                }
            }
            sz = j;
            // _bad_id = p.id();
            BADLOG(display(verbose_stream() << "simplify ", p, true));

            unsigned k = p.k() - true_val;

            if (k == 1 && p.lit() == sat::null_literal) {
                literal_vector lits(sz, p.literals().data());
                s().mk_clause(sz, lits.data(), sat::status::th(p.learned(), get_id()));
                remove_constraint(p, "is clause");
                return;
            }
            p.set_size(sz);
            p.set_k(k);
            if (p.lit() == sat::null_literal || value(p.lit()) == l_true) {
                init_watch(p);
            }
            else {
                SASSERT(value(p.lit()) == l_undef);
            }
            BADLOG(display(verbose_stream() << "simplified ", p, true); verbose_stream() << "\n");
            // display(verbose_stream(), c, true);
            _bad_id = 11111111;
            SASSERT(p.well_formed());
            m_simplify_change = true;

        }
    }

    /*
      \brief split PB constraint into two because root is reused in arguments.
    
      x <=> a*x + B*y >= k
     
      x => a*x + By >= k
      ~x => a*x + By < k
     
      k*~x + a*x + By >= k
      (B+a-k + 1)*x + a*~x + B*~y >= B + a - k + 1

      (k - a) * ~x + By >= k - a
      k' * x + B'y >= k'
       
    */
    
    void solver::split_root(constraint& p) {
        SASSERT(p.lit() != sat::null_literal);
        SASSERT(!p.learned());
        m_weights.resize(2*s().num_vars(), 0);
        unsigned k = p.k();
        unsigned w, w1, w2;
        literal root = p.lit();
        m_weights[(~root).index()] = k;
        for (unsigned i = 0; i < p.size(); ++i) {
            m_weights[p.get_lit(i).index()] += p.get_coeff(i);
        }
        literal_vector lits(p.literals());
        lits.push_back(~root);

        for (literal l : lits) {
            w1 = m_weights[l.index()];
            w2 = m_weights[(~l).index()];
            if (w1 >= w2) {
                if (w2 >= k) {
                    for (literal l2 : lits) m_weights[l2.index()] = 0;
                    // constraint is true
                    return;
                }
                k -= w2;
                m_weights[(~l).index()] = 0;
                m_weights[l.index()] = w1 - w2;
            }
        }
        SASSERT(k > 0);

        // ~root * (k - a) + p >= k - a

        m_wlits.reset();
        for (literal l : lits) {
            w = m_weights[l.index()];
            if (w != 0) {
                m_wlits.push_back(wliteral(w, l));
            } 
            m_weights[l.index()] = 0;
        }
        
        add_pb_ge(sat::null_literal, m_wlits, k, false);        
    }


    // -------------------
    // pb


    /*
      Chai Kuhlmann:
      Lw - set of watched literals
      Lu - set of unwatched literals that are not false
      
      Lw = Lw \ { alit }
      Sw -= value
      a_max = max { a | l in Lw u Lu, l = undef }
      while (Sw < k + a_max & Lu != 0) {
        a_s = max { a | l in Lu }
        Sw += a_s
        Lw = Lw u {l_s}
        Lu = Lu \ {l_s}
      }
      if (Sw < k) return conflict
      for (li in Lw | Sw < k + ai) 
         assign li
      return no-conflict

     a_max index: index of non-false literal with maximal weight.
    */

    void solver::add_index(pbc& p, unsigned index, literal lit) {
        if (value(lit) == l_undef) {
            m_pb_undef.push_back(index);
            auto [w, l] = p[index];
            if (w > m_a_max) {
                m_a_max = w;
            }
        }
    }    
    
    /*
      \brief propagate assignment to alit in constraint p.
      
      TBD: 
      - consider reordering literals in watch list so that the search for watched literal takes average shorter time.
      - combine with caching literals that are assigned to 'true' to a cold store where they are not being revisited.
        Since 'true' literals may be unassigned (unless they are assigned at level 0) the cache has to be backtrack
        friendly (and the overhead of backtracking has to be taken into account).
     */
    lbool solver::add_assign(pbc& p, literal alit) {
        BADLOG(display(verbose_stream() << "assign: " << alit << " watch: " << p.num_watch() << " size: " << p.size(), p, true));
        TRACE(pb, display(tout << "assign: " << alit << "\n", p, true););
        SASSERT(!inconsistent());
        unsigned sz = p.size();
        unsigned bound = p.k();
        unsigned num_watch = p.num_watch();
        unsigned slack = p.slack();
        SASSERT(value(alit) == l_false);
        SASSERT(p.lit() == sat::null_literal || value(p.lit()) == l_true);
        SASSERT(num_watch <= sz);
        SASSERT(num_watch > 0);
        SASSERT(validate_watch(p, sat::null_literal));
        unsigned index = 0;
        m_a_max = 0;
        m_pb_undef.reset();
        for (; index < num_watch; ++index) {
            auto [w, lit] = p[index];
            if (lit == alit) {
                break;
            }
            add_index(p, index, lit);
        }
        if (index == num_watch || num_watch == 0) {
            _bad_id = p.id();
            BADLOG(
                verbose_stream() << "BAD: " << p.id() << "\n";
                display(verbose_stream(), p, true);
                verbose_stream() << "alit: " << alit << "\n";
                verbose_stream() << "num watch " << num_watch << "\n");
            UNREACHABLE();
            return l_undef;
        }
        
        
        SASSERT(index < num_watch);
        unsigned index1 = index + 1;
        for (; m_a_max == 0 && index1 < num_watch; ++index1) {
            auto [w, lit] = p[index1];
            add_index(p, index1, lit);
        }
        
        auto [val, alit_lit] = p[index];
        SASSERT(value(alit_lit) == l_false);
        SASSERT(val <= slack);
        slack -= val;

        // find literals to swap with:            
        for (unsigned j = num_watch; j < sz && slack < bound + m_a_max; ++j) {
            auto [w, lit] = p[j];
            if (value(lit) != l_false) {
                slack += w;
                SASSERT(!p.is_watched(*this, lit));
                p.watch_literal(*this, lit);
                p.swap(num_watch, j);
                add_index(p, num_watch, lit);             
                ++num_watch;
            }
        }
        
        SASSERT(!inconsistent());
        DEBUG_CODE(for (auto idx : m_pb_undef) { SASSERT(value(p[idx].second) == l_undef); });
        
        if (slack < bound) {
            // maintain watching the literal
            slack += val;
            p.set_slack(slack);
            p.set_num_watch(num_watch);
            SASSERT(validate_watch(p, sat::null_literal));
            BADLOG(display(verbose_stream() << "conflict: " << alit << " watch: " << p.num_watch() << " size: " << p.size(), p, true));            
            SASSERT(bound <= slack);
            TRACE(pb, tout << "conflict " << alit << "\n";);
            set_conflict(p, alit);
            return l_false;
        }

        if (num_watch == 1) { _bad_id = p.id(); }

        BADLOG(verbose_stream() << "size: " << p.size() << " index: " << index << " num watch: " << num_watch << "\n");

        // swap out the watched literal.
        --num_watch;
        SASSERT(num_watch > 0);
        p.set_slack(slack);
        p.set_num_watch(num_watch);
        p.swap(num_watch, index);



        // 
        // slack >= bound, but slack - w(l) < bound 
        // l must be true.
        // 
        if (slack < bound + m_a_max) {            
            BADLOG(verbose_stream() << "slack " << slack << " " << bound << " " << m_a_max << "\n";);
            TRACE(pb, tout << p << "\n"; for(auto j : m_pb_undef) tout << j << " "; tout << "\n";);
            for (unsigned index1 : m_pb_undef) {
                if (index1 == num_watch) {
                    index1 = index;
                }
                auto [w, lit] = p[index1];
                SASSERT(value(lit) == l_undef);
                if (slack < bound + w) {
                    BADLOG(verbose_stream() << "Assign " << lit << " " << w << "\n");                
                    assign(p, lit);
                }
            }
        }

        SASSERT(validate_watch(p, alit)); // except that alit is still watched.

        TRACE(pb, display(tout << "assign: " << alit << "\n", p, true););

        BADLOG(verbose_stream() << "unwatch " << alit << " watch: " << p.num_watch() << " size: " << p.size() << " slack: " << p.slack() << " " << inconsistent() << "\n");

        return l_undef;
    }

    std::pair<unsigned, unsigned> solver::normalize(wliteral* begin, wliteral* end, unsigned k) {
        m_weights.resize(2 * s().num_vars(), 0);
        for (auto it = begin; it != end; ++it) {
            auto [w, lit] = *it;        
            m_weights[lit.index()] += w;
        }        
        auto j = begin;
        unsigned sz = 0;
        for (auto it = begin; it != end; ++it) {
            auto [w, l] = *it;
            unsigned w1 = m_weights[l.index()];
            unsigned w2 = m_weights[(~l).index()];
            if (w1 == 0 || w1 < w2) {
                continue;
            }
            else if (k <= w2) {
                k = 0;
                break;
            }
            else {
                SASSERT(w2 <= w1 && w2 < k);
                k -= w2;
                w1 -= w2;
                m_weights[l.index()] = 0;
                m_weights[(~l).index()] = 0;
                if (w1 == 0) {
                    continue;
                }
                else {
                    *j = wliteral(w1, l);
                    ++j;
                    ++sz;
                }
            }
        }
        // clear weights
        while (begin != end) {
            auto [w, l] = *begin;
            m_weights[l.index()] = 0;
            m_weights[(~l).index()] = 0;
            ++begin;
        }
        return {sz, k};
    }

    void solver::recompile(pbc& p) {
        // IF_VERBOSE(2, verbose_stream() << "re: " << p << "\n";);

        auto [sz, k] = normalize(p.data(), p.data() + p.size(), p.k());
        p.set_size(sz);
        auto all_units = all_of(p, [](wliteral const& wl) { return wl.first == 1; });

        if (k == 0) {
            if (p.lit() != sat::null_literal) {
                s().assign_scoped(p.lit());
            }
            remove_constraint(p, "recompiled to true");
            return;
        }

        else if (k == 1 && p.lit() == sat::null_literal) {
            literal_vector lits(sz, p.literals().data());
            s().mk_clause(sz, lits.data(), sat::status::th(p.learned(), get_id()));
            remove_constraint(p, "recompiled to clause");
            return;
        }

        else if (all_units) {
            literal_vector lits(sz, p.literals().data());
            add_at_least(p.lit(), lits, k, p.learned());
            remove_constraint(p, "recompiled to cardinality");
            return;
        }
        else {            
            p.update_max_sum();
            if (p.max_sum() < k) {
                if (p.lit() == sat::null_literal) {
                    s().set_conflict(sat::justification(0));
                }
                else {
                    s().assign_scoped(~p.lit());
                }
                remove_constraint(p, "recompiled to false");
                return;
            }
            p.set_k(k);
            SASSERT(p.well_formed());
            
            if (clausify(p)) {
                return;
            }
            if (p.lit() == sat::null_literal || value(p.lit()) == l_true) {
                init_watch(p);
            }
        }
    }


    // ---------------------------
    // conflict resolution
    

    void solver::inc_coeff(literal l, unsigned offset) {
        SASSERT(offset > 0);
        bool_var v = l.var();
        SASSERT(v != sat::null_bool_var);
        m_coeffs.reserve(v + 1, 0);
        TRACE(ba_verbose, tout << l << " " << offset << "\n";);

        int64_t coeff0 = m_coeffs[v];
        if (coeff0 == 0) {
            m_active_vars.push_back(v);
        }
        
        int64_t loffset = static_cast<int64_t>(offset);
        int64_t inc = l.sign() ? -loffset : loffset;
        int64_t coeff1 = inc + coeff0;
        m_coeffs[v] = coeff1;
        if (coeff1 > INT_MAX || coeff1 < INT_MIN) {
            m_overflow = true;
            return;
        }

        if (coeff0 > 0 && inc < 0) {
            inc_bound(std::max((int64_t)0, coeff1) - coeff0);
        }
        else if (coeff0 < 0 && inc > 0) {
            inc_bound(coeff0 - std::min((int64_t)0, coeff1));
        }
        int64_t lbound = static_cast<int64_t>(m_bound);

        // reduce coefficient to be no larger than bound.
        if (coeff1 > lbound) {
            m_coeffs[v] = lbound;
        }
        else if (coeff1 < 0 && -coeff1 > lbound) {
            m_coeffs[v] = -lbound;
        }        
    }

    int64_t solver::get_coeff(bool_var v) const {
        return m_coeffs.get(v, 0);
    }

    uint64_t solver::get_coeff(literal lit) const {
        int64_t c1 = get_coeff(lit.var());
        SASSERT((c1 < 0) == lit.sign());
        int64_t c = std::abs(c1);
        m_overflow |= (c != c1);
        return static_cast<uint64_t>(c);
    }

    wliteral solver::get_wliteral(bool_var v) {
        int64_t c1 = get_coeff(v);
        literal l = literal(v, c1 < 0);
        c1 = std::abs(c1);
        unsigned c = static_cast<unsigned>(c1);
        // TRACE(pb, tout << l << " " << c << "\n";);
        m_overflow |= c != c1;
        return wliteral(c, l);
    }

    unsigned solver::get_abs_coeff(bool_var v) const {
        int64_t c1 = std::abs(get_coeff(v));
        unsigned c = static_cast<unsigned>(c1);
        m_overflow |= c != c1;
        return c;
    }

    int solver::get_int_coeff(bool_var v) const {
        int64_t c1 = m_coeffs.get(v, 0);
        int c = static_cast<int>(c1);
        m_overflow |= c != c1;
        return c;
    }

    void solver::inc_bound(int64_t i) {
        int64_t new_bound = m_bound;
        new_bound += i;
        unsigned nb = static_cast<unsigned>(new_bound);
        m_overflow |= new_bound < 0 || nb != new_bound;
        m_bound = nb;        
    }

    void solver::reset_coeffs() {
        for (unsigned i = m_active_vars.size(); i-- > 0; ) {
            m_coeffs[m_active_vars[i]] = 0;
        }
        m_active_vars.reset();
    }


    static bool _debug_conflict = false;
    static literal _debug_consequent = sat::null_literal;
    static unsigned_vector _debug_var2position;

// #define DEBUG_CODE(_x_) _x_

    void solver::bail_resolve_conflict(unsigned idx) {
        literal_vector const& lits = s().m_trail;
        while (m_num_marks > 0) {
            bool_var v = lits[idx].var();
            if (s().is_marked(v)) {
                s().reset_mark(v);
                --m_num_marks;
            }
            if (idx == 0 && !_debug_conflict && m_num_marks > 0) {
                _debug_conflict = true;
                _debug_var2position.reserve(s().num_vars());
                for (unsigned i = 0; i < lits.size(); ++i) {
                    _debug_var2position[lits[i].var()] = i;
                }
                IF_VERBOSE(0, verbose_stream() << "num marks: " << m_num_marks << "\n");
                IF_VERBOSE(0, 
                           active2pb(m_A);
                           uint64_t c = 0;
                           for (auto [w, l] : m_A.m_wlits) c += w;
                           verbose_stream() << "sum of coefficients: " << c << "\n";
                           display(verbose_stream(), m_A, true);
                           verbose_stream() << "conflicting literal: " << s().m_not_l << "\n";);

                for (literal l : lits) {
                    if (s().is_marked(l.var())) {
                        IF_VERBOSE(0, verbose_stream() << "missing mark: " << l << "\n";);
                        s().reset_mark(l.var());
                    }
                }
                m_num_marks = 0;
                resolve_conflict();
                exit(0);
            }
            --idx;
        }
    }

    lbool solver::resolve_conflict() { 
        if (0 == m_num_propagations_since_pop) 
            return l_undef;

        if (s().m_config.m_pb_resolve == sat::PB_ROUNDING) 
            return resolve_conflict_rs();
       
        m_overflow = false;
        reset_coeffs();
        m_num_marks = 0;
        m_bound = 0;
        literal consequent = s().m_not_l;
        sat::justification js = s().m_conflict;
        TRACE(pb, tout << consequent << " " << js << "\n";);
        bool unique_max;
        m_conflict_lvl = s().get_max_lvl(consequent, js, unique_max);
        if (m_conflict_lvl == 0) {
            return l_undef;
        }
        if (consequent != sat::null_literal) {
            consequent.neg();
            process_antecedent(consequent, 1);
        }
        literal_vector const& lits = s().m_trail;
        unsigned idx = lits.size() - 1;
        unsigned offset = 1;
        DEBUG_CODE(active2pb(m_A););

        do {


            if (m_overflow || offset > (1 << 12)) {
                IF_VERBOSE(20, verbose_stream() << "offset: " << offset << "\n";
                           DEBUG_CODE(active2pb(m_A); display(verbose_stream(), m_A);););
                goto bail_out;
            }

            if (offset == 0) {
                goto process_next_resolvent;            
            }

            DEBUG_CODE(TRACE(sat_verbose, display(tout, m_A);););
            TRACE(pb, tout << "process consequent: " << consequent << " : "; s().display_justification(tout, js) << "\n";);
            SASSERT(offset > 0);
            
            if (_debug_conflict) {
                IF_VERBOSE(0, 
                           verbose_stream() << consequent << "\n";
                           s().display_justification(verbose_stream(), js);
                           verbose_stream() << "\n";);
                _debug_consequent = consequent;
            }
            switch(js.get_kind()) {
            case sat::justification::NONE:
                SASSERT (consequent != sat::null_literal);
                inc_bound(offset);
                break;
            case sat::justification::BINARY:
                inc_bound(offset);
                SASSERT (consequent != sat::null_literal);
                inc_coeff(consequent, offset);
                process_antecedent(js.get_literal(), offset);
                break;
            case sat::justification::CLAUSE: {
                inc_bound(offset); 
                sat::clause & c = s().get_clause(js);
                unsigned i = 0;
                if (consequent != sat::null_literal) {
                    inc_coeff(consequent, offset);
                    if (c[0] == consequent) {
                        i = 1;
                    }
                    else {
                        SASSERT(c[1] == consequent);
                        process_antecedent(c[0], offset);
                        i = 2;
                    }
                }
                unsigned sz = c.size();
                for (; i < sz; ++i)
                    process_antecedent(c[i], offset);
                break;
            }
            case sat::justification::EXT_JUSTIFICATION: {
                auto cindex = js.get_ext_justification_idx();
                auto* ext = sat::constraint_base::to_extension(cindex);
                if (ext != this) 
                    goto bail_out;
                
                constraint& cnstr = index2constraint(cindex);
                ++m_stats.m_num_resolves;
                switch (cnstr.tag()) {
                case pb::tag_t::card_t: {
                    card& c = cnstr.to_card();
                    inc_bound(static_cast<int64_t>(offset) * c.k());
                    process_card(c, offset);
                    break;
                }
                case pb::tag_t::pb_t: {
                    pbc& p = cnstr.to_pb();
                    m_lemma.reset();
                    inc_bound(offset);
                    inc_coeff(consequent, offset);
                    get_antecedents(consequent, p, m_lemma);
                    TRACE(pb, display(tout, p, true); tout << m_lemma << "\n";);
                    if (_debug_conflict) {
                        verbose_stream() << consequent << " ";
                        verbose_stream() << "antecedents: " << m_lemma << "\n";
                    }
                    for (literal l : m_lemma) process_antecedent(~l, offset);
                    break;
                }
                default:
                    UNREACHABLE();
                    break;
                }
                break;
            }
            default:
                UNREACHABLE();
                break;
            }
            
            SASSERT(validate_lemma());            

            DEBUG_CODE(
                active2pb(m_C);
                VERIFY(validate_resolvent());
                m_A = m_C;
                TRACE(pb, display(tout << "conflict: ", m_A);););

            cut();

        process_next_resolvent:
            
            // find the next marked variable in the assignment stack
            bool_var v;
            while (true) {
                consequent = lits[idx];
                v = consequent.var();
                if (s().is_marked(v)) {
                    if (s().lvl(v) == m_conflict_lvl) {
                        break;
                    }
                }
                if (idx == 0) {
                    IF_VERBOSE(2, verbose_stream() << "did not find marked literal\n";);
                    goto bail_out;
                }
                SASSERT(idx > 0);
                --idx;
            }
            
            SASSERT(lvl(v) == m_conflict_lvl);
            s().reset_mark(v);
            --idx;
            TRACE(sat_verbose, tout << "Unmark: v" << v << "\n";);
            --m_num_marks;
            js = s().m_justification[v];
            offset = get_abs_coeff(v);
            if (offset > m_bound) {
                int64_t bound64 = static_cast<int64_t>(m_bound);
                m_coeffs[v] = (get_coeff(v) < 0) ? -bound64 : bound64;
                offset = m_bound;
                DEBUG_CODE(active2pb(m_A););
            }
            SASSERT(value(consequent) == l_true);
        }        
        while (m_num_marks > 0);
        
        DEBUG_CODE(for (bool_var i = 0; i < static_cast<bool_var>(s().num_vars()); ++i) SASSERT(!s().is_marked(i)););
        SASSERT(validate_lemma());

        if (!create_asserting_lemma()) {
            goto bail_out;
        }
        active2lemma();


        DEBUG_CODE(VERIFY(validate_conflict(m_lemma, m_A)););
        
        return l_true;

    bail_out:
        if (m_overflow) {
            ++m_stats.m_num_overflow;
            m_overflow = false;
        }
        bail_resolve_conflict(idx);
        return l_undef;
    }


    unsigned solver::ineq::bv_coeff(bool_var v) const {
        for (unsigned i = size(); i-- > 0; ) {
            if (lit(i).var() == v) return coeff(i);
        }
        UNREACHABLE();
        return 0;
    }

    void solver::ineq::divide(unsigned c) {
        if (c == 1) return;
        for (unsigned i = size(); i-- > 0; ) {
            m_wlits[i].first = (coeff(i) + c - 1) / c;
        }
        m_k = (m_k + c - 1) / c;
    }

    /**
     * Remove literal at position i, subtract coefficient from bound.
     */
    void solver::ineq::weaken(unsigned i) {
        unsigned ci = coeff(i);
        SASSERT(m_k >= ci);
        m_k -= ci;
        m_wlits[i] = m_wlits.back();
        m_wlits.pop_back();
    }

    /** 
     * Round coefficient of inequality to 1.
     */
    void solver::round_to_one(ineq& ineq, bool_var v) {
        unsigned c = ineq.bv_coeff(v);
        if (c == 1) return;
        unsigned sz = ineq.size();
        for (unsigned i = 0; i < sz; ++i) {
            unsigned ci = ineq.coeff(i); 
            unsigned q = ci % c;
            if (q != 0 && !is_false(ineq.lit(i))) {
#if 1
                // code review by Elffers:
                ineq.weaken(i);
                --i;
                --sz;                
#else
                if (q == ci) {
                    ineq.weaken(i);
                    --i;
                    --sz;
                }
                else {
                    ineq.m_wlits[i].first -= q;
                    ineq.m_k -= q;
                }
#endif
            }
        }
        ineq.divide(c);
        TRACE(pb, display(tout << "var: " << v << " " << c << ": ", ineq, true););
    }

    void solver::round_to_one(bool_var w) {
        unsigned c = get_abs_coeff(w);
        if (c == 1 || c == 0) return;
        for (bool_var v : m_active_vars) {
            auto [coeff, l] = get_wliteral(v);
            unsigned q = coeff % c;
            if (q != 0 && !is_false(l)) {
                m_coeffs[v] = coeff - q;
                m_bound -= q;
                SASSERT(m_bound > 0);
            }
        }        
        SASSERT(validate_lemma());
        divide(c);
        SASSERT(validate_lemma());
        TRACE(pb, active2pb(m_B); display(tout, m_B, true););
    }

    void solver::divide(unsigned c) {
        SASSERT(c != 0);
        if (c == 1) return;
        reset_active_var_set();
        unsigned j = 0, sz = m_active_vars.size();
        for (unsigned i = 0; i < sz; ++i) {
            bool_var v = m_active_vars[i];
            int ci = get_int_coeff(v);
            if (!test_and_set_active(v) || ci == 0) continue;
            if (ci > 0) {
                m_coeffs[v] = (ci + c - 1) / c;
            }
            else {
                m_coeffs[v] = -static_cast<int64_t>((-ci + c - 1) / c);
            }
            m_active_vars[j++] = v;
        }
        m_active_vars.shrink(j);
        m_bound = static_cast<unsigned>((m_bound + c - 1) / c);                    
    }

    void solver::resolve_on(literal consequent) {
        round_to_one(consequent.var());
        m_coeffs[consequent.var()] = 0;
    }

    void solver::resolve_with(ineq const& ineq) {
        TRACE(pb, display(tout, ineq, true););
        inc_bound(ineq.m_k);        
        TRACE(pb, tout << "bound: " << m_bound << "\n";);

        for (unsigned i = ineq.size(); i-- > 0; ) {
            literal l = ineq.lit(i);
            inc_coeff(l, static_cast<unsigned>(ineq.coeff(i)));
            TRACE(pb, tout << "bound: " << m_bound << " lit: " << l << " coeff: " << ineq.coeff(i) << "\n";);
        }
    }

    void solver::reset_marks(unsigned idx) {
        while (m_num_marks > 0) {
            SASSERT(idx > 0);
            bool_var v = s().m_trail[idx].var();
            if (s().is_marked(v)) {
                s().reset_mark(v);
                --m_num_marks;
            }
            --idx;
        }
    }
    
    /**
     * \brief mark variables that are on the assignment stack but 
     * below the current processing level.
     */
    void solver::mark_variables(ineq const& ineq) {
        for (auto [w, l] : ineq.m_wlits) {
            if (!is_false(l)) continue;
            bool_var v = l.var();
            unsigned level = lvl(v);
            if (!s().is_marked(v) && !is_visited(v) && level == m_conflict_lvl) {
                s().mark(v);
                ++m_num_marks;
            }
        }
    }

    lbool solver::resolve_conflict_rs() {
        if (0 == m_num_propagations_since_pop) {
            return l_undef;
        }
        m_overflow = false;
        reset_coeffs();
        init_visited();
        m_num_marks = 0;
        m_bound = 0;
        literal consequent = s().m_not_l;
        sat::justification js = s().m_conflict;
        bool unique_max;
        m_conflict_lvl = s().get_max_lvl(consequent, js, unique_max);
        if (m_conflict_lvl == 0) {
            return l_undef;
        }
        if (consequent != sat::null_literal) {
            consequent.neg();
            process_antecedent(consequent, 1);
        }
        TRACE(pb, tout << consequent << " " << js << "\n";);
        unsigned idx = s().m_trail.size() - 1;
        
        do {
            TRACE(pb, s().display_justification(tout << "process consequent: " << consequent << " : ", js) << "\n";
                  if (consequent != sat::null_literal) { active2pb(m_A); display(tout, m_A, true); }
                  );

            switch (js.get_kind()) {
            case sat::justification::NONE:
                SASSERT(consequent != sat::null_literal);
                round_to_one(consequent.var());
                inc_bound(1);
                inc_coeff(consequent, 1);
                break;
            case sat::justification::BINARY:
                SASSERT(consequent != sat::null_literal);
                round_to_one(consequent.var());
                inc_bound(1);
                inc_coeff(consequent, 1);
                process_antecedent(js.get_literal());
                break;
            case sat::justification::CLAUSE: {
                sat::clause & c = s().get_clause(js);
                unsigned i = 0;
                if (consequent != sat::null_literal) {
                    round_to_one(consequent.var());
                    inc_coeff(consequent, 1);
                    if (c[0] == consequent) {
                        i = 1;
                    }
                    else {
                        SASSERT(c[1] == consequent);
                        process_antecedent(c[0]);
                        i = 2;
                    }
                }
                inc_bound(1);
                unsigned sz = c.size();
                for (; i < sz; ++i)
                    process_antecedent(c[i]);
                break;
            }
            case sat::justification::EXT_JUSTIFICATION: {
                ++m_stats.m_num_resolves;
                sat::ext_justification_idx index = js.get_ext_justification_idx();
                auto* ext = sat::constraint_base::to_extension(index);
                if (ext != this) {
                    m_lemma.reset();
                    ext->get_antecedents(consequent, index, m_lemma, false);
                    for (literal l : m_lemma) 
                        process_antecedent(~l, 1);
                    break;
                }
                constraint& p = index2constraint(index);
                SASSERT(!p.was_removed());
                unsigned k = p.k(), sz = p.size();
                m_A.reset(0);
                for (unsigned i = 0; i < sz; ++i) {
                    literal l = p.get_lit(i);
                    unsigned c = p.get_coeff(i);
                    if (l == consequent || !is_visited(l.var())) {
                        m_A.push(l, c);
                    }
                    else {
                        SASSERT(k > c);
                        TRACE(pb, tout << "visited: " << l << "\n";);
                        k -= c;
                    }
                }
                SASSERT(k > 0);
                if (p.lit() != sat::null_literal) m_A.push(~p.lit(), k);
                m_A.m_k = k;

                mark_variables(m_A);
                if (consequent == sat::null_literal) {
                    SASSERT(validate_ineq(m_A)); 
                    m_bound = static_cast<unsigned>(m_A.m_k);
                    for (auto [w, lit] : m_A.m_wlits) {
                        process_antecedent(lit, w);
                    } 
                }
                else {
                    round_to_one(consequent.var());
                    if (p.is_pb()) round_to_one(m_A, consequent.var()); 
                    SASSERT(validate_ineq(m_A)); 
                    resolve_with(m_A);
                }
                break;
            }
            default:
                UNREACHABLE();
                break;
            }            

            SASSERT(validate_lemma());
            cut();

            // find the next marked variable in the assignment stack
            bool_var v;
            while (true) {
                consequent = s().m_trail[idx];
                v = consequent.var();
                mark_visited(v);
                if (s().is_marked(v)) {
                    int64_t c = get_coeff(v);
                    if (c == 0 || ((c < 0) == consequent.sign())) {
                        s().reset_mark(v);
                        --m_num_marks;
                    }
                    else {
                        break;
                    }
                }
                if (idx == 0) {
                    TRACE(pb, tout << "there is no consequent\n";);
                    goto bail_out;
                }
                --idx;
            }
            
            SASSERT(lvl(v) == m_conflict_lvl);
            s().reset_mark(v);
            --idx;
            --m_num_marks;
            js = s().m_justification[v];
        }        
        while (m_num_marks > 0 && !m_overflow);
        TRACE(pb, active2pb(m_A); display(tout, m_A, true););

        // TBD: check if this is useful
        if (!m_overflow && consequent != sat::null_literal) {
            round_to_one(consequent.var());
        }
        if (!m_overflow && create_asserting_lemma()) {
            active2lemma();
            return l_true;
        }
        
    bail_out:
        TRACE(pb, tout << "bail " << m_overflow << "\n";);
        if (m_overflow) {
            ++m_stats.m_num_overflow;
            m_overflow = false;
        }
        return l_undef;
    }


    bool solver::create_asserting_lemma() {
        int64_t bound64 = m_bound;
        int64_t slack = -bound64;
        reset_active_var_set();
        unsigned j = 0, sz = m_active_vars.size();
        for (unsigned i = 0; i < sz; ++i) {
            bool_var v = m_active_vars[i];
            unsigned c = get_abs_coeff(v);
            if (!test_and_set_active(v) || c == 0) continue;
            slack += c;
            m_active_vars[j++] = v;
        }
        m_active_vars.shrink(j);
        m_lemma.reset();        
        m_lemma.push_back(sat::null_literal);
        unsigned num_skipped = 0;
        int64_t asserting_coeff = 0;
        for (unsigned i = 0; 0 <= slack && i < m_active_vars.size(); ++i) { 
            bool_var v = m_active_vars[i];
            int64_t coeff = get_coeff(v);
            lbool val = value(v);
            bool is_true = val == l_true;
            bool append = coeff != 0 && val != l_undef && ((coeff < 0) == is_true);
            if (append) {
                literal lit(v, !is_true);
                if (lvl(lit) == m_conflict_lvl) {
                    if (m_lemma[0] == sat::null_literal) {
                        asserting_coeff = std::abs(coeff);
                        slack -= asserting_coeff;
                        m_lemma[0] = ~lit;
                    }
                    else {
                        ++num_skipped;
                        if (asserting_coeff < std::abs(coeff)) {
                            m_lemma[0] = ~lit;
                            slack -= (std::abs(coeff) - asserting_coeff);
                            asserting_coeff = std::abs(coeff);
                        }
                    }
                }
                else if (lvl(lit) < m_conflict_lvl) {
                    slack -= std::abs(coeff);
                    m_lemma.push_back(~lit);
                }
            }
        }
        if (slack >= 0) {
            TRACE(pb, tout << "slack is non-negative\n";);
            IF_VERBOSE(20, verbose_stream() << "(sat.card slack: " << slack << " skipped: " << num_skipped << ")\n";);
            return false;
        }
        if (m_overflow) {
            TRACE(pb, tout << "overflow\n";);
            return false;
        }        
        if (m_lemma[0] == sat::null_literal) {
            if (m_lemma.size() == 1) {
                s().set_conflict(sat::justification(0));
            }
            TRACE(pb, tout << "no asserting literal\n";);
            return false;
        }

        TRACE(pb, tout << m_lemma << "\n";);

        if (get_config().m_drat && m_solver) {
            s().m_drat.add(m_lemma, sat::status::th(true, get_id()));
        }

        s().m_lemma.reset();
        s().m_lemma.append(m_lemma);
        for (unsigned i = 1; i < m_lemma.size(); ++i) {
            CTRACE(pb, s().is_marked(m_lemma[i].var()), tout << "marked: " << m_lemma[i] << "\n";);
            s().mark(m_lemma[i].var());
        }
        return true;
    }

    /*
      \brief compute a cut for current resolvent.
     */

    void solver::cut() {

        // bypass cut if there is a unit coefficient
        for (bool_var v : m_active_vars) {
            if (1 == get_abs_coeff(v)) return;
        }

        unsigned g = 0;

        for (unsigned i = 0; g != 1 && i < m_active_vars.size(); ++i) {
            bool_var v = m_active_vars[i];
            unsigned coeff = get_abs_coeff(v);
            if (coeff == 0) {
                continue;
            }
            if (m_bound < coeff) {
                int64_t bound64 = m_bound;
                if (get_coeff(v) > 0) {
                    m_coeffs[v] = bound64;
                }
                else {
                    m_coeffs[v] = -bound64;
                }
                coeff = m_bound;
            }
            SASSERT(0 < coeff && coeff <= m_bound);
            if (g == 0) {
                g = coeff;
            }
            else {
                g = u_gcd(g, coeff);
            }
        }

        if (g >= 2) {
            reset_active_var_set();
            unsigned j = 0, sz = m_active_vars.size();
            for (unsigned i = 0; i < sz; ++i) {
                bool_var v = m_active_vars[i];
                int64_t c = m_coeffs[v];
                if (!test_and_set_active(v) || c == 0) continue;
                m_coeffs[v] /= static_cast<int>(g);
                m_active_vars[j++] = v;
            }
            m_active_vars.shrink(j);
            m_bound = (m_bound + g - 1) / g;
            ++m_stats.m_num_cut;
        }        
    }

    void solver::process_card(card& c, unsigned offset) {
        literal lit = c.lit();
        SASSERT(c.k() <= c.size());       
        SASSERT(lit == sat::null_literal || value(lit) != l_undef);
        SASSERT(0 < offset);
        for (unsigned i = c.k(); i < c.size(); ++i) {
            process_antecedent(c[i], offset);
        }
        for (unsigned i = 0; i < c.k(); ++i) {
            inc_coeff(c[i], offset);                        
        }
        if (lit != sat::null_literal) {
            uint64_t offset1 = static_cast<uint64_t>(offset) * c.k();
            if (offset1 > UINT_MAX) {
                m_overflow = true;
            }
            if (value(lit) == l_true) {
                process_antecedent(~lit, static_cast<unsigned>(offset1));
            }
            else {
                process_antecedent(lit, static_cast<unsigned>(offset1));
            }
        }
    }

    void solver::process_antecedent(literal l, unsigned offset) {
        SASSERT(value(l) == l_false);
        bool_var v = l.var();
        unsigned level = lvl(v);

        if (!s().is_marked(v) && level == m_conflict_lvl) {
            s().mark(v);
            ++m_num_marks;
            if (_debug_conflict && _debug_consequent != sat::null_literal && _debug_var2position[_debug_consequent.var()] < _debug_var2position[l.var()]) {
                IF_VERBOSE(0, verbose_stream() << "antecedent " << l << " is above consequent in stack\n";);
            }
        }
        inc_coeff(l, offset);                
    }   

    literal solver::get_asserting_literal(literal p) {
        if (get_abs_coeff(p.var()) != 0) {
            return p;
        }
        unsigned level = 0;        
        for (unsigned i = 0; i < m_active_vars.size(); ++i) { 
            bool_var v = m_active_vars[i];
            literal lit(v, get_coeff(v) < 0);
            if (value(lit) == l_false && lvl(lit) > level) {
                p = lit;
                level = lvl(lit);
            }
        }
        return p;        
    }

    solver::solver(euf::solver& ctx, euf::theory_id id) :
        solver(ctx.get_manager(), ctx.get_si(), id) {
        m_ctx = &ctx;
    }

    solver::solver(ast_manager& m, sat::sat_internalizer& si, euf::theory_id id)
        : euf::th_solver(m, symbol("pb"), id),
          si(si), m_pb(m),
          m_lookahead(nullptr), 
          m_constraint_id(0), m_ba(*this), m_sort(m_ba) {
        m_num_propagations_since_pop = 0;
    }

    solver::~solver() {
        m_stats.reset();
        for (constraint* c : m_constraints) 
            c->deallocate(m_allocator);        
        for (constraint* c : m_learned) 
            c->deallocate(m_allocator);        
    }

    void solver::add_at_least(bool_var v, literal_vector const& lits, unsigned k) {
        literal lit = v == sat::null_bool_var ? sat::null_literal : literal(v, false);
        add_at_least(lit, lits, k, m_is_redundant);
    }

    constraint* solver::add_at_least(literal lit, literal_vector const& lits, unsigned k, bool learned) {
        if (k == 1 && lit == sat::null_literal) {
            literal_vector _lits(lits);
            s().mk_clause(_lits.size(), _lits.data(), sat::status::th(learned, get_id()));
            return nullptr;
        }

        if (k == 0) {
            if (lit != sat::null_literal)
                s().add_clause(lit, sat::status::th(false, get_id()));
            return nullptr;
        }

        if (k > lits.size()) {
            if (lit == sat::null_literal)
                s().add_clause(0, nullptr, sat::status::th(false, get_id()));
            else
                s().add_clause(~lit, sat::status::th(false, get_id()));
            return nullptr;
        }

        if (!learned && clausify(lit, lits.size(), lits.data(), k)) {
            return nullptr;
        }
        init_visited();
        for (literal l : lits) {
            auto v = l.var();
            if (is_visited(v)) {
                svector<wliteral> wlits;
                for (literal l : lits) 
                    wlits.push_back(wliteral(1, l));
                return add_pb_ge(lit, wlits, k, learned);
            }
            mark_visited(v);
        }
        void * mem = m_allocator.allocate(card::get_obj_size(lits.size()));
        sat::constraint_base::initialize(mem, this);
        card* c = new (sat::constraint_base::ptr2mem(mem)) card(next_id(), lit, lits, k);
        c->set_learned(learned);
        add_constraint(c);
        return c;
    }

    void solver::add_constraint(constraint* c) {
        literal_vector lits(c->literals());
        if (c->learned()) {
            m_learned.push_back(c);
        }
        else {
            SASSERT(!m_solver || s().at_base_lvl());
            m_constraints.push_back(c);
        }
        literal lit = c->lit();
        if (c->learned() && m_solver && !s().at_base_lvl()) {
            SASSERT(lit == sat::null_literal);
            // gets initialized after backjump.
            m_constraint_to_reinit.push_back(c);
        }
        else if (lit == sat::null_literal) {
            init_watch(*c);
            if (c->is_pb()) 
                validate_watch(c->to_pb(), sat::null_literal);
        }
        else {
            if (m_solver) m_solver->set_external(lit.var());
            c->watch_literal(*this, lit);
            c->watch_literal(*this, ~lit);
        }     
        if (!c->well_formed()) 
            IF_VERBOSE(0, verbose_stream() << *c << "\n");
        SASSERT(c->well_formed());
        VERIFY(c->well_formed());
        if (m_solver && m_solver->get_config().m_drat) {
            auto * out = s().get_drat().out();
            if (out)
                *out << "c ba constraint " << *c << " 0\n";
        }
    }


    bool solver::init_watch(constraint& c) {
        return !inconsistent() && c.init_watch(*this);
    }

    lbool solver::add_assign(constraint& c, literal l) {
        switch (c.tag()) {
        case pb::tag_t::card_t: return add_assign(c.to_card(), l);
        case pb::tag_t::pb_t: return add_assign(c.to_pb(), l);
        }
        UNREACHABLE();
        return l_undef;
    }

    constraint* solver::add_pb_ge(literal lit, svector<wliteral> const& wlits, unsigned k, bool learned) {
        bool units = true;
        for (auto [w, l] : wlits) 
            units &= w == 1;

        if (k == 0) {
            if (lit != sat::null_literal)
                s().add_clause(lit, sat::status::th(false, get_id()));
            return nullptr;
        }
        rational weight(0);
        for (auto const &[w, l] : wlits)
            weight += w;
        if (weight < k) {
            if (lit == sat::null_literal)
                s().add_clause(0, nullptr, sat::status::th(false, get_id()));
            else
                s().add_clause(~lit, sat::status::th(false, get_id()));
            return nullptr;
        }
        init_visited();
        for (auto const&[w, l] : wlits) {
            auto v = l.var();
            if (is_visited(v)) {
                svector<wliteral> wlits2(wlits);
                auto [sz, k2] = normalize(wlits2.data(), wlits2.data() + wlits2.size(), k);
                wlits2.shrink(sz);
                return add_pb_ge(lit, wlits2, k2, learned);
            }
            mark_visited(v);
        }
        if (!learned) {
            for (auto [w, l] : wlits) 
                s().set_external(l.var()); 
        }
        if (units || k == 1) {
            literal_vector lits;
            for (auto [w, l] : wlits) lits.push_back(l);
            return add_at_least(lit, lits, k, learned);
        }
        void * mem = m_allocator.allocate(pbc::get_obj_size(wlits.size()));
        sat::constraint_base::initialize(mem, this);
        pbc* p = new (sat::constraint_base::ptr2mem(mem)) pbc(next_id(), lit, wlits, k);
        p->set_learned(learned);
        add_constraint(p);
        return p;
    }

    void solver::add_pb_ge(bool_var v, bool sign, svector<wliteral> const& wlits, unsigned k) {
        literal lit = v == sat::null_bool_var ? sat::null_literal : literal(v, sign);
        add_pb_ge(lit, wlits, k, m_is_redundant);
    }

    bool solver::is_external(bool_var v) {
        return false;
    }

    /*
      \brief return true to keep watching literal.
    */
    bool solver::propagated(literal l, sat::ext_constraint_idx idx) {
        SASSERT(value(l) == l_true);
        constraint& c = index2constraint(idx);
        if (c.lit() != sat::null_literal && l.var() == c.lit().var()) {
            init_watch(c);
            return true;
        }
        else if (c.lit() != sat::null_literal && value(c.lit()) != l_true) {
            return true;
        }
        else {
            return l_undef != add_assign(c, ~l);
        }
    }


    double solver::get_reward(literal l, sat::ext_justification_idx idx, sat::literal_occs_fun& occs) const {
        constraint const& c = index2constraint(idx);
        return c.get_reward(*this, occs);
    }


    void solver::ensure_parity_size(bool_var v) {
        if (m_parity_marks.size() <= static_cast<unsigned>(v)) {
            m_parity_marks.resize(static_cast<unsigned>(v) + 1, 0);
        }
    }
    
    unsigned solver::get_parity(bool_var v) {
        return m_parity_marks.get(v, 0);
    }

    void solver::inc_parity(bool_var v) {
        ensure_parity_size(v);
        m_parity_marks[v]++;
    }

    void solver::reset_parity(bool_var v) {
        ensure_parity_size(v);
        m_parity_marks[v] = 0;
    }
    

    /**
       \brief retrieve a sufficient set of literals from p that imply l.
       
       Find partition: 

         - Ax + coeff*l + B*y >= k
         - all literals in x are false.
         - B < k

       Then x is an explanation for l

     */

    bool solver::assigned_above(literal above, literal below) {
        unsigned l = lvl(above);
        SASSERT(l == lvl(below));
        if (l == 0) return false;
        unsigned start = s().m_scopes[l-1].m_trail_lim;
        literal_vector const& lits = s().m_trail;
        for (unsigned sz = lits.size(); sz-- > start; ) {
            if (lits[sz] == above) return true;
            if (lits[sz] == below) return false;
        }
        UNREACHABLE();
        return false;
    }

    void solver::get_antecedents(literal l, pbc const& p, literal_vector& r) {
        TRACE(pb, display(tout << l << " level: " << s().scope_lvl() << " ", p, true););
        SASSERT(p.lit() == sat::null_literal || value(p.lit()) == l_true);

        if (p.lit() != sat::null_literal) {
            r.push_back(p.lit());
        }

        unsigned k = p.k();

        if (_debug_conflict) {
            IF_VERBOSE(0, display(verbose_stream(), p, true);
                       verbose_stream() << "literal: " << l << " value: " << value(l) << " num-watch: " << p.num_watch() << " slack: " << p.slack() << "\n";);
        }

        if (value(l) == l_false) {
            // The literal comes from a conflict.
            // it is forced true, but assigned to false.
            unsigned slack = 0;
            for (auto [w, lit] : p) {
                if (value(lit) != l_false) {
                    slack += w;
                }
            }
            SASSERT(slack < k);
            for (auto [w, lit] : p) {
                if (lit != l && value(lit) == l_false) {
                    if (slack + w < k) {
                        slack += w;
                    }
                    else {
                        r.push_back(~lit);
                    }
                } 
            }
        }
        else {
            // comes from a unit propagation
            SASSERT(value(l) == l_true);
            unsigned coeff = 0, j = 0;
            for (; j < p.size(); ++j) {
                auto [w, lit] = p[j];
                if (lit == l) {
                    coeff = w;
                    break;
                }
            }
            
            ++j;
            if (j < p.num_watch()) {
                j = p.num_watch();
            }
            CTRACE(pb, coeff == 0, display(tout << l << " coeff: " << coeff << "\n", p, true);); 
            
            if (_debug_conflict) {
                IF_VERBOSE(0, verbose_stream() << "coeff " << coeff << "\n";);
            }

            SASSERT(coeff > 0);
            unsigned slack = p.max_sum() - coeff;
            
            // we need antecedents to be deeper than alit.
            for (; j < p.size(); ++j) {
                auto [w, lit] = p[j];
                if (l_false != value(lit)) {
                    // skip
                }
                else if (lvl(lit) > lvl(l)) {
                    // skip
                }
                else if (lvl(lit) == lvl(l) && assigned_above(~lit, l)) {
                    // skip
                }
                else if (slack + w < k) {
                    slack += w;
                }
                else {
                    r.push_back(~lit); 
                }
            }
        }
        SASSERT(validate_unit_propagation(p, r, l));
    }

    bool solver::is_extended_binary(sat::ext_justification_idx idx, literal_vector & r) {
        return index2constraint(idx).is_extended_binary(r);
    }


    void solver::get_antecedents(literal l, card const& c, literal_vector& r) {
        if (l == ~c.lit()) {
            for (unsigned i = c.k() - 1; i < c.size(); ++i) {
                VERIFY(value(c[i]) == l_false);
                r.push_back(~c[i]);
            }   
            return;
        }
        DEBUG_CODE(
            bool found = false;
            for (unsigned i = 0; !found && i < c.k(); ++i) {
                found = c[i] == l;
            }
            CTRACE(pb,!found, s().display(tout << l << ":" << c << "\n"););
            SASSERT(found););
        
        VERIFY(c.lit() == sat::null_literal || value(c.lit()) != l_false);
        if (c.lit() != sat::null_literal) r.push_back(value(c.lit()) == l_true ? c.lit() : ~c.lit());
        for (unsigned i = c.k(); i < c.size(); ++i) {
            SASSERT(value(c[i]) == l_false);
            r.push_back(~c[i]);
        }
    }


    // ----------------------------
    // constraint generic methods

    void solver::get_antecedents(literal l, sat::ext_justification_idx idx, literal_vector & r, bool probing) {
        get_antecedents(l, index2constraint(idx), r, probing);
    }


    void solver::get_antecedents(literal l, constraint const& c, literal_vector& r, bool probing) {
        switch (c.tag()) {
        case pb::tag_t::card_t: get_antecedents(l, c.to_card(), r); break;
        case pb::tag_t::pb_t: get_antecedents(l, c.to_pb(), r); break;
        default: UNREACHABLE(); break;            
        }
        if (get_config().m_drat && m_solver && !probing) {
            literal_vector lits;
            for (literal lit : r) 
                lits.push_back(~lit);
            lits.push_back(l);
            s().m_drat.add(lits, sat::status::th(true, get_id()));
        }
    }

    void solver::clear_watch(constraint& c) {
        c.clear_watch(*this);
    }

    void solver::remove_constraint(constraint& c, char const* reason) {
        TRACE(pb, display(tout << "remove ", c, true) << " " << reason << "\n";);
        IF_VERBOSE(21, display(verbose_stream() << "remove " << reason << " ", c, true););
        c.nullify_tracking_literal(*this);
        clear_watch(c);
        c.set_removed();
        m_constraint_removed = true;
    }

    // --------------------------------
    // validation

    bool solver::validate_unit_propagation(constraint const& c, literal l) const {
        return true;
        return c.validate_unit_propagation(*this, l);
    }

    bool solver::validate_conflict(constraint const& c) const {
        return eval(c) == l_false;
    }

    lbool solver::eval(constraint const& c) const {
        lbool v1 = c.lit() == sat::null_literal ? l_true : value(c.lit());
        return eval(v1, c.eval(*this));
    }

    lbool solver::eval(sat::model const& m, constraint const& c) const {
        lbool v1 = c.lit() == sat::null_literal ? l_true : pb::value(m, c.lit());
        return eval(v1, c.eval(m));
    }

    lbool solver::eval(lbool a, lbool b) const {
        if (a == l_undef || b == l_undef) return l_undef;
        return (a == b) ? l_true : l_false;
    }

    bool solver::validate() {
        if (!validate_watch_literals()) {
            return false;
        }
        for (constraint* c : m_constraints) {
            if (!validate_watched_constraint(*c)) 
                return false;
        }
        for (constraint* c : m_learned) {
            if (!validate_watched_constraint(*c)) 
                return false;
        }
        return true;
    }

    bool solver::validate_watch_literals() const {
        for (unsigned v = 0; v < s().num_vars(); ++v) {
            literal lit(v, false);
            if (lvl(lit) == 0) continue;
            if (!validate_watch_literal(lit)) return false;
            if (!validate_watch_literal(~lit)) return false;
        }        
        return true;
    }

    bool solver::validate_watch_literal(literal lit) const {
        if (lvl(lit) == 0) return true;
        for (auto const & w : get_wlist(lit)) {
            if (w.get_kind() == sat::watched::EXT_CONSTRAINT) {
                constraint const& c = index2constraint(w.get_ext_constraint_idx());
                if (!c.is_watching(~lit) && lit.var() != c.lit().var()) {
                    IF_VERBOSE(0, display(verbose_stream() << lit << " " << lvl(lit) << " is not watched in " << c << "\n", c, true););
                    UNREACHABLE();
                    return false;
                }
            }
        }
        return true;
    }

    bool solver::validate_watched_constraint(constraint const& c) const {
        if (c.is_pb() && !validate_watch(c.to_pb(), sat::null_literal)) {
            return false;
        }
        if (c.lit() != sat::null_literal && value(c.lit()) != l_true) return true;
        SASSERT(c.lit() == sat::null_literal || lvl(c.lit()) == 0 || (c.is_watched(*this, c.lit()) && c.is_watched(*this, ~c.lit())));
        if (eval(c) == l_true) 
            return true;
        
        literal_vector lits(c.literals());
        for (literal l : lits) {
            if (lvl(l) == 0) continue;
            bool found = c.is_watched(*this, l);
            if (found != c.is_watching(l)) {

                IF_VERBOSE(0, 
                           verbose_stream() << "Discrepancy of watched literal: " << l << " id: " << c.id() 
                           << " clause: " << c << (found?" is watched, but shouldn't be":" not watched, but should be") << "\n";
                           s().display_watch_list(verbose_stream() <<  l << ": ", get_wlist(l)) << "\n";
                           s().display_watch_list(verbose_stream() << ~l << ": ", get_wlist(~l)) << "\n";
                           verbose_stream() << "value: " << value(l) << " level: " << lvl(l) << "\n";
                           display(verbose_stream(), c, true);
                           if (c.lit() != sat::null_literal) verbose_stream() << value(c.lit()) << "\n";);

                IF_VERBOSE(0, s().display_watches(verbose_stream()));

                UNREACHABLE();
                return false;
            }
        }
        return true;
    }

    bool solver::validate_watch(pbc const& p, literal alit) const {
        if (p.lit() == sat::null_literal || value(p.lit()) != l_true)
            return true;
        for (unsigned i = 0; i < p.size(); ++i) {
            auto [w, l] = p[i];
            if (l != alit && lvl(l) != 0 && p.is_watched(*this, l) != (i < p.num_watch())) {
                IF_VERBOSE(0, display(verbose_stream(), p, true);
                           verbose_stream() << "literal " << l << " at position " << i << " " << p.is_watched(*this, l) << "\n";);
                UNREACHABLE();
                return false;
            }
        }
        unsigned slack = 0;
        for (unsigned i = 0; i < p.num_watch(); ++i) {
            auto [w, l] = p[i];
            slack += w;
        }
        if (slack != p.slack()) {
            IF_VERBOSE(0, display(verbose_stream(), p, true););
            UNREACHABLE();
            return false;
        }
        return true;
    }

    
    /**
       \brief Lex on (glue, size)
    */
    struct constraint_glue_psm_lt {
        bool operator()(constraint const * c1, constraint const * c2) const {
            return 
                (c1->glue()  < c2->glue()) ||
                (c1->glue() == c2->glue() && 
                 (c1->psm() < c2->psm() || 
                  (c1->psm() == c2->psm() && c1->size() < c2->size())));
        }
    };

    void solver::update_psm(constraint& c) const {
        unsigned r = 0;
        switch (c.tag()) {            
        case pb::tag_t::card_t:
            for (literal l : c.to_card()) {                
                if (s().m_phase[l.var()] == !l.sign()) ++r;
            }
            break;
        case pb::tag_t::pb_t:
            for (auto [w, l] : c.to_pb()) {                
                if (s().m_phase[l.var()] == !l.sign()) ++r;
            }
            break;
        default:
            break;
        }
        c.set_psm(r);
    }
    
    void solver::gc() {
        if (m_learned.size() >= 2 * m_constraints.size() && 
            (s().at_search_lvl() || s().at_base_lvl())) {
            for (auto & c : m_learned) update_psm(*c);
            std::stable_sort(m_learned.begin(), m_learned.end(), constraint_glue_psm_lt());
            gc_half("glue-psm");
            cleanup_constraints(m_learned, true);
        }
    }

    void solver::gc_half(char const* st_name) {
        TRACE(pb, tout << "gc\n";);
        unsigned sz     = m_learned.size();
        unsigned new_sz = sz/2;
        unsigned removed = 0;
        for (unsigned i = new_sz; i < sz; ++i) {
            constraint* c = m_learned[i];
            if (!m_constraint_to_reinit.contains(c)) {
                remove_constraint(*c, "gc");
                c->deallocate(m_allocator);
                ++removed;
            }
            else {
                m_learned[new_sz++] = c;
            }
        }
        m_stats.m_num_gc += removed;
        m_learned.shrink(new_sz);
        IF_VERBOSE(2, verbose_stream() << "(sat-gc :strategy " << st_name << " :deleted " << removed << ")\n";);
    }


    void solver::gc_vars(unsigned num_vars) {
        gc_vars(num_vars, m_constraints);
        gc_vars(num_vars, m_learned);
    }

    void solver::gc_vars(unsigned num_vars, ptr_vector<constraint>& cs) {
        unsigned j = 0;
        for (unsigned i = 0; i < cs.size(); ++i) {
            auto* c = cs[i];
            unsigned m = c->fold_max_var(0);
            if (m >= num_vars) {
                clear_watch(*c);
                c->nullify_tracking_literal(*this);
                c->deallocate(m_allocator);
            }
            else 
                cs[j++] = c;
        }
        cs.shrink(j);
    }


    lbool solver::add_assign(card& c, literal alit) {
        // literal is assigned to false.        
        unsigned sz = c.size();
        unsigned bound = c.k();
        TRACE(pb, tout << "assign: " << c.lit() << ": " << ~alit << "@" << lvl(~alit) << " " << c << "\n";);

        SASSERT(0 < bound && bound <= sz);
        if (bound == sz) {
            if (c.lit() != sat::null_literal && value(c.lit()) == l_undef) {
                assign(c, ~c.lit());
                return inconsistent() ? l_false : l_true;
            }
            set_conflict(c, alit);
            return l_false;
        }
        SASSERT(value(alit) == l_false);
        VERIFY(c.lit() == sat::null_literal || value(c.lit()) != l_false);
        unsigned index = 0;
        for (index = 0; index <= bound; ++index) {
            if (c[index] == alit) {
                break;
            }
        }
        if (index == bound + 1) {
            // literal is no longer watched.
            return l_undef;
        }
        VERIFY(index <= bound);
        VERIFY(c[index] == alit);
        
        // find a literal to swap with:
        for (unsigned i = bound + 1; i < sz; ++i) {
            literal lit2 = c[i];
            if (value(lit2) != l_false) {
                c.swap(index, i);
                c.watch_literal(*this, lit2);
                return l_undef;
            }
        }

        // conflict
        if (bound != index && value(c[bound]) == l_false) {
            TRACE(pb, tout << "conflict " << c[bound] << " " << alit << "\n";);
            if (c.lit() != sat::null_literal && value(c.lit()) == l_undef) {
                if (index + 1 < bound) c.swap(index, bound - 1);
                assign(c, ~c.lit());
                return inconsistent() ? l_false : l_true;
            }
            set_conflict(c, alit);
            return l_false;
        }

        if (index != bound) {
            c.swap(index, bound);
        }        

        // TRACE(pb, tout << "no swap " << index << " " << alit << "\n";);
        // there are no literals to swap with,
        // prepare for unit propagation by swapping the false literal into 
        // position bound. Then literals in positions 0..bound-1 have to be
        // assigned l_true.

        if (c.lit() != sat::null_literal && value(c.lit()) == l_undef) {
            return l_true;
        }

        for (unsigned i = 0; i < bound; ++i) {
            assign(c, c[i]);
        }

        if (c.learned() && c.glue() > 2) {
            unsigned glue;
            if (s().num_diff_false_levels_below(c.size(), c.begin(), c.glue()-1, glue)) {
                c.set_glue(glue);
            }
        }

        return inconsistent() ? l_false : l_true;
    }

    void solver::asserted(literal l) {
    }


    sat::check_result solver::check() { return sat::check_result::CR_DONE; }

    void solver::push() {
        m_constraint_to_reinit_lim.push_back(m_constraint_to_reinit.size());
    }

    void solver::pop(unsigned n) {        
        TRACE(sat_verbose, tout << "pop:" << n << "\n";);
        unsigned new_lim = m_constraint_to_reinit_lim.size() - n;
        m_constraint_to_reinit_last_sz = m_constraint_to_reinit_lim[new_lim];
        m_constraint_to_reinit_lim.shrink(new_lim);
        m_num_propagations_since_pop = 0;
    }

    void solver::pop_reinit() {
        unsigned sz = m_constraint_to_reinit_last_sz;
        for (unsigned i = sz; i < m_constraint_to_reinit.size(); ++i) {
            constraint* c = m_constraint_to_reinit[i];
            if (!init_watch(*c) && !s().at_base_lvl()) {
                m_constraint_to_reinit[sz++] = c;
            }
        }
        m_constraint_to_reinit.shrink(sz);        
    }

    void solver::simplify() {
        if (!s().at_base_lvl()) 
            s().pop_to_base_level();
        if (s().inconsistent())
            return;
        unsigned trail_sz = 0, count = 0;
        do {
            trail_sz = s().init_trail_size();
            m_simplify_change = false;
            m_clause_removed = false;
            m_constraint_removed = false;
            for (unsigned sz = m_constraints.size(), i = 0; i < sz; ++i) simplify(*m_constraints[i]);
            for (unsigned sz = m_learned.size(), i = 0; i < sz; ++i) simplify(*m_learned[i]);
            init_use_lists();
            // remove_unused_defs();
            set_non_external();
            elim_pure();
            for (unsigned sz = m_constraints.size(), i = 0; i < sz; ++i) subsumption(*m_constraints[i]);
            for (unsigned sz = m_learned.size(), i = 0; i < sz; ++i) subsumption(*m_learned[i]);    
            unit_strengthen();
            cleanup_clauses();
            cleanup_constraints();

            count++;
        }        
        while (count < 10 && (m_simplify_change || trail_sz < s().init_trail_size()));

        gc();

        // validate_eliminated();

        IF_VERBOSE(1, 
                   unsigned subs = m_stats.m_num_bin_subsumes + m_stats.m_num_clause_subsumes + m_stats.m_num_pb_subsumes;
                   verbose_stream() << "(ba.simplify" << " :constraints " << m_constraints.size();
                   if (!m_learned.empty()) verbose_stream() << " :lemmas " << m_learned.size();
                   if (subs > 0) verbose_stream() << " :subsumes " << subs;
                   if (m_stats.m_num_gc > 0) verbose_stream() << " :gc " << m_stats.m_num_gc;
                   verbose_stream() << ")\n";);

        // IF_VERBOSE(0, s().display(verbose_stream()));
        // mutex_reduction();
        // if (s().m_clauses.size() < 80000) lp_lookahead_reduction();
    }

    void solver::mutex_reduction() {
        literal_vector lits;
        for (unsigned v = 0; v < s().num_vars(); ++v) {
            lits.push_back(literal(v, false));
            lits.push_back(literal(v, true));
        }
        vector<literal_vector> mutexes;
        s().find_mutexes(lits, mutexes);
        for (literal_vector& mux : mutexes) {
            if (mux.size() > 2) {
                IF_VERBOSE(1, verbose_stream() << "mux: " << mux << "\n";);
                for (unsigned i = 0; i < mux.size(); ++i) mux[i].neg(); 
                add_at_least(sat::null_literal, mux, mux.size() - 1, false);
            }
        }
    }

    // -------------------------
    // sorting networks
    literal solver::ba_sort::mk_false() {
        return ~mk_true();
    }

    literal solver::ba_sort::mk_true() {
        if (m_true == sat::null_literal) {
            bool_var v = s.s().mk_var(false, false);
            m_true = literal(v, false);
            s.s().mk_clause(1,&m_true);
        }
        VERIFY(m_true != sat::null_literal);
        return m_true;
    }

    literal solver::ba_sort::mk_not(literal l) { 
        return ~l; 
    }

    literal solver::ba_sort::fresh(char const*) {
        bool_var v = s.s().mk_var(false, true);
        return literal(v, false);
    }


    literal solver::ba_sort::mk_max(unsigned n, literal const* lits) {
        m_lits.reset();        
        for (unsigned i = 0; i < n; ++i) {
            if (lits[i] == m_true) return m_true;
            if (lits[i] == ~m_true) continue;
            m_lits.push_back(lits[i]);
        }
        switch (m_lits.size()) {
        case 0: 
            return ~m_true;
        case 1: 
            return m_lits[0];
        default: {
            literal max = fresh("max");
            for (unsigned i = 0; i < n; ++i) {
                s.s().mk_clause(~m_lits[i], max);
            }
            m_lits.push_back(~max);
            s.s().mk_clause(m_lits.size(), m_lits.data());
            return max;
        }
        }
    }

    literal solver::ba_sort::mk_min(unsigned n, literal const* lits) {
        m_lits.reset();        
        for (unsigned i = 0; i < n; ++i) {
            if (lits[i] == ~m_true) return ~m_true;
            if (lits[i] == m_true) continue;
            m_lits.push_back(lits[i]);
        }
        switch (m_lits.size()) {
        case 0: 
            return m_true;
        case 1: 
            return m_lits[0];
        default: {
            literal min = fresh("min");
            for (unsigned i = 0; i < n; ++i) {
                s.s().mk_clause(~min, m_lits[i]);
                m_lits[i] = ~m_lits[i];
            }
            m_lits.push_back(min);
            s.s().mk_clause(m_lits.size(), m_lits.data());
            return min;
        }
        }
    }

    void solver::ba_sort::mk_clause(unsigned n, literal const* lits) {
        m_lits.reset();
        m_lits.append(n, lits);
        s.s().mk_clause(n, m_lits.data());
    }

    std::ostream& solver::ba_sort::pp(std::ostream& out, literal l) const {
        return out << l;
    }

    
    // -------------------------------
    // set literals equivalent

    void solver::reserve_roots() {
        m_root_vars.reserve(s().num_vars(), false);
        for (unsigned i = m_roots.size(); i < 2 * s().num_vars(); ++i) {
            m_roots.push_back(sat::to_literal(i));
        }
    }

    bool solver::set_root(literal l, literal r) {
        if (s().is_assumption(l.var())) 
            return false;
        reserve_roots();
        m_roots[l.index()] = r;
        m_roots[(~l).index()] = ~r;
        m_roots[r.index()] = r;
        m_roots[(~r).index()] = ~r;
        m_root_vars[l.var()] = true;
        return true;
    }

    void solver::flush_roots() {
        if (m_roots.empty())
            return;
        reserve_roots();
        DEBUG_CODE(validate(););
        m_constraint_removed = false;
        for (unsigned sz = m_constraints.size(), i = 0; i < sz; ++i) 
            flush_roots(*m_constraints[i]);
        for (unsigned sz = m_learned.size(), i = 0; i < sz; ++i) 
            flush_roots(*m_learned[i]);
        cleanup_constraints();
        DEBUG_CODE(validate(););
        DEBUG_CODE(validate_eliminated(););
    }

    void solver::validate_eliminated() {
        validate_eliminated(m_constraints);
        validate_eliminated(m_learned);
    }

    void solver::validate_eliminated(ptr_vector<constraint> const& cs) {
        for (constraint const* c : cs) {
            if (c->learned())
                continue;
            for (auto l : constraint::literal_iterator(*c))
                VERIFY(!s().was_eliminated(l.var()));
        }
    }

    void solver::recompile(constraint& c) {
        if (c.id() == _bad_id) {
            IF_VERBOSE(0, display(verbose_stream() << "recompile\n", c, true););
        }
        switch (c.tag()) {
        case pb::tag_t::card_t:
            recompile(c.to_card());
            break;
        case pb::tag_t::pb_t:
            recompile(c.to_pb());
            break;
        default:
            UNREACHABLE();
        }                
    }

    void solver::recompile(card& c) {
        SASSERT(c.lit() == sat::null_literal || c.is_watched(*this, c.lit()));

        // pre-condition is that the literals, except c.lit(), in c are unwatched.
        //if (c.id() == _bad_id) std::cout << "recompile: " << c << "\n";
        m_weights.resize(2*s().num_vars(), 0);
        for (literal l : c) {
            ++m_weights[l.index()];
        }
        unsigned k = c.k();
        bool all_units = true;
        unsigned sz = c.size();
        unsigned_vector coeffs;
        literal_vector lits;
        unsigned j = 0;
        for (unsigned i = 0; i < sz && 0 < k; ++i) {
            literal l = c[i];
            unsigned w = m_weights[l.index()];
            unsigned w2 = m_weights[(~l).index()];
            if (w == 0 || w < w2) {
                continue;
            }
            else if (k <= w2) {
                k = 0;
                break;
            }
            else {
                SASSERT(w2 <= w && w2 < k);
                k -= w2;
                w -= w2;
                m_weights[(~l).index()] = 0;        
                m_weights[l.index()] = 0;        
                if (w == 0) {
                    continue;
                }    
                else {
                    all_units &= (w == 1);
                    coeffs.push_back(w);
                    c[j++] = l;
                }
            }
        }
        sz = j;

        // clear weights
        for (literal l : c) {
            m_weights[l.index()] = 0;
            m_weights[(~l).index()] = 0;
        }       

        if (k == 0 && c.lit() == sat::null_literal) {
            remove_constraint(c, "recompiled to true");
            return;
        }

        if (k == 1 && c.lit() == sat::null_literal) {
            literal_vector lits(sz, c.literals().data());
            s().mk_clause(sz, lits.data(), sat::status::th(c.learned(), get_id()));
            remove_constraint(c, "recompiled to clause");
            return;
        }

        if (sz == 0) {
            if (c.lit() == sat::null_literal) {
                if (k > 0) {
                    s().mk_clause(0, nullptr, sat::status::th(false, get_id()));
                }
            }
            else if (k > 0) {
                literal lit = ~c.lit();
                s().mk_clause(1, &lit, sat::status::th(c.learned(), get_id()));
            }
            else {
                literal lit = c.lit();
                s().mk_clause(1, &lit, sat::status::th(c.learned(), get_id()));
            }
            remove_constraint(c, "recompiled to clause");
            return;
        }
        if (all_units && sz < k) {
            if (c.lit() == sat::null_literal) {
                s().mk_clause(0, nullptr, sat::status::th(c.learned(), get_id()));
            }
            else {
                literal lit = ~c.lit();
                s().mk_clause(1, &lit, sat::status::th(c.learned(), get_id()));
            }
            remove_constraint(c, "recompiled to clause");
            return;            
        }
        VERIFY(!all_units || c.size() - c.k() >= sz - k);
        c.set_size(sz);
        c.set_k(k);    

        if (all_units && clausify(c)) {
            return;
        }

        if (!all_units) {            
            TRACE(pb, tout << "replacing by pb: " << c << "\n";);
            m_wlits.reset();
            for (unsigned i = 0; i < sz; ++i) {
                m_wlits.push_back(wliteral(coeffs[i], c[i]));
            }
            literal root = c.lit();
            remove_constraint(c, "recompiled to pb");
            add_pb_ge(root, m_wlits, k, c.learned());
        }
        else {
            if (c.lit() == sat::null_literal || value(c.lit()) == l_true) {
                init_watch(c);
            }
            SASSERT(c.lit() == sat::null_literal || c.is_watched(*this, c.lit()));
            SASSERT(c.well_formed());
        }        
    }

    bool solver::clausify(literal lit, unsigned n, literal const* lits, unsigned k) {
        return false;
        bool is_def = lit != sat::null_literal;
        if ((!is_def || !s().was_eliminated(lit)) && 
            !std::any_of(lits, lits + n, [&](literal l) { return s().was_eliminated(l); })) {
            literal def_lit = m_sort.ge(is_def, k, n, lits);
            if (is_def) {
                s().mk_clause(~lit,  def_lit);
                s().mk_clause( lit, ~def_lit);
            }
            return true;
        }
        return false;
    }


    bool solver::clausify(card& c) {
        return false;
        if (get_config().m_card_solver)
            return false;

        //
        // TBD: conditions for when to clausify are TBD and
        // handling of conditional cardinality as well.
        // 
        if (!c.learned() && clausify(c.lit(), c.size(), c.begin(), c.k())) {
            IF_VERBOSE(1, verbose_stream() << "clausify " << c << "\n";);                       
            // compiled
        }        
        remove_constraint(c, "recompiled to clauses");
        return true;        
    }

    bool solver::clausify(pbc& p) {
        return false;
        if (get_config().m_card_solver) 
            return false;
        
        bool ok = !p.learned();
        bool is_def = p.lit() != sat::null_literal;
        for (auto [w, lit] : p) {
            ok &= !s().was_eliminated(lit);
        }
        ok &= !is_def || !s().was_eliminated(p.lit());
        if (!ok) {
            remove_constraint(p, "recompiled to clauses");
            return true;
        }

        if (is_cardinality(p, m_lemma)) {
            literal lit = m_sort.ge(is_def, p.k(), m_lemma.size(), m_lemma.data());
            if (is_def) {
                s().mk_clause(p.lit(), ~lit);
                s().mk_clause(~p.lit(), lit);
            }
            remove_constraint(p, "recompiled to clauses");
            return true;
        }
        return false;
    }

    bool solver::is_cardinality(pbc const& p, literal_vector& lits) {
        lits.reset();
        p.size();
        for (auto [w, lit] : p) {
            if (lits.size() > 2*p.size() + w) {
                return false;
            }
            for (unsigned i = 0; i < w; ++i) {
                lits.push_back(lit);
            }
        }
        return true;
    }

    void solver::flush_roots(constraint& c) {
        if (c.lit() != sat::null_literal && !c.is_watched(*this, c.lit())) {
            c.watch_literal(*this, c.lit());
            c.watch_literal(*this, ~c.lit());
        }
        SASSERT(c.lit() == sat::null_literal || c.is_watched(*this, c.lit()));
        bool found = c.lit() != sat::null_literal && m_root_vars[c.lit().var()];
        for (unsigned i = 0; !found && i < c.size(); ++i) {
            found = m_root_vars[c.get_lit(i).var()];
        }
        if (!found)
            return;
        clear_watch(c);

        // this could create duplicate literals
        for (unsigned i = 0; i < c.size(); ++i) {
            literal lit = m_roots[c.get_lit(i).index()];
            c.set_lit(i, lit);
        }

        literal root = c.lit();
        if (root != sat::null_literal && m_roots[root.index()] != root) {
            root = m_roots[root.index()];
            c.nullify_tracking_literal(*this);
            c.update_literal(root);
            c.watch_literal(*this, root);
            c.watch_literal(*this, ~root);
        }

        bool found_dup = false;
        bool found_root = false;
        init_visited();
        for (unsigned i = 0; i < c.size(); ++i) {
            literal l = c.get_lit(i);
            if (is_visited(l)) {
                found_dup = true;
                break;
            }
            else {
                mark_visited(l);
                mark_visited(~l);
            }
        }
        for (unsigned i = 0; i < c.size(); ++i) {
            found_root |= c.get_lit(i).var() == root.var();
        }

        if (found_root) {
            split_root(c);
            c.negate();
            split_root(c);
            remove_constraint(c, "flush roots");
        }
        else if (found_dup) {
            recompile(c);
        }
        else {
            if (c.lit() == sat::null_literal || value(c.lit()) != l_undef) init_watch(c);            
            SASSERT(c.well_formed());
        }
    }

    unsigned solver::get_num_unblocked_bin(literal l) {
        return s().m_simplifier.num_nonlearned_bin(l);
    }

    /*
      \brief garbage collection.
      This entails 
      - finding pure literals, 
      - setting literals that are not used in the extension to non-external.
      - subsumption
      - resolution 
      - blocked literals
     */
    void solver::init_use_lists() {
        m_clause_use_list.init(s().num_vars());
        m_cnstr_use_list.reset();
        m_cnstr_use_list.resize(2*s().num_vars());
        for (sat::clause* c : s().m_clauses) {
            if (!c->frozen()) 
                m_clause_use_list.insert(*c);
        }
        for (constraint* cp : m_constraints) {
            literal lit = cp->lit();
            if (lit != sat::null_literal) {
                m_cnstr_use_list[lit.index()].push_back(cp);
                m_cnstr_use_list[(~lit).index()].push_back(cp);
            }
            for (literal l : constraint::literal_iterator(*cp)) {
                m_cnstr_use_list[l.index()].push_back(cp);
                if (lit != sat::null_literal) m_cnstr_use_list[(~l).index()].push_back(cp);
            }
        }
    }

    void solver::remove_unused_defs() {
        if (incremental_mode()) 
            return;
        // remove constraints where indicator literal isn't used.
        NOT_IMPLEMENTED_YET();
        // TODO: #6675
        // need to add this inequality to the model reconstruction
        // stack in order to produce correct models.
        for (constraint* cp : m_constraints) {
            constraint& c = *cp;
            literal lit = c.lit();
            if (lit != sat::null_literal &&
                value(lit) == l_undef && 
                use_count(lit) == 1 &&
                use_count(~lit) == 1 &&
                get_num_unblocked_bin(lit) == 0 && 
                get_num_unblocked_bin(~lit) == 0) {
                remove_constraint(c, "unused def");
            }
        }
    }

    bool solver::incremental_mode() const {
        sat_simplifier_params p(s().m_params);
        bool incremental_mode = s().get_config().m_incremental && !p.override_incremental();
        incremental_mode |=  s().tracking_assumptions();
        return incremental_mode;
    }
    
    unsigned solver::set_non_external() {
        // set variables to be non-external if they are not used in theory constraints.
        unsigned ext = 0;
        if (!incremental_mode() && s().get_extension() == this) {
            for (unsigned v = 0; v < s().num_vars(); ++v) {
                literal lit(v, false);
                if (s().is_external(v) && 
                    m_cnstr_use_list[lit.index()].empty() && 
                    m_cnstr_use_list[(~lit).index()].empty()) {
                    s().set_non_external(v);
                    ++ext;
                }            
            }
        }
        // ensure that lemmas use only non-eliminated variables
        for (constraint* cp : m_learned) {
            constraint& c = *cp;
            if (c.was_removed()) continue;
            SASSERT(c.lit() == sat::null_literal);
            for (unsigned i = 0; i < c.size(); ++i) {
                bool_var v = c.get_lit(i).var();
                if (s().was_eliminated(v)) {
                    remove_constraint(c, "contains eliminated var");                    
                    break;
                }
            }
        }
        return ext;
    }

    bool solver::elim_pure(literal lit) {
        if (value(lit) == l_undef && !m_cnstr_use_list[lit.index()].empty() && 
            use_count(~lit) == 0 && get_num_unblocked_bin(~lit) == 0) {
            IF_VERBOSE(100, verbose_stream() << "pure literal: " << lit << "\n";);
            s().assign_scoped(lit);
            return true;
        }
        return false;
    }

    unsigned solver::elim_pure() {
        if (!get_config().m_elim_vars || incremental_mode()) {
            return 0;
        }
        // eliminate pure literals
        unsigned pure_literals = 0;
        for (unsigned v = 0; v < s().num_vars(); ++v) {
            literal lit(v, false);
            if (value(v) != l_undef) continue;
            if (m_cnstr_use_list[lit.index()].empty() &&
                m_cnstr_use_list[(~lit).index()].empty()) continue;

            if (elim_pure(lit) || elim_pure(~lit)) {
                ++pure_literals;
            }
        }
        return pure_literals;
    }

    /**
     * Strengthen inequalities using binary implication information.
     *
     * x -> ~y, x -> ~z,   y + z + u >= 2
     * ----------------------------------
     *       y + z + u + ~x >= 3
     * 
     * for c : constraints
     *   for l : c:
     *    slack <- of c under root(~l)
     *    if slack < 0:
     *       add ~root(~l) to c, k <- k + 1
     */ 
    void solver::unit_strengthen() {
        return;

        // TODO - this is unsound exposed by 4_21_21_-1.txt

        sat::big big(s().m_rand);
        big.init(s(), true);
        for (unsigned sz = m_constraints.size(), i = 0; i < sz; ++i) 
            unit_strengthen(big, *m_constraints[i]);
        for (unsigned sz = m_learned.size(), i = 0; i < sz; ++i) 
            unit_strengthen(big, *m_learned[i]);          
    }

    void solver::unit_strengthen(sat::big& big, constraint& p) {
        if (p.lit() != sat::null_literal) 
            return;
        unsigned sz = p.size();
        for (unsigned i = 0; i < sz; ++i) {
            literal u = p.get_lit(i);
            literal r = big.get_root(u);
            if (r == u) continue;
            unsigned k = p.k(), b = 0;
            for (unsigned j = 0; j < sz; ++j) {
                literal v = p.get_lit(j);
                if (r == big.get_root(v)) {
                    b += p.get_coeff(j);
                }
            }            
            if (b > k) {
                r.neg();
                unsigned coeff = b - k;
                
                svector<wliteral> wlits;
                // add coeff * r to p
                wlits.push_back(wliteral(coeff, r));
                for (unsigned j = 0; j < sz; ++j) {
                    u = p.get_lit(j);
                    unsigned c = p.get_coeff(j);
                    if (r == u) {
                        wlits[0].first += c;
                    }
                    else if (~r == u) {
                        if (coeff == c) {
                            wlits[0] = wlits.back();
                            wlits.pop_back();
                            b -= c;
                        }
                        else if (coeff < c) {
                            wlits[0].first = c - coeff;
                            wlits[0].second.neg();
                            b -= coeff;
                        }
                        else {
                            // coeff > c
                            wlits[0].first = coeff - c;
                            b -= c;
                        }
                    }
                    else {
                        wlits.push_back(wliteral(c, u));
                    }
                }
                ++m_stats.m_num_big_strengthenings;
                add_pb_ge(sat::null_literal, wlits, b, p.learned());
                p.set_removed();
                return;
            }
        }
    }

    void solver::subsumption(constraint& cnstr) {
        if (cnstr.was_removed())
            return;
        if (cnstr.k() <= 1)
            return;
        switch (cnstr.tag()) {
        case pb::tag_t::card_t:
            subsumption(cnstr.to_card());
            break;
        case pb::tag_t::pb_t:
            subsumption(cnstr.to_pb());
            break;
        }
    }

    void solver::init_visited() { s().init_visited(); }
    void solver::mark_visited(literal l) { s().mark_visited(l); }
    void solver::mark_visited(bool_var v) { s().mark_visited(v); }
    bool solver::is_visited(bool_var v) const { return s().is_visited(v); }    
    bool solver::is_visited(literal l) const { return s().is_visited(l); }

    void solver::cleanup_clauses() {
        if (m_clause_removed) {
            cleanup_clauses(s().m_clauses);
            cleanup_clauses(s().m_learned);
        }
    }

    typedef sat::clause_vector clause_vector;
    typedef sat::clause clause;

    void solver::cleanup_clauses(clause_vector& clauses) {
        // version in simplify first clears 
        // all watch literals, then reinserts them.
        // this ensures linear time cleanup.
        clause_vector::iterator it = clauses.begin();
        clause_vector::iterator end = clauses.end();
        clause_vector::iterator it2 = it;
        for (; it != end; ++it) {
            clause* c = *it;
            if (c->was_removed() && s().can_delete(*c)) {
                s().detach_clause(*c);
                s().del_clause(*c);
            }
            else {
                if (it2 != it) {
                    *it2 = *it;
                }
                ++it2;
            }
        }
        clauses.set_end(it2);        
    }
    
    void solver::cleanup_constraints() {
        if (m_constraint_removed) {
            cleanup_constraints(m_constraints, false);
            cleanup_constraints(m_learned, true);
            m_constraint_removed = false;
        }
    }

    void solver::cleanup_constraints(ptr_vector<constraint>& cs, bool learned) {
        ptr_vector<constraint>::iterator it = cs.begin();
        ptr_vector<constraint>::iterator it2 = it;
        ptr_vector<constraint>::iterator end = cs.end();
        for (; it != end; ++it) {
            constraint& c = *(*it);            
            if (c.was_removed()) {
                clear_watch(c);
                c.nullify_tracking_literal(*this);
                c.deallocate(m_allocator);
            }
            else if (learned && !c.learned()) {
                m_constraints.push_back(&c);
            }
            else {
                if (it != it2) {
                    *it2 = *it;
                }
                ++it2;
            }
        }
        cs.set_end(it2);
    }


    /*
      \brief subsumption between two cardinality constraints
      - A >= k       subsumes A + B >= k' for k' <= k
      - A + A' >= k  subsumes A + B >= k' for k' + |A'| <= k
      - A + lit >= k self subsumes A + ~lit + B >= k' into A + B >= k' for k' <= k
      - version that generalizes self-subsumption to more than one literal
        A + ~L + B >= k'   =>    A + B >= k'    if A + A' + L >= k and k' + |L| + |A'| <= k
     */
    bool solver::subsumes(card& c1, card& c2, literal_vector & comp) {
        if (c2.lit() != sat::null_literal) return false; 

        unsigned common = 0;
        comp.reset();
        for (literal l : c2) {
            if (is_visited(l)) {
                ++common;
            }
            else if (is_visited(~l)) {
                comp.push_back(l);
            }
        }

        unsigned c1_exclusive = c1.size() - common - comp.size();
        return c1_exclusive + c2.k() + comp.size() <= c1.k();
    }

    /*
      \brief L + A >= k subsumes L + C if |A| < k
             A + L + B >= k self-subsumes A + ~L + C >= 1
             if k + 1 - |B| - |C| - |L| > 0
     */
    bool solver::subsumes(card& c1, sat::clause& c2, bool& self) {
        unsigned common = 0, complement = 0, c2_exclusive = 0;
        self = false;
        
        for (literal l : c2) {
            if (is_visited(l)) {
                ++common;
            }
            else if (is_visited(~l)) {
                ++complement;
            }
            else {
                ++c2_exclusive;
            }
        }
        unsigned c1_exclusive = c1.size() - common - complement;
        if (complement > 0 && c1.k() + 1 > c1_exclusive + c2_exclusive + common) {
            self = true;
            return true; 
        }
        return c1.size() - common < c1.k();
    }

    /*
      \brief Ax >= k subsumes By >= k' if
      all coefficients in A are <= B and k >= k'
     */
    bool solver::subsumes(pbc const& p1, constraint const& p2) {
        if (p1.k() < p2.k() || p1.size() > p2.size()) return false;
        unsigned num_sub = 0;
        for (unsigned i = 0; i < p2.size(); ++i) {
            literal l = p2.get_lit(i);
            if (is_visited(l) && m_weights[l.index()] <= p2.get_coeff(i)) {
                ++num_sub;
            }
            if (p1.size() + i > p2.size() + num_sub) return false;
        }
        return num_sub == p1.size();
    }

    void solver::subsumes(pbc& p1, literal lit) {
        for (constraint* c : m_cnstr_use_list[lit.index()]) {
            if (c == &p1 || c->was_removed() || c->lit() != sat::null_literal)
                continue;
            bool sub = false;
            switch (c->tag()) {
            case pb::tag_t::card_t:
                sub = subsumes(p1, c->to_card()); 
                break;
            case pb::tag_t::pb_t:
                sub = subsumes(p1, c->to_pb()); 
                break;
            default: 
                break;
            }
            if (sub) {
                ++m_stats.m_num_pb_subsumes;                
                set_non_learned(p1);
                remove_constraint(*c, "subsumed");
            }
        }
    }

    literal solver::get_min_occurrence_literal(card const& c) {
        unsigned occ_count = UINT_MAX;
        literal lit = sat::null_literal;
        for (literal l : c) {
            unsigned occ_count1 = m_cnstr_use_list[l.index()].size();
            if (occ_count1 < occ_count) {
                lit = l;
                occ_count = occ_count1;
            }
        }
        return lit;
    }

    void solver::card_subsumption(card& c1, literal lit) {
        literal_vector slit;
        for (constraint* c : m_cnstr_use_list[lit.index()]) {
            if (!c->is_card() || c == &c1 || c->was_removed()) {
                continue;
            }
            card& c2 = c->to_card();

            SASSERT(&c1 != &c2);
            if (subsumes(c1, c2, slit)) {
                if (slit.empty()) {
                    TRACE(pb, tout << "subsume cardinality\n" << c1 << "\n" << c2 << "\n";);
                    remove_constraint(c2, "subsumed");
                    ++m_stats.m_num_pb_subsumes;
                    set_non_learned(c1);
                }
                else {
                    TRACE(pb, tout << "self subsume cardinality\n";);
                    IF_VERBOSE(11, 
                               verbose_stream() << "self-subsume cardinality\n"; 
                               verbose_stream() << c1 << "\n";
                               verbose_stream() << c2 << "\n";);
                    clear_watch(c2);                    
                    unsigned j = 0;
                    for (unsigned i = 0; i < c2.size(); ++i) {
                        if (!is_visited(~c2[i])) {
                            c2[j++] = c2[i];
                        }
                    }
                    c2.set_size(j);
                    init_watch(c2);
                    m_simplify_change = true;
                }
            }
        }
    }

    void solver::clause_subsumption(card& c1, literal lit, sat::clause_vector& removed_clauses) {
        SASSERT(!c1.was_removed());
        sat::clause_use_list& occurs = m_clause_use_list.get(lit);
        sat::clause_use_list::iterator it = occurs.mk_iterator();
        while (!it.at_end()) {
            sat::clause& c2 = it.curr();
            bool self;
            if (!c2.was_removed() && subsumes(c1, c2, self)) {
                if (self) {
                    // self-subsumption is TBD
                }
                else {
                    TRACE(pb, tout << "remove\n" << c1 << "\n" << c2 << "\n";);
                    removed_clauses.push_back(&c2);
                    ++m_stats.m_num_clause_subsumes;
                    set_non_learned(c1);
                }            
            }
            it.next();
        }
    }

    void solver::set_non_learned(constraint& c) {
        literal lit = c.lit();
        if (lit != sat::null_literal) {
            s().set_external(lit.var());
        }
        for (literal lit : constraint::literal_iterator(c)) {
            s().set_external(lit.var());             
            SASSERT(!s().was_eliminated(lit.var()));
        }
        c.set_learned(false);
    }

    typedef sat::watch_list watch_list;

    void solver::binary_subsumption(card& c1, literal lit) {
        if (c1.k() + 1 != c1.size()) return;
        SASSERT(is_visited(lit));
        SASSERT(!c1.was_removed());
        watch_list & wlist = get_wlist(~lit);
        watch_list::iterator it = wlist.begin();
        watch_list::iterator it2 = it;
        watch_list::iterator end = wlist.end();
        for (; it != end; ++it) {
            sat::watched w = *it;
            if (w.is_binary_clause() && is_visited(w.get_literal())) {
                ++m_stats.m_num_bin_subsumes;
                IF_VERBOSE(20, verbose_stream() << c1 << " subsumes (" << lit << " " << w.get_literal() << ")\n";);
                if (!w.is_learned()) {
                    set_non_learned(c1);
                }
            }
            else {
                if (it != it2) {
                    *it2 = *it;
                }
                ++it2;
            }
        }
        wlist.set_end(it2);        
    }

    void solver::subsumption(card& c1) {
        if (c1.was_removed() || c1.lit() != sat::null_literal) {
            return;
        }
        sat::clause_vector removed_clauses;
        init_visited();
        for (literal l : c1) mark_visited(l);  
        for (unsigned i = 0; i < std::min(c1.size(), c1.k() + 1); ++i) {
            literal lit = c1[i];            
            card_subsumption(c1, lit);
            clause_subsumption(c1, lit, removed_clauses);
            binary_subsumption(c1, lit);                   
        }
        m_clause_removed |= !removed_clauses.empty();
        for (clause *c : removed_clauses) {
            c->set_removed(true);
            m_clause_use_list.erase(*c);
        }
    }

    void solver::subsumption(pbc& p1) {
        if (p1.was_removed() || p1.lit() != sat::null_literal) {
            return;
        }
        init_visited();
        for (auto [w, l] : p1) {
            SASSERT(m_weights.size() <= l.index() || m_weights[l.index()] == 0);
            m_weights.setx(l.index(), w, 0);
            mark_visited(l);  
        }
        for (unsigned i = 0; i < std::min(10u, p1.num_watch()); ++i) {
            unsigned j = s().m_rand() % p1.num_watch();
            auto [w, lit] = p1[j];
            subsumes(p1, lit);
        }
        for (auto [w, l] : p1) {
            m_weights[l.index()] = 0;
        }        
    }

    void solver::clauses_modifed() {}

    lbool solver::get_phase(bool_var v) { return l_undef; }

    /*
      \brief lit <=> conjunction of unconstrained lits
     */
    void solver::assert_unconstrained(literal lit, literal_vector const& lits) {
        if (lit == sat::null_literal) {
            for (literal l : lits) {
                if (value(l) == l_undef) {
                    s().assign_scoped(l);
                }
            }
        }
        else {
            // add clauses for: lit <=> conjunction of undef literals
            SASSERT(value(lit) == l_undef);
            literal_vector cl;
            cl.push_back(lit);
            for (literal l : lits) {
                if (value(l) == l_undef) {
                    s().mk_clause(~lit, l);
                    cl.push_back(~l);
                }
            }    
            s().mk_clause(cl);
        }
    }

    sat::extension* solver::copy(sat::solver* s) {
        return clone_aux(m, *s, si, m_id);
    }

    euf::th_solver* solver::clone(euf::solver& new_ctx) {
        return clone_aux(new_ctx.get_manager(), new_ctx.s(), new_ctx.get_si(), get_id());
    }

    euf::th_solver* solver::clone_aux(ast_manager& m, sat::solver& s, sat::sat_internalizer& si, euf::theory_id id) {
        solver* result = alloc(solver, m, si, id);
        result->set_solver(&s);
        copy_constraints(result, m_constraints);
        return result;
    }

    void solver::copy_constraints(solver* result, ptr_vector<constraint> const& constraints) {
        literal_vector lits;
        svector<wliteral> wlits;
        for (constraint* cp : constraints) {
            switch (cp->tag()) {
            case pb::tag_t::card_t: {
                card const& c = cp->to_card();
                lits.reset();
                for (literal l : c) lits.push_back(l);
                result->add_at_least(c.lit(), lits, c.k(), c.learned());        
                break;
            }
            case pb::tag_t::pb_t: {
                pbc const& p = cp->to_pb();
                wlits.reset();
                for (wliteral w : p) {
                    wlits.push_back(w);
                }
                result->add_pb_ge(p.lit(), wlits, p.k(), p.learned());
                break;
            }
            default:
                UNREACHABLE();
            }                
        }
    }

    void solver::init_use_list(sat::ext_use_list& ul) {
        ul.init(s().num_vars());
        for (constraint const* cp : m_constraints) {
            sat::ext_constraint_idx idx = cp->cindex();
            if (cp->lit() != sat::null_literal) {
                ul.insert(cp->lit(), idx);
                ul.insert(~cp->lit(), idx);                
            }
            cp->init_use_list(ul);
        }
    }

    //
    // literal is used in a clause (C or l), it
    // it occurs negatively in constraint c.
    // all literals in C are marked
    // 
    bool solver::is_blocked(literal l, sat::ext_constraint_idx idx) {
        constraint const& c = index2constraint(idx);
        sat::simplifier& sim = s().m_simplifier;
        if (c.lit() != sat::null_literal) return false;
        return c.is_blocked(sim, l);
    }


    void solver::find_mutexes(literal_vector& lits, vector<literal_vector> & mutexes) {
        sat::literal_set slits(lits);
        bool change = false;
        
        for (constraint* cp : m_constraints) {
            if (!cp->is_card()) 
                continue;
            if (cp->lit() != sat::null_literal)
                continue;
            card const& c = cp->to_card();
            if (c.size() != c.k() + 1) 
                continue;

            literal_vector mux;
            for (literal lit : c) 
                if (slits.contains(~lit)) 
                    mux.push_back(~lit);

            if (mux.size() <= 1) 
                continue;
            
            for (literal m : mux) 
                slits.remove(m);

            change = true;
            mutexes.push_back(mux);            
        }        
        if (!change) 
            return;
        lits.reset();
        for (literal l : slits) 
            lits.push_back(l);
    }

    void solver::display(std::ostream& out, ineq const& ineq, bool values) const {
        for (unsigned i = 0; i < ineq.size(); ++i) {
            if (ineq.coeff(i) != 1) out << ineq.coeff(i) << "*";
            out << ineq.lit(i) << " ";
            if (values) out << value(ineq.lit(i)) << " ";
        }
        out << ">= " << ineq.m_k << "\n";
    }


    std::ostream& solver::display(std::ostream& out) const {
        for (constraint const* c : m_constraints) {
            out << (*c) << "\n";
        }
        if (!m_learned.empty()) {
            out << "learned:\n";
        }
        for (constraint const* c : m_learned) {
            out << (*c) << "\n";
        }
        return out;
    }

    std::ostream& solver::display_justification(std::ostream& out, sat::ext_justification_idx idx) const {
        return out << index2constraint(idx);
    }

    std::ostream& solver::display_constraint(std::ostream& out, sat::ext_constraint_idx idx) const {
        return out << index2constraint(idx);
    }

    std::ostream& solver::display(std::ostream& out, constraint const& c, bool values) const {
        return c.display(out, *this, values);
    }

    void solver::collect_statistics(statistics& st) const {
        st.update("pb propagations", m_stats.m_num_propagations);
        st.update("pb conflicts", m_stats.m_num_conflicts);
        st.update("pb resolves", m_stats.m_num_resolves);
        st.update("pb cuts", m_stats.m_num_cut);
        st.update("pb gc", m_stats.m_num_gc);
        st.update("pb overflow", m_stats.m_num_overflow);
        st.update("pb big strengthenings", m_stats.m_num_big_strengthenings);
        st.update("pb lemmas", m_stats.m_num_lemmas);
        st.update("pb subsumes", m_stats.m_num_bin_subsumes + m_stats.m_num_clause_subsumes + m_stats.m_num_pb_subsumes);
    }


    bool solver::validate_unit_propagation(pbc const& p, literal_vector const& r, literal alit) const {
        // all elements of r are true, 
        for (literal l : r) {
            if (value(l) != l_true) {
                IF_VERBOSE(0, verbose_stream() << "value of " << l << " is " << value(l) << "\n";
                           display(verbose_stream(), p, true););
                return false;
            }
            if (value(alit) == l_true && lvl(l) > lvl(alit)) {
                IF_VERBOSE(0, 
                           verbose_stream() << "level of premise " << l << " is " << lvl(l) << "\n";
                           verbose_stream() << "level of asserting literal " << alit << " is " << lvl(alit) << "\n";
                           display(verbose_stream(), p, true););
                return false;                
            }
        }
        // the sum of elements not in r or alit add up to less than k.
        unsigned sum = 0;
        // 
        // a*x + b*alit + c*r >= k
        // sum a < k
        // val(r) = false
        // hence alit has to be true.
        for (auto [w, lit] : p) {
            if (lit != alit && !r.contains(~lit)) {
                sum += w;
            }
        }
        if (sum >= p.k()) {
            IF_VERBOSE(0,             
                       verbose_stream() << "sum is " << sum << " >= " << p.k() << "\n";
                       display(verbose_stream(), p, true);
                       verbose_stream() << "id: " << p.id() << "\n";
                       sum = 0;
                       for (auto [w, lit] : p) sum += w;
                       verbose_stream() << "overall sum " << sum << "\n";
                       verbose_stream() << "asserting literal: " << alit << "\n";
                       verbose_stream() << "reason: " << r << "\n";);
            return false;
        }
        for (auto [w, lit] : p) {
            if (alit == lit) {
                return true;
            }
        }
        IF_VERBOSE(0, verbose_stream() << alit << " not found among literals\n";);
        return false;
    }


    bool solver::validate_lemma() { 
        int64_t bound64 = m_bound;
        int64_t val = -bound64;
        reset_active_var_set();
        for (bool_var v : m_active_vars) {
            if (!test_and_set_active(v)) continue;
            auto [w, l] = get_wliteral(v);
            if (w == 0) continue;
            if (!is_false(l)) {
                val += w;
            }
        }
        CTRACE(pb, val >= 0, active2pb(m_A); display(tout, m_A, true););
        return val < 0;
    }

    /**
     * the slack of inequalities on the stack should be non-positive.
     */
    bool solver::validate_ineq(ineq const& ineq) const {
        int64_t k = -static_cast<int64_t>(ineq.m_k);
        for (auto [w, lit] : ineq.m_wlits) {
            if (!is_false(lit))
                k += w;
        }
        CTRACE(pb, k > 0, display(tout, ineq, true););
        return k <= 0;
    }

    void solver::reset_active_var_set() {
        while (!m_active_var_set.empty()) m_active_var_set.erase();
    }

    bool solver::test_and_set_active(bool_var v) {
        if (m_active_var_set.contains(v)) {
            return false;
        }
        else {
            m_active_var_set.insert(v);
            return true;
        }
    }

    void solver::active2pb(ineq& p) {
        p.reset(m_bound);
        active2wlits(p.m_wlits);
    }

    void solver::active2wlits() {
        m_wlits.reset();
        active2wlits(m_wlits);
    }

    void solver::active2wlits(svector<wliteral>& wlits) {
        uint64_t sum = 0;        
        reset_active_var_set();
        for (bool_var v : m_active_vars) {
            if (!test_and_set_active(v)) continue;
            wliteral wl = get_wliteral(v);
            auto [w, l] = wl;
            if (w == 0) continue;
            wlits.push_back(wl);
            sum += w;
        }
        m_overflow |= sum >= UINT_MAX/2;
    }

    constraint* solver::active2lemma() {
        switch (get_config().m_pb_lemma_format) {
        case sat::PB_LEMMA_CARDINALITY:
            return active2card();
        case sat::PB_LEMMA_PB:
            return active2constraint();
        default:
            UNREACHABLE();
            return nullptr;
        }
    }

    constraint* solver::active2constraint() {
        active2wlits();
        if (m_overflow) {
            return nullptr;
        }
        constraint* c = add_pb_ge(sat::null_literal, m_wlits, m_bound, true);                
        TRACE(pb, if (c) display(tout, *c, true););
        ++m_stats.m_num_lemmas;
        return c;
    }
    
    /*
      Chai Kuhlmann:
      
      a1*l1 + ... + a_n*l_n >= k
      s.t.
      a1 >= a2 >= .. >= a_n

      let m be such that

         sum_{i = 1}^{m-1} a_i < k <= sum_{i = 1}^{m}

      then 

      l1 + ... + l_n >= m

      furthermore, for the largest n' <= n, such that

         sum_{i = n'+1}^n a_i + sum_{i = 1}^{m-1} a_i < k

      then 

         l1 + ... + l_n' >= m
      
     */
    struct compare_wlit {
        bool operator()(wliteral l1, wliteral l2) const {
            return l1.first > l2.first;
        }
    };


    constraint* solver::active2card() {
        active2wlits();
        if (m_overflow) {
            return nullptr;
        }
        std::sort(m_wlits.begin(), m_wlits.end(), compare_wlit());
        unsigned k = 0;
        uint64_t sum = 0, sum0 = 0;
        for (auto [w, lit] : m_wlits) {
            if (sum >= m_bound) break;
            sum0 = sum;
            sum += w;
            ++k;
        }
        if (k == 1) {
            return nullptr;
        }
        while (!m_wlits.empty()) {
            auto [w, lit] = m_wlits.back();
            if (w + sum0 >= m_bound) break;
            m_wlits.pop_back();
            sum0 += w;
        }

        unsigned slack = 0;
        unsigned max_level = 0;
        for (auto [w, lit] : m_wlits) {
            if (value(lit) != l_false) ++slack;
            unsigned level = lvl(lit);
            if (level > max_level) {
                max_level = level;
            }
            else if (max_level == level) {
            }
        }
        if (m_overflow) 
            return nullptr;

        if (slack >= k) 
            return nullptr;

        // produce asserting cardinality constraint
        literal_vector lits;
        for (auto [w, lit] : m_wlits) { 
            lits.push_back(lit);
        }       
        constraint* c = add_at_least(sat::null_literal, lits, k, true);      

        ++m_stats.m_num_lemmas;

        if (c) {
            lits.reset();
            for (auto [w, lit] : m_wlits) {
                if (value(lit) == l_false) lits.push_back(lit);        
            }
            unsigned glue = s().num_diff_levels(lits.size(), lits.data());
            c->set_glue(glue);
        }
        return c;
    }

    void solver::constraint2pb(constraint& cnstr, literal lit, unsigned offset, ineq& ineq) {
        switch (cnstr.tag()) {
        case pb::tag_t::card_t: {
            card& c = cnstr.to_card();
            ineq.reset(static_cast<uint64_t>(offset)*c.k());
            for (literal l : c) ineq.push(l, offset);
            if (c.lit() != sat::null_literal) ineq.push(~c.lit(), offset*c.k());                
            break;
        }
        case pb::tag_t::pb_t: {
            pbc& p = cnstr.to_pb();
            ineq.reset(static_cast<uint64_t>(offset) * p.k());
            for (auto [w, lit] : p) ineq.push(lit, offset * w);
            if (p.lit() != sat::null_literal) ineq.push(~p.lit(), offset * p.k());
            break;
        }
        default:
            UNREACHABLE();
            break;
        }
    }

    // validate that m_A & m_B implies m_C

    bool solver::validate_resolvent() {
        return true;
        u_map<uint64_t> coeffs;
        uint64_t k = m_A.m_k + m_B.m_k;
        for (unsigned i = 0; i < m_A.size(); ++i) {
            uint64_t coeff = m_A.coeff(i);
            SASSERT(!coeffs.contains(m_A.lit(i).index()));
            coeffs.insert(m_A.lit(i).index(), coeff);
        }
        for (unsigned i = 0; i < m_B.size(); ++i) {
            uint64_t coeff1 = m_B.coeff(i), coeff2;
            literal lit = m_B.lit(i);
            if (coeffs.find((~lit).index(), coeff2)) {
                if (coeff1 == coeff2) {
                    coeffs.remove((~lit).index());
                    k += coeff1;
                }
                else if (coeff1 < coeff2) {
                    coeffs.insert((~lit).index(), coeff2 - coeff1);
                    k += coeff1;
                }
                else {
                    SASSERT(coeff2 < coeff1);
                    coeffs.remove((~lit).index());
                    coeffs.insert(lit.index(), coeff1 - coeff2);
                    k += coeff2;
                }
            }
            else if (coeffs.find(lit.index(), coeff2)) {
                coeffs.insert(lit.index(), coeff1 + coeff2);
            }
            else {
                coeffs.insert(lit.index(), coeff1);
            }
        }
        // C is above the sum of A and B
        for (unsigned i = 0; i < m_C.size(); ++i) {
            literal lit = m_C.lit(i);
            uint64_t coeff;
            if (coeffs.find(lit.index(), coeff)) {
                if (coeff > m_C.coeff(i) && m_C.coeff(i) < m_C.m_k) {
                    goto violated;
                }
                coeffs.remove(lit.index());
            }
        }
        if (!coeffs.empty()) goto violated;
        if (m_C.m_k > k) goto violated;
        SASSERT(coeffs.empty());
        SASSERT(m_C.m_k <= k);
        return true;

    violated:
        // last ditch effort by translating to SAT.
        sat::solver s0(s().m_params, s().rlimit());
        u_map<bool_var> translation;
        literal l1 = translate_to_sat(s0, translation, m_A);
        if (l1 == sat::null_literal) return true;
        literal l2 = translate_to_sat(s0, translation, m_B);
        if (l2 == sat::null_literal) return true;
        ineq notC = negate(m_B);
        literal l3 = translate_to_sat(s0, translation, notC);
        if (l3 == sat::null_literal) return true;
        s0.assign_scoped(l1);
        s0.assign_scoped(l2);
        s0.assign_scoped(l3);
        lbool is_sat = s0.check();
        TRACE(pb, s0.display(tout << "trying sat encoding"););
        if (is_sat == l_false) return true;

        IF_VERBOSE(0, 
                   display(verbose_stream(), m_A);
                   display(verbose_stream(), m_B);
                   display(verbose_stream(), m_C);
                   for (auto& e : coeffs) {
                       verbose_stream() << sat::to_literal(e.m_key) << ": " << e.m_value << "\n";
                   });
        
        UNREACHABLE();
        return false;
    }

    /**
       \brief translate PB inequality to SAT formula.
     */
    literal solver::translate_to_sat(sat::solver& s, u_map<bool_var>& translation, ineq const& pb) {
        SASSERT(pb.m_k > 0);
        if (pb.size() > 1) {
            ineq a, b;
            a.reset(pb.m_k);
            b.reset(pb.m_k);
            for (unsigned i = 0; i < pb.size()/2; ++i) {
                a.push(pb.lit(i), pb.coeff(i));
            }
            for (unsigned i = pb.size()/2; i < pb.size(); ++i) {
                b.push(pb.lit(i), pb.coeff(i));
            }
            bool_var v = s.mk_var();
            literal lit(v, false);
            literal_vector lits;
            lits.push_back(~lit);            
            push_lit(lits, translate_to_sat(s, translation, a));
            push_lit(lits, translate_to_sat(s, translation, b));
            push_lit(lits, translate_to_sat(s, translation, a, b));
            s.mk_clause(lits);
            return lit;
        }
        if (pb.coeff(0) >= pb.m_k) {
            return translate_to_sat(s, translation, pb.lit(0));
        }
        else {
            return sat::null_literal;
        }
    }

    /*
      \brief encode the case where Sum(a) >= k-1 & Sum(b) >= 1 \/ ... \/ Sum(a) >= 1 & Sum(b) >= k-1
     */
    literal solver::translate_to_sat(sat::solver& s, u_map<bool_var>& translation, ineq& a, ineq& b) {
        uint64_t k0 = a.m_k;
        literal_vector lits;
        for (unsigned k = 1; k < a.m_k - 1; ++k) {
            a.m_k = k; b.m_k = k0 - k;
            literal lit1 = translate_to_sat(s, translation, a);
            literal lit2 = translate_to_sat(s, translation, b);
            if (lit1 != sat::null_literal && lit2 != sat::null_literal) {
                bool_var v = s.mk_var();
                literal lit(v, false);
                s.mk_clause(~lit, lit1);
                s.mk_clause(~lit, lit2);
                lits.push_back(lit);
            }
        }
        a.m_k = k0;
        b.m_k = k0;
        switch (lits.size()) {
        case 0: return sat::null_literal;
        case 1: return lits[0];
        default: {
            bool_var v = s.mk_var();
            literal lit(v, false);
            lits.push_back(~lit);
            s.mk_clause(lits);
            return lit;
        }
        }
    }
    
    literal solver::translate_to_sat(sat::solver& s, u_map<bool_var>& translation, literal lit) {
        bool_var v;
        if (!translation.find(lit.var(), v)) {            
            v = s.mk_var();
            translation.insert(lit.var(), v);
        }
        return literal(v, lit.sign());
    }

    solver::ineq solver::negate(ineq const& a) const {
        ineq result;
        uint64_t sum = 0;
        for (unsigned i = 0; i < a.size(); ++i) { 
            result.push(~a.lit(i), a.coeff(i));
            sum += a.coeff(i);
        }
        SASSERT(sum >= a.m_k + 1);
        result.m_k = sum + 1 - a.m_k;
        return result;
    }

    void solver::push_lit(literal_vector& lits, literal lit) {
        if (lit != sat::null_literal) {
            lits.push_back(lit);
        }
    }

    bool solver::validate_conflict(literal_vector const& lits, ineq& p) { 
        for (literal l : lits) {
            if (value(l) != l_false) {
                TRACE(pb, tout << "literal " << l << " is not false\n";);
                return false;
            }
            if (!p.contains(l)) {
                TRACE(pb, tout << "lemma contains literal " << l << " not in inequality\n";);
                return false;
            }
        }
        uint64_t value = 0;        
        for (unsigned i = 0; i < p.size(); ++i) {
            uint64_t coeff = p.coeff(i);
            if (!lits.contains(p.lit(i))) {
                value += coeff;
            }
        }
        CTRACE(pb, value >= p.m_k, tout << "slack: " << value << " bound " << p.m_k << "\n";
               display(tout, p);
               tout << lits << "\n";);
        return value < p.m_k;
    }

    bool solver::check_model(sat::model const& m) const {
        bool ok = true;
        for (constraint const* c : m_constraints) {
            if (c->was_removed()) {
                continue;
            }
            if (c->is_pure() && c->lit() != sat::null_literal && m[c->lit().var()] == (c->lit().sign() ? l_true : l_false)) {
                continue;
            }
            switch (eval(m, *c)) {
            case l_false: 
                IF_VERBOSE(0, verbose_stream() << "failed checking " << c->id() << ": " << *c << "\n";);
                ok = false;
                break;
            case l_true:
                break;
            case l_undef:
                IF_VERBOSE(0, verbose_stream() << "undef " << c->id() << ": " << *c << "\n";);
                break;
            }
        }
        return ok;
    }

    bool solver::extract_pb(std::function<void(unsigned sz, literal const* c, unsigned k)>& add_cardinality,
                               std::function<void(unsigned sz, literal const* c, unsigned const* coeffs, unsigned k)>& add_pb) {
        
        unsigned_vector coeffs;
        literal_vector lits;
        for (constraint* cp : m_constraints) {
            switch (cp->tag()) {
            case pb::tag_t::card_t: {
                card const& c = cp->to_card();
                unsigned n = c.size();
                unsigned k = c.k();

                if (c.lit() == sat::null_literal) {
                    //    c.lits() >= k 
                    // <=> 
                    //    ~c.lits() <= n - k
                    lits.reset();
                    for (unsigned j = 0; j < n; ++j) lits.push_back(c[j]);
                    add_cardinality(lits.size(), lits.data(), n - k);
                }
                else {
                    //
                    // c.lit() <=> c.lits() >= k
                    // 
                    //    (c.lits() < k) or c.lit()
                    // =  (c.lits() + (n - k + 1)*~c.lit()) <= n    
                    //
                    //    ~c.lit() or (c.lits() >= k)
                    // =  ~c.lit() or (~c.lits() <= n - k)
                    // =  k*c.lit() + ~c.lits() <= n 
                    // 
                    lits.reset();
                    coeffs.reset();
                    for (literal l : c) lits.push_back(l), coeffs.push_back(1);
                    lits.push_back(~c.lit()); coeffs.push_back(n - k + 1);
                    add_pb(lits.size(), lits.data(), coeffs.data(), n);

                    lits.reset();
                    coeffs.reset();
                    for (literal l : c) lits.push_back(~l), coeffs.push_back(1);
                    lits.push_back(c.lit()); coeffs.push_back(k);
                    add_pb(lits.size(), lits.data(), coeffs.data(), n);
                }
                break;
            }
            case pb::tag_t::pb_t: {
                pbc const& p = cp->to_pb();
                lits.reset();
                coeffs.reset();
                unsigned sum = 0;
                for (auto [w, lit] : p) sum += w;

                if (p.lit() == sat::null_literal) {
                    //   w1 + .. + w_n >= k
                    // <=> 
                    //  ~wl + ... + ~w_n <= sum_of_weights - k
                    for (auto [w, lit] : p) lits.push_back(~lit), coeffs.push_back(w);
                    add_pb(lits.size(), lits.data(), coeffs.data(), sum - p.k());
                }
                else {
                    //    lit <=> w1 + .. + w_n >= k
                    // <=>
                    //     lit or w1 + .. + w_n <= k - 1
                    //    ~lit or w1 + .. + w_n >= k
                    // <=> 
                    //     (sum - k + 1)*~lit + w1 + .. + w_n <= sum
                    //     k*lit + ~wl + ... + ~w_n <= sum
                    lits.push_back(p.lit()), coeffs.push_back(p.k());
                    for (auto [w, lit] : p) lits.push_back(~lit), coeffs.push_back(w);
                    add_pb(lits.size(), lits.data(), coeffs.data(), sum);

                    lits.reset();
                    coeffs.reset();
                    lits.push_back(~p.lit()), coeffs.push_back(sum + 1 - p.k());
                    for (auto [w, lit] : p) lits.push_back(lit), coeffs.push_back(w);
                    add_pb(lits.size(), lits.data(), coeffs.data(), sum);
                }
                break;
            }
            }
        }
        return true;
    }
    
};