File: ml_code_gen.m

package info (click to toggle)
mercury 0.10.1-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 21,984 kB
  • ctags: 11,923
  • sloc: objc: 187,634; ansic: 66,107; sh: 7,570; lisp: 1,568; cpp: 1,337; makefile: 614; perl: 511; awk: 274; asm: 252; exp: 32; xml: 12; fortran: 3; csh: 1
file content (2986 lines) | stat: -rw-r--r-- 98,644 bytes parent folder | download
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
%-----------------------------------------------------------------------------%
% Copyright (C) 1999-2001 The University of Melbourne.
% This file may only be copied under the terms of the GNU General
% Public License - see the file COPYING in the Mercury distribution.
%-----------------------------------------------------------------------------%

% File: ml_code_gen.m
% Main author: fjh

% MLDS code generation -- convert from HLDS to MLDS.

% This module is an alternative to the original code generator.
% The original code generator compiles from HLDS to LLDS, generating
% very low-level code.  This code generator instead compiles to MLDS,
% generating much higher-level code than the original code generator.

% One of the aims of the MLDS is to be able to generated human-readable
% code in languages like C or Java.  This means that unlike the LLDS back-end,
% we do not want to rely on macros or conditional compilation.  If the
% final code is going to depend on the setting of some compilation option,
% our philosophy is to reflect that change in the generated MLDS and C code
% where possible, rather than generating C code which calls macros that do
% different things in different grades.  This is important both for
% readability of the generated code, and to make sure that we can easily
% adapt the MLDS code generator to target languages like Java that don't
% support macros or conditional compilation.

% A big challenge in generating MLDS code is handling nondeterminism.
% For nondeterministic procedures, we generate code using an explicit
% continuation passing style.  Each nondeterministic procedures gets
% translated into a function which takes an extra parameter which is a
% function pointer that points to the success continuation.  On success,
% the function calls its success continuation, and on failure it returns.

% To keep things easy, this pass generates code which may contain nested
% functions; if the target language doesn't support nested functions (or
% doesn't support them _efficiently_) then a later MLDS->MLDS simplification
% pass will convert it to a form that does not use nested functions.

% Note that when we take the address of a nested function, we only ever
% do two things with it: pass it as a continuation argument, or call it.
% The continuations are never returned and never stored inside heap objects
% or global variables.  These conditions are sufficient to ensure that
% we never keep the address of a nested function after the containing
% functions has returned, so we won't get any dangling continuations.

%-----------------------------------------------------------------------------%
% CODE GENERATION SUMMARY
%-----------------------------------------------------------------------------%
%
% In each procedure, we declare a local variable `bool succeeded'.
% This is used to hold the success status of semidet sub-goals.
% Note that the comments below show local declarations for the
% `succeeded' variable in all the places where they would be
% needed if we were generating them locally, but currently
% we actually just generate a single `succeeded' variable for
% each procedure.
%
% The calling convention for sub-goals is as follows.
%
%	model_det goal:
%		On success, fall through.
%		(May clobber `succeeded'.)
%	model_semi goal:
%		On success, set `succeeded' to TRUE and fall through.
%		On failure, set `succeeded' to FALSE and fall through.
%	multi/nondet goal:
%		On success, call the current success continuation.
%		On failure, fall through.
%		(May clobber `succeeded' in either case.)
%
% In comments, we use the following notation to distinguish between
% these three.
%
%	model_det goal:
%		<do Goal>
%			This means execute Goal (which must be model_det).
%	model_semi goal:
%		<succeeded = Goal>
%			This means execute Goal, and set `succeeded' to
%			TRUE if the goal succeeds and FALSE if it fails.
%	model_non goal:
%		<Goal && CONT()>
%			This means execute Goal, calling the success
%			continuation function CONT() if it succeeds,
%			and falling through if it fails.
%
% The notation 
%
%	[situation]:
%		<[construct]>
%	===>
%		[code]
%
% means that in the situation described by [situation],
% for the the specified [construct] we will generate the specified [code].

% There is one other important thing which can be considered part of the
% calling convention for the code that we generate for each goal.
% If static ground term optimization is enabled, then for the terms
% marked as static by mark_static_terms.m, we will generate static consts.
% These static consts can refer to other static consts defined earlier.
% We need to be careful about the scopes of variables to ensure that
% for any term that mark_static_terms.m marks as static, the C constants
% representing the arguments of that term are in scope at the point
% where that term is constructed.  Basically this means that
% all the static consts generated inside a goal must be hoist out to
% the top level scope for that goal, except for goal types where
% goal_expr_mark_static_terms (in mark_static_terms.m) returns the
% same static_info unchanged, i.e. branched goals and negations.
%
% Handling static constants also requires that the calls to ml_gen_goal
% for each subgoal must be done in the right order, so that the
% const_num_map in the ml_gen_info holds the right sequence numbers
% for the constants in scope.

%-----------------------------------------------------------------------------%
%
% Code for wrapping goals
%
%	If a model_foo goal occurs in a model_bar context, where foo != bar,
%	then we need to modify the code that we emit for the goal so that
%	it conforms to the calling convenion expected for model_bar.

%	det goal in semidet context:
%		<succeeded = Goal>
%	===>
%		<do Goal>
%		succeeded = TRUE;

%	det goal in nondet context:
%		<Goal && SUCCEED()>
%	===>
%		<do Goal>
%		SUCCEED();

%	semi goal in nondet context:
%		<Goal && SUCCEED()>
%	===>
%		bool succeeded;
%	
%		<succeeded = Goal>
%		if (succeeded) SUCCEED();

%-----------------------------------------------------------------------------%
%
% Code for commits
%

% There's several different ways of handling commits:
%	- using catch/throw
%	- using setjmp/longjmp
%	- using GCC's __builtin_setjmp/__builtin_longjmp
%	- exiting nested functions via gotos to
%	  their containing functions
%
% The MLDS data structure abstracts away these differences
% using the `try_commit' and `do_commit' instructions.
% The comments below show the MLDS try_commit/do_commit version first,
% but for clarity I've also included sample code using each of the three
% different techniques.
%
% Note that if we're using GCC's __builtin_longjmp(),
% then it is important that the call to __builtin_longjmp() be
% put in its own function, to ensure that it is not in the same
% function as the __builtin_setjmp().
% The code generation schema below does that automatically.
% We will need to be careful with MLDS optimizations to
% ensure that we preserve that invariant, though.
% (Alternatively, we could just call a function that
% calls __builtin_longjmp() rather than calling it directly.
% But that would be a little less efficient.)
%
% If those methods turn out to be too inefficient,
% another alternative would be to change the generated
% code so that after every function call, it would check a flag,
% and if that flag was set, it would return.
% Then MR_DO_COMMIT would just set the flag and return.
% The flag could be in a global (or thread-local) variable,
% or it could be an additional value returned from each function.

%	model_non in semi context: (using try_commit/do_commit)
%		<succeeded = Goal>
% 	===>
%		MR_COMMIT_TYPE ref;
%		void success() {
%			MR_DO_COMMIT(ref);
%		}
%		MR_TRY_COMMIT(ref, {
%			<Goal && success()>
%			succeeded = FALSE;
%		}, {
%			succeeded = TRUE;
%		})

%	model_non in semi context: (using catch/throw)
%		<succeeded = Goal>
% 	===>
%		void success() {
%			throw COMMIT;
%		}
%		try {
%			<Goal && success()>
%			succeeded = FALSE;
%		} catch (COMMIT) {
%			succeeded = TRUE;
%		}

%	model_non in semi context: (using setjmp/longjmp)
%		<succeeded = Goal>
% 	===>
%		jmp_buf buf;
%		void success() {
%			longjmp(buf, 1);
%		}
%		if (setjmp(buf)) {
%			succeeded = TRUE;
%		} else {
%			<Goal && success()>
%			succeeded = FALSE;
%		}

%	model_non in semi context: (using GNU C nested functions,
%				GNU C local labels, and exiting
%				the nested function by a goto
%				to a label in the containing function)
%		<succeeded = Goal>
% 	===>
%		__label__ commit;
%		void success() {
%			goto commit;
%		}
%		<Goal && success()>
%		succeeded = FALSE;
%		goto commit_done;
%	commit:
%		succeeded = TRUE;
%	commit_done:
%		;

%	model_non in det context: (using try_commit/do_commit)
%		<do Goal>
%	===>
%		MR_COMMIT_TYPE ref;
%		void success() {
%			MR_DO_COMMIT(ref);
%		}
%		MR_TRY_COMMIT(ref, {
%			<Goal && success()>
%		}, {})

%	model_non in det context (using GNU C nested functions,
%				GNU C local labels, and exiting
%				the nested function by a goto
%				to a label in the containing function)
%		<do Goal>
%	===>
%		__label__ done;
%		void success() {
%			goto done;
%		}
%		try {
%			<Goal && success()>
%		} catch (COMMIT) {}
%	done:	;

%	model_non in det context (using catch/throw):
%		<do Goal>
%	===>
%		void success() {
%			throw COMMIT;
%		}
%		try {
%			<Goal && success()>
%		} catch (COMMIT) {}

%	model_non in det context (using setjmp/longjmp):
%		<do Goal>
% 	===>
%		jmp_buf buf;
%		void success() {
%			longjmp(buf, TRUE);
%		}
%		if (setjmp(buf) == 0) {
%			<Goal && success()>
%		}

% Note that for all of these versions, we must hoist any static declarations
% generated for <Goal> out to the top level; this is needed so that such
% declarations remain in scope for any following goals.

%-----------------------------------------------------------------------------%
%
% Code for empty conjunctions (`true')
%

%	model_det goal:
%		<do true>
%	===>
%		/* fall through */

%	model_semi goal:
%		<succeeded = true>
%	===>
%		succceeded = TRUE;

%	model_non goal
%		<true && CONT()>
%	===>
%		CONT();

%-----------------------------------------------------------------------------%
%
% Code for non-empty conjunctions
%

% We need to handle the case where the first goal cannot succeed
% specially:
%
%	at_most_zero Goal:
%		<Goal, Goals>
%	===>
%		<Goal>
%
% The remaining cases for conjunction all assume that the first
% goal's determinism is not `erroneous' or `failure'.

% If the first goal is model_det, it is straight-forward:
%
%	model_det Goal:
%		<Goal, Goals>
% 	===>
%		<do Goal>
%		<Goals>

% If the first goal is model_semidet, then there are two cases:
% if the conj as a whole is semidet, things are simple, and
% if the conj as a whole is model_non, then we do the same as
% for the semidet case, except that we also (ought to) declare
% a local `succeeded' variable.
%
%	model_semi Goal in model_semi conj:
%		<succeeded = (Goal, Goals)>
% 	===>
%		<succeeded = Goal>;
%		if (succeeded) {
%			<Goals>;
%		}
%
%	model_semi Goal in model_non conj:
%		<Goal && Goals>
% 	===>
%		bool succeeded;
%
%		<succeeded = Goal>;
%		if (succeeded) {
%			<Goals>;
%		}
%
% The actual code generation scheme we use is slightly
% different to that: we hoist any declarations generated
% for <Goals> to the outer scope, rather than keeping
% them inside the `if', so that they remain in
% scope for any later goals which follow this.
% This is needed for declarations of static consts.

% For model_non goals, there are a couple of different
% ways that we could generate code, depending on whether
% we are aiming to maximize readability, or whether we
% prefer to generate code that may be more efficient
% but is a little less readable.  The more readable method
% puts the generated goals in the same order that
% they occur in the source code:
%
%	model_non Goal (optimized for readability)
%		<Goal, Goals>
% 	===>
%		entry_func() {
%			<Goal && succ_func()>;
%		}
%		succ_func() {
%			<Goals && SUCCEED()>;
%		}
%
%		entry_func();
%
% The more efficient method generates the goals in
% reverse order, so it's less readable, but it has fewer
% function calls and can make it easier for the C compiler
% to inline things:
%
%	model_non Goal (optimized for efficiency):
%		<Goal, Goals>
% 	===>
%		succ_func() {
%			<Goals && SUCCEED()>;
%		}
%
%		<Goal && succ_func()>;
%
% The more efficient method is the one we actually use.
%
% Here's how those two methods look on longer
% conjunctions of nondet goals:
%
%	model_non goals (optimized for readability):
%		<Goal1, Goal2, Goal3, Goals>
% 	===>
%		label0_func() {
%			<Goal1 && label1_func()>;
%		}
%		label1_func() {
%			<Goal2 && label2_func()>;
%		}
%		label2_func() {
%			<Goal3 && label3_func()>;
%		}
%		label3_func() {
%			<Goals && SUCCEED()>;
%		}
%
%		label0_func();
%
%	model_non goals (optimized for efficiency):
%		<Goal1, Goal2, Goal3, Goals>
% 	===>
%		label1_func() {
%			label2_func() {
%				label3_func() {
%					<Goals && SUCCEED()>;
%				}
%				<Goal3 && label3_func()>;
%			}
%			<Goal2 && label2_func()>;
%		}
%		<Goal1 && label1_func()>;
%
% Note that it might actually make more sense to generate
% conjunctions of nondet goals like this:
%
%	model_non goals (optimized for efficiency, alternative version):
%		<Goal1, Goal2, Goal3, Goals>
% 	===>
%		label3_func() {
%			<Goals && SUCCEED()>;
%		}
%		label2_func() {
%			<Goal3 && label3_func()>;
%		}
%		label1_func() {
%			<Goal2 && label2_func()>;
%		}
%
%		<Goal1 && label1_func()>;
%
% This would avoid the undesirable deep nesting that we sometimes get
% with our current scheme.  However, if we're eliminating nested
% functions, as is normally the case, then after the ml_elim_nested
% transformation all the functions and variables have been hoisted
% to the top level, so there is no difference between these two.
%
% As with semidet conjunctions, we hoist declarations
% out so that they remain in scope for any following goals.
% This is needed for declarations of static consts.
% However, we want to keep the declarations of non-static
% variables local, since accessing local variables is more
% efficient that accessing variables in the environment
% from a nested function.  So we only hoist declarations
% of static constants.

%-----------------------------------------------------------------------------%
%
% Code for empty disjunctions (`fail')
%

%	model_semi goal:
%		<succeeded = fail>
%	===>
%		succeeded = FALSE;

%	model_non goal:
%		<fail && CONT()>
%	===>
%		/* fall through */

%-----------------------------------------------------------------------------%
%
% Code for non-empty disjunctions
%

% model_det disj:

%	model_det Goal:
%		<do (Goal ; Goals)>
%	===>
%		<do Goal>
%		/* <Goals> will never be reached */

%	model_semi Goal:
%		<do (Goal ; Goals)>
%	===>
%		bool succeeded;
%	
%		<succeeded = Goal>;
%		if (!succeeded) {
%			<do Goals>;
%		}

% model_semi disj:

%	model_det Goal:
%		<succeeded = (Goal ; Goals)>
%	===>
%		bool succeeded;
%
%		<do Goal>
%		succeeded = TRUE
%		/* <Goals> will never be reached */

%	model_semi Goal:
%		<succeeded = (Goal ; Goals)>
%	===>
%		bool succeeded;
%
%		<succeeded = Goal>;
%		if (!succeeded) {
%			<succeeded = Goals>;
%		}

% model_non disj:
%
%	model_det Goal:
%		<(Goal ; Goals) && SUCCEED()>
%	===>
%		<Goal>
%		SUCCEED();
%		<Goals && SUCCEED()>
%
%	model_semi Goal:
%		<(Goal ; Goals) && SUCCEED()>
%	===>
%		bool succeeded;
%	
%		<succeeded = Goal>
%		if (succeeded) SUCCEED();
%		<Goals && SUCCEED()>
%
%	model_non Goal:
%		<(Goal ; Goals) && SUCCEED()>
%	===>
%		<Goal && SUCCEED()>
%		<Goals && SUCCEED()>

%-----------------------------------------------------------------------------%
%
% Code for if-then-else
%

%	model_det Cond:
%		<(Cond -> Then ; Else)>
%	===>
%		<Cond>
%		<Then>

%	model_semi Cond:
%		<(Cond -> Then ; Else)>
%	===>
%		bool succeeded;
%	
%		<succeeded = Cond>
%		if (succeeded) {
%			<Then>
%		} else {
%			<Else>
%		}

%	/*
%	** XXX The following transformation does not do as good a job of GC
%	**     as it could.  Ideally we ought to ensure that stuff used only
%	**     in the `Else' part will be reclaimed if a GC occurs during
%	**     the `Then' part.  But that is a bit tricky to achieve.
%	*/
%
%	model_non Cond:
%		<(Cond -> Then ; Else)>
%	===>
%		bool cond_<N>;
%
%		void then_func() {
%			cond_<N> = TRUE;
%			<Then>
%		}
%
%		cond_<N> = FALSE;
%		<Cond && then_func()>
%		if (!cond_<N>) {
%			<Else>
%		}
%	except that we hoist any declarations generated
%	for <Cond> to the top of the scope, so that they
%	are in scope for the <Then> goal
%	(this is needed for declarations of static consts)

%-----------------------------------------------------------------------------%
%
% Code for negation
%

% model_det negation
%		<not(Goal)>
%	===>
%		bool succeeded;
%		<succeeded = Goal>
%		/* now ignore the value of succeeded,
%		   which we know will be FALSE */

% model_semi negation, model_det Goal:
%		<succeeded = not(Goal)>
%	===>
%		<do Goal>
%		succeeded = FALSE;

% model_semi negation, model_semi Goal:
%		<succeeded = not(Goal)>
%	===>
%		<succeeded = Goal>
%		succeeded = !succeeded;

%-----------------------------------------------------------------------------%
%
% Code for deconstruction unifications
%

%	det (cannot_fail) deconstruction:
%		<succeeded = (X => f(A1, A2, ...))>
% 	===>
%		A1 = arg(X, f, 1);		% extract arguments
%		A2 = arg(X, f, 2);
%		...

%	semidet (can_fail) deconstruction:
%		<X => f(A1, A2, ...)>
% 	===>
%		<succeeded = (X => f(_, _, _, _))>	% tag test
%		if (succeeded) {
%			A1 = arg(X, f, 1);		% extract arguments
%			A2 = arg(X, f, 2);
%			...
%		}

%-----------------------------------------------------------------------------%


% This back-end is still not yet 100% complete.
%
% Done:
%	- function prototypes
%	- code generation for det, semidet, and nondet predicates/functions:
%		- conjunctions
%		- disjunctions
%		- negation
%		- if-then-else
%		- predicate/function calls
%		- higher-order calls
%		- unifications
%			- assignment
%			- simple tests
%			- constructions
%			- deconstructions
%		- switches
%		- commits
%		- `pragma c_code'
%	- RTTI
%	- high level data representation
%	  (i.e. generate MLDS type declarations for user-defined types)
%
% BUGS:
%	- XXX parameter passing problem for abstract equivalence types
%         that are defined as float (or anything which doesn't map to `Word')
%
% TODO:
%	- XXX define compare & unify preds RTTI types
%	- XXX need to generate correct layout information for closures
%	      so that tests/hard_coded/copy_pred works.
%	- XXX fix ANSI/ISO C conformance of the generated code (i.e. port to lcc)
%
% UNIMPLEMENTED FEATURES:
%	- test --det-copy-out
%	- fix --gcc-nested-functions (need forward declarations for
%	  nested functions)
%	- support debugging (with mdb)
%	- support genuine parallel conjunction
%	- support fact tables
%	- support --split-c-files
%	- support aditi
%	- support trailing
%	- support accurate GC
%
% POTENTIAL EFFICIENCY IMPROVEMENTS:
%	- optimize unboxed float on DEC Alphas.
%	- generate better code for switches:
%		- optimize switches so that the recursive case comes first
%		  (see switch_gen.m).
%		- apply the reverse tag test optimization
%		  for types with two functors (see unify_gen.m)
%		- binary search switches
%		- lookup switches
%	- generate local declarations for the `succeeded' variable;
%	  this would help in nondet code, because it would avoid
%	  the need to access the outermost function's `succeeded'
%	  variable via the environment pointer
%	  (be careful about the interaction with setjmp(), though)

%-----------------------------------------------------------------------------%

:- module ml_code_gen.

:- interface.

:- import_module prog_data.
:- import_module hlds_module, hlds_goal.
:- import_module code_model.
:- import_module mlds, ml_code_util.
:- import_module io.

%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%

	% Generate MLDS code for an entire module.
	%
:- pred ml_code_gen(module_info, mlds, io__state, io__state).
:- mode ml_code_gen(in, out, di, uo) is det.

	% Generate MLDS code for the specified goal in the
	% specified code model.  Return the result as a single statement
	% (which may be a block statement containing nested declarations).
	%
:- pred ml_gen_goal(code_model, hlds_goal, mlds__statement,
			ml_gen_info, ml_gen_info).
:- mode ml_gen_goal(in, in, out, in, out) is det.

	% Generate MLDS code for the specified goal in the
	% specified code model.  Return the result as two lists,
	% one containing the necessary declarations and the other
	% containing the generated statements.
	%
:- pred ml_gen_goal(code_model, hlds_goal, mlds__defns, mlds__statements,
			ml_gen_info, ml_gen_info).
:- mode ml_gen_goal(in, in, out, out, in, out) is det.

	% ml_gen_wrap_goal(OuterCodeModel, InnerCodeModel, Context,
	%		MLDS_Statements0, MLDS_Statements):
	%
	%	OuterCodeModel is the code model expected by the
	%	context in which a goal is called. InnerCodeModel
	%	is the code model which the goal actually has.
	%	This predicate converts the code generated for
	%	the goal using InnerCodeModel into code that uses
	%	the calling convention appropriate for OuterCodeModel.
	%
:- pred ml_gen_wrap_goal(code_model, code_model, prog_context,
		mlds__statements, mlds__statements,
		ml_gen_info, ml_gen_info).
:- mode ml_gen_wrap_goal(in, in, in, in, out, in, out) is det.

%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%

:- implementation.

:- import_module ml_type_gen, ml_call_gen, ml_unify_gen, ml_switch_gen.
:- import_module ml_code_util.
:- import_module arg_info, llds, llds_out. % XXX needed for pragma foreign code
:- import_module export, foreign. % XXX needed for pragma foreign code
:- import_module hlds_pred, hlds_data.
:- import_module goal_util, type_util, mode_util, builtin_ops.
:- import_module passes_aux, modules.
:- import_module globals, options.

:- import_module assoc_list, bool, string, list, map.
:- import_module int, set, term, require, std_util.

%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%

	% Generate MLDS code for an entire module.
	%
ml_code_gen(ModuleInfo, MLDS) -->
	{ module_info_name(ModuleInfo, ModuleName) },
	ml_gen_foreign_code(ModuleInfo, ForeignCode),
	{ ml_gen_imports(ModuleInfo, Imports) },
	ml_gen_defns(ModuleInfo, Defns),
	{ MLDS = mlds(ModuleName, ForeignCode, Imports, Defns) }.

:- pred ml_gen_foreign_code(module_info, mlds__foreign_code,
				io__state, io__state).
:- mode ml_gen_foreign_code(in, out, di, uo) is det.

ml_gen_foreign_code(ModuleInfo, MLDS_ForeignCode) -->
	{ module_info_get_foreign_decl(ModuleInfo, ForeignDecls) },
	{ module_info_get_foreign_body_code(ModuleInfo, ForeignBodys) },
	globals__io_lookup_foreign_language_option(use_foreign_language,
		UseForeignLanguage),
	{ foreign__filter_decls(UseForeignLanguage, ForeignDecls,
		WantedForeignDecls, _OtherForeignDecls) },
	{ foreign__filter_bodys(UseForeignLanguage, ForeignBodys,
		WantedForeignBodys, _OtherForeignBodys) },
	{ ConvBody = (func(foreign_body_code(L, S, C)) = 
		user_foreign_code(L, S, C)) },
	{ MLDSWantedForeignBodys = list__map(ConvBody, WantedForeignBodys) },
	{ ml_gen_pragma_export(ModuleInfo, MLDS_PragmaExports) },
	{ MLDS_ForeignCode = mlds__foreign_code(WantedForeignDecls,
			MLDSWantedForeignBodys, MLDS_PragmaExports) }.

:- pred ml_gen_imports(module_info, mlds__imports).
:- mode ml_gen_imports(in, out) is det.

ml_gen_imports(ModuleInfo, MLDS_ImportList) :-
	module_info_get_all_deps(ModuleInfo, AllImports),
	MLDS_ImportList = list__map(mercury_module_name_to_mlds,
		set__to_sorted_list(AllImports)).

:- pred ml_gen_defns(module_info, mlds__defns, io__state, io__state).
:- mode ml_gen_defns(in, out, di, uo) is det.

ml_gen_defns(ModuleInfo, MLDS_Defns) -->
	ml_gen_types(ModuleInfo, MLDS_TypeDefns),
	ml_gen_preds(ModuleInfo, MLDS_PredDefns),
	{ MLDS_Defns = list__append(MLDS_TypeDefns, MLDS_PredDefns) }.

%-----------------------------------------------------------------------------%
%
% For each pragma export declaration we associate with it the 
% information used to generate the function prototype for the MLDS
% entity.
%

:- pred ml_gen_pragma_export(module_info, list(mlds__pragma_export)).
:- mode ml_gen_pragma_export(in, out) is det.

ml_gen_pragma_export(ModuleInfo, MLDS_PragmaExports) :-
	module_info_get_pragma_exported_procs(ModuleInfo, PragmaExports),
	list__map(ml_gen_pragma_export_proc(ModuleInfo),
			PragmaExports, MLDS_PragmaExports).

:- pred ml_gen_pragma_export_proc(module_info::in,
		pragma_exported_proc::in, mlds__pragma_export::out) is det.

ml_gen_pragma_export_proc(ModuleInfo,
		pragma_exported_proc(PredId, ProcId, C_Name, ProgContext),
		ML_Defn) :-

	ml_gen_proc_label(ModuleInfo, PredId, ProcId,
		MLDS_Name, MLDS_ModuleName),
	MLDS_FuncParams = ml_gen_proc_params(ModuleInfo, PredId, ProcId),
	MLDS_Context = mlds__make_context(ProgContext),
	ML_Defn = ml_pragma_export(C_Name, qual(MLDS_ModuleName, MLDS_Name),
			MLDS_FuncParams, MLDS_Context).


	%
	% Test to see if the procedure is 
	% a model_det function whose function result has an output mode
	% (whose type is not a dummy argument type like io__state),
	% and if so, bind RetVar to the procedure's return value.
	% These procedures need to handled specially: for such functions,
	% we map the Mercury function result to an MLDS return value.
	%
:- pred is_output_det_function(module_info, pred_id, proc_id, prog_var).
:- mode is_output_det_function(in, in, in, out) is semidet.

is_output_det_function(ModuleInfo, PredId, ProcId, RetArgVar) :-
	module_info_pred_proc_info(ModuleInfo, PredId, ProcId, PredInfo,
			ProcInfo),
	
	pred_info_get_is_pred_or_func(PredInfo, function),
	proc_info_interface_code_model(ProcInfo, model_det),

	proc_info_argmodes(ProcInfo, Modes),
	pred_info_arg_types(PredInfo, ArgTypes),
	proc_info_headvars(ProcInfo, ArgVars),
	modes_to_arg_modes(ModuleInfo, Modes, ArgTypes, ArgModes),
	pred_args_to_func_args(ArgModes, _InputArgModes, RetArgMode),
	pred_args_to_func_args(ArgTypes, _InputArgTypes, RetArgType),
	pred_args_to_func_args(ArgVars, _InputArgVars, RetArgVar),

	RetArgMode = top_out,
	\+ type_util__is_dummy_argument_type(RetArgType).

%-----------------------------------------------------------------------------%
%
% Stuff to generate MLDS code for HLDS predicates & functions.
%

	% Generate MLDS definitions for all the non-imported
	% predicates (and functions) in the HLDS.
	%
:- pred ml_gen_preds(module_info, mlds__defns, io__state, io__state).
:- mode ml_gen_preds(in, out, di, uo) is det.

ml_gen_preds(ModuleInfo, MLDS_PredDefns) -->
	{ module_info_preds(ModuleInfo, PredTable) },
	{ map__keys(PredTable, PredIds) },
	{ MLDS_PredDefns0 = [] },
	ml_gen_preds_2(ModuleInfo, PredIds, PredTable,
		MLDS_PredDefns0, MLDS_PredDefns).

:- pred ml_gen_preds_2(module_info, list(pred_id), pred_table,
			mlds__defns, mlds__defns, io__state, io__state).
:- mode ml_gen_preds_2(in, in, in, in, out, di, uo) is det.

ml_gen_preds_2(ModuleInfo, PredIds0, PredTable, MLDS_Defns0, MLDS_Defns) --> 
	(
		{ PredIds0 = [PredId|PredIds] }
	->
		{ map__lookup(PredTable, PredId, PredInfo) },
		{ pred_info_import_status(PredInfo, ImportStatus) },
		( { ImportStatus = imported(_) } ->
			{ MLDS_Defns1 = MLDS_Defns0 }
		;
			ml_gen_pred(ModuleInfo, PredId, PredInfo, ImportStatus,
				MLDS_Defns0, MLDS_Defns1)
		),
		ml_gen_preds_2(ModuleInfo, PredIds, PredTable,
			MLDS_Defns1, MLDS_Defns)
	;
		{ MLDS_Defns = MLDS_Defns0 }
	).

	% Generate MLDS definitions for all the non-imported
	% procedures of a given predicate (or function).
	%
:- pred ml_gen_pred(module_info, pred_id, pred_info, import_status,
			mlds__defns, mlds__defns, io__state, io__state).
:- mode ml_gen_pred(in, in, in, in, in, out, di, uo) is det.

ml_gen_pred(ModuleInfo, PredId, PredInfo, ImportStatus,
		MLDS_Defns0, MLDS_Defns) -->
	( { ImportStatus = external(_) } ->
		{ pred_info_procids(PredInfo, ProcIds) }
	;
		{ pred_info_non_imported_procids(PredInfo, ProcIds) }
	),
	( { ProcIds = [] } ->
		{ MLDS_Defns = MLDS_Defns0 }
	;
		write_pred_progress_message("% Generating MLDS code for ",
			PredId, ModuleInfo),
		{ pred_info_procedures(PredInfo, ProcTable) },
		{ ml_gen_procs(ProcIds, ModuleInfo, PredId, PredInfo,
				ProcTable, MLDS_Defns0, MLDS_Defns) }
	).

:- pred ml_gen_procs(list(proc_id), module_info, pred_id, pred_info,
			proc_table, mlds__defns, mlds__defns).
:- mode ml_gen_procs(in, in, in, in, in, in, out) is det.

ml_gen_procs([], _, _, _, _) --> [].
ml_gen_procs([ProcId | ProcIds], ModuleInfo, PredId, PredInfo, ProcTable)
		--> 
	{ map__lookup(ProcTable, ProcId, ProcInfo) },
	ml_gen_proc(ModuleInfo, PredId, ProcId, PredInfo, ProcInfo),
	ml_gen_procs(ProcIds, ModuleInfo, PredId, PredInfo, ProcTable).

%-----------------------------------------------------------------------------%
%
% Code for handling individual procedures
%

	% Generate MLDS code for the specified procedure.
	%
:- pred ml_gen_proc(module_info, pred_id, proc_id, pred_info, proc_info,
			mlds__defns, mlds__defns).
:- mode ml_gen_proc(in, in, in, in, in, in, out) is det.

ml_gen_proc(ModuleInfo, PredId, ProcId, _PredInfo, ProcInfo, Defns0, Defns) :-
	proc_info_context(ProcInfo, Context),

	ml_gen_proc_label(ModuleInfo, PredId, ProcId, MLDS_Name, _ModuleName),
	MLDS_Context = mlds__make_context(Context),
	MLDS_DeclFlags = ml_gen_proc_decl_flags(ModuleInfo, PredId, ProcId),
	ml_gen_proc_defn(ModuleInfo, PredId, ProcId,
		MLDS_ProcDefnBody, ExtraDefns),
	MLDS_ProcDefn = mlds__defn(MLDS_Name, MLDS_Context, MLDS_DeclFlags,
				MLDS_ProcDefnBody),
	Defns1 = list__append(ExtraDefns, [MLDS_ProcDefn | Defns0]),
	ml_gen_maybe_add_table_var(ModuleInfo, PredId, ProcId, ProcInfo,
		Defns1, Defns).

:- pred ml_gen_maybe_add_table_var(module_info, pred_id, proc_id, proc_info,
		mlds__defns, mlds__defns).
:- mode ml_gen_maybe_add_table_var(in, in, in, in, in, out) is det.

ml_gen_maybe_add_table_var(ModuleInfo, PredId, ProcId, ProcInfo,
		Defns0, Defns) :-
	proc_info_eval_method(ProcInfo, EvalMethod),
	(
		eval_method_has_per_proc_tabling_pointer(EvalMethod) = yes
	->
		ml_gen_pred_label(ModuleInfo, PredId, ProcId,
			MLDS_PredLabel, _MLDS_PredModule),
		Var = tabling_pointer(MLDS_PredLabel - ProcId),
		Type = mlds__generic_type,
		Initializer = init_obj(const(null(Type))),
		proc_info_context(ProcInfo, Context),
		TablePointerVarDefn = ml_gen_mlds_var_decl(
			Var, Type, Initializer, mlds__make_context(Context)),
		Defns = [TablePointerVarDefn | Defns0]
	;
		Defns = Defns0
	).

	% Return the declaration flags appropriate for a procedure definition.
	%
:- func ml_gen_proc_decl_flags(module_info, pred_id, proc_id)
		= mlds__decl_flags.
ml_gen_proc_decl_flags(ModuleInfo, PredId, ProcId) = MLDS_DeclFlags :-
	module_info_pred_info(ModuleInfo, PredId, PredInfo),
	( procedure_is_exported(PredInfo, ProcId) ->
		Access = public
	;
		Access = private
	),
	PerInstance = per_instance,
	Virtuality = non_virtual,
	Finality = overridable,
	Constness = modifiable,
	Abstractness = concrete,
	MLDS_DeclFlags = init_decl_flags(Access, PerInstance,
		Virtuality, Finality, Constness, Abstractness).

	% Generate an MLDS definition for the specified procedure.
	%
:- pred ml_gen_proc_defn(module_info, pred_id, proc_id, mlds__entity_defn,
		mlds__defns).
:- mode ml_gen_proc_defn(in, in, in, out, out) is det.

ml_gen_proc_defn(ModuleInfo, PredId, ProcId, MLDS_ProcDefnBody, ExtraDefns) :-
	module_info_pred_proc_info(ModuleInfo, PredId, ProcId,
			PredInfo, ProcInfo),
	pred_info_import_status(PredInfo, ImportStatus),
	pred_info_arg_types(PredInfo, ArgTypes),
	proc_info_interface_code_model(ProcInfo, CodeModel),
	proc_info_headvars(ProcInfo, HeadVars),
	proc_info_goal(ProcInfo, Goal0),

	%
	% The HLDS front-end sometimes over-estimates
	% the set of non-locals.  We need to restrict
	% the set of non-locals for the top-level goal
	% to just the headvars, because otherwise variables
	% which occur in the top-level non-locals but which
	% are not really non-local will not be declared.
	%
	Goal0 = GoalExpr - GoalInfo0,
	goal_info_get_code_gen_nonlocals(GoalInfo0, NonLocals0),
	set__list_to_set(HeadVars, HeadVarsSet),
	set__intersect(HeadVarsSet, NonLocals0, NonLocals),
	goal_info_set_code_gen_nonlocals(GoalInfo0, NonLocals, GoalInfo),
	Goal = GoalExpr - GoalInfo,

	goal_info_get_context(GoalInfo, Context),

	MLDSGenInfo0 = ml_gen_info_init(ModuleInfo, PredId, ProcId),
	MLDS_Params = ml_gen_proc_params(ModuleInfo, PredId, ProcId),

	( ImportStatus = external(_) ->
		%
		% For Mercury procedures declared `:- external', we generate 
		% an MLDS definition for them with no function body.
		% The MLDS -> target code pass can treat this accordingly,
		% e.g. for C it outputs a function declaration with no
		% corresponding definition, making sure that the function
		% is declared as `extern' rather than `static'.
		%
		MaybeStatement = no,
		ExtraDefns = []
	;
		% Set up the initial success continuation, if any.
		% Also figure out which output variables are returned by
		% value (rather than being passed by reference) and remove
		% them from the byref_output_vars field in the ml_gen_info.
		( CodeModel = model_non ->
			ml_set_up_initial_succ_cont(ModuleInfo,
				CopiedOutputVars, MLDSGenInfo0, MLDSGenInfo1)
		;
			(
				is_output_det_function(ModuleInfo, PredId,
					ProcId, ResultVar)
			->
				CopiedOutputVars = [ResultVar],
				ml_gen_info_get_byref_output_vars(MLDSGenInfo0,
					ByRefOutputVars0),
				list__delete_all(ByRefOutputVars0,
					ResultVar, ByRefOutputVars),
				ml_gen_info_set_byref_output_vars(
					ByRefOutputVars,
					MLDSGenInfo0, MLDSGenInfo1)
			;
				CopiedOutputVars = [],
				MLDSGenInfo1 = MLDSGenInfo0
			)
		),

		% This would generate all the local variables at the top of
		% the function:
		%	MLDS_LocalVars = ml_gen_all_local_var_decls(Goal,
		% 		VarSet, VarTypes, HeadVars, ModuleInfo),
		% But instead we now generate them locally for each goal.
		% We just declare the `succeeded' var here, plus locals
		% for any output arguments that are returned by value
		% (e.g. if --nondet-copy-out is enabled, or for det function
		% return values).
		MLDS_Context = mlds__make_context(Context),
		( CopiedOutputVars = [] ->
			% optimize common case
			OutputVarLocals = []
		;
			proc_info_varset(ProcInfo, VarSet),
			proc_info_vartypes(ProcInfo, VarTypes),
			% note that for headvars we must use the types from
			% the procedure interface, not from the procedure body
			HeadVarTypes = map__from_corresponding_lists(HeadVars,
				ArgTypes),
			OutputVarLocals = ml_gen_local_var_decls(VarSet,
				map__overlay(VarTypes, HeadVarTypes),
				MLDS_Context, ModuleInfo, CopiedOutputVars)
		),
		MLDS_LocalVars = [ml_gen_succeeded_var_decl(MLDS_Context) |
				OutputVarLocals],
		ml_gen_proc_body(CodeModel, HeadVars, ArgTypes,
				CopiedOutputVars, Goal,
				MLDS_Decls0, MLDS_Statements,
				MLDSGenInfo1, MLDSGenInfo),
		ml_gen_info_get_extra_defns(MLDSGenInfo, ExtraDefns),
		MLDS_Decls = list__append(MLDS_LocalVars, MLDS_Decls0),
		MLDS_Statement = ml_gen_block(MLDS_Decls, MLDS_Statements,
			Context),
		MaybeStatement = yes(MLDS_Statement)
	),
	MLDS_ProcDefnBody = mlds__function(yes(proc(PredId, ProcId)),
			MLDS_Params, MaybeStatement).

:- pred ml_set_up_initial_succ_cont(module_info, list(prog_var),
		ml_gen_info, ml_gen_info).
:- mode ml_set_up_initial_succ_cont(in, out, in, out) is det.

ml_set_up_initial_succ_cont(ModuleInfo, NondetCopiedOutputVars) -->
	{ module_info_globals(ModuleInfo, Globals) },
	{ globals__lookup_bool_option(Globals, nondet_copy_out,
		NondetCopyOut) },
	( { NondetCopyOut = yes } ->
		% for --nondet-copy-out, we generate local variables
		% for the output variables and then pass them to the
		% continuation, rather than passing them by reference.
		=(MLDSGenInfo0),
		{ ml_gen_info_get_byref_output_vars(MLDSGenInfo0,
			NondetCopiedOutputVars) },
		ml_gen_info_set_byref_output_vars([])
	;
		{ NondetCopiedOutputVars = [] }
	),
	ml_gen_var_list(NondetCopiedOutputVars, OutputVarLvals),
	ml_variable_types(NondetCopiedOutputVars, OutputVarTypes),
	ml_initial_cont(OutputVarLvals, OutputVarTypes, InitialCont),
	ml_gen_info_push_success_cont(InitialCont).

	% Generate MLDS definitions for all the local variables in a function.
	%
	% Note that this function generates all the local variables at the
	% top of the function.  It might be a better idea to instead
	% generate local declarations for all the variables used in
	% each sub-goal.
	%
:- func ml_gen_all_local_var_decls(hlds_goal, prog_varset,
		map(prog_var, prog_type), list(prog_var), module_info) =
		mlds__defns.
ml_gen_all_local_var_decls(Goal, VarSet, VarTypes, HeadVars, ModuleInfo) =
		MLDS_LocalVars :-
	Goal = _ - GoalInfo,
	goal_info_get_context(GoalInfo, Context),
	goal_util__goal_vars(Goal, AllVarsSet),
	set__delete_list(AllVarsSet, HeadVars, LocalVarsSet),
	set__to_sorted_list(LocalVarsSet, LocalVars),
	MLDS_Context = mlds__make_context(Context),
	MLDS_LocalVars0 = ml_gen_local_var_decls(VarSet, VarTypes,
				MLDS_Context, ModuleInfo, LocalVars),
	MLDS_SucceededVar = ml_gen_succeeded_var_decl(MLDS_Context),
	MLDS_LocalVars = [MLDS_SucceededVar | MLDS_LocalVars0].

	% Generate declarations for a list of local variables.
	%
:- func ml_gen_local_var_decls(prog_varset, map(prog_var, prog_type),
		mlds__context, module_info, prog_vars) = mlds__defns.
ml_gen_local_var_decls(VarSet, VarTypes, Context, ModuleInfo, Vars) =
		LocalDecls :-
	list__filter_map(ml_gen_local_var_decl(VarSet, VarTypes, Context,
		ModuleInfo), Vars, LocalDecls).

	% Generate a declaration for a local variable.
	%
:- pred ml_gen_local_var_decl(prog_varset, map(prog_var, prog_type),
		mlds__context, module_info, prog_var, mlds__defn).
:- mode ml_gen_local_var_decl(in, in, in, in, in, out) is semidet.
ml_gen_local_var_decl(VarSet, VarTypes, Context, ModuleInfo, Var, MLDS_Defn) :-
	map__lookup(VarTypes, Var, Type),
	not type_util__is_dummy_argument_type(Type),
	VarName = ml_gen_var_name(VarSet, Var),
	MLDS_Defn = ml_gen_var_decl(VarName, Type, Context, ModuleInfo).

	% Generate the code for a procedure body.
	%
:- pred ml_gen_proc_body(code_model, list(prog_var), list(prog_type),
		list(prog_var), hlds_goal, mlds__defns, mlds__statements,
		ml_gen_info, ml_gen_info).
:- mode ml_gen_proc_body(in, in, in, in, in, out, out, in, out) is det.

ml_gen_proc_body(CodeModel, HeadVars, ArgTypes, CopiedOutputVars, Goal,
		MLDS_Decls, MLDS_Statements) -->
	{ Goal = _ - GoalInfo },
	{ goal_info_get_context(GoalInfo, Context) },

	%
	% First just generate the code for the procedure's goal.
	%
	{ DoGenGoal = ml_gen_goal(CodeModel, Goal) },

	%
	% In certain cases -- for example existentially typed procedures,
	% or unification/compare procedures for equivalence types --
	% the parameters types may not match the types of the head variables.
	% In such cases, we need to box/unbox/cast them to the right type.
	% We also grab the original (uncast) lvals for the copied output
	% variables (if any) here, since for the return statement that
	% we append below, we want the original vars, not their cast versions.
	%
	ml_gen_var_list(CopiedOutputVars, CopiedOutputVarOriginalLvals),
	ml_gen_convert_headvars(HeadVars, ArgTypes, CopiedOutputVars, Context,
		ConvDecls, ConvInputStatements, ConvOutputStatements),
	(
		{ ConvDecls = [] },
		{ ConvInputStatements = [] },
		{ ConvOutputStatements = [] }
	->
		% No boxing/unboxing/casting required.
		DoGenGoal(MLDS_Decls, MLDS_Statements1)
	;
		% Boxing/unboxing/casting required.
		% We need to convert the input arguments,
		% generate the goal, convert the output arguments,
		% and then succeeed.
		{ DoConvOutputs = (pred(Decls::out, Statements::out, in, out)
					is det -->
			ml_gen_success(CodeModel, Context, SuccStatements),
			{ Decls = [] },
			{ Statements = list__append(ConvOutputStatements,
				SuccStatements) }
		) },
		ml_combine_conj(CodeModel, Context,
			DoGenGoal, DoConvOutputs,
			MLDS_Decls0, MLDS_Statements0),
		{ MLDS_Statements1 = list__append(ConvInputStatements,
			MLDS_Statements0) },
		{ MLDS_Decls = list__append(ConvDecls, MLDS_Decls0) }
	),

	%
	% Finally append an appropriate `return' statement, if needed.
	%
	ml_append_return_statement(CodeModel, CopiedOutputVarOriginalLvals,
		Context, MLDS_Statements1, MLDS_Statements).

%
% In certain cases -- for example existentially typed procedures,
% or unification/compare procedures for equivalence types --
% the parameter types may not match the types of the head variables.
% In such cases, we need to box/unbox/cast them to the right type.
% This procedure handles that.
%
:- pred ml_gen_convert_headvars(list(prog_var), list(prog_type),
		list(prog_var), prog_context,
		mlds__defns, mlds__statements, mlds__statements,
		ml_gen_info, ml_gen_info).
:- mode ml_gen_convert_headvars(in, in, in, in, out, out, out, in, out) is det.

ml_gen_convert_headvars([], [], _, _, [], [], []) --> [].
ml_gen_convert_headvars([Var|Vars], [HeadType|HeadTypes], CopiedOutputVars,
		Context, Decls, InputStatements, OutputStatements) -->
	ml_variable_type(Var, BodyType),
	(
		%
		% Check whether HeadType is the same as BodyType
		% (modulo the term__contexts)
		%
		{ map__init(Subst0) },
		{ type_unify(HeadType, BodyType, [], Subst0, Subst) },
		{ map__is_empty(Subst) }
	->
		% just recursively process the remaining arguments
		ml_gen_convert_headvars(Vars, HeadTypes, CopiedOutputVars,
			Context, Decls, InputStatements, OutputStatements)
	;
		%
		% generate the lval for the head variable
		%
		ml_gen_var_with_type(Var, HeadType, HeadVarLval),

		%
		% generate code to box or unbox that head variable,
		% to convert its type from HeadType to BodyType
		%
		=(MLDSGenInfo),
		{ ml_gen_info_get_varset(MLDSGenInfo, VarSet) },
		{ VarName = ml_gen_var_name(VarSet, Var) },
		ml_gen_box_or_unbox_lval(HeadType, BodyType, HeadVarLval,
			VarName, Context, BodyLval, ConvDecls,
			ConvInputStatements, ConvOutputStatements),

		%
		% Ensure that for any uses of this variable in the procedure
		% body, we use the BodyLval (which has type BodyType)
		% rather than the HeadVarLval (which has type HeadType).
		%
		ml_gen_info_set_var_lval(Var, BodyLval),

		%
		% Recursively process the remaining arguments
		%
		ml_gen_convert_headvars(Vars, HeadTypes, CopiedOutputVars,
			Context, Decls1, InputStatements1, OutputStatements1),

		%
		% Add the code to convert this input or output.
		%
		=(MLDSGenInfo2),
		{ ml_gen_info_get_byref_output_vars(MLDSGenInfo2,
			ByRefOutputVars) },
		{
			( list__member(Var, ByRefOutputVars)
			; list__member(Var, CopiedOutputVars)
			)
		->
			InputStatements = InputStatements1,
			OutputStatements = list__append(OutputStatements1,
				ConvOutputStatements)
		;
			InputStatements = list__append(ConvInputStatements,
				InputStatements1),
			OutputStatements = OutputStatements1
		},
		{ list__append(ConvDecls, Decls1, Decls) }
	).
ml_gen_convert_headvars([], [_|_], _, _, _, _, _) -->
	{ error("ml_gen_convert_headvars: length mismatch") }.
ml_gen_convert_headvars([_|_], [], _, _, _, _, _) -->
	{ error("ml_gen_convert_headvars: length mismatch") }.

%-----------------------------------------------------------------------------%
%
% Stuff to generate code for goals.
%

	% Generate MLDS code for the specified goal in the
	% specified code model.  Return the result as a single statement
	% (which may be a block statement containing nested declarations).
	%
ml_gen_goal(CodeModel, Goal, MLDS_Statement) -->
	ml_gen_goal(CodeModel, Goal, MLDS_Decls, MLDS_Statements),
	{ Goal = _ - GoalInfo },
	{ goal_info_get_context(GoalInfo, Context) },
	{ MLDS_Statement = ml_gen_block(MLDS_Decls, MLDS_Statements,
		Context) }.

	% Generate MLDS code for the specified goal in the
	% specified code model.  Return the result as two lists,
	% one containing the necessary declarations and the other
	% containing the generated statements.
	%
ml_gen_goal(CodeModel, Goal, MLDS_Decls, MLDS_Statements) -->
	{ Goal = GoalExpr - GoalInfo },
	%
	% Generate the local variables for this goal.
	% We need to declare any variables which
	% are local to this goal (including its subgoals),
	% but which are not local to a subgoal.
	% (If they're local to a subgoal, they'll be declared
	% when we generate code for that subgoal.)

	{ Locals = goal_local_vars(Goal) },
	{ SubGoalLocals = union_of_direct_subgoal_locals(Goal) },
	{ set__difference(Locals, SubGoalLocals, VarsToDeclareHere) },
	{ set__to_sorted_list(VarsToDeclareHere, VarsList) },
	=(MLDSGenInfo),
	{ ml_gen_info_get_varset(MLDSGenInfo, VarSet) },
	{ ml_gen_info_get_var_types(MLDSGenInfo, VarTypes) },
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	{ VarDecls = ml_gen_local_var_decls(VarSet, VarTypes,
		mlds__make_context(Context), ModuleInfo, VarsList) },

	%
	% Generate code for the goal in its own code model.
	%
	{ goal_info_get_context(GoalInfo, Context) },
	{ goal_info_get_code_model(GoalInfo, GoalCodeModel) },
	ml_gen_goal_expr(GoalExpr, GoalCodeModel, Context,
		GoalDecls, GoalStatements0),

	%
	% Add whatever wrapper is needed to convert the goal's
	% code model to the desired code model.
	%
	ml_gen_wrap_goal(CodeModel, GoalCodeModel, Context,
		GoalStatements0, GoalStatements),
	
	{ ml_join_decls(VarDecls, [], GoalDecls, GoalStatements, Context,
		MLDS_Decls, MLDS_Statements) }.

	% Return the set of variables which occur in the specified goal
	% (including in its subgoals) and which are local to that goal.
:- func goal_local_vars(hlds_goal) = set(prog_var).
goal_local_vars(Goal) = LocalVars :-
	% find all the variables in the goal
	goal_util__goal_vars(Goal, GoalVars),
	% delete the non-locals
	Goal = _ - GoalInfo,
	goal_info_get_code_gen_nonlocals(GoalInfo, NonLocalVars),
	set__difference(GoalVars, NonLocalVars, LocalVars).

:- func union_of_direct_subgoal_locals(hlds_goal) = set(prog_var).

union_of_direct_subgoal_locals(Goal - _GoalInfo) =
	promise_only_solution((pred(UnionOfSubGoalLocals::out) is cc_multi :-
		set__init(EmptySet),
		unsorted_aggregate(direct_subgoal(Goal),
			union_subgoal_locals, EmptySet, UnionOfSubGoalLocals)
	)).

:- pred union_subgoal_locals(hlds_goal, set(prog_var), set(prog_var)).
:- mode union_subgoal_locals(in, in, out) is det.

union_subgoal_locals(SubGoal, UnionOfSubGoalLocals0, UnionOfSubGoalLocals) :-
	SubGoalLocals = goal_local_vars(SubGoal),
	set__union(UnionOfSubGoalLocals0, SubGoalLocals, UnionOfSubGoalLocals).

	% ml_gen_wrap_goal(OuterCodeModel, InnerCodeModel, Context,
	%		MLDS_Statements0, MLDS_Statements):
	%
	%	OuterCodeModel is the code model expected by the
	%	context in which a goal is called. InnerCodeModel
	%	is the code model which the goal actually has.
	%	This predicate converts the code generated for
	%	the goal using InnerCodeModel into code that uses
	%	the calling convention appropriate for OuterCodeModel.

	%
	% If the inner and outer code models are equal,
	% we don't need to do anything special.

ml_gen_wrap_goal(model_det, model_det, _,
		MLDS_Statements, MLDS_Statements) --> [].
ml_gen_wrap_goal(model_semi, model_semi, _,
		MLDS_Statements, MLDS_Statements) --> [].
ml_gen_wrap_goal(model_non, model_non, _,
		MLDS_Statements, MLDS_Statements) --> [].

	% If the inner code model is more precise than the outer code
	% model, then we need to append some statements to convert
	% the calling convention for the inner code model to that of
	% the outer code model.

ml_gen_wrap_goal(model_semi, model_det, Context,
		MLDS_Statements0, MLDS_Statements) -->
	%
	% det goal in semidet context:
	%	<succeeded = Goal>
	% ===>
	%	<do Goal>
	%	succeeded = TRUE
	%
	ml_gen_set_success(const(true), Context, SetSuccessTrue),
	{ MLDS_Statements = list__append(MLDS_Statements0, [SetSuccessTrue]) }.

ml_gen_wrap_goal(model_non, model_det, Context,
		MLDS_Statements0, MLDS_Statements) -->
	%
	% det goal in nondet context:
	%	<Goal && SUCCEED()>
	% ===>
	%	<do Goal>
	%	SUCCEED()
	%
	ml_gen_call_current_success_cont(Context, CallCont),
	{ MLDS_Statements = list__append(MLDS_Statements0, [CallCont]) }.

ml_gen_wrap_goal(model_non, model_semi, Context,
		MLDS_Statements0, MLDS_Statements) -->
	%
	% semi goal in nondet context:
	%	<Goal && SUCCEED()>
	% ===>
	%	bool succeeded;
	%
	%	<succeeded = Goal>
	%	if (succeeded) SUCCEED()
	%
	ml_gen_test_success(Succeeded),
	ml_gen_call_current_success_cont(Context, CallCont),
	{ IfStmt = if_then_else(Succeeded, CallCont, no) },
	{ IfStatement = mlds__statement(IfStmt, mlds__make_context(Context)) },
	{ MLDS_Statements = list__append(MLDS_Statements0, [IfStatement]) }.

	% If the inner code model is less precise than the outer code model,
	% then simplify.m is supposed to wrap the goal inside a `some'
	% to indicate that a commit is needed.

ml_gen_wrap_goal(model_det, model_semi, _, _, _) -->
	{ error("ml_gen_wrap_goal: code model mismatch -- semi in det") }.
ml_gen_wrap_goal(model_det, model_non, _, _, _) -->
	{ error("ml_gen_wrap_goal: code model mismatch -- nondet in det") }.
ml_gen_wrap_goal(model_semi, model_non, _, _, _) -->
	{ error("ml_gen_wrap_goal: code model mismatch -- nondet in semi") }.

	% Generate code for a commit.
	%
:- pred ml_gen_commit(hlds_goal, code_model, prog_context,
			mlds__defns, mlds__statements,
			ml_gen_info, ml_gen_info).
:- mode ml_gen_commit(in, in, in, out, out, in, out) is det.

ml_gen_commit(Goal, CodeModel, Context, MLDS_Decls, MLDS_Statements) -->
	{ Goal = _ - GoalInfo },
	{ goal_info_get_code_model(GoalInfo, GoalCodeModel) },
	{ goal_info_get_context(GoalInfo, GoalContext) },

	( { GoalCodeModel = model_non, CodeModel = model_semi } ->

		%	model_non in semi context: (using try_commit/do_commit)
		%		<succeeded = Goal>
		% 	===>
		%		bool succeeded;
		%	#ifdef NONDET_COPY_OUT
		%		<local var decls>
		%	#endif
		%	#ifdef PUT_COMMIT_IN_OWN_FUNC
		%	    /*
		%	    ** to avoid problems with setjmp() and non-volatile
		%	    ** local variables, we need to put the call to
		%	    ** setjmp() in its own nested function
		%	    */
		%	    void commit_func()
		%	    {
		%       #endif
		%		MR_COMMIT_TYPE ref;
		%		void success() {
		%			MR_DO_COMMIT(ref);
		%		}
		%		MR_TRY_COMMIT(ref, {
		%			<Goal && success()>
		%			succeeded = FALSE;
		%		}, {
		%	#ifdef NONDET_COPY_OUT
		%			<copy local vars to output args>
		%	#endif
		%			succeeded = TRUE;
		%		})
		%	#ifdef PUT_COMMIT_IN_OWN_FUNC
		%	    }
		%	    commit_func();
		%       #endif

		ml_gen_maybe_make_locals_for_output_args(GoalInfo,
			LocalVarDecls, CopyLocalsToOutputArgs,
			OrigVarLvalMap),

		% generate the `success()' function
		ml_gen_new_func_label(no, SuccessFuncLabel, 
			SuccessFuncLabelRval),
		/* push nesting level */
		{ MLDS_Context = mlds__make_context(Context) },
		ml_gen_info_new_commit_label(CommitLabelNum),
		{ string__format("commit_%d", [i(CommitLabelNum)],
			CommitRef) },
		ml_qualify_var(CommitRef, CommitRefLval),
		{ CommitRefDecl = ml_gen_commit_var_decl(MLDS_Context,
			CommitRef) },
		{ DoCommitStmt = do_commit(lval(CommitRefLval)) },
		{ DoCommitStatement = mlds__statement(DoCommitStmt,
			MLDS_Context) },
		/* pop nesting level */
		ml_gen_nondet_label_func(SuccessFuncLabel, Context,
			DoCommitStatement, SuccessFunc),

		ml_get_env_ptr(EnvPtrRval),
		{ SuccessCont = success_cont(SuccessFuncLabelRval,
			EnvPtrRval, [], []) },
		ml_gen_info_push_success_cont(SuccessCont),
		ml_gen_goal(model_non, Goal, GoalDecls, GoalStatements),
		% hoist any static constant declarations for Goal
		% out to the top level
		{ list__filter(ml_decl_is_static_const, GoalDecls,
			GoalStaticDecls, GoalOtherDecls) },
		{ GoalStatement = ml_gen_block(GoalOtherDecls,
			GoalStatements, GoalContext) },
		ml_gen_info_pop_success_cont,
		ml_gen_set_success(const(false), Context, SetSuccessFalse),
		ml_gen_set_success(const(true), Context, SetSuccessTrue),
		{ TryCommitStmt = try_commit(CommitRefLval,
			ml_gen_block([], [GoalStatement, SetSuccessFalse],
				Context),
			ml_gen_block([], list__append(CopyLocalsToOutputArgs,
				[SetSuccessTrue]), Context)) },
		{ TryCommitStatement = mlds__statement(TryCommitStmt,
			MLDS_Context) },
		{ CommitFuncLocalDecls = [CommitRefDecl, SuccessFunc |
			GoalStaticDecls] },
		maybe_put_commit_in_own_func(CommitFuncLocalDecls,
			[TryCommitStatement], Context,
			CommitFuncDecls, MLDS_Statements),
		{ MLDS_Decls = LocalVarDecls ++ CommitFuncDecls },

		ml_gen_info_set_var_lvals(OrigVarLvalMap)

	; { GoalCodeModel = model_non, CodeModel = model_det } ->

		%	model_non in det context: (using try_commit/do_commit)
		%		<do Goal>
		%	===>
		%	#ifdef NONDET_COPY_OUT
		%		<local var decls>
		%	#endif
		%	#ifdef PUT_COMMIT_IN_NESTED_FUNC
		%	    /*
		%	    ** to avoid problems with setjmp() and non-volatile
		%	    ** local variables, we need to put the call to
		%	    ** setjmp() in its own nested functions
		%	    */
		%	    void commit_func()
		%	    {
		%       #endif
		%		MR_COMMIT_TYPE ref;
		%		void success() {
		%			MR_DO_COMMIT(ref);
		%		}
		%		MR_TRY_COMMIT(ref, {
		%			<Goal && success()>
		%		}, {
		%	#ifdef NONDET_COPY_OUT
		%			<copy local vars to output args>
		%	#endif
		%		})
		%	#ifdef PUT_COMMIT_IN_NESTED_FUNC
		%	    }
		%	    commit_func();
		%       #endif

		ml_gen_maybe_make_locals_for_output_args(GoalInfo,
			LocalVarDecls, CopyLocalsToOutputArgs,
			OrigVarLvalMap),

		% generate the `success()' function
		ml_gen_new_func_label(no,
			SuccessFuncLabel, SuccessFuncLabelRval),
		/* push nesting level */
		{ MLDS_Context = mlds__make_context(Context) },
		ml_gen_info_new_commit_label(CommitLabelNum),
		{ string__format("commit_%d", [i(CommitLabelNum)],
			CommitRef) },
		ml_qualify_var(CommitRef, CommitRefLval),
		{ CommitRefDecl = ml_gen_commit_var_decl(MLDS_Context,
			CommitRef) },
		{ DoCommitStmt = do_commit(lval(CommitRefLval)) },
		{ DoCommitStatement = mlds__statement(DoCommitStmt,
			MLDS_Context) },
		/* pop nesting level */
		ml_gen_nondet_label_func(SuccessFuncLabel, Context,
			DoCommitStatement, SuccessFunc),

		ml_get_env_ptr(EnvPtrRval),
		{ SuccessCont = success_cont(SuccessFuncLabelRval,
			EnvPtrRval, [], []) },
		ml_gen_info_push_success_cont(SuccessCont),
		ml_gen_goal(model_non, Goal, GoalDecls, GoalStatements),
		% hoist any static constant declarations for Goal
		% out to the top level
		{ list__filter(ml_decl_is_static_const, GoalDecls,
			GoalStaticDecls, GoalOtherDecls) },
		{ GoalStatement = ml_gen_block(GoalOtherDecls,
			GoalStatements, GoalContext) },
		ml_gen_info_pop_success_cont,

		{ TryCommitStmt = try_commit(CommitRefLval, GoalStatement,
			ml_gen_block([], CopyLocalsToOutputArgs, Context)) },
		{ TryCommitStatement = mlds__statement(TryCommitStmt,
			MLDS_Context) },
		{ CommitFuncLocalDecls = [CommitRefDecl, SuccessFunc |
			GoalStaticDecls] },
		maybe_put_commit_in_own_func(CommitFuncLocalDecls,
			[TryCommitStatement], Context,
			CommitFuncDecls, MLDS_Statements),
		{ MLDS_Decls = LocalVarDecls ++ CommitFuncDecls },

		ml_gen_info_set_var_lvals(OrigVarLvalMap)
	;
		% no commit required
		ml_gen_goal(CodeModel, Goal, MLDS_Decls, MLDS_Statements)
	).

	% maybe_put_commit_in_own_func(Defns0, Stmts0, Defns, Stmts):
	% if the --put-commit-in-own-func option is set, put
	% the commit in its own function.  This is needed for
	% the high-level C back-end, to handle problems with
	% setjmp()/longjmp() clobbering non-volatile local variables.
	%
	% Detailed explanation:
	%   For the high-level C back-end, we implement commits using
	%   setjmp()/longjmp().  Unfortunately for us, ANSI/ISO C says
	%   that longjmp() is allowed to clobber the values of any
	%   non-volatile local variables in the function that called
	%   setjmp() which have been modified between the setjmp()
	%   and the longjmp().
	%
	%   To avoid this, whenever we generate a commit, we put
	%   it in its own nested function, with the local variables
	%   (e.g. `succeeded', plus any outputs from the goal that
	%   we're committing over) remaining in the containing function.
	%   This ensures that none of the variables which get modified
	%   between the setjmp() and the longjmp() and which get
	%   referenced after the longjmp() are local variables in the
	%   function containing the setjmp().
	%
	%   [The obvious alternative of declaring the local variables in
	%   the function containing setjmp() as `volatile' doesn't work,
	%   since the assignments to those output variables may be deep
	%   in some function called indirectly from the goal that we're
	%   committing across, and assigning to a volatile-qualified
	%   variable via a non-volatile pointer is undefined behaviour.
	%   The only way to make it work would be to be to declare
	%   *every* output argument that we pass by reference as
	%   `volatile T *'.  But that would impose distributed fat and
	%   would make interoperability difficult.]
	%
:- pred maybe_put_commit_in_own_func(mlds__defns, mlds__statements,
		prog_context, mlds__defns, mlds__statements,
		ml_gen_info, ml_gen_info).
:- mode maybe_put_commit_in_own_func(in, in, in, out, out, in, out) is det.

maybe_put_commit_in_own_func(CommitFuncLocalDecls, TryCommitStatements,
		Context, MLDS_Decls, MLDS_Statements) -->
	ml_gen_info_put_commit_in_own_func(PutCommitInOwnFunc),
	( { PutCommitInOwnFunc = yes } ->
		%
		% Generate the `void commit_func() { ... }' wrapper
		% around the main body that we generated above
		%
		ml_gen_new_func_label(no, CommitFuncLabel, 
			CommitFuncLabelRval),
		/* push nesting level */
		{ CommitFuncBody = ml_gen_block(CommitFuncLocalDecls,
			TryCommitStatements, Context) },
		/* pop nesting level */
		ml_gen_nondet_label_func(CommitFuncLabel, Context,
			CommitFuncBody, CommitFunc),
		%
		% Generate the call to `commit_func();'
		%
		ml_gen_info_use_gcc_nested_functions(UseNestedFuncs),
		( { UseNestedFuncs = yes } ->
			{ ArgRvals = [] },
			{ ArgTypes = [] }
		;
			ml_get_env_ptr(EnvPtrRval),
			{ ArgRvals = [EnvPtrRval] },
			{ ArgTypes = [mlds__generic_env_ptr_type] }
		),
		{ RetTypes = [] },
		{ Signature = mlds__func_signature(ArgTypes, RetTypes) },
		{ CallOrTailcall = call },
		{ CallStmt = call(Signature, CommitFuncLabelRval, no,
			ArgRvals, [], CallOrTailcall) },
		{ CallStatement = mlds__statement(CallStmt,
			mlds__make_context(Context)) },
		% Package it all up
		{ MLDS_Statements = [CallStatement] },
		{ MLDS_Decls = [CommitFunc] }
	;
		{ MLDS_Statements = TryCommitStatements },
		{ MLDS_Decls = CommitFuncLocalDecls }
	).

	%
	% In commits, you have model_non code called from a model_det or
	% model_semi context.  With --nondet-copy-out, when generating code
	% for commits, if the context is a model_det or model_semi procedure
	% with output arguments passed by reference, then we need to introduce
	% local variables corresponding to those output arguments,
	% and at the end of the commit we'll copy the local variables into
	% the output arguments.
	%
:- pred ml_gen_maybe_make_locals_for_output_args(hlds_goal_info, mlds__defns,
		mlds__statements, map(prog_var, mlds__lval),
		ml_gen_info, ml_gen_info).
:- mode ml_gen_maybe_make_locals_for_output_args(in, out, out, out, in, out)
		is det.

ml_gen_maybe_make_locals_for_output_args(GoalInfo,
		LocalVarDecls, CopyLocalsToOutputArgs, OrigVarLvalMap) -->
	=(MLDSGenInfo0),
	{ ml_gen_info_get_var_lvals(MLDSGenInfo0, OrigVarLvalMap) },
	ml_gen_info_get_globals(Globals),
	{ globals__lookup_bool_option(Globals, nondet_copy_out,
		NondetCopyOut) },
	( { NondetCopyOut = yes } ->
		{ goal_info_get_context(GoalInfo, Context) },
		{ goal_info_get_nonlocals(GoalInfo, NonLocals) },
		{ ml_gen_info_get_byref_output_vars(MLDSGenInfo0,
			ByRefOutputVars) },
		{ VarsToCopy = set__intersect(set__list_to_set(ByRefOutputVars),
			NonLocals) },
		ml_gen_make_locals_for_output_args(
			set__to_sorted_list(VarsToCopy), Context,
			LocalVarDecls, CopyLocalsToOutputArgs)
	;
		{ LocalVarDecls = [] },
		{ CopyLocalsToOutputArgs = [] }
	).

:- pred ml_gen_make_locals_for_output_args(list(prog_var), prog_context,
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_make_locals_for_output_args(in, in, out, out, in, out) is det.

ml_gen_make_locals_for_output_args([], _, [], []) --> [].
ml_gen_make_locals_for_output_args([Var | Vars], Context,
		LocalDefns, Assigns) -->
	ml_gen_make_locals_for_output_args(Vars, Context,
		LocalDefns0, Assigns0),
	ml_variable_type(Var, Type),
	( { type_util__is_dummy_argument_type(Type) } ->
		{ LocalDefns = LocalDefns0 },
		{ Assigns = Assigns0 }
	;
		ml_gen_make_local_for_output_arg(Var, Type, Context,
			LocalDefn, Assign),
		{ LocalDefns = [LocalDefn | LocalDefns0] },
		{ Assigns = [Assign | Assigns0] }
	).

:- pred ml_gen_make_local_for_output_arg(prog_var, prog_type, prog_context,
		mlds__defn, mlds__statement, ml_gen_info, ml_gen_info).
:- mode ml_gen_make_local_for_output_arg(in, in, in, out, out, in, out) is det.

ml_gen_make_local_for_output_arg(OutputVar, Type, Context,
		LocalVarDefn, Assign) -->
	%
	% Look up the name of the output variable
	%
	=(MLDSGenInfo),
	{ ml_gen_info_get_varset(MLDSGenInfo, VarSet) },
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	{ OutputVarName = ml_gen_var_name(VarSet, OutputVar) },

	%
	% Generate a declaration for a corresponding local variable.
	%
	{ string__append("local_", OutputVarName, LocalVarName) },
	{ LocalVarDefn = ml_gen_var_decl(LocalVarName, Type,
		mlds__make_context(Context), ModuleInfo) },

	%
	% Generate code to assign from the local var to the output var
	%
	ml_gen_var(OutputVar, OutputVarLval),
	ml_qualify_var(LocalVarName, LocalVarLval),
	{ Assign = ml_gen_assign(OutputVarLval, lval(LocalVarLval), Context) },

	%
	% Update the lval for this variable so that any references to it
	% inside the commit refer to the local variable rather than
	% to the output argument.
	% (Note that we reset all the var lvals at the end of the commit.)
	%
	ml_gen_info_set_var_lval(OutputVar, LocalVarLval).

	% Generate the declaration for the `commit' variable.
	%
:- func ml_gen_commit_var_decl(mlds__context, mlds__var_name) = mlds__defn.
ml_gen_commit_var_decl(Context, VarName) =
	ml_gen_mlds_var_decl(var(VarName), mlds__commit_type, Context).

	% Generate MLDS code for the different kinds of HLDS goals.
	%
:- pred ml_gen_goal_expr(hlds_goal_expr, code_model, prog_context,
			mlds__defns, mlds__statements,
			ml_gen_info, ml_gen_info).
:- mode ml_gen_goal_expr(in, in, in, out, out, in, out) is det.

ml_gen_goal_expr(switch(Var, CanFail, CasesList, _), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_switch(Var, CanFail, CasesList, CodeModel, Context,
		MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(some(_Vars, _CanRemove, Goal), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_commit(Goal, CodeModel, Context, MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(if_then_else(_Vars, Cond, Then, Else, _),
		CodeModel, Context, MLDS_Decls, MLDS_Statements) -->
	ml_gen_ite(CodeModel, Cond, Then, Else, Context,
			MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(not(Goal), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_negation(Goal, CodeModel, Context, MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(conj(Goals), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_conj(Goals, CodeModel, Context, MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(disj(Goals, _), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_disj(Goals, CodeModel, Context, MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(par_conj(Goals, _SM), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	%
	% XXX currently we treat parallel conjunction the same as
	%     sequential conjunction -- parallelism is not yet implemented
	%
	ml_gen_conj(Goals, CodeModel, Context, MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(generic_call(GenericCall, Vars, Modes, Detism), CodeModel,
		Context, MLDS_Decls, MLDS_Statements) -->
	{ determinism_to_code_model(Detism, CallCodeModel) },
	{ require(unify(CodeModel, CallCodeModel),
		"ml_gen_generic_call: code model mismatch") },
	ml_gen_generic_call(GenericCall, Vars, Modes, CodeModel, Context,
		MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(call(PredId, ProcId, ArgVars, BuiltinState, _, PredName),
		CodeModel, Context, MLDS_Decls, MLDS_Statements) -->
	(
		{ BuiltinState = not_builtin }
	->
		ml_gen_var_list(ArgVars, ArgLvals),
		=(MLDSGenInfo),
		{ ml_gen_info_get_varset(MLDSGenInfo, VarSet) },
		{ ArgNames = ml_gen_var_names(VarSet, ArgVars) },
		ml_variable_types(ArgVars, ActualArgTypes),
		ml_gen_call(PredId, ProcId, ArgNames, ArgLvals, ActualArgTypes,
			CodeModel, Context, MLDS_Decls, MLDS_Statements)
	;
		% For the MLDS back-end, we can't treat
		% private_builtin:unsafe_type_cast as an
		% ordinary builtin, since the code that
		% builtin_ops__translate_builtin generates
		% for it is not type-correct.  Instead,
		% we handle it separately here.
		{ PredName = qualified(_, "unsafe_type_cast") }
	->
		ml_gen_var_list(ArgVars, ArgLvals),
		ml_variable_types(ArgVars, ArgTypes),
		(
			{ ArgLvals = [SrcLval, DestLval] },
			{ ArgTypes = [SrcType, DestType] }
		->
			ml_gen_box_or_unbox_rval(SrcType, DestType,
				lval(SrcLval), CastRval),
			{ Assign = ml_gen_assign(DestLval, CastRval,
				Context) },
			{ MLDS_Statements = [Assign] },
			{ MLDS_Decls = [] }
		;
			{ error("wrong number of args for unsafe_type_cast") }
		)
	;
		ml_gen_builtin(PredId, ProcId, ArgVars, CodeModel, Context,
			MLDS_Decls, MLDS_Statements)
	).

ml_gen_goal_expr(unify(_A, _B, _, Unification, _), CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_unification(Unification, CodeModel, Context,
		MLDS_Decls, MLDS_Statements).

ml_gen_goal_expr(pragma_foreign_code(Attributes,
                PredId, ProcId, ArgVars, ArgDatas, OrigArgTypes, PragmaImpl),
		CodeModel, OuterContext, MLDS_Decls, MLDS_Statements) -->
        (
                { PragmaImpl = ordinary(C_Code, _MaybeContext) },
                ml_gen_ordinary_pragma_c_code(CodeModel, Attributes,
                        PredId, ProcId, ArgVars, ArgDatas, OrigArgTypes,
                        C_Code, OuterContext, MLDS_Decls, MLDS_Statements)
        ;
                { PragmaImpl = nondet(
                        LocalVarsDecls, LocalVarsContext,
			FirstCode, FirstContext, LaterCode, LaterContext,
			_Treatment, SharedCode, SharedContext) },
                ml_gen_nondet_pragma_c_code(CodeModel, Attributes,
                        PredId, ProcId, ArgVars, ArgDatas, OrigArgTypes,
			OuterContext, LocalVarsDecls, LocalVarsContext,
			FirstCode, FirstContext, LaterCode, LaterContext,
			SharedCode, SharedContext, MLDS_Decls, MLDS_Statements)
	;
		{ PragmaImpl = import(Name, HandleReturn, Vars, _Context) },
		{ C_Code = string__append_list([HandleReturn, " ",
				Name, "(", Vars, ");"]) },
                ml_gen_ordinary_pragma_c_code(CodeModel, Attributes,
                        PredId, ProcId, ArgVars, ArgDatas, OrigArgTypes,
                        C_Code, OuterContext, MLDS_Decls, MLDS_Statements)
        ).

ml_gen_goal_expr(bi_implication(_, _), _, _, _, _) -->
	% these should have been expanded out by now
	{ error("ml_gen_goal_expr: unexpected bi_implication") }.

:- pred ml_gen_nondet_pragma_c_code(code_model, pragma_foreign_code_attributes,
		pred_id, proc_id, list(prog_var),
		list(maybe(pair(string, mode))), list(prog_type), prog_context,
		string, maybe(prog_context), string, maybe(prog_context),
		string, maybe(prog_context), string, maybe(prog_context),
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_nondet_pragma_c_code(in, in, in, in, in, in, in, in,
		in, in, in, in, in, in, in, in, out, out, in, out) is det.

	% For model_non pragma c_code,
	% we generate code of the following form:
	%
	%	#define MR_PROC_LABEL <procedure name>
	% 	<declaration of locals needed for boxing/unboxing>
	%	{
	% 		<declaration of one local variable for each arg>
	%		struct {
	%			<user's local_vars decls>
	%		} MR_locals;
	%		bool MR_done = FALSE;
	%		bool MR_succeeded = FALSE;
	%
	%		#define FAIL		(MR_done = TRUE)
	%		#define SUCCEED		(MR_succeeded = TRUE)
	%		#define SUCCEED_LAST	(MR_succeeded = TRUE, \
	%					 MR_done = TRUE)
	%		#define LOCALS		(&MR_locals)
	%
	%		<assign input args>
	%		<obtain global lock>
	%		<user's first_code C code>
	%		while (true) {
	%			<user's shared_code C code>
	%			<release global lock>
	%			if (MR_succeeded) {
	%				<assign output args>
	% 				<boxing/unboxing of outputs>
	%				CONT();
	%			}
	%			if (MR_done) break;
	%			<obtain global lock>
	%			<user's later_code C code>
	%		}
	%
	%		#undef FAIL
	%		#undef SUCCEED
	%		#undef SUCCEED_LAST
	%		#undef LOCALS
	%	}
	%	#undef MR_PROC_LABEL
	%
	% We insert a #define for MR_PROC_LABEL, so that the C code in
	% the Mercury standard library that allocates memory manually
	% can use MR_PROC_LABEL as the procname argument to
	% incr_hp_msg(), for memory profiling.  Hard-coding the procname
	% argument in the C code would be wrong, since it wouldn't
	% handle the case where the original pragma c_code procedure
	% gets inlined and optimized away.  Of course we also need to
	% #undef it afterwards.
	%		
ml_gen_nondet_pragma_c_code(CodeModel, Attributes,
		PredId, _ProcId, ArgVars, ArgDatas, OrigArgTypes, Context,
		LocalVarsDecls, LocalVarsContext, FirstCode, FirstContext,
		LaterCode, LaterContext, SharedCode, SharedContext,
		MLDS_Decls, MLDS_Statements) -->
	%
	% Combine all the information about the each arg
	%
	{ ml_make_c_arg_list(ArgVars, ArgDatas, OrigArgTypes,
		ArgList) },

	%
	% Generate <declaration of one local variable for each arg>
	%
	{ ml_gen_pragma_c_decls(ArgList, ArgDeclsList) },

	%
	% Generate definitions of the FAIL, SUCCEED, SUCCEED_LAST,
	% and LOCALS macros
	%
	{ string__append_list([
"	#define FAIL		(MR_done = TRUE)\n",
"	#define SUCCEED		(MR_succeeded = TRUE)\n",
"	#define SUCCEED_LAST	(MR_succeeded = TRUE, MR_done = TRUE)\n",
"	#define LOCALS		(&MR_locals)\n"
		], HashDefines) },
	{ string__append_list([
			"	#undef	FAIL\n",
			"	#undef	SUCCEED\n",
			"	#undef	SUCCEED_LAST\n",
			"	#undef	LOCALS\n"
		], HashUndefs) },

	%
	% Generate code to set the values of the input variables.
	%
	ml_gen_pragma_c_input_arg_list(ArgList, AssignInputsList),

	%
	% Generate code to assign the values of the output variables.
	%
	ml_gen_pragma_c_output_arg_list(ArgList, Context,
		AssignOutputsList, ConvDecls, ConvStatements),

	%
	% Generate code fragments to obtain and release the global lock
	%
	{ thread_safe(Attributes, ThreadSafe) },
	ml_gen_obtain_release_global_lock(ThreadSafe, PredId,
		ObtainLock, ReleaseLock),

	%
	% Generate the MR_PROC_LABEL #define
	%
	ml_gen_hash_define_mr_proc_label(HashDefine),

	%
	% Put it all together
	%
	{ Starting_C_Code = list__condense([
			[raw_target_code("{\n")],
			HashDefine,
			ArgDeclsList,
			[raw_target_code("\tstruct {\n"),
			user_target_code(LocalVarsDecls, LocalVarsContext),
			raw_target_code("\n"),
			raw_target_code("\t} MR_locals;\n"),
			raw_target_code("\tbool MR_succeeded = FALSE;\n"),
			raw_target_code("\tbool MR_done = FALSE;\n"),
			raw_target_code("\n"),
			raw_target_code(HashDefines),
			raw_target_code("\n")],
			AssignInputsList,
			[raw_target_code(ObtainLock),
			raw_target_code("\t{\n"),
			user_target_code(FirstCode, FirstContext),
			raw_target_code("\n\t;}\n"),
			raw_target_code("\twhile (1) {\n"),
			raw_target_code("\t\t{\n"),
			user_target_code(SharedCode, SharedContext),
			raw_target_code("\n\t\t;}\n"),
			raw_target_code("#undef MR_PROC_LABEL\n"),
			raw_target_code(ReleaseLock),
			raw_target_code("\t\tif (MR_succeeded) {\n")],
			AssignOutputsList
	]) },
	=(MLDSGenInfo),
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	{ module_info_globals(ModuleInfo, Globals) },
	{ globals__lookup_string_option(Globals, target, Target) },
	( { CodeModel = model_non } ->

		% For IL code, we can't call continutations because
		% there is no syntax for calling managed function
		% pointers in managed C++.  Instead we
		% have to call back into IL and make the continuation
		% call in IL.  This is called an "indirect" success
		% continuation call.
		
		(
			{ Target = "il" }
		->
			ml_gen_call_current_success_cont_indirectly(Context,
				CallCont)
		;
			ml_gen_call_current_success_cont(Context, CallCont)
		)
	;
		{ error("ml_gen_nondet_pragma_c_code: unexpected code model") }
	),
	{ Ending_C_Code = [
			raw_target_code("\t\t}\n"),
			raw_target_code("\t\tif (MR_done) break;\n"),
			raw_target_code(ObtainLock),
			raw_target_code("\t\t{\n"),
			user_target_code(LaterCode, LaterContext),
			raw_target_code("\n\t\t;}\n"),
			raw_target_code("\t}\n"),
			raw_target_code("\n"),
			raw_target_code(HashUndefs),
			raw_target_code("}\n")
	] },
	{ Starting_C_Code_Stmt = target_code(lang_C, Starting_C_Code) },
	{ Starting_C_Code_Statement = mlds__statement(
		atomic(Starting_C_Code_Stmt), mlds__make_context(Context)) },
	{ Ending_C_Code_Stmt = target_code(lang_C, Ending_C_Code) },
	{ Ending_C_Code_Statement = mlds__statement(
		atomic(Ending_C_Code_Stmt), mlds__make_context(Context)) },
	{ MLDS_Statements = list__condense([
		[Starting_C_Code_Statement],
		ConvStatements,
		[CallCont,
		Ending_C_Code_Statement]
	]) },
	{ MLDS_Decls = ConvDecls }.

:- pred ml_gen_ordinary_pragma_c_code(code_model, 
		pragma_foreign_code_attributes,
		pred_id, proc_id, list(prog_var),
		list(maybe(pair(string, mode))), list(prog_type),
		string, prog_context,
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_ordinary_pragma_c_code(in, in, in, in, in, in, 
		in, in, in, out, out, in, out) is det.

	% For ordinary (not model_non) pragma c_code,
	% we generate code of the following form:
	%
	% model_det pragma_c_code:
	%
	%	#define MR_PROC_LABEL <procedure name>
	% 	<declaration of locals needed for boxing/unboxing>
	%	{
	% 		<declaration of one local variable for each arg>
	%
	%		<assign input args>
	%		<obtain global lock>
	%		<c code>
	% 		<boxing/unboxing of outputs>
	%		<release global lock>
	%		<assign output args>
	%	}
	%	#undef MR_PROC_LABEL
	%		
	% model_semi pragma_c_code:
	%
	%	#define MR_PROC_LABEL <procedure name>
	% 	<declaration of locals needed for boxing/unboxing>
	%	{
	% 		<declaration of one local variable for each arg>
	%		bool SUCCESS_INDICATOR;
	%
	%		<assign input args>
	%		<obtain global lock>
	%		<c code>
	%		<release global lock>
	%		if (SUCCESS_INDICATOR) {
	%			<assign output args>
	% 			<boxing/unboxing of outputs>
	%		}
	%		
	%		<succeeded> = SUCCESS_INDICATOR;
	%	}
	%	#undef MR_PROC_LABEL
	%
	% We insert a #define for MR_PROC_LABEL, so that the C code in
	% the Mercury standard library that allocates memory manually
	% can use MR_PROC_LABEL as the procname argument to
	% incr_hp_msg(), for memory profiling.  Hard-coding the procname
	% argument in the C code would be wrong, since it wouldn't
	% handle the case where the original pragma c_code procedure
	% gets inlined and optimized away.  Of course we also need to
	% #undef it afterwards.
	%		
	% Note that we generate this code directly as
	% `target_code(lang_C, <string>)' instructions in the MLDS.
	% It would probably be nicer to encode more of the structure
	% in the MLDS, so that (a) we could do better MLDS optimization
	% and (b) so that the generation of C code strings could be
	% isolated in mlds_to_c.m.  Also we will need to do something
	% different for targets other than C, e.g. when compiling to
	% Java.
	%
ml_gen_ordinary_pragma_c_code(CodeModel, Attributes,
		PredId, _ProcId, ArgVars, ArgDatas, OrigArgTypes,
		C_Code, Context, MLDS_Decls, MLDS_Statements) -->
	%
	% Combine all the information about the each arg
	%
	{ ml_make_c_arg_list(ArgVars, ArgDatas, OrigArgTypes,
		ArgList) },

	%
	% Generate <declaration of one local variable for each arg>
	%
	{ ml_gen_pragma_c_decls(ArgList, ArgDeclsList) },

	%
	% Generate code to set the values of the input variables.
	%
	ml_gen_pragma_c_input_arg_list(ArgList, AssignInputsList),

	%
	% Generate code to assign the values of the output variables.
	%
	ml_gen_pragma_c_output_arg_list(ArgList, Context,
		AssignOutputsList, ConvDecls, ConvStatements),

	%
	% Generate code fragments to obtain and release the global lock
	%
	{ thread_safe(Attributes, ThreadSafe) },
	ml_gen_obtain_release_global_lock(ThreadSafe, PredId,
		ObtainLock, ReleaseLock),

	%
	% Generate the MR_PROC_LABEL #define
	%
	ml_gen_hash_define_mr_proc_label(HashDefine),

	%
	% Put it all together
	%
	( { CodeModel = model_det } ->
		{ Starting_C_Code = list__condense([
			[raw_target_code("{\n")],
			HashDefine,
			ArgDeclsList,
			[raw_target_code("\n")],
			AssignInputsList,
			[raw_target_code(ObtainLock),
			raw_target_code("\t\t{\n"),
			user_target_code(C_Code, yes(Context)),
			raw_target_code("\n\t\t;}\n"),
			raw_target_code("#undef MR_PROC_LABEL\n"),
			raw_target_code(ReleaseLock)],
			AssignOutputsList
		]) },
		{ Ending_C_Code = [raw_target_code("}\n")] }
	; { CodeModel = model_semi } ->
		ml_success_lval(SucceededLval),
		{ Starting_C_Code = list__condense([
			[raw_target_code("{\n")],
			HashDefine,
			ArgDeclsList,
			[raw_target_code("\tbool SUCCESS_INDICATOR;\n"),
			raw_target_code("\n")],
			AssignInputsList,
			[raw_target_code(ObtainLock),
			raw_target_code("\t\t{\n"),
			user_target_code(C_Code, yes(Context)),
			raw_target_code("\n\t\t;}\n"),
			raw_target_code("#undef MR_PROC_LABEL\n"),
			raw_target_code(ReleaseLock),
			raw_target_code("\tif (SUCCESS_INDICATOR) {\n")],
			AssignOutputsList
		]) },
		{ Ending_C_Code = [
			raw_target_code("\t}\n"),
			target_code_output(SucceededLval),
			raw_target_code(" = SUCCESS_INDICATOR;\n"),
			raw_target_code("}\n")
		] }
	;
		{ error("ml_gen_ordinary_pragma_c_code: unexpected code model") }
	),
	{ Starting_C_Code_Stmt = target_code(lang_C, Starting_C_Code) },
	{ Ending_C_Code_Stmt = target_code(lang_C, Ending_C_Code) },
	{ Starting_C_Code_Statement = mlds__statement(
		atomic(Starting_C_Code_Stmt), mlds__make_context(Context)) },
	{ Ending_C_Code_Statement = mlds__statement(atomic(Ending_C_Code_Stmt),
		mlds__make_context(Context)) },
	{ MLDS_Statements = list__condense([
		[Starting_C_Code_Statement],
		ConvStatements,
		[Ending_C_Code_Statement]
	]) },
	{ MLDS_Decls = ConvDecls }.

	% Generate code fragments to obtain and release the global lock
	% (this is used for ensuring thread safety in a concurrent
	% implementation)
	%
:- pred ml_gen_obtain_release_global_lock(thread_safe, pred_id,
		string, string, ml_gen_info, ml_gen_info).
:- mode ml_gen_obtain_release_global_lock(in, in, out, out, in, out) is det.

ml_gen_obtain_release_global_lock(ThreadSafe, PredId,
		ObtainLock, ReleaseLock) -->
	=(MLDSGenInfo),
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	{ module_info_globals(ModuleInfo, Globals) },
	{ globals__lookup_bool_option(Globals, parallel, Parallel) },
	{
		Parallel = yes,
		ThreadSafe = not_thread_safe
	->
		module_info_pred_info(ModuleInfo, PredId, PredInfo),
		pred_info_name(PredInfo, Name),
		llds_out__quote_c_string(Name, MangledName),
		string__append_list(["\tMR_OBTAIN_GLOBAL_LOCK(""",
			MangledName, """);\n"], ObtainLock),
		string__append_list(["\tMR_RELEASE_GLOBAL_LOCK(""",
			MangledName, """);\n"], ReleaseLock)
	;
		ObtainLock = "",
		ReleaseLock = ""
	}.

:- pred ml_gen_hash_define_mr_proc_label(list(target_code_component)::out,
		ml_gen_info::in, ml_gen_info::out) is det.

ml_gen_hash_define_mr_proc_label(HashDefine) -->
	=(MLDSGenInfo),
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	% Note that we use the pred_id and proc_id of the current procedure,
	% not the one that the pragma foreign_code originally came from.
	% There may not be any function address for the latter, e.g. if it
	% has been inlined and the original definition optimized away.
	{ ml_gen_info_get_pred_id(MLDSGenInfo, PredId) },
	{ ml_gen_info_get_proc_id(MLDSGenInfo, ProcId) },
	{ ml_gen_proc_label(ModuleInfo, PredId, ProcId, MLDS_Name,
			MLDS_Module) },
	{ HashDefine = [raw_target_code("#define MR_PROC_LABEL "),
			name(qual(MLDS_Module, MLDS_Name)),
			raw_target_code("\n")] }.


%---------------------------------------------------------------------------%

%
% we gather all the information about each pragma_c argument
% together into this struct
%

:- type ml_c_arg
	--->	ml_c_arg(
			prog_var,
			maybe(pair(string, mode)),	% name and mode
			prog_type	% original type before
					% inlining/specialization
					% (the actual type may be an instance
					% of this type, if this type is
					% polymorphic).
		).

:- pred ml_make_c_arg_list(list(prog_var)::in,
		list(maybe(pair(string, mode)))::in, list(prog_type)::in,
		list(ml_c_arg)::out) is det.

ml_make_c_arg_list(Vars, ArgDatas, Types, ArgList) :-
	( Vars = [], ArgDatas = [], Types = [] ->
		ArgList = []
	; Vars = [V|Vs], ArgDatas = [N|Ns], Types = [T|Ts] ->
		Arg = ml_c_arg(V, N, T),
		ml_make_c_arg_list(Vs, Ns, Ts, Args),
		ArgList = [Arg | Args]
	;
		error("ml_code_gen:make_c_arg_list - length mismatch")
	).

%---------------------------------------------------------------------------%

% ml_gen_pragma_c_decls generates C code to declare the arguments
% for a `pragma c_code' declaration.
%
:- pred ml_gen_pragma_c_decls(list(ml_c_arg)::in,
		list(target_code_component)::out) is det.

ml_gen_pragma_c_decls([], []).
ml_gen_pragma_c_decls([Arg|Args], [Decl|Decls]) :-
	ml_gen_pragma_c_decl(Arg, Decl),
	ml_gen_pragma_c_decls(Args, Decls).

% ml_gen_pragma_c_decl generates C code to declare an argument
% of a `pragma c_code' declaration.
%
:- pred ml_gen_pragma_c_decl(ml_c_arg::in, target_code_component::out) is det.

ml_gen_pragma_c_decl(ml_c_arg(_Var, MaybeNameAndMode, Type), Decl) :-
	(
		MaybeNameAndMode = yes(ArgName - _Mode),
		\+ var_is_singleton(ArgName)
	->
		export__type_to_type_string(Type, TypeString),
		string__format("\t%s %s;\n", [s(TypeString), s(ArgName)],
			DeclString)
	;
		% if the variable doesn't occur in the ArgNames list,
		% it can't be used, so we just ignore it
		DeclString = ""
	),
	Decl = raw_target_code(DeclString).

%-----------------------------------------------------------------------------%

% var_is_singleton determines whether or not a given pragma_c variable
% is singleton (i.e. starts with an underscore)
%
% Singleton vars should be ignored when generating the declarations for
% pragma_c arguments because:
%
%	- they should not appear in the C code
% 	- they could clash with the system name space
%
:- pred var_is_singleton(string) is semidet.
:- mode var_is_singleton(in) is semidet.

var_is_singleton(Name) :-
	string__first_char(Name, '_', _).

%-----------------------------------------------------------------------------%

:- pred ml_gen_pragma_c_input_arg_list(list(ml_c_arg)::in,
		list(target_code_component)::out,
		ml_gen_info::in, ml_gen_info::out) is det.

ml_gen_pragma_c_input_arg_list(ArgList, AssignInputs) -->
	list__map_foldl(ml_gen_pragma_c_input_arg, ArgList, AssignInputsList),
	{ list__condense(AssignInputsList, AssignInputs) }.

% ml_gen_pragma_c_input_arg generates C code to assign the value of an input
% arg for a `pragma c_code' declaration.
%
:- pred ml_gen_pragma_c_input_arg(ml_c_arg::in,
		list(target_code_component)::out,
		ml_gen_info::in, ml_gen_info::out) is det.

ml_gen_pragma_c_input_arg(ml_c_arg(Var, MaybeNameAndMode, OrigType),
		AssignInput) -->
	=(MLDSGenInfo),
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	(
		{ MaybeNameAndMode = yes(ArgName - Mode) },
		{ \+ var_is_singleton(ArgName) },
		{ mode_to_arg_mode(ModuleInfo, Mode, OrigType, top_in) }
	->
		ml_variable_type(Var, VarType),
		ml_gen_var(Var, VarLval),
		( { type_util__is_dummy_argument_type(VarType) } ->
			% The variable may not have been declared,
			% so we need to generate a dummy value for it.
			% Using `0' here is more efficient than
			% using private_builtin__dummy_var, which is
			% what ml_gen_var will have generated for this
			% variable.
			{ ArgRval = const(int_const(0)) }
		;
			ml_gen_box_or_unbox_rval(VarType, OrigType,
				lval(VarLval), ArgRval)
		),
		{ module_info_globals(ModuleInfo, Globals) },
		{ globals__lookup_bool_option(Globals, highlevel_data,
			HighLevelData) },
		{ HighLevelData = yes ->
			% In general, the types used for the C interface
			% are not the same as the types used by
			% --high-level-data, so we always use a cast here.
			% (Strictly speaking the cast is not needed for
			% a few cases like `int', but it doesn't do any harm.)
			export__type_to_type_string(OrigType, TypeString),
			string__format("(%s)", [s(TypeString)], Cast)
		;
			% For --no-high-level-data, we only need to use
			% a cast is for polymorphic types, which are
			% `Word' in the C interface but `MR_Box' in the
			% MLDS back-end.
			( type_util__var(OrigType, _) ->
				Cast = "(MR_Word) "
			;
				Cast = ""
			)
		},
		{ string__format("\t%s = %s\n",
			[s(ArgName), s(Cast)],
			AssignToArgName) },
		{ AssignInput = [
			raw_target_code(AssignToArgName),
			target_code_input(ArgRval),
			raw_target_code(";\n")
		] }
	;
		% if the variable doesn't occur in the ArgNames list,
		% it can't be used, so we just ignore it
		{ AssignInput = [] }
	).

:- pred ml_gen_pragma_c_output_arg_list(list(ml_c_arg)::in, prog_context::in,
		list(target_code_component)::out,
		mlds__defns::out, mlds__statements::out,
		ml_gen_info::in, ml_gen_info::out) is det.

ml_gen_pragma_c_output_arg_list([], _, [], [], []) --> [].
ml_gen_pragma_c_output_arg_list([C_Arg | C_Args], Context, Components,
		ConvDecls, ConvStatements) -->
	ml_gen_pragma_c_output_arg(C_Arg, Context, Components1,
			ConvDecls1, ConvStatements1),
	ml_gen_pragma_c_output_arg_list(C_Args, Context, Components2,
			ConvDecls2, ConvStatements2),
	{ Components = list__append(Components1, Components2) },
	{ ConvDecls = list__append(ConvDecls1, ConvDecls2) },
	{ ConvStatements = list__append(ConvStatements1, ConvStatements2) }.

% ml_gen_pragma_c_output_arg generates C code to assign the value of an output
% arg for a `pragma c_code' declaration.
%
:- pred ml_gen_pragma_c_output_arg(ml_c_arg::in, prog_context::in,
		list(target_code_component)::out,
		mlds__defns::out, mlds__statements::out,
		ml_gen_info::in, ml_gen_info::out) is det.

ml_gen_pragma_c_output_arg(ml_c_arg(Var, MaybeNameAndMode, OrigType),
		Context, AssignOutput, ConvDecls, ConvOutputStatements) -->
	=(MLDSGenInfo),
	{ ml_gen_info_get_module_info(MLDSGenInfo, ModuleInfo) },
	(
		{ MaybeNameAndMode = yes(ArgName - Mode) },
		{ \+ var_is_singleton(ArgName) },
		{ \+ type_util__is_dummy_argument_type(OrigType) },
		{ mode_to_arg_mode(ModuleInfo, Mode, OrigType, top_out) }
	->
		ml_variable_type(Var, VarType),
		ml_gen_var(Var, VarLval),
		ml_gen_box_or_unbox_lval(VarType, OrigType, VarLval, ArgName,
			Context, ArgLval, ConvDecls, _ConvInputStatements,
			ConvOutputStatements),
		{ module_info_globals(ModuleInfo, Globals) },
		{ globals__lookup_bool_option(Globals, highlevel_data,
			HighLevelData) },
		{ HighLevelData = yes ->
			% In general, the types used for the C interface
			% are not the same as the types used by
			% --high-level-data, so we always use a cast here.
			% (Strictly speaking the cast is not needed for
			% a few cases like `int', but it doesn't do any harm.)
			% Note that we can't easily obtain the type string
			% for the RHS of the assignment, so instead we
			% cast the LHS.
			export__type_to_type_string(OrigType, TypeString),
			string__format("*(%s *)&", [s(TypeString)], LHS_Cast),
			RHS_Cast = ""
		;
			% For --no-high-level-data, we only need to use
			% a cast is for polymorphic types, which are
			% `Word' in the C interface but `MR_Box' in the
			% MLDS back-end.
			( type_util__var(VarType, _) ->
				RHS_Cast = "(MR_Box) "
			;
				RHS_Cast = ""
			),
			LHS_Cast = ""
		},
		{ string__format(" = %s%s;\n", [s(RHS_Cast), s(ArgName)],
			AssignFromArgName) },
		{ string__format("\t%s\n", [s(LHS_Cast)], AssignTo) },
		{ AssignOutput = [
			raw_target_code(AssignTo),
			target_code_output(ArgLval),
			raw_target_code(AssignFromArgName)
		] }
	;
		% if the variable doesn't occur in the ArgNames list,
		% it can't be used, so we just ignore it
		{ AssignOutput = [] },
		{ ConvDecls = [] },
		{ ConvOutputStatements = [] }
	).

%-----------------------------------------------------------------------------%
%
% Code for if-then-else
%

:- pred ml_gen_ite(code_model, hlds_goal, hlds_goal, hlds_goal, prog_context,
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_ite(in, in, in, in, in, out, out, in, out) is det.

ml_gen_ite(CodeModel, Cond, Then, Else, Context,
		MLDS_Decls, MLDS_Statements) -->
	{ Cond = _ - CondGoalInfo },
	{ goal_info_get_code_model(CondGoalInfo, CondCodeModel) },
	(
		%	model_det Cond:
		%		<(Cond -> Then ; Else)>
		%	===>
		%		<Cond>
		%		<Then>
		{ CondCodeModel = model_det },
		ml_gen_goal(model_det, Cond, CondStatement),
		ml_gen_goal(CodeModel, Then, ThenStatement),
		{ MLDS_Decls = [] },
		{ MLDS_Statements = [CondStatement, ThenStatement] }
	;
		%	model_semi cond:
		%		<(Cond -> Then ; Else)>
		%	===>
		%		bool succeeded;
		%	
		%		<succeeded = Cond>
		%		if (succeeded) {
		%			<Then>
		%		} else {
		%			<Else>
		%		}
		{ CondCodeModel = model_semi },
		ml_gen_goal(model_semi, Cond, CondDecls, CondStatements),
		ml_gen_test_success(Succeeded),
		ml_gen_goal(CodeModel, Then, ThenStatement),
		ml_gen_goal(CodeModel, Else, ElseStatement),
		{ IfStmt = if_then_else(Succeeded, ThenStatement,
			yes(ElseStatement)) },
		{ IfStatement = mlds__statement(IfStmt,
			mlds__make_context(Context)) },
		{ MLDS_Decls = CondDecls },
		{ MLDS_Statements = list__append(CondStatements,
			[IfStatement]) }
	;
		%	/*
		%	** XXX The following transformation does not do as
		%	**     good a job of GC as it could.  Ideally we ought
		%	**     to ensure that stuff used only in the `Else'
		%	**     part will be reclaimed if a GC occurs during
		%	**     the `Then' part.  But that is a bit tricky to
		%	**     achieve.
		%	*/
		%
		%	model_non cond:
		%		<(Cond -> Then ; Else)>
		%	===>
		%		bool cond_<N>;
		%
		%		void then_func() {
		%			cond_<N> = TRUE;
		%			<Then>
		%		}
		%
		%		cond_<N> = FALSE;
		%		<Cond && then_func()>
		%		if (!cond_<N>) {
		%			<Else>
		%		}
		%	except that we hoist any declarations generated
		%	for <Cond> to the top of the scope, so that they
		%	are in scope for the <Then> goal
		%	(this is needed for declarations of static consts)


		{ CondCodeModel = model_non },

		% generate the `cond_<N>' var and the code to initialize it to false
		ml_gen_info_new_cond_var(CondVar),
		{ MLDS_Context = mlds__make_context(Context) },
		{ CondVarDecl = ml_gen_cond_var_decl(CondVar, MLDS_Context) },
		ml_gen_set_cond_var(CondVar, const(false), Context,
			SetCondFalse),

		% allocate a name for the `then_func'
		ml_gen_new_func_label(no, ThenFuncLabel, ThenFuncLabelRval),

		% generate <Cond && then_func()>
		ml_get_env_ptr(EnvPtrRval),
		{ SuccessCont = success_cont(ThenFuncLabelRval, EnvPtrRval,
			[], []) },
		ml_gen_info_push_success_cont(SuccessCont),
		ml_gen_goal(model_non, Cond, CondDecls, CondStatements),
		ml_gen_info_pop_success_cont,

		% generate the `then_func'
		/* push nesting level */
		{ Then = _ - ThenGoalInfo },
		{ goal_info_get_context(ThenGoalInfo, ThenContext) },
		ml_gen_set_cond_var(CondVar, const(true), ThenContext,
			SetCondTrue),
		ml_gen_goal(CodeModel, Then, ThenStatement),
		{ ThenFuncBody = ml_gen_block([],
			[SetCondTrue, ThenStatement], ThenContext) },
		/* pop nesting level */
		ml_gen_nondet_label_func(ThenFuncLabel, ThenContext,
			ThenFuncBody, ThenFunc),

		% generate `if (!cond_<N>) { <Else> }'
		ml_gen_test_cond_var(CondVar, CondSucceeded),
		ml_gen_goal(CodeModel, Else, ElseStatement),
		{ IfStmt = if_then_else(unop(std_unop(not), CondSucceeded),
			ElseStatement, no) },
		{ IfStatement = mlds__statement(IfStmt, MLDS_Context) },

		% package it all up in the right order
		{ MLDS_Decls = list__append([CondVarDecl | CondDecls], [ThenFunc]) },
		{ MLDS_Statements = list__append(
			[SetCondFalse | CondStatements], [IfStatement]) }
	).

%-----------------------------------------------------------------------------%
%
% Code for negation
%

:- pred ml_gen_negation(hlds_goal, code_model, prog_context,
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_negation(in, in, in, out, out, in, out) is det.

ml_gen_negation(Cond, CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	{ Cond = _ - CondGoalInfo },
	{ goal_info_get_code_model(CondGoalInfo, CondCodeModel) },
	(
		% model_det negation:
		%		<not(Goal)>
		%	===>
		%	{
		%		bool succeeded;
		%		<succeeded = Goal>
		%		/* now ignore the value of succeeded,
		%		   which we know will be FALSE */
		%	}
		{ CodeModel = model_det },
		ml_gen_goal(model_semi, Cond, MLDS_Decls, MLDS_Statements)
	;
		% model_semi negation, model_det goal:
		%		<succeeded = not(Goal)>
		%	===>
		%		<do Goal>
		%		succeeded = FALSE;
		{ CodeModel = model_semi, CondCodeModel = model_det },
		ml_gen_goal(model_det, Cond, CondDecls, CondStatements),
		ml_gen_set_success(const(false), Context, SetSuccessFalse),
		{ MLDS_Decls = CondDecls },
		{ MLDS_Statements = list__append(CondStatements,
			[SetSuccessFalse]) }
	;
		% model_semi negation, model_semi goal:
		%		<succeeded = not(Goal)>
		%	===>
		%		<succeeded = Goal>
		%		succeeded = !succeeded;
		{ CodeModel = model_semi, CondCodeModel = model_semi },
		ml_gen_goal(model_semi, Cond, CondDecls, CondStatements),
		ml_gen_test_success(Succeeded),
		ml_gen_set_success(unop(std_unop(not), Succeeded), Context,
			InvertSuccess),
		{ MLDS_Decls = CondDecls },
		{ MLDS_Statements = list__append(CondStatements,
			[InvertSuccess]) }
	;
		{ CodeModel = model_semi, CondCodeModel = model_non },
		{ error("ml_gen_negation: nondet cond") }
	;
		{ CodeModel = model_non },
		{ error("ml_gen_negation: nondet negation") }
	).

%-----------------------------------------------------------------------------%
%
% Code for conjunctions
%

:- pred ml_gen_conj(hlds_goals, code_model, prog_context,
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_conj(in, in, in, out, out, in, out) is det.

ml_gen_conj([], CodeModel, Context, [], MLDS_Statements) -->
	ml_gen_success(CodeModel, Context, MLDS_Statements).
ml_gen_conj([SingleGoal], CodeModel, _Context,
		MLDS_Decls, MLDS_Statements) -->
	ml_gen_goal(CodeModel, SingleGoal, MLDS_Decls, MLDS_Statements).
ml_gen_conj([First | Rest], CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	{ Rest = [_ | _] },
	{ First = _ - FirstGoalInfo },
	{ goal_info_get_determinism(FirstGoalInfo, FirstDeterminism) },
	( { determinism_components(FirstDeterminism, _, at_most_zero) } ->
		% the `Rest' code is unreachable
		ml_gen_goal(CodeModel, First, MLDS_Decls, MLDS_Statements)
	;
		{ determinism_to_code_model(FirstDeterminism, FirstCodeModel) },
		{ DoGenFirst = ml_gen_goal(FirstCodeModel, First) },
		{ DoGenRest = ml_gen_conj(Rest, CodeModel, Context) },
		ml_combine_conj(FirstCodeModel, Context,
			DoGenFirst, DoGenRest, MLDS_Decls, MLDS_Statements)
	).

%-----------------------------------------------------------------------------%
%
% Code for disjunctions
%

:- pred ml_gen_disj(hlds_goals, code_model, prog_context,
		mlds__defns, mlds__statements, ml_gen_info, ml_gen_info).
:- mode ml_gen_disj(in, in, in, out, out, in, out) is det.

	%
	% handle empty disjunctions (a.ka. `fail')
	%
ml_gen_disj([], CodeModel, Context, [], Statements) -->
	ml_gen_failure(CodeModel, Context, Statements).

	%
	% handle singleton disjunctions
	% (the HLDS should not contain singleton disjunctions,
	% but this code is needed to handle recursive calls to ml_gen_disj)
	% Note that each arm of the model_non disjunction is placed into
	% a block.  This avoids a problem where ml_join_decls can create
	% block nesting proportional to the size of the disjunction.
	% The nesting can hit fixed limit problems in some C compilers.
	%
ml_gen_disj([SingleGoal], CodeModel, Context, [], [MLDS_Statement]) -->
	ml_gen_goal(CodeModel, SingleGoal, Goal_Decls, Goal_Statements),
	{ MLDS_Statement = ml_gen_block(Goal_Decls, Goal_Statements,
			Context) }.

ml_gen_disj([First | Rest], CodeModel, Context,
		MLDS_Decls, MLDS_Statements) -->
	{ Rest = [_ | _] },
	( { CodeModel = model_non } ->
		%
		% model_non disj:
		%
		%		<(Goal ; Goals) && SUCCEED()>
		%	===>
		%		<Goal && SUCCEED()>
		%		<Goals && SUCCEED()>
		%
		ml_gen_goal(model_non, First, FirstDecls, FirstStatements),
		ml_gen_disj(Rest, model_non, Context,
			RestDecls, RestStatements),

		(
			{ RestDecls = [] }
		->
			{ FirstBlock = ml_gen_block(FirstDecls,
					FirstStatements, Context) },
			{ MLDS_Decls = [] },
			{ MLDS_Statements = [FirstBlock | RestStatements] }
		;
			{ error("ml_gen_disj: RestDecls not empty.") }
		)

	; /* CodeModel is model_det or model_semi */
		%
		% model_det/model_semi disj:
		%
		%	model_det goal:
		%		<Goal ; Goals>
		%	===>
		%		<Goal>
		%		/* <Goals> will never be reached */
		%
		%	model_semi goal:
		%		<Goal ; Goals>
		%	===>
		%	{
		%		bool succeeded;
		%	
		%		<succeeded = Goal>;
		%		if (!succeeded) {
		%			<Goals>;
		%		}
		%	}
		%
		{ First = _ - FirstGoalInfo },
		{ goal_info_get_code_model(FirstGoalInfo, FirstCodeModel) },
		(
			{ FirstCodeModel = model_det },
			ml_gen_goal(model_det, First,
				MLDS_Decls, MLDS_Statements)
		;
			{ FirstCodeModel = model_semi },
			ml_gen_goal(model_semi, First,
				FirstDecls, FirstStatements),
			ml_gen_test_success(Succeeded),
			ml_gen_disj(Rest, CodeModel, Context,
				RestDecls, RestStatements),
			{ RestStatement = ml_gen_block(RestDecls,
				RestStatements, Context) },
			{ IfStmt = if_then_else(unop(std_unop(not), Succeeded),
						RestStatement, no) },
			{ IfStatement = mlds__statement(IfStmt,
				mlds__make_context(Context)) },
			{ MLDS_Decls = FirstDecls },
			{ MLDS_Statements = list__append(FirstStatements,
				[IfStatement]) }
		;
			{ FirstCodeModel = model_non },
			% simplify.m should get wrap commits around these
			{ error("model_non disj in model_det disjunction") }
		)
	).

%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%