File: llds_out.m

package info (click to toggle)
mercury 0.9-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 18,488 kB
  • ctags: 9,800
  • sloc: objc: 146,680; ansic: 51,418; sh: 6,436; lisp: 1,567; cpp: 1,040; perl: 854; makefile: 450; asm: 232; awk: 203; exp: 32; fortran: 3; csh: 1
file content (4258 lines) | stat: -rw-r--r-- 144,564 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
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
%-----------------------------------------------------------------------------%
% Copyright (C) 1996-1999 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.
%-----------------------------------------------------------------------------%

% LLDS - The Low-Level Data Structure.

% This module defines the routines for printing out LLDS,
% the Low Level Data Structure.

% Main authors: conway, fjh, zs.

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

:- module llds_out.

:- interface.

:- import_module llds, builtin_ops, prog_data, hlds_data, rl_file.
:- import_module set_bbbtree, bool, io, std_util.

	% Given a 'c_file' structure, output the LLDS code inside it
	% into one or more .c files, depending on the setting of the
	% --split-c-files option. The second argument gives the set of
	% labels that have layout structures. The third gives the Aditi-RL
	% code for the module.

:- pred output_llds(c_file, set_bbbtree(label), maybe(rl_file),
		io__state, io__state).
:- mode output_llds(in, in, in, di, uo) is det.

	% Convert an lval to a string description of that lval.

:- pred llds_out__lval_to_string(lval, string).
:- mode llds_out__lval_to_string(in, out) is semidet.

	% Convert a register to a string description of that register.

:- pred llds_out__reg_to_string(reg_type, int, string).
:- mode llds_out__reg_to_string(in, in, out) is det.

	% Convert a binary operator to a string description of that operator.

:- pred llds_out__binary_op_to_string(binary_op, string).
:- mode llds_out__binary_op_to_string(in, out) is det.

	% Output an instruction and (if the third arg is yes) the comment.
	% This predicate is provided for debugging use only.

:- pred output_instruction_and_comment(instr, string, bool,
	io__state, io__state).
:- mode output_instruction_and_comment(in, in, in, di, uo) is det.

	% Output an instruction.
	% This predicate is provided for debugging use only.

:- pred output_instruction(instr, io__state, io__state).
:- mode output_instruction(in, di, uo) is det.

	% Output a label (used by garbage collection).

:- pred output_label(label, io__state, io__state).
:- mode output_label(in, di, uo) is det.

	% Output a proc label (used for building static call graph for prof).

:- pred output_proc_label(proc_label, io__state, io__state).
:- mode output_proc_label(in, di, uo) is det.

	% Get a proc label string (used by procs which are exported to C).
	% The boolean controls whether a prefix ("mercury__") is added to the
	% proc label.

:- pred llds_out__get_proc_label(proc_label, bool, string).
:- mode llds_out__get_proc_label(in, in, out) is det.

	% Get a label string.
	% The boolean controls whether a prefix ("mercury__") is added to the
	% label.

:- pred llds_out__get_label(label, bool, string).
:- mode llds_out__get_label(in, in, out) is det.

	% Mangle an arbitrary name into a C identifier

:- pred llds_out__name_mangle(string, string).
:- mode llds_out__name_mangle(in, out) is det.

	% Mangle a possibly module-qualified Mercury symbol name
	% into a C identifier.

:- pred llds_out__sym_name_mangle(sym_name, string).
:- mode llds_out__sym_name_mangle(in, out) is det.

	% Produces a string of the form Module__Name.

:- pred llds_out__qualify_name(string, string, string).
:- mode llds_out__qualify_name(in, in, out) is det.

	% Convert a string into a form suitable for outputting as a C string,
	% by converting special characters into backslashes escapes.
:- pred llds_out__quote_c_string(string, string).
:- mode llds_out__quote_c_string(in, out) is det.

	% Like quote_c_string except the resulting string is written to
	% the current output stream.
:- pred output_c_quoted_string(string, io__state, io__state).
:- mode output_c_quoted_string(in, di, uo) is det.

	% Like quote_c_quoted_string except that the string may have
	% NULL characters embedded in it.
:- pred output_c_quoted_multi_string(int, string, io__state, io__state).
:- mode output_c_quoted_multi_string(in, in, di, uo) is det.

	% Create a name for type_ctor_*

:- pred llds_out__make_type_ctor_name(base_data, string, arity, string).
:- mode llds_out__make_type_ctor_name(in, in, in, out) is det.

	% Create a name for base_typeclass_info

:- pred llds_out__make_base_typeclass_info_name(class_id, string, string).
:- mode llds_out__make_base_typeclass_info_name(in, in, out) is det.

	% Convert a label to a string description of the stack layout
	% structure of that label.

:- pred llds_out__make_stack_layout_name(label, string).
:- mode llds_out__make_stack_layout_name(in, out) is det.

	% Returns the name of the initialization function
	% for a given module.

:- pred llds_out__make_init_name(module_name, string).
:- mode llds_out__make_init_name(in, out) is det.

	% Returns the name of the Aditi-RL code constant
	% for a given module.

:- pred llds_out__make_rl_data_name(module_name, string).
:- mode llds_out__make_rl_data_name(in, out) is det.

:- pred llds_out__trace_port_to_string(trace_port, string).
:- mode llds_out__trace_port_to_string(in, out) is det.

:- pred llds_out__trace_port_to_num(trace_port, int).
:- mode llds_out__trace_port_to_num(in, out) is det.

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

:- implementation.

:- import_module globals, options.
:- import_module exprn_aux, prog_util, prog_out, hlds_pred.
:- import_module export, mercury_to_mercury, modules.
:- import_module c_util.

:- import_module int, list, char, string, map, std_util.
:- import_module set, bintree_set, assoc_list, require.
:- import_module varset, term.
:- import_module library.	% for the version number.

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

% Every time we emit a declaration for a symbol, we insert it into the
% set of symbols we've already declared.  That way, we avoid generating
% the same symbol twice, which would cause an error in the C code.

:- type decl_id --->	create_label(int)
		;	float_label(string)
		;	code_addr(code_addr)
		;	data_addr(data_addr)
		;	pragma_c_struct(string).

:- type decl_set ==	map(decl_id, unit).

:- pred decl_set_init(decl_set::out) is det.

decl_set_init(DeclSet) :-
	map__init(DeclSet).

:- pred decl_set_insert(decl_set::in, decl_id::in, decl_set::out) is det.

decl_set_insert(DeclSet0, DeclId, DeclSet) :-
	map__set(DeclSet0, DeclId, unit, DeclSet).

:- pred decl_set_is_member(decl_id::in, decl_set::in) is semidet.

decl_set_is_member(DeclId, DeclSet) :-
	map__search(DeclSet, DeclId, _).

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

output_llds(C_File, StackLayoutLabels, MaybeRLFile) -->
	globals__io_lookup_bool_option(split_c_files, SplitFiles),
	( { SplitFiles = yes } ->
		{ C_File = c_file(ModuleName, C_HeaderInfo,
			UserCCodes, Exports, Vars, Datas, Modules) },
		module_name_to_file_name(ModuleName, ".dir", yes, ObjDirName),
		make_directory(ObjDirName),
		output_split_c_file_init(ModuleName, Modules, Datas,
			StackLayoutLabels, MaybeRLFile),
		output_split_user_c_codes(UserCCodes, ModuleName,
			C_HeaderInfo, StackLayoutLabels, 1, Num1),
		output_split_c_exports(Exports, ModuleName,
			C_HeaderInfo, StackLayoutLabels, Num1, Num2),
		output_split_comp_gen_c_vars(Vars, ModuleName,
			C_HeaderInfo, StackLayoutLabels, Num2, Num3),
		output_split_comp_gen_c_datas(Datas, ModuleName,
			C_HeaderInfo, StackLayoutLabels, Num3, Num4),
		output_split_comp_gen_c_modules(Modules, ModuleName,
			C_HeaderInfo, StackLayoutLabels, Num4, _Num)
	;
		output_single_c_file(C_File, no,
			StackLayoutLabels, MaybeRLFile)
	).

:- pred output_split_user_c_codes(list(user_c_code)::in,
	module_name::in, list(c_header_code)::in, set_bbbtree(label)::in,
	int::in, int::out, io__state::di, io__state::uo) is det.

output_split_user_c_codes([], _, _, _, Num, Num) --> [].
output_split_user_c_codes([UserCCode | UserCCodes], ModuleName, C_HeaderLines,
		StackLayoutLabels, Num0, Num) -->
	{ CFile = c_file(ModuleName, C_HeaderLines,
		[UserCCode], [], [], [], []) },
	output_single_c_file(CFile, yes(Num0), StackLayoutLabels, no),
	{ Num1 is Num0 + 1 },
	output_split_user_c_codes(UserCCodes, ModuleName, C_HeaderLines,
		StackLayoutLabels, Num1, Num).

:- pred output_split_c_exports(list(c_export)::in,
	module_name::in, list(c_header_code)::in, set_bbbtree(label)::in,
	int::in, int::out, io__state::di, io__state::uo) is det.

output_split_c_exports([], _, _, _, Num, Num) --> [].
output_split_c_exports([Export | Exports], ModuleName, C_HeaderLines,
		StackLayoutLabels, Num0, Num) -->
	{ CFile = c_file(ModuleName, C_HeaderLines,
		[], [Export], [], [], []) },
	output_single_c_file(CFile, yes(Num0), StackLayoutLabels, no),
	{ Num1 is Num0 + 1 },
	output_split_c_exports(Exports, ModuleName, C_HeaderLines,
		StackLayoutLabels, Num1, Num).

:- pred output_split_comp_gen_c_vars(list(comp_gen_c_var)::in,
	module_name::in, list(c_header_code)::in, set_bbbtree(label)::in,
	int::in, int::out, io__state::di, io__state::uo) is det.

output_split_comp_gen_c_vars([], _, _, _, Num, Num) --> [].
output_split_comp_gen_c_vars([Var | Vars], ModuleName, C_HeaderLines,
		StackLayoutLabels, Num0, Num) -->
	{ CFile = c_file(ModuleName, C_HeaderLines, [], [], [Var], [], []) },
	output_single_c_file(CFile, yes(Num0), StackLayoutLabels, no),
	{ Num1 is Num0 + 1 },
	output_split_comp_gen_c_vars(Vars, ModuleName, C_HeaderLines,
		StackLayoutLabels, Num1, Num).

:- pred output_split_comp_gen_c_datas(list(comp_gen_c_data)::in,
	module_name::in, list(c_header_code)::in, set_bbbtree(label)::in,
	int::in, int::out, io__state::di, io__state::uo) is det.

output_split_comp_gen_c_datas([], _, _, _, Num, Num) --> [].
output_split_comp_gen_c_datas([Data | Datas], ModuleName, C_HeaderLines,
		StackLayoutLabels, Num0, Num) -->
	{ CFile = c_file(ModuleName, C_HeaderLines, [], [], [], [Data], []) },
	output_single_c_file(CFile, yes(Num0), StackLayoutLabels, no),
	{ Num1 is Num0 + 1 },
	output_split_comp_gen_c_datas(Datas, ModuleName, C_HeaderLines,
		StackLayoutLabels, Num1, Num).

:- pred output_split_comp_gen_c_modules(list(comp_gen_c_module)::in,
	module_name::in, list(c_header_code)::in, set_bbbtree(label)::in,
	int::in, int::out, io__state::di, io__state::uo) is det.

output_split_comp_gen_c_modules([], _, _, _, Num, Num) --> [].
output_split_comp_gen_c_modules([Module | Modules], ModuleName, C_HeaderLines,
		StackLayoutLabels, Num0, Num) -->
	{ CFile = c_file(ModuleName, C_HeaderLines,
		[], [], [], [], [Module]) },
	output_single_c_file(CFile, yes(Num0), StackLayoutLabels, no),
	{ Num1 is Num0 + 1 },
	output_split_comp_gen_c_modules(Modules, ModuleName, C_HeaderLines,
		StackLayoutLabels, Num1, Num).

:- pred output_split_c_file_init(module_name, list(comp_gen_c_module),
	list(comp_gen_c_data), set_bbbtree(label), maybe(rl_file),
	io__state, io__state).
:- mode output_split_c_file_init(in, in, in, in, in, di, uo) is det.

output_split_c_file_init(ModuleName, Modules, Datas,
		StackLayoutLabels, MaybeRLFile) -->
	module_name_to_file_name(ModuleName, ".m", no, SourceFileName),
	module_name_to_split_c_file_name(ModuleName, 0, ".c", FileName),

	io__tell(FileName, Result),
	(
		{ Result = ok }
	->
		{ library__version(Version) },
		output_c_file_intro_and_grade(SourceFileName, Version),
		output_init_comment(ModuleName),
		output_c_file_mercury_headers,
		io__write_string("\n"),
		output_c_data_init_list_decls(Datas),
		io__write_string("\n"),
		output_c_module_init_list(ModuleName, Modules, Datas,
			StackLayoutLabels),
		output_rl_file(ModuleName, MaybeRLFile),
		io__told
	;
		io__progname_base("llds.m", ProgName),
		io__write_string("\n"),
		io__write_string(ProgName),
		io__write_string(": can't open `"),
		io__write_string(FileName),
		io__write_string("' for output\n"),
		io__set_exit_status(1)
	).

:- pred output_c_file_mercury_headers(io__state, io__state).
:- mode output_c_file_mercury_headers(di, uo) is det.

output_c_file_mercury_headers -->
	globals__io_get_trace_level(TraceLevel),
	( { TraceLevel \= none } ->
		io__write_string("#include ""mercury_imp.h""\n"),
		io__write_string("#include ""mercury_trace_base.h""\n")
	;
		io__write_string("#include ""mercury_imp.h""\n")
	).

:- pred output_c_file_intro_and_grade(string, string, io__state, io__state).
:- mode output_c_file_intro_and_grade(in, in, di, uo) is det.

output_c_file_intro_and_grade(SourceFileName, Version) -->
	globals__io_lookup_int_option(num_tag_bits, NumTagBits),
	{ string__int_to_string(NumTagBits, NumTagBitsStr) },
	globals__io_lookup_bool_option(unboxed_float, UnboxedFloat),
	{ convert_bool_to_string(UnboxedFloat, UnboxedFloatStr) },

	io__write_strings(["/*\n",
		"** Automatically generated from `", SourceFileName,
			"' by the Mercury compiler,\n",
		"** version ", Version, ".\n",
		"** Do not edit.\n",
		"**\n",
		"** The autoconfigured grade settings governing\n",
		"** the generation of this C file were\n",
		"**\n",
		"** TAG_BITS=", NumTagBitsStr, "\n",
		"** UNBOXED_FLOAT=", UnboxedFloatStr, "\n",
		"**\n",
		"** END_OF_C_GRADE_INFO\n",
		"*/\n"
	]).

:- pred convert_bool_to_string(bool, string).
:- mode convert_bool_to_string(in, out) is det.

convert_bool_to_string(no, "no").
convert_bool_to_string(yes, "yes").

:- pred output_single_c_file(c_file, maybe(int), set_bbbtree(label),
	maybe(rl_file), io__state, io__state).
:- mode output_single_c_file(in, in, in, in, di, uo) is det.

output_single_c_file(CFile, SplitFiles, StackLayoutLabels, MaybeRLFile) -->
	{ CFile = c_file(ModuleName, C_HeaderLines,
		UserCCode, Exports, Vars, Datas, Modules) },
	( { SplitFiles = yes(Num) } ->
		module_name_to_split_c_file_name(ModuleName, Num, ".c",
			FileName)
	;
		module_name_to_file_name(ModuleName, ".c", yes, FileName)
	),
	io__tell(FileName, Result),
	(
		{ Result = ok }
	->
		{ library__version(Version) },
		module_name_to_file_name(ModuleName, ".m", no, SourceFileName),
		output_c_file_intro_and_grade(SourceFileName, Version),
		( { SplitFiles = yes(_) } ->
			[]
		;
			output_init_comment(ModuleName)
		),
		output_c_file_mercury_headers,

		output_c_header_include_lines(C_HeaderLines),
		io__write_string("\n"),

		{ gather_c_file_labels(Modules, Labels) },
		{ decl_set_init(DeclSet0) },
		output_c_label_decl_list(Labels, StackLayoutLabels,
			DeclSet0, DeclSet1),
		output_comp_gen_c_var_list(Vars, DeclSet1, DeclSet2),
		output_c_data_def_list(Datas, DeclSet2, DeclSet3),
		output_comp_gen_c_data_list(Datas, DeclSet3, DeclSet4),
		output_comp_gen_c_module_list(Modules, StackLayoutLabels,
			DeclSet4, _DeclSet),
		output_user_c_code_list(UserCCode),
		output_exported_c_functions(Exports),

		( { SplitFiles = yes(_) } ->
			[]
		;
			io__write_string("\n"),
			output_c_module_init_list(ModuleName, Modules, Datas,
				StackLayoutLabels)
		),
		output_rl_file(ModuleName, MaybeRLFile),
		io__told
	;
		io__progname_base("llds.m", ProgName),
		io__write_string("\n"),
		io__write_string(ProgName),
		io__write_string(": can't open `"),
		io__write_string(FileName),
		io__write_string("' for output\n"),
		io__set_exit_status(1)
	).

:- pred output_c_module_init_list(module_name::in, list(comp_gen_c_module)::in,
	list(comp_gen_c_data)::in, set_bbbtree(label)::in,
	io__state::di, io__state::uo) is det.

output_c_module_init_list(ModuleName, Modules, Datas, StackLayoutLabels) -->
	{ MustInit = lambda([Module::in] is semidet, (
		module_defines_label_with_layout(Module, StackLayoutLabels)
	)) },
	{ list__filter(MustInit, Modules,
		AlwaysInitModules, MaybeInitModules) },
	{ list__chunk(AlwaysInitModules, 40, AlwaysInitModuleBunches) },
	{ list__chunk(MaybeInitModules, 40, MaybeInitModuleBunches) },
	globals__io_lookup_bool_option(split_c_files, SplitFiles),

	output_init_bunch_defs(AlwaysInitModuleBunches, ModuleName,
		"always", 0, SplitFiles),

	( { MaybeInitModuleBunches = [] } ->
		[]
	;
		io__write_string("#ifdef MR_MAY_NEED_INITIALIZATION\n\n"),
		output_init_bunch_defs(MaybeInitModuleBunches, ModuleName,
			"maybe", 0, SplitFiles),
		io__write_string("#endif\n\n")
	),

	io__write_string("void "),
	output_init_name(ModuleName),
	io__write_string("(void);"),
	io__write_string("/* suppress gcc -Wmissing-decls warning */\n"),
	io__write_string("void "),
	output_init_name(ModuleName),
	io__write_string("(void)\n"),
	io__write_string("{\n"),
	io__write_string("\tstatic bool done = FALSE;\n"),
	io__write_string("\tif (!done) {\n"),
	io__write_string("\t\tdone = TRUE;\n"),

	output_init_bunch_calls(AlwaysInitModuleBunches, ModuleName,
		"always", 0),

	( { MaybeInitModuleBunches = [] } ->
		[]
	;
		io__write_string("\n#ifdef MR_MAY_NEED_INITIALIZATION\n"),
		output_init_bunch_calls(MaybeInitModuleBunches, ModuleName,
			"maybe", 0),
		io__write_string("#endif\n\n")
	),

	output_c_data_init_list(Datas),
	io__write_string("\t}\n"),
	io__write_string("}\n\n"),
	io__write_string(
		"/* ensure everything is compiled with the same grade */\n"),
	io__write_string(
		"static const void *const MR_grade = &MR_GRADE_VAR;\n").

:- pred module_defines_label_with_layout(comp_gen_c_module::in,
	set_bbbtree(label)::in) is semidet.

module_defines_label_with_layout(Module, StackLayoutLabels) :-
		% Checking whether the set is empty or not
		% allows us to avoid calling gather_c_module_labels.
	\+ set_bbbtree__empty(StackLayoutLabels),
	Module = comp_gen_c_module(_, Procedures),
	gather_c_module_labels(Procedures, Labels),
	list__member(Label, Labels),
	set_bbbtree__member(Label, StackLayoutLabels).

:- pred output_init_bunch_defs(list(list(comp_gen_c_module))::in,
	module_name::in, string::in, int::in, bool::in,
	io__state::di, io__state::uo) is det.

output_init_bunch_defs([], _, _, _, _) --> [].
output_init_bunch_defs([Bunch | Bunches], ModuleName, InitStatus, Seq,
		SplitFiles) -->
	io__write_string("static void "),
	output_bunch_name(ModuleName, InitStatus, Seq),
	io__write_string("(void)\n"),
	io__write_string("{\n"),
	output_init_bunch_def(Bunch, ModuleName, SplitFiles),
	io__write_string("}\n\n"),
	{ NextSeq is Seq + 1 },
	output_init_bunch_defs(Bunches, ModuleName, InitStatus, NextSeq,
		SplitFiles).

:- pred output_init_bunch_def(list(comp_gen_c_module)::in, module_name::in,
	bool::in, io__state::di, io__state::uo) is det.

output_init_bunch_def([], _, _) --> [].
output_init_bunch_def([Module | Modules], ModuleName, SplitFiles) -->
	{ Module = comp_gen_c_module(C_ModuleName, _) },
	( { SplitFiles = yes } ->
		io__write_string("\t{ extern ModuleFunc "),
		io__write_string(C_ModuleName),
		io__write_string(";\n"),
		io__write_string("\t  "),
		io__write_string(C_ModuleName),
		io__write_string("(); }\n")
	;
		io__write_string("\t"),
		io__write_string(C_ModuleName),
		io__write_string("();\n")
	),
	output_init_bunch_def(Modules, ModuleName, SplitFiles).

:- pred output_init_bunch_calls(list(list(comp_gen_c_module))::in,
	module_name::in, string::in, int::in, io__state::di, io__state::uo)
	is det.

output_init_bunch_calls([], _, _, _) --> [].
output_init_bunch_calls([_ | Bunches], ModuleName, InitStatus, Seq) -->
	io__write_string("\t\t"),
	output_bunch_name(ModuleName, InitStatus, Seq),
	io__write_string("();\n"),
	{ NextSeq is Seq + 1 },
	output_init_bunch_calls(Bunches, ModuleName, InitStatus, NextSeq).

	% Output declarations for each module layout defined in this module
	% (there should only be one, of course).
:- pred output_c_data_init_list_decls(list(comp_gen_c_data)::in,
	io__state::di, io__state::uo) is det.

output_c_data_init_list_decls([]) --> [].
output_c_data_init_list_decls([Data | Datas]) -->
	(
		{ Data = comp_gen_c_data(ModuleName, DataName, _, _, _, _) },
		{ DataName = module_layout }
	->
		{ decl_set_init(DeclSet0) },
		output_data_addr_decls(data_addr(ModuleName, DataName), "", "",
			0, _, DeclSet0, _DeclSet)
	;
		[]
	),
	output_c_data_init_list_decls(Datas).

	% Output MR_INIT_TYPE_CTOR_INFO(TypeCtorInfo, TypeId);
	% for each type_ctor_info defined in this module.
	% Also output calls to MR_register_module_layout()
	% for each module layout defined in this module
	% (there should only be one, of course).

:- pred output_c_data_init_list(list(comp_gen_c_data)::in,
	io__state::di, io__state::uo) is det.

output_c_data_init_list([]) --> [].
output_c_data_init_list([Data | Datas]) -->
	(
		{ Data = comp_gen_c_data(ModuleName, DataName, _, _, _, _) },
		{ DataName = type_ctor(info, TypeName, Arity) }
	->
		io__write_string("\t\tMR_INIT_TYPE_CTOR_INFO(\n\t\t"),
		output_data_addr(ModuleName, DataName),
		io__write_string(",\n\t\t\t"),
		{ llds_out__sym_name_mangle(ModuleName, ModuleNameString) },
		{ string__append(ModuleNameString, "__", UnderscoresModule) },
		( 
			{ string__append(UnderscoresModule, _, TypeName) } 
		->
			[]
		;
			io__write_string(UnderscoresModule)
		),
		{ llds_out__name_mangle(TypeName, MangledTypeName) },
		io__write_string(MangledTypeName),
		io__write_string("_"),
		io__write_int(Arity),
		io__write_string("_0);\n")
	;
		{ Data = comp_gen_c_data(ModuleName, DataName, _, ArgRvals, _, _) },
		{ DataName = base_typeclass_info(_ClassName, _ClassArity) }
	->
		io__write_string("#ifndef MR_STATIC_CODE_ADDRESSES\n"),
		output_init_method_pointers(1, ArgRvals, DataName, ModuleName),
		io__write_string("#endif /* MR_STATIC_CODE_ADDRESSES */\n")
	;
		{ Data = comp_gen_c_data(ModuleName, DataName, _, _, _, _) },
		{ DataName = module_layout }
	->
		io__write_string("\t\tif (MR_register_module_layout != NULL) {\n"),
		io__write_string("\t\t\t(*MR_register_module_layout)("),
		io__write_string("(MR_Module_Layout *)\n\t\t\t\t&"),
		output_data_addr(ModuleName, DataName),
		io__write_string(");\n\t\t}\n")
	;
		[]
	),
	output_c_data_init_list(Datas).

:- pred output_init_method_pointers(int, list(maybe(rval)), data_name, module_name,
	io__state, io__state).
:- mode output_init_method_pointers(in, in, in, in, di, uo) is det.

output_init_method_pointers(_, [], _, _) --> [].
output_init_method_pointers(ArgNum, [Arg|Args], DataName, ModuleName) -->
	( { Arg = yes(const(code_addr_const(CodeAddr))) } ->
		io__write_string("\t\t"),
		output_data_addr(ModuleName, DataName),
		io__format(".f%d =\n\t\t\t", [i(ArgNum)]),
		output_code_addr(CodeAddr),
		io__write_string(";\n")
	;
		[]
	),
	output_init_method_pointers(ArgNum + 1, Args, DataName, ModuleName).

	% Output a comment to tell mkinit what functions to
	% call from <module>_init.c.
:- pred output_init_comment(module_name, io__state, io__state).
:- mode output_init_comment(in, di, uo) is det.

output_init_comment(ModuleName) -->
	io__write_string("/*\n"),
	io__write_string("INIT "),
	output_init_name(ModuleName),
	io__write_string("\n"),
	globals__io_lookup_bool_option(aditi, Aditi),
	( { Aditi = yes } ->
		{ llds_out__make_rl_data_name(ModuleName, RLName) },
		io__write_string("ADITI_DATA "),
		io__write_string(RLName),
		io__write_string("\n")
	;
		[]
	),
	io__write_string("ENDINIT\n"),
	io__write_string("*/\n\n").

:- pred output_init_name(module_name, io__state, io__state).
:- mode output_init_name(in, di, uo) is det.

output_init_name(ModuleName) -->
	{ llds_out__make_init_name(ModuleName, InitName) },
	io__write_string(InitName).

llds_out__make_init_name(ModuleName, InitName) :-
	llds_out__sym_name_mangle(ModuleName, MangledModuleName),
	string__append_list(["mercury__", MangledModuleName, "__init"],
		InitName).

llds_out__make_rl_data_name(ModuleName, RLDataConstName) :-
	llds_out__sym_name_mangle(ModuleName, MangledModuleName),
	string__append("mercury__aditi_rl_data__", MangledModuleName,
		RLDataConstName).

:- pred output_bunch_name(module_name, string, int, io__state, io__state).
:- mode output_bunch_name(in, in, in, di, uo) is det.

output_bunch_name(ModuleName, InitStatus, Number) -->
	io__write_string("mercury__"),
	{ llds_out__sym_name_mangle(ModuleName, MangledModuleName) },
	io__write_string(MangledModuleName),
	io__write_string("_"),
	io__write_string(InitStatus),
	io__write_string("_bunch_"),
	io__write_int(Number).

	%
	% output_c_data_def_list outputs all the type definitions of
	% the module.  This is needed because some compilers need the
	% data definition to appear before any use of the type in
	% forward declarations of static constants.
	%
:- pred output_c_data_def_list(list(comp_gen_c_data), decl_set, decl_set, 
	io__state, io__state).
:- mode output_c_data_def_list(in, in, out, di, uo) is det.

output_c_data_def_list([], DeclSet, DeclSet) --> [].
output_c_data_def_list([M | Ms], DeclSet0, DeclSet) -->
	output_c_data_def(M, DeclSet0, DeclSet1),
	output_c_data_def_list(Ms, DeclSet1, DeclSet).

:- pred output_c_data_def(comp_gen_c_data, decl_set, decl_set,
	io__state, io__state).
:- mode output_c_data_def(in, in, out, di, uo) is det.

output_c_data_def(comp_gen_c_data(ModuleName, VarName, ExportedFromModule,
		ArgVals, ArgTypes, _Refs), DeclSet0, DeclSet) -->
	io__write_string("\n"),
	{ DataAddr = data_addr(data_addr(ModuleName, VarName)) },

	{ linkage(VarName, Linkage) },
	{
		( Linkage = extern, ExportedFromModule = yes
		; Linkage = static, ExportedFromModule = no
		)
	->
		true
	;
		error("linkage mismatch")
	},

		% The code for data local to a Mercury module
		% should normally be visible only within the C file
		% generated for that module. However, if we generate
		% multiple C files, the code in each C file must be
		% visible to the other C files for that Mercury module.
	( { ExportedFromModule = yes } ->
		{ ExportedFromFile = yes }
	;
		globals__io_lookup_bool_option(split_c_files, SplitFiles),
		{ ExportedFromFile = SplitFiles }
	),

	output_const_term_decl(ArgVals, ArgTypes, DataAddr, ExportedFromFile, 
			yes, yes, no, "", "", 0, _),
	{ decl_set_insert(DeclSet0, DataAddr, DeclSet) }.

:- pred output_comp_gen_c_module_list(list(comp_gen_c_module)::in,
	set_bbbtree(label)::in, decl_set::in, decl_set::out,
	io__state::di, io__state::uo) is det.

output_comp_gen_c_module_list([], _, DeclSet, DeclSet) --> [].
output_comp_gen_c_module_list([Module | Modules], StackLayoutLabels,
		DeclSet0, DeclSet) -->
	output_comp_gen_c_module(Module, StackLayoutLabels,
		DeclSet0, DeclSet1),
	output_comp_gen_c_module_list(Modules, StackLayoutLabels,
		DeclSet1, DeclSet).

:- pred output_comp_gen_c_module(comp_gen_c_module::in, set_bbbtree(label)::in,
	decl_set::in, decl_set::out, io__state::di, io__state::uo) is det.

output_comp_gen_c_module(comp_gen_c_module(ModuleName, Procedures),
		StackLayoutLabels, DeclSet0, DeclSet) -->
	io__write_string("\n"),
	output_c_procedure_list_decls(Procedures, DeclSet0, DeclSet),
	io__write_string("\n"),
	io__write_string("BEGIN_MODULE("),
	io__write_string(ModuleName),
	io__write_string(")\n"),
	{ gather_c_module_labels(Procedures, Labels) },
	output_c_label_init_list(Labels, StackLayoutLabels),
	io__write_string("BEGIN_CODE\n"),
	io__write_string("\n"),
	globals__io_lookup_bool_option(auto_comments, PrintComments),
	globals__io_lookup_bool_option(emit_c_loops, EmitCLoops),
	output_c_procedure_list(Procedures, PrintComments, EmitCLoops),
	io__write_string("END_MODULE\n").

:- pred output_comp_gen_c_var_list(list(comp_gen_c_var)::in,
	decl_set::in, decl_set::out, io__state::di, io__state::uo) is det.

output_comp_gen_c_var_list([], DeclSet, DeclSet) --> [].
output_comp_gen_c_var_list([Var | Vars], DeclSet0, DeclSet) -->
	output_comp_gen_c_var(Var, DeclSet0, DeclSet1),
	output_comp_gen_c_var_list(Vars, DeclSet1, DeclSet).

:- pred output_comp_gen_c_var(comp_gen_c_var::in,
	decl_set::in, decl_set::out, io__state::di, io__state::uo) is det.

output_comp_gen_c_var(tabling_pointer_var(ModuleName, ProcLabel),
		DeclSet0, DeclSet) -->
	io__write_string("\nWord mercury_var__tabling__"),
	output_proc_label(ProcLabel),
	io__write_string(" = 0;\n"),
	{ DataAddr = data_addr(ModuleName, tabling_pointer(ProcLabel)) },
	{ decl_set_insert(DeclSet0, data_addr(DataAddr), DeclSet) }.

:- pred output_comp_gen_c_data_list(list(comp_gen_c_data)::in,
	decl_set::in, decl_set::out, io__state::di, io__state::uo) is det.

output_comp_gen_c_data_list([], DeclSet, DeclSet) --> [].
output_comp_gen_c_data_list([Data | Datas], DeclSet0, DeclSet) -->
	output_comp_gen_c_data(Data, DeclSet0, DeclSet1),
	output_comp_gen_c_data_list(Datas, DeclSet1, DeclSet).

:- pred output_comp_gen_c_data(comp_gen_c_data::in,
	decl_set::in, decl_set::out, io__state::di, io__state::uo) is det.

output_comp_gen_c_data(comp_gen_c_data(ModuleName, VarName, ExportedFromModule,
		ArgVals, ArgTypes, _Refs), DeclSet0, DeclSet) -->
	io__write_string("\n"),
	{ DataAddr = data_addr(data_addr(ModuleName, VarName)) },
	output_cons_arg_decls(ArgVals, "", "", 0, _, DeclSet0, DeclSet1),

	%
	% sanity check: check that the (redundant) ExportedFromModule field
	% in the c_data, which we use for the definition, matches the linkage
	% computed by linkage/2 from the dataname, which we use for any
	% prior declarations.
	%
	{ linkage(VarName, Linkage) },
	{
		( Linkage = extern, ExportedFromModule = yes
		; Linkage = static, ExportedFromModule = no
		)
	->
		true
	;
		error("linkage mismatch")
	},
	
		% The code for data local to a Mercury module
		% should normally be visible only within the C file
		% generated for that module. However, if we generate
		% multiple C files, the code in each C file must be
		% visible to the other C files for that Mercury module.
	( { ExportedFromModule = yes } ->
		{ ExportedFromFile = yes }
	;
		globals__io_lookup_bool_option(split_c_files, SplitFiles),
		{ ExportedFromFile = SplitFiles }
	),
	output_const_term_decl(ArgVals, ArgTypes, DataAddr, ExportedFromFile,
		no, yes, yes, "", "", 0, _),
	{ decl_set_insert(DeclSet1, DataAddr, DeclSet) }.

llds_out__trace_port_to_string(call, "MR_PORT_CALL").
llds_out__trace_port_to_string(exit, "MR_PORT_EXIT").
llds_out__trace_port_to_string(redo, "MR_PORT_REDO").
llds_out__trace_port_to_string(fail, "MR_PORT_FAIL").
llds_out__trace_port_to_string(exception, "MR_PORT_EXCEPTION").
llds_out__trace_port_to_string(ite_cond, "MR_PORT_COND").
llds_out__trace_port_to_string(ite_then, "MR_PORT_THEN").
llds_out__trace_port_to_string(ite_else, "MR_PORT_ELSE").
llds_out__trace_port_to_string(neg_enter,   "MR_PORT_NEG_ENTER").
llds_out__trace_port_to_string(neg_success, "MR_PORT_NEG_SUCCESS").
llds_out__trace_port_to_string(neg_failure, "MR_PORT_NEG_FAILURE").
llds_out__trace_port_to_string(disj,   "MR_PORT_DISJ").
llds_out__trace_port_to_string(switch, "MR_PORT_SWITCH").
llds_out__trace_port_to_string(nondet_pragma_first, "MR_PORT_PRAGMA_FIRST").
llds_out__trace_port_to_string(nondet_pragma_later, "MR_PORT_PRAGMA_LATER").

llds_out__trace_port_to_num(call, 0).
llds_out__trace_port_to_num(exit, 1).
llds_out__trace_port_to_num(redo, 2).
llds_out__trace_port_to_num(fail, 3).
llds_out__trace_port_to_num(exception, 4).
llds_out__trace_port_to_num(ite_cond, 5).
llds_out__trace_port_to_num(ite_then, 6).
llds_out__trace_port_to_num(ite_else, 7).
llds_out__trace_port_to_num(neg_enter,   8).
llds_out__trace_port_to_num(neg_success, 9).
llds_out__trace_port_to_num(neg_failure, 10).
llds_out__trace_port_to_num(disj,   11).
llds_out__trace_port_to_num(switch, 12).
llds_out__trace_port_to_num(nondet_pragma_first, 13).
llds_out__trace_port_to_num(nondet_pragma_later, 14).

:- pred output_user_c_code_list(list(user_c_code)::in,
	io__state::di, io__state::uo) is det.

output_user_c_code_list([]) --> [].
output_user_c_code_list([UserCCode | UserCCodes]) -->
	output_user_c_code(UserCCode),
	output_user_c_code_list(UserCCodes).

:- pred output_user_c_code(user_c_code::in, io__state::di, io__state::uo)
	is det.

output_user_c_code(user_c_code(C_Code, Context)) -->
	globals__io_lookup_bool_option(auto_comments, PrintComments),
	( { PrintComments = yes } ->
		io__write_string("/* "),
		prog_out__write_context(Context),
		io__write_string(" pragma c_code */\n")
	;
		[]
	),
	output_set_line_num(Context),
	io__write_string(C_Code),
	io__write_string("\n"),
	output_reset_line_num.

	% output_c_header_include_lines reverses the list of c header lines
	% and passes them to output_c_header_include_lines_2 which outputs them.
	% The list must be reversed since they are inserted in reverse order.
:- pred output_c_header_include_lines(list(c_header_code)::in,
	io__state::di, io__state::uo) is det.

output_c_header_include_lines(Headers) -->
	{ list__reverse(Headers, RevHeaders) },
	output_c_header_include_lines_2(RevHeaders).

:- pred output_c_header_include_lines_2(list(c_header_code)::in,
	io__state::di, io__state::uo) is det.

output_c_header_include_lines_2([]) --> [].
output_c_header_include_lines_2([Code - Context | Hs]) -->
	globals__io_lookup_bool_option(auto_comments, PrintComments),
	( { PrintComments = yes } ->
		io__write_string("/* "),
		prog_out__write_context(Context),
		io__write_string(" pragma(c_header_code) */\n")
	;
		[]
	),
	output_set_line_num(Context),
	io__write_string(Code),
	io__write_string("\n"),
	output_reset_line_num,
	output_c_header_include_lines_2(Hs).

:- pred output_exported_c_functions(list(string), io__state, io__state).
:- mode output_exported_c_functions(in, di, uo) is det.

output_exported_c_functions([]) --> [].
output_exported_c_functions([F | Fs]) -->
	io__write_string(F),
	output_exported_c_functions(Fs).

:- pred output_c_label_decl_list(list(label), set_bbbtree(label),
		decl_set, decl_set, io__state, io__state).
:- mode output_c_label_decl_list(in, in, in, out, di, uo) is det.

output_c_label_decl_list([], _, DeclSet, DeclSet) --> [].
output_c_label_decl_list([Label | Labels], StackLayoutLabels,
		DeclSet0, DeclSet) -->
	output_c_label_decl(Label, StackLayoutLabels, DeclSet0, DeclSet1),
	output_c_label_decl_list(Labels, StackLayoutLabels, DeclSet1, DeclSet).

:- pred output_c_label_decl(label, set_bbbtree(label), decl_set, decl_set,
		io__state, io__state).
:- mode output_c_label_decl(in, in, in, out, di, uo) is det.

output_c_label_decl(Label, StackLayoutLabels, DeclSet0, DeclSet) -->
	%
	% Declare the stack layout entry for this label, if needed.
	%
	( { set_bbbtree__member(Label, StackLayoutLabels) } ->
		{ Label = local(_, _) ->
			DataName = internal_layout(Label)
		;
			DataName = proc_layout(Label)
		},
		{ ProcLabel = get_proc_label(Label) },
		{ ModuleName = get_defining_module_name(ProcLabel) },
		{ DataAddr = data_addr(ModuleName, DataName) },
		output_data_addr_decls(DataAddr, "", "", 0, _,
			DeclSet0, DeclSet1)
	;
		{ DeclSet1 = DeclSet0 }
	),
	%
	% Declare the label itself.
	%
	(
		{ Label = exported(_) },
		io__write_string("Define_extern_entry(")
	;
		{ Label = local(_) },
		% The code for procedures local to a Mercury module
		% should normally be visible only within the C file
		% generated for that module. However, if we generate
		% multiple C files, the code in each C file must be
		% visible to the other C files for that Mercury module.
		globals__io_lookup_bool_option(split_c_files,
			SplitFiles),
		( { SplitFiles = no } ->
			io__write_string("Declare_static(")
		;
			io__write_string("Define_extern_entry(")
		)
	;
		{ Label = c_local(_) },
		io__write_string("Declare_local(")
	;
		{ Label = local(_, _) },
		io__write_string("Declare_label(")
	),
	{ decl_set_insert(DeclSet1, code_addr(label(Label)), DeclSet) },
	output_label(Label),
	io__write_string(");\n").

:- func get_proc_label(label) = proc_label.
get_proc_label(exported(ProcLabel)) = ProcLabel.
get_proc_label(local(ProcLabel)) = ProcLabel.
get_proc_label(c_local(ProcLabel)) = ProcLabel.
get_proc_label(local(ProcLabel, _)) = ProcLabel.

:- func get_defining_module_name(proc_label) = module_name.
get_defining_module_name(proc(ModuleName, _, _, _, _, _)) = ModuleName.
get_defining_module_name(special_proc(ModuleName, _, _, _, _, _)) = ModuleName.

:- pred output_c_label_init_list(list(label), set_bbbtree(label),
	io__state, io__state).
:- mode output_c_label_init_list(in, in, di, uo) is det.

output_c_label_init_list([], _) --> [].
output_c_label_init_list([Label | Labels], StackLayoutLabels) -->
	output_c_label_init(Label, StackLayoutLabels),
	output_c_label_init_list(Labels, StackLayoutLabels).

:- pred output_c_label_init(label, set_bbbtree(label), io__state, io__state).
:- mode output_c_label_init(in, in, di, uo) is det.

output_c_label_init(Label, StackLayoutLabels) -->
	{ set_bbbtree__member(Label, StackLayoutLabels) ->
		SuffixOpen = "_sl(",
		( label_is_proc_entry(Label, yes) ->
			% Labels whose stack layouts are proc layouts may need
			% to have the code address in that layout initialized
			% at run time (if code addresses are not static).
			InitProcLayout = yes
		;
			% Labels whose stack layouts are internal layouts
			% do not have code addresses in their layouts.
			InitProcLayout = no
		)
	;
		SuffixOpen = "(",
		% This label has no stack layout to initialize.
		InitProcLayout = no
	},
	(
		{ Label = exported(_) },
		{ TabInitMacro = "\tinit_entry" }
	;
		{ Label = local(_) },
		{ TabInitMacro = "\tinit_entry" }
	;
		{ Label = c_local(_) },
		{ TabInitMacro = "\tinit_local" }
	;
		{ Label = local(_, _) },
		{ TabInitMacro = "\tinit_label" }
	),
	io__write_string(TabInitMacro),
	io__write_string(SuffixOpen),
	output_label(Label),
	io__write_string(");\n"),
	( { InitProcLayout = yes } ->
		io__write_string("\tMR_INIT_PROC_LAYOUT_ADDR("),
		output_label(Label),
		io__write_string(");\n")
	;
		[]
	).

:- pred label_is_proc_entry(label::in, bool::out) is det.

label_is_proc_entry(local(_, _), no).
label_is_proc_entry(c_local(_), yes).
label_is_proc_entry(local(_), yes).
label_is_proc_entry(exported(_), yes).

:- pred output_c_procedure_list_decls(list(c_procedure), decl_set, decl_set,
	io__state, io__state).
:- mode output_c_procedure_list_decls(in, in, out, di, uo) is det.

output_c_procedure_list_decls([], DeclSet, DeclSet) --> [].
output_c_procedure_list_decls([Proc | Procs], DeclSet0, DeclSet) -->
	output_c_procedure_decls(Proc, DeclSet0, DeclSet1),
	output_c_procedure_list_decls(Procs, DeclSet1, DeclSet).

:- pred output_c_procedure_list(list(c_procedure), bool, bool,
				io__state, io__state).
:- mode output_c_procedure_list(in, in, in, di, uo) is det.

output_c_procedure_list([], _, _) --> [].
output_c_procedure_list([Proc | Procs], PrintComments, EmitCLoops) -->
	output_c_procedure(Proc, PrintComments, EmitCLoops),
	output_c_procedure_list(Procs, PrintComments, EmitCLoops).

:- pred output_c_procedure_decls(c_procedure, decl_set, decl_set,
				io__state, io__state).
:- mode output_c_procedure_decls(in, in, out, di, uo) is det.

output_c_procedure_decls(Proc, DeclSet0, DeclSet) -->
	{ Proc = c_procedure(_Name, _Arity, _PredProcId, Instrs) },
	output_instruction_list_decls(Instrs, DeclSet0, DeclSet).

:- pred output_c_procedure(c_procedure, bool, bool,
	io__state, io__state).
:- mode output_c_procedure(in, in, in, di, uo) is det.

output_c_procedure(Proc, PrintComments, EmitCLoops) -->
	{ Proc = c_procedure(Name, Arity, proc(_PredId, ProcId), Instrs) },
	{ proc_id_to_int(ProcId, ModeNum) },
	( { PrintComments = yes } ->
		io__write_string("\n/*-------------------------------------"),
		io__write_string("------------------------------------*/\n")
	;
		[]
	),
	io__write_string("/* code for predicate '"),
		% Now that we have unused_args.m mangling predicate names,
		% we should probably demangle them here.
	io__write_string(Name),
	io__write_string("'/"),
	io__write_int(Arity),
	io__write_string(" in mode "),
	io__write_int(ModeNum),
	io__write_string(" */\n"),
	{ llds_out__find_caller_label(Instrs, CallerLabel) },
	{ bintree_set__init(ContLabelSet0) },
	{ llds_out__find_cont_labels(Instrs, ContLabelSet0, ContLabelSet) },
	{ bintree_set__init(WhileSet0) },
	( { EmitCLoops = yes } ->
		{ llds_out__find_while_labels(Instrs, WhileSet0, WhileSet) }
	;
		{ WhileSet = WhileSet0 }
	),
	output_instruction_list(Instrs, PrintComments,
		CallerLabel - ContLabelSet, WhileSet).

	% Find the entry label for the procedure, 
	% for use as the profiling "caller label"
	% field in calls within this procedure.

:- pred llds_out__find_caller_label(list(instruction), label).
:- mode llds_out__find_caller_label(in, out) is det.

llds_out__find_caller_label([], _) :-
	error("cannot find caller label").
llds_out__find_caller_label([Instr0 - _ | Instrs], CallerLabel) :-
	( Instr0 = label(Label) ->
		( Label = local(_, _) ->
			error("caller label is internal label")
		;
			CallerLabel = Label
		)
	;
		llds_out__find_caller_label(Instrs, CallerLabel)
	).

	% Locate all the labels which are the continuation labels for calls,
	% nondet disjunctions, forks or joins, and store them in ContLabelSet.

:- pred llds_out__find_cont_labels(list(instruction),
	bintree_set(label), bintree_set(label)).
:- mode llds_out__find_cont_labels(in, in, out) is det.

llds_out__find_cont_labels([], ContLabelSet, ContLabelSet).
llds_out__find_cont_labels([Instr - _ | Instrs], ContLabelSet0, ContLabelSet)
		:-
	(
		(
			Instr = call(_, label(ContLabel), _, _, _)
		;
			Instr = mkframe(_, label(ContLabel))
		;
			Instr = join_and_continue(_, ContLabel)
		;
			Instr = assign(redoip(lval(_)), 
				const(code_addr_const(label(ContLabel))))
		)
	->
		bintree_set__insert(ContLabelSet0, ContLabel, ContLabelSet1)
	;
		Instr = fork(Label1, Label2, _)
	->
		bintree_set__insert_list(ContLabelSet0, [Label1, Label2],
			ContLabelSet1)
	;
		Instr = block(_, _, Block)
	->
		llds_out__find_cont_labels(Block, ContLabelSet0, ContLabelSet1)
	;
		ContLabelSet1 = ContLabelSet0
	),
	llds_out__find_cont_labels(Instrs, ContLabelSet1, ContLabelSet).

	% Locate all the labels which can be profitably turned into
	% labels starting while loops. The idea is to do this transform:
	%
	% L1:				L1:
	%				     while (1) {
	%	...				...
	%	if (...) goto L1		if (...) continue
	%	...		   =>		...
	%	if (...) goto L?		if (...) goto L?
	%	...				...
	%	if (...) goto L1		if (...) continue
	%	...				...
	%					break;
	%				     }
	% L2:				L2:
	%
	% The second of these is better if we don't have fast jumps.

:- pred llds_out__find_while_labels(list(instruction),
	bintree_set(label), bintree_set(label)).
:- mode llds_out__find_while_labels(in, in, out) is det.

llds_out__find_while_labels([], WhileSet, WhileSet).
llds_out__find_while_labels([Instr0 - _ | Instrs0], WhileSet0, WhileSet) :-
	(
		Instr0 = label(Label),
		llds_out__is_while_label(Label, Instrs0, Instrs1, 0, UseCount),
		UseCount > 0
	->
		bintree_set__insert(WhileSet0, Label, WhileSet1),
		llds_out__find_while_labels(Instrs1, WhileSet1, WhileSet)
	;
		llds_out__find_while_labels(Instrs0, WhileSet0, WhileSet)
	).

:- pred llds_out__is_while_label(label, list(instruction), list(instruction),
	int, int).
:- mode llds_out__is_while_label(in, in, out, in, out) is det.

llds_out__is_while_label(_, [], [], Count, Count).
llds_out__is_while_label(Label, [Instr0 - Comment0 | Instrs0], Instrs,
		Count0, Count) :-
	( Instr0 = label(_) ->
		Count = Count0,
		Instrs = [Instr0 - Comment0 | Instrs0]
	; Instr0 = goto(label(Label)) ->
		Count1 is Count0 + 1,
		llds_out__is_while_label(Label, Instrs0, Instrs, Count1, Count)
	; Instr0 = if_val(_, label(Label)) ->
		Count1 is Count0 + 1,
		llds_out__is_while_label(Label, Instrs0, Instrs, Count1, Count)
	;
		llds_out__is_while_label(Label, Instrs0, Instrs, Count0, Count)
	).

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

:- pred output_instruction_list_decls(list(instruction), decl_set, decl_set,
					io__state, io__state).
:- mode output_instruction_list_decls(in, in, out, di, uo) is det.

output_instruction_list_decls([], DeclSet, DeclSet) --> [].
output_instruction_list_decls([Instr0 - _Comment0 | Instrs],
		DeclSet0, DeclSet) -->
	output_instruction_decls(Instr0, DeclSet0, DeclSet1),
	output_instruction_list_decls(Instrs, DeclSet1, DeclSet).

:- pred output_instruction_decls(instr, decl_set, decl_set,
	io__state, io__state).
:- mode output_instruction_decls(in, in, out, di, uo) is det.

output_instruction_decls(comment(_), DeclSet, DeclSet) --> [].
output_instruction_decls(livevals(_), DeclSet, DeclSet) --> [].
output_instruction_decls(block(_TempR, _TempF, Instrs),
		DeclSet0, DeclSet) --> 
	output_instruction_list_decls(Instrs, DeclSet0, DeclSet).
output_instruction_decls(assign(Lval, Rval), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet1),
	output_rval_decls(Rval, "", "", 0, _, DeclSet1, DeclSet).
output_instruction_decls(call(Target, ContLabel, _,_,_), DeclSet0, DeclSet) -->
	output_code_addr_decls(Target, "", "", 0, _, DeclSet0, DeclSet1),
	output_code_addr_decls(ContLabel, "", "", 0, _, DeclSet1, DeclSet).
output_instruction_decls(c_code(_), DeclSet, DeclSet) --> [].
output_instruction_decls(mkframe(FrameInfo, FailureContinuation),
		DeclSet0, DeclSet) -->
	(
		{ FrameInfo = ordinary_frame(_, _, yes(Struct)) },
		{ Struct = pragma_c_struct(StructName, StructFields,
				MaybeStructFieldsContext) }
	->
		{
			decl_set_is_member(pragma_c_struct(StructName),
				DeclSet0)
		->
			string__append_list(["struct ", StructName,
				" has been declared already"], Msg),
			error(Msg)
		;
			true
		},
		io__write_string("struct "),
		io__write_string(StructName),
		io__write_string(" {\n"),
		( { MaybeStructFieldsContext = yes(StructFieldsContext) } ->
			output_set_line_num(StructFieldsContext),
			io__write_string(StructFields),
			output_reset_line_num
		;
			io__write_string(StructFields)
		),
		io__write_string("\n};\n"),
		{ decl_set_insert(DeclSet0, pragma_c_struct(StructName),
			DeclSet1) }
	;
		{ DeclSet1 = DeclSet0 }
	),
	output_code_addr_decls(FailureContinuation, "", "", 0, _,
		DeclSet1, DeclSet).
output_instruction_decls(label(_), DeclSet, DeclSet) --> [].
output_instruction_decls(goto(CodeAddr), DeclSet0, DeclSet) -->
	output_code_addr_decls(CodeAddr, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(computed_goto(Rval, _Labels), DeclSet0, DeclSet) -->
	output_rval_decls(Rval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(if_val(Rval, Target), DeclSet0, DeclSet) -->
	output_rval_decls(Rval, "", "", 0, _, DeclSet0, DeclSet1),
	output_code_addr_decls(Target, "", "", 0, _, DeclSet1, DeclSet).
output_instruction_decls(incr_hp(Lval, _Tag, Rval, _), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet1),
	output_rval_decls(Rval, "", "", 0, _, DeclSet1, DeclSet).
output_instruction_decls(mark_hp(Lval), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(restore_hp(Rval), DeclSet0, DeclSet) -->
	output_rval_decls(Rval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(store_ticket(Lval), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(reset_ticket(Rval, _Reason), DeclSet0, DeclSet) -->
	output_rval_decls(Rval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(discard_ticket, DeclSet, DeclSet) --> [].
output_instruction_decls(mark_ticket_stack(Lval), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(discard_tickets_to(Rval), DeclSet0, DeclSet) -->
	output_rval_decls(Rval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(incr_sp(_, _), DeclSet, DeclSet) --> [].
output_instruction_decls(decr_sp(_), DeclSet, DeclSet) --> [].
output_instruction_decls(pragma_c(_, Comps, _, _, _, _), DeclSet0, DeclSet) -->
	output_pragma_c_component_list_decls(Comps, DeclSet0, DeclSet).
output_instruction_decls(init_sync_term(Lval, _), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(fork(Child, Parent, _), DeclSet0, DeclSet) -->
	output_code_addr_decls(label(Child), "", "", 0, _, DeclSet0, DeclSet2),
	output_code_addr_decls(label(Parent), "", "", 0, _, DeclSet2, DeclSet).
output_instruction_decls(join_and_terminate(Lval), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet).
output_instruction_decls(join_and_continue(Lval, Label), DeclSet0, DeclSet) -->
	output_lval_decls(Lval, "", "", 0, _, DeclSet0, DeclSet1),
	output_code_addr_decls(label(Label), "", "", 0, _, DeclSet1, DeclSet).

:- pred output_pragma_c_component_list_decls(list(pragma_c_component),
	decl_set, decl_set, io__state, io__state).
:- mode output_pragma_c_component_list_decls(in, in, out, di, uo) is det.

output_pragma_c_component_list_decls([], DeclSet, DeclSet) --> [].
output_pragma_c_component_list_decls([Component | Components],
		DeclSet0, DeclSet) -->
	output_pragma_c_component_decls(Component, DeclSet0, DeclSet1),
	output_pragma_c_component_list_decls(Components, DeclSet1, DeclSet).

:- pred output_pragma_c_component_decls(pragma_c_component,
	decl_set, decl_set, io__state, io__state).
:- mode output_pragma_c_component_decls(in, in, out, di, uo) is det.

output_pragma_c_component_decls(pragma_c_inputs(Inputs), DeclSet0, DeclSet) -->
	output_pragma_input_rval_decls(Inputs, DeclSet0, DeclSet).
output_pragma_c_component_decls(pragma_c_outputs(Outputs), DeclSet0, DeclSet)
		-->
	output_pragma_output_lval_decls(Outputs, DeclSet0, DeclSet).
output_pragma_c_component_decls(pragma_c_raw_code(_), DeclSet, DeclSet) --> [].
output_pragma_c_component_decls(pragma_c_user_code(_, _), DeclSet, DeclSet)
		--> [].
output_pragma_c_component_decls(pragma_c_fail_to(_), DeclSet, DeclSet) --> [].
output_pragma_c_component_decls(pragma_c_noop, DeclSet, DeclSet) --> [].

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

:- pred output_instruction_list(list(instruction), bool,
	pair(label, bintree_set(label)), bintree_set(label),
	io__state, io__state).
:- mode output_instruction_list(in, in, in, in, di, uo) is det.

output_instruction_list([], _, _, _) --> [].
output_instruction_list([Instr0 - Comment0 | Instrs], PrintComments, ProfInfo,
		WhileSet) -->
	output_instruction_and_comment(Instr0, Comment0,
		PrintComments, ProfInfo),
	( { Instr0 = label(Label), bintree_set__is_member(Label, WhileSet) } ->
		io__write_string("\twhile (1) {\n"),
		output_instruction_list_while(Instrs, Label,
			PrintComments, ProfInfo, WhileSet)
	;
		output_instruction_list(Instrs, PrintComments, ProfInfo,
			WhileSet)
	).

:- pred output_instruction_list_while(list(instruction), label,
	bool, pair(label, bintree_set(label)), bintree_set(label),
	io__state, io__state).
:- mode output_instruction_list_while(in, in, in, in, in, di, uo) is det.

output_instruction_list_while([], _, _, _, _) -->
	io__write_string("\tbreak; } /* end while */\n").
output_instruction_list_while([Instr0 - Comment0 | Instrs], Label,
		PrintComments, ProfInfo, WhileSet) -->
	( { Instr0 = label(_) } ->
		io__write_string("\tbreak; } /* end while */\n"),
		output_instruction_list([Instr0 - Comment0 | Instrs],
			PrintComments, ProfInfo, WhileSet)
	; { Instr0 = goto(label(Label)) } ->
		io__write_string("\t/* continue */ } /* end while */\n"),
		output_instruction_list(Instrs, PrintComments, ProfInfo,
			WhileSet)
	; { Instr0 = if_val(Rval, label(Label)) } ->
		io__write_string("\tif ("),
		output_rval(Rval),
		io__write_string(")\n\t\tcontinue;\n"),
		( { PrintComments = yes, Comment0 \= "" } ->
			io__write_string("\t\t/* "),
			io__write_string(Comment0),
			io__write_string(" */\n")
		;
			[]
		),
		output_instruction_list_while(Instrs, Label,
			PrintComments, ProfInfo, WhileSet)
	;
		output_instruction_and_comment(Instr0, Comment0,
			PrintComments, ProfInfo),
		output_instruction_list_while(Instrs, Label,
			PrintComments, ProfInfo, WhileSet)
	).

:- pred output_instruction_and_comment(instr, string, bool,
	pair(label, bintree_set(label)), io__state, io__state).
:- mode output_instruction_and_comment(in, in, in, in, di, uo) is det.

output_instruction_and_comment(Instr, Comment, PrintComments,
		ProfInfo) -->
	(
		{ PrintComments = no },
		( { Instr = comment(_) ; Instr = livevals(_) } ->
			[]
		;
			output_instruction(Instr, ProfInfo)
		)
	;
		{ PrintComments = yes },
		output_instruction(Instr, ProfInfo),
		( { Comment = "" } ->
			[]
		;
			io__write_string("\t\t/* "),
			io__write_string(Comment),
			io__write_string(" */\n")
		)
	).

	% output_instruction_and_comment/5 is only for debugging.
	% Normally we use output_instruction_and_comment/6.

output_instruction_and_comment(Instr, Comment, PrintComments) -->
	{ bintree_set__init(ContLabelSet) },
	{ hlds_pred__initial_proc_id(ProcId) },
	{ DummyModule = unqualified("DEBUG") },
	{ DummyPredName = "DEBUG" },
	{ ProfInfo = local(proc(DummyModule, predicate, DummyModule,
			DummyPredName, 0, ProcId)) - ContLabelSet },
	output_instruction_and_comment(Instr, Comment, PrintComments, ProfInfo).

	% output_instruction/3 is only for debugging.
	% Normally we use output_instruction/4.

output_instruction(Instr) -->
	{ bintree_set__init(ContLabelSet) },
	{ hlds_pred__initial_proc_id(ProcId) },
	{ DummyModule = unqualified("DEBUG") },
	{ DummyPredName = "DEBUG" },
	{ ProfInfo = local(proc(DummyModule, predicate, DummyModule,
			DummyPredName, 0, ProcId)) - ContLabelSet },
	output_instruction(Instr, ProfInfo).

:- pred output_instruction(instr, pair(label, bintree_set(label)),
	io__state, io__state).
:- mode output_instruction(in, in, di, uo) is det.

output_instruction(comment(Comment), _) -->
	io__write_strings(["/* ", Comment, " */\n"]).

output_instruction(livevals(LiveVals), _) -->
	io__write_string("/*\n * Live lvalues:\n"),
	{ set__to_sorted_list(LiveVals, LiveValsList) },
	output_livevals(LiveValsList),
	io__write_string(" */\n").

output_instruction(block(TempR, TempF, Instrs), ProfInfo) -->
	io__write_string("\t{\n"),
	( { TempR > 0 } ->
		io__write_string("\tWord "),
		output_temp_decls(TempR, "r"),
		io__write_string(";\n")
	;
		[]
	),
	( { TempF > 0 } ->
		io__write_string("\tFloat "),
		output_temp_decls(TempF, "f"),
		io__write_string(";\n")
	;
		[]
	),
	globals__io_lookup_bool_option(auto_comments, PrintComments),
	{ bintree_set__init(WhileSet0) },
	output_instruction_list(Instrs, PrintComments, ProfInfo,
		WhileSet0),
	io__write_string("\t}\n").

output_instruction(assign(Lval, Rval), _) -->
	io__write_string("\t"),
	output_lval(Lval),
	io__write_string(" = "),
	{ llds__lval_type(Lval, Type) },
	output_rval_as_type(Rval, Type),
	io__write_string(";\n").

output_instruction(call(Target, ContLabel, LiveVals, _, _), ProfInfo) -->
	{ ProfInfo = CallerLabel - _ },
	output_call(Target, ContLabel, CallerLabel),
	output_gc_livevals(LiveVals).

output_instruction(c_code(C_Code_String), _) -->
	io__write_string("\t"),
	io__write_string(C_Code_String).

output_instruction(mkframe(FrameInfo, FailCont), _) -->
	(
		{ FrameInfo = ordinary_frame(Msg, Num, MaybeStruct) },
		( { MaybeStruct = yes(pragma_c_struct(StructName, _, _)) } ->
			io__write_string("\tMR_mkpragmaframe("""),
			output_c_quoted_string(Msg),
			io__write_string(""", "),
			io__write_int(Num),
			io__write_string(", "),
			io__write_string(StructName),
			io__write_string(", "),
			output_code_addr(FailCont),
			io__write_string(");\n")
		;
			io__write_string("\tMR_mkframe("""),
			output_c_quoted_string(Msg),
			io__write_string(""", "),
			io__write_int(Num),
			io__write_string(", "),
			output_code_addr(FailCont),
			io__write_string(");\n")
		)
	;
		{ FrameInfo = temp_frame(Kind) },
		(
			{ Kind = det_stack_proc },
			io__write_string("\tMR_mkdettempframe("),
			output_code_addr(FailCont),
			io__write_string(");\n")
		;
			{ Kind = nondet_stack_proc },
			io__write_string("\tMR_mktempframe("),
			output_code_addr(FailCont),
			io__write_string(");\n")
		)
	).

output_instruction(label(Label), ProfInfo) -->
	output_label_defn(Label),
	maybe_output_update_prof_counter(Label, ProfInfo).

output_instruction(goto(CodeAddr), ProfInfo) -->
	{ ProfInfo = CallerLabel - _ },
	io__write_string("\t"),
	output_goto(CodeAddr, CallerLabel).

output_instruction(computed_goto(Rval, Labels), _) -->
	io__write_string("\tCOMPUTED_GOTO("),
	output_rval_as_type(Rval, unsigned),
	io__write_string(",\n\t\t"),
	output_label_list(Labels),
	io__write_string(");\n").

output_instruction(if_val(Rval, Target), ProfInfo) -->
	{ ProfInfo = CallerLabel - _ },
	io__write_string("\tif ("),
	output_rval_as_type(Rval, bool),
	io__write_string(")\n\t\t"),
	output_goto(Target, CallerLabel).

output_instruction(incr_hp(Lval, MaybeTag, Rval, TypeMsg), ProfInfo) -->
	(
		{ MaybeTag = no },
		io__write_string("\tincr_hp_msg("),
		output_lval_as_word(Lval)
	;
		{ MaybeTag = yes(Tag) },
		io__write_string("\ttag_incr_hp_msg("),
		output_lval_as_word(Lval),
		io__write_string(", "),
		output_tag(Tag)
	),
	io__write_string(", "),
	output_rval_as_type(Rval, word),
	io__write_string(", "),
	{ ProfInfo = CallerLabel - _ },
	output_label(CallerLabel),
	io__write_string(", """),
	output_c_quoted_string(TypeMsg),
	io__write_string(""");\n").

output_instruction(mark_hp(Lval), _) -->
	io__write_string("\tmark_hp("),
	output_lval_as_word(Lval),
	io__write_string(");\n").

output_instruction(restore_hp(Rval), _) -->
	io__write_string("\trestore_hp("),
	output_rval_as_type(Rval, word),
	io__write_string(");\n").

output_instruction(store_ticket(Lval), _) -->
	io__write_string("\tMR_store_ticket("),
	output_lval_as_word(Lval),
	io__write_string(");\n").

output_instruction(reset_ticket(Rval, Reason), _) -->
	io__write_string("\tMR_reset_ticket("),
	output_rval_as_type(Rval, word),
	io__write_string(", "),
	output_reset_trail_reason(Reason),
	io__write_string(");\n").

output_instruction(discard_ticket, _) -->
	io__write_string("\tMR_discard_ticket();\n").

output_instruction(mark_ticket_stack(Lval), _) -->
	io__write_string("\tMR_mark_ticket_stack("),
	output_lval_as_word(Lval),
	io__write_string(");\n").

output_instruction(discard_tickets_to(Rval), _) -->
	io__write_string("\tMR_discard_tickets_to("),
	output_rval_as_type(Rval, word),
	io__write_string(");\n").

output_instruction(incr_sp(N, Msg), _) -->
	io__write_string("\tMR_incr_sp_push_msg("),
	io__write_int(N),
	io__write_string(", """),
	output_c_quoted_string(Msg),
	io__write_string(""");\n").

output_instruction(decr_sp(N), _) -->
	io__write_string("\tMR_decr_sp_pop_msg("),
	io__write_int(N),
	io__write_string(");\n").

output_instruction(pragma_c(Decls, Components, _, _, _, _), _) -->
	io__write_string("\t{\n"),
	output_pragma_decls(Decls),
	output_pragma_c_components(Components),
	io__write_string("\n\t}\n").

output_instruction(init_sync_term(Lval, N), _) -->
	io__write_string("\tMR_init_sync_term("),
	output_lval_as_word(Lval),
	io__write_string(", "),
	io__write_int(N),
	io__write_string(");\n").

output_instruction(fork(Child, Parent, Lval), _) -->
	io__write_string("\tMR_fork_new_context("),
	output_label_as_code_addr(Child),
	io__write_string(", "),
	output_label_as_code_addr(Parent),
	io__write_string(", "),
	io__write_int(Lval),
	io__write_string(");\n").

output_instruction(join_and_terminate(Lval), _) -->
	io__write_string("\tMR_join_and_terminate("),
	output_lval(Lval),
	io__write_string(");\n").

output_instruction(join_and_continue(Lval, Label), _) -->
	io__write_string("\tMR_join_and_continue("),
	output_lval(Lval),
	io__write_string(", "),
	output_label_as_code_addr(Label),
	io__write_string(");\n").

:- pred output_pragma_c_components(list(pragma_c_component),
	io__state, io__state).
:- mode output_pragma_c_components(in, di, uo) is det.

output_pragma_c_components([]) --> [].
output_pragma_c_components([C | Cs]) -->
	output_pragma_c_component(C),
	output_pragma_c_components(Cs).

:- pred output_pragma_c_component(pragma_c_component, io__state, io__state).
:- mode output_pragma_c_component(in, di, uo) is det.

output_pragma_c_component(pragma_c_inputs(Inputs)) -->
	output_pragma_inputs(Inputs).
output_pragma_c_component(pragma_c_outputs(Outputs)) -->
	output_pragma_outputs(Outputs).
output_pragma_c_component(pragma_c_user_code(MaybeContext, C_Code)) -->
	( { C_Code = "" } ->
		[]
	;
			% We should start the C_Code on a new line,
			% just in case it starts with a proprocessor directive.
		( { MaybeContext = yes(Context) } ->
			io__write_string("{\n"),
			output_set_line_num(Context),
			io__write_string(C_Code),
			io__write_string(";}\n"),
			output_reset_line_num
		;
			io__write_string("{\n"),
			io__write_string(C_Code),
			io__write_string(";}\n")
		)
	).
output_pragma_c_component(pragma_c_raw_code(C_Code)) -->
	io__write_string(C_Code).
output_pragma_c_component(pragma_c_fail_to(Label)) -->
	io__write_string("if (!r1) GOTO_LABEL("),
	output_label(Label),
	io__write_string(");\n").
output_pragma_c_component(pragma_c_noop) --> [].

	% Output the local variable declarations at the top of the 
	% pragma_c_code code.
:- pred output_pragma_decls(list(pragma_c_decl), io__state, io__state).
:- mode output_pragma_decls(in, di, uo) is det.

output_pragma_decls([]) --> [].
output_pragma_decls([D|Decls]) -->
	(
		{ D = pragma_c_arg_decl(Type, VarName) },
		% Apart from special cases, the local variables are Words
		{ export__type_to_type_string(Type, VarType) },
		io__write_string("\t"),
		io__write_string(VarType),
		io__write_string("\t"),
		io__write_string(VarName),
		io__write_string(";\n")
	;
		{ D = pragma_c_struct_ptr_decl(StructTag, VarName) },
		io__write_string("\tstruct "),
		io__write_string(StructTag),
		io__write_string("\t*"),
		io__write_string(VarName),
		io__write_string(";\n")
	),
	output_pragma_decls(Decls).

	% Output declarations for any rvals used to initialize the inputs
:- pred output_pragma_input_rval_decls(list(pragma_c_input), decl_set, decl_set,
					io__state, io__state).
:- mode output_pragma_input_rval_decls(in, in, out, di, uo) is det.

output_pragma_input_rval_decls([], DeclSet, DeclSet) --> [].
output_pragma_input_rval_decls([I | Inputs], DeclSet0, DeclSet) -->
	{ I = pragma_c_input(_VarName, _Type, Rval) },
	output_rval_decls(Rval, "\t", "\t", 0, _N, DeclSet0, DeclSet1),
	output_pragma_input_rval_decls(Inputs, DeclSet1, DeclSet).

	% Output the input variable assignments at the top of the 
	% pragma_c_code code.
:- pred output_pragma_inputs(list(pragma_c_input), io__state, io__state).
:- mode output_pragma_inputs(in, di, uo) is det.

output_pragma_inputs([]) --> [].
output_pragma_inputs([I|Inputs]) -->
	{ I = pragma_c_input(VarName, Type, Rval) },
	io__write_string("\t"),
	io__write_string(VarName),
	io__write_string(" = "),
	(
        	{ Type = term__functor(term__atom("string"), [], _) }
	->
		io__write_string("(String) "),
		output_rval_as_type(Rval, word)
	;
        	{ Type = term__functor(term__atom("float"), [], _) }
	->
		output_rval_as_type(Rval, float)
	;
		output_rval_as_type(Rval, word)
	),
	io__write_string(";\n"),
	output_pragma_inputs(Inputs).

	% Output declarations for any lvals used for the outputs
:- pred output_pragma_output_lval_decls(list(pragma_c_output),
				decl_set, decl_set, io__state, io__state).
:- mode output_pragma_output_lval_decls(in, in, out, di, uo) is det.

output_pragma_output_lval_decls([], DeclSet, DeclSet) --> [].
output_pragma_output_lval_decls([O | Outputs], DeclSet0, DeclSet) -->
	{ O = pragma_c_output(Lval, _Type, _VarName) },
	output_lval_decls(Lval, "\t", "\t", 0, _N, DeclSet0, DeclSet1),
	output_pragma_output_lval_decls(Outputs, DeclSet1, DeclSet).

	% Output the output variable assignments at the bottom of the
	% pragma_c_code
:- pred output_pragma_outputs(list(pragma_c_output), io__state, io__state).
:- mode output_pragma_outputs(in, di, uo) is det.

output_pragma_outputs([]) --> [].
output_pragma_outputs([O|Outputs]) --> 
	{ O = pragma_c_output(Lval, Type, VarName) },
	io__write_string("\t"),
	output_lval_as_word(Lval),
	io__write_string(" = "),
	(
        	{ Type = term__functor(term__atom("string"), [], _) }
	->
		io__write_string("(Word) "),
		io__write_string(VarName)
	;
        	{ Type = term__functor(term__atom("float"), [], _) }
	->
		io__write_string("float_to_word("),
		io__write_string(VarName),
		io__write_string(")")
	;
		io__write_string(VarName)
	),
	io__write_string(";\n"),
	output_pragma_outputs(Outputs).

:- pred output_reset_trail_reason(reset_trail_reason, io__state, io__state).
:- mode output_reset_trail_reason(in, di, uo) is det.

output_reset_trail_reason(undo) -->
	io__write_string("MR_undo").
output_reset_trail_reason(commit) -->
	io__write_string("MR_commit").
output_reset_trail_reason(solve) -->
	io__write_string("MR_solve").
output_reset_trail_reason(exception) -->
	io__write_string("MR_exception").
output_reset_trail_reason(retry) -->
	io__write_string("MR_retry").
output_reset_trail_reason(gc) -->
	io__write_string("MR_gc").

:- pred output_livevals(list(lval), io__state, io__state).
:- mode output_livevals(in, di, uo) is det.

output_livevals([]) --> [].
output_livevals([Lval|Lvals]) -->
	io__write_string(" *\t"),
	output_lval(Lval),
	io__write_string("\n"),
	output_livevals(Lvals).

:- pred output_gc_livevals(list(liveinfo), io__state, io__state).
:- mode output_gc_livevals(in, di, uo) is det.

output_gc_livevals(LiveVals) -->
	globals__io_lookup_bool_option(auto_comments, PrintAutoComments),
	( { PrintAutoComments = yes } ->
		io__write_string("/*\n"),
		io__write_string(" * Garbage collection livevals info\n"),
		output_gc_livevals_2(LiveVals),
		io__write_string(" */\n")
	;
		[]
	).

:- pred output_gc_livevals_2(list(liveinfo), io__state, io__state).
:- mode output_gc_livevals_2(in, di, uo) is det.

output_gc_livevals_2([]) --> [].
output_gc_livevals_2([LiveInfo | LiveInfos]) -->
	{ LiveInfo = live_lvalue(Locn, LiveValueType, TypeParams) },
	io__write_string(" *\t"),
	output_layout_locn(Locn),
	io__write_string("\t"),
	output_live_value_type(LiveValueType),
	io__write_string("\t"),
	{ map__to_assoc_list(TypeParams, TypeParamList) },
	output_gc_livevals_params(TypeParamList),
	io__write_string("\n"),
	output_gc_livevals_2(LiveInfos).

:- pred output_gc_livevals_params(assoc_list(tvar, set(layout_locn)),
	io__state, io__state).
:- mode output_gc_livevals_params(in, di, uo) is det.

output_gc_livevals_params([]) --> [].
output_gc_livevals_params([Var - LocnSet | Locns]) -->
	{ term__var_to_int(Var, VarInt) },
	io__write_int(VarInt),
	io__write_string(" - "),
	{ set__to_sorted_list(LocnSet, LocnList) },
	output_layout_locns(LocnList),
	io__write_string("  "),
	output_gc_livevals_params(Locns).

:- pred output_layout_locns(list(layout_locn), io__state, io__state).
:- mode output_layout_locns(in, di, uo) is det.

output_layout_locns([]) --> [].
output_layout_locns([Locn | Locns]) -->
	output_layout_locn(Locn),
	( { Locns = [] } ->
		[]
	;
		io__write_string(" and "),
		output_layout_locns(Locns)
	).

:- pred output_layout_locn(layout_locn, io__state, io__state).
:- mode output_layout_locn(in, di, uo) is det.

output_layout_locn(Locn) -->
	(
		{ Locn = direct(Lval) },
		output_lval(Lval)
	;
		{ Locn = indirect(Lval, Offset) },
		io__write_string("offset "),
		io__write_int(Offset),
		io__write_string(" from "),
		output_lval(Lval)
	).

:- pred output_live_value_type(live_value_type, io__state, io__state).
:- mode output_live_value_type(in, di, uo) is det.

output_live_value_type(succip) --> io__write_string("type succip").
output_live_value_type(curfr) --> io__write_string("type curfr").
output_live_value_type(maxfr) --> io__write_string("type maxfr").
output_live_value_type(redofr) --> io__write_string("type redofr").
output_live_value_type(redoip) --> io__write_string("type redoip").
output_live_value_type(hp) --> io__write_string("type hp").
output_live_value_type(trail_ptr) --> io__write_string("type trail_ptr").
output_live_value_type(ticket) --> io__write_string("type ticket").
output_live_value_type(unwanted) --> io__write_string("unwanted").
output_live_value_type(var(Var, Name, Type, LldsInst)) --> 
	io__write_string("var("),
	{ term__var_to_int(Var, VarInt) },
	io__write_int(VarInt),
	io__write_string(", "),
	io__write_string(Name),
	io__write_string(", "),
		% XXX Fake type varset
	{ varset__init(NewTVarset) },
	mercury_output_term(Type, NewTVarset, no),
	io__write_string(", "),
	(
		{ LldsInst = ground },
		io__write_string("ground")
	;
		{ LldsInst = partial(Inst) },
			% XXX Fake inst varset
		{ varset__init(NewIVarset) },
		mercury_output_inst(Inst, NewIVarset)
	),
	io__write_string(")").

:- pred output_temp_decls(int, string, io__state, io__state).
:- mode output_temp_decls(in, in, di, uo) is det.

output_temp_decls(N, Type) --> 
	output_temp_decls_2(1, N, Type).

:- pred output_temp_decls_2(int, int, string, io__state, io__state).
:- mode output_temp_decls_2(in, in, in, di, uo) is det.

output_temp_decls_2(Next, Max, Type) --> 
	( { Next =< Max } ->
		( { Next > 1 } ->
			io__write_string(", ")
		;
			[]
		),
		io__write_string("MR_temp"),
		io__write_string(Type),
		io__write_int(Next),
		{ Next1 is Next + 1 },
		output_temp_decls_2(Next1, Max, Type)
	;
		[]
	).

% output_rval_decls(Rval, ...) outputs the declarations of any
% static constants, etc. that need to be declared before
% output_rval(Rval) is called.

% Every time we emit a declaration for a symbol, we insert it into the
% set of symbols we've already declared. That way, we avoid generating
% the same symbol twice, which would cause an error in the C code.

:- pred output_rval_decls(rval, string, string, int, int, decl_set, decl_set,
	io__state, io__state).
:- mode output_rval_decls(in, in, in, in, out, in, out, di, uo) is det.

output_rval_decls(lval(Lval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_lval_decls(Lval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_rval_decls(var(_), _, _, _, _, _, _) --> 
	{ error("output_rval_decls: unexpected var") }.
output_rval_decls(mkword(_, Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) --> 
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_rval_decls(const(Const), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	( { Const = code_addr_const(CodeAddress) } ->
		output_code_addr_decls(CodeAddress, FirstIndent, LaterIndent,
			N0, N, DeclSet0, DeclSet)
	; { Const = data_addr_const(DataAddr) } ->
		output_data_addr_decls(DataAddr,
			FirstIndent, LaterIndent, N0, N, DeclSet0, DeclSet)
	; { Const = float_const(FloatVal) } ->
		%
		% If floats are boxed, and the static ground terms
		% option is enabled, then for each float constant
		% which we might want to box we declare a static const
		% variable holding that constant. 
		%
		globals__io_lookup_bool_option(unboxed_float, UnboxedFloat),
		globals__io_lookup_bool_option(static_ground_terms,
			StaticGroundTerms),
		( { UnboxedFloat = no, StaticGroundTerms = yes } ->
			{ llds_out__float_literal_name(FloatVal, FloatName) },
			{ FloatLabel = float_label(FloatName) },
			( { decl_set_is_member(FloatLabel, DeclSet0) } ->
				{ N = N0 },
				{ DeclSet = DeclSet0 }
			;
				{ decl_set_insert(DeclSet0, FloatLabel,
					DeclSet) },
				{ string__float_to_string(FloatVal,
					FloatString) },
				output_indent(FirstIndent, LaterIndent, N0),
				{ N is N0 + 1 },
				io__write_strings([
					"static const Float ",
					"mercury_float_const_", FloatName,
					" = ", FloatString, ";\n"
				])
			)
		;
			{ N = N0 },
			{ DeclSet = DeclSet0 }
		)
	;
		{ N = N0 },
		{ DeclSet = DeclSet0 }
	).
output_rval_decls(unop(_, Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_rval_decls(binop(Op, Rval1, Rval2), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval1, FirstIndent, LaterIndent, N0, N1,
		DeclSet0, DeclSet1),
	output_rval_decls(Rval2, FirstIndent, LaterIndent, N1, N2,
		DeclSet1, DeclSet2),
		%
		% If floats are boxed, and the static ground terms
		% option is enabled, then for each float constant
		% which we might want to box we declare a static const
		% variable holding that constant. 
		%
	( { c_util__float_op(Op, OpStr) } ->
	    globals__io_lookup_bool_option(unboxed_float, UnboxFloat),
	    globals__io_lookup_bool_option(static_ground_terms,
					StaticGroundTerms),
	    (
		{ UnboxFloat = no, StaticGroundTerms = yes },
		{ llds_out__float_const_binop_expr_name(Op, Rval1, Rval2,
			FloatName) }
	    ->
		{ FloatLabel = float_label(FloatName) },
		( { decl_set_is_member(FloatLabel, DeclSet2) } ->
			{ N = N2 },
			{ DeclSet = DeclSet2 }
		;
			{ decl_set_insert(DeclSet2, FloatLabel, DeclSet) },
			output_indent(FirstIndent, LaterIndent, N2),
			{ N is N2 + 1 },
			io__write_string(
				"static const Float mercury_float_const_"),
			io__write_string(FloatName),
			io__write_string(" = "),
				% note that we just output the expression
				% here, and let the C compiler evaluate it,
				% rather than evaluating it ourselves;
				% this avoids having to deal with some nasty
				% issues regarding floating point accuracy
				% when doing cross-compilation.
			output_rval_as_type(Rval1, float),
			io__write_string(" "),
			io__write_string(OpStr),
			io__write_string(" "),
			output_rval_as_type(Rval2, float),
			io__write_string(";\n")
		)
	    ;
		{ N = N2 },
		{ DeclSet = DeclSet2 }
	    )
	;
	    { N = N2 },
	    { DeclSet = DeclSet2 }
	).
output_rval_decls(create(_Tag, ArgVals, CreateArgTypes, _StatDyn, Label, _),
		FirstIndent, LaterIndent, N0, N, DeclSet0, DeclSet) -->
	{ CreateLabel = create_label(Label) },
	( { decl_set_is_member(CreateLabel, DeclSet0) } ->
		{ N = N0 },
		{ DeclSet = DeclSet0 }
	;
		{ decl_set_insert(DeclSet0, CreateLabel, DeclSet1) },
		output_cons_arg_decls(ArgVals, FirstIndent, LaterIndent,
			N0, N1, DeclSet1, DeclSet),
		output_const_term_decl(ArgVals, CreateArgTypes, CreateLabel,
			no, yes, yes, yes, FirstIndent, LaterIndent, N1, N)
	).
output_rval_decls(mem_addr(MemRef), FirstIndent, LaterIndent,
		N0, N, DeclSet0, DeclSet) -->
	output_mem_ref_decls(MemRef, FirstIndent, LaterIndent,
		N0, N, DeclSet0, DeclSet).

:- pred output_mem_ref_decls(mem_ref, string, string, int, int,
	decl_set, decl_set, io__state, io__state).
:- mode output_mem_ref_decls(in, in, in, in, out, in, out, di, uo) is det.

output_mem_ref_decls(stackvar_ref(_), _, _, N, N, DeclSet, DeclSet) --> [].
output_mem_ref_decls(framevar_ref(_), _, _, N, N, DeclSet, DeclSet) --> [].
output_mem_ref_decls(heap_ref(Rval, _, _), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).

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

% The following predicates are used to compute the names used for
% floating point static constants.

:- pred llds_out__float_const_expr_name(rval::in, string::out) is semidet.

% Given an rval, succeed iff it is a floating point constant expression;
% if so, return a name for that rval that is suitable for use in a C identifier.
% Different rvals must be given different names.

llds_out__float_const_expr_name(Expr, Name) :-
	( Expr = const(float_const(Float)) ->
		llds_out__float_literal_name(Float, Name)
	; Expr = binop(Op, Arg1, Arg2) ->
		llds_out__float_const_binop_expr_name(Op, Arg1, Arg2, Name)
	;
		fail
	).

:- pred llds_out__float_const_binop_expr_name(binary_op::in, rval::in, rval::in,
				string::out) is semidet.

% Given a binop rval, succeed iff that rval is a floating point constant
% expression; if so, return a name for that rval that is suitable for use in
% a C identifier.  Different rvals must be given different names.

llds_out__float_const_binop_expr_name(Op, Arg1, Arg2, Name) :-
	llds_out__float_op_name(Op, OpName),
	llds_out__float_const_expr_name(Arg1, Arg1Name),
	llds_out__float_const_expr_name(Arg2, Arg2Name),
	% we use prefix notation (operator, argument, argument)
	% rather than infix, to ensure that different rvals get
	% different names
	string__append_list([OpName, "_", Arg1Name, "_", Arg2Name],
		Name).

:- pred llds_out__float_literal_name(float::in, string::out) is det.

% Given an rval which is a floating point literal, return
% a name for that rval that is suitable for use in a C identifier.
% Different rvals must be given different names.

llds_out__float_literal_name(Float, FloatName) :-
	%
	% The name of the variable is based on the
	% value of the float const, with "pt" instead
	% of ".", "plus" instead of "+", and "neg" instead of "-".
	%
	string__float_to_string(Float, FloatName0),
	string__replace_all(FloatName0, ".", "pt", FloatName1),
	string__replace_all(FloatName1, "+", "plus", FloatName2),
	string__replace_all(FloatName2, "-", "neg", FloatName).

:- pred llds_out__float_op_name(binary_op, string).
:- mode llds_out__float_op_name(in, out) is semidet.
	
% succeed iff the binary operator is an operator whose return
% type is float; bind the output string to a name for that operator
% that is suitable for use in a C identifier

llds_out__float_op_name(float_plus, "plus").
llds_out__float_op_name(float_minus, "minus").
llds_out__float_op_name(float_times, "times").
llds_out__float_op_name(float_divide, "divide").

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

	% We output constant terms as follows:
	%
	%	static const struct <foo>_struct {
	%		Word field1;			// Def
	%		Float field2;			
	%		Word * field3;
	%		...
	%	} 
	%	<foo> 					// Decl
	%	= {					// Init
	%		...
	%	};
	%
	% Unless the term contains code addresses, and we don't have
	% static code addresses available, in which case we'll have
	% to initialize them dynamically, so we must omit `const'
	% from the above structure.
	%
	% Also we now conditionally output some parts.  The parts that
	% are conditionally output are Def, Decl and Init.  It is an
	% error for Init to be yes and Decl to be no.

:- pred output_const_term_decl(list(maybe(rval)), create_arg_types, decl_id,
	bool, bool, bool, bool, string, string, int, int, io__state, io__state).
:- mode output_const_term_decl(in, in, in, in, in, in,
	in, in, in, in, out, di, uo) is det.

output_const_term_decl(ArgVals, CreateArgTypes, DeclId, Exported,
		Def, Decl, Init, FirstIndent, LaterIndent, N1, N) -->
	(
		{ Init = yes }, { Decl = no }
	->
		{ error("output_const_term_decl: Inconsistent Decl and Init") }
	;
		[]
	),
	output_indent(FirstIndent, LaterIndent, N1),
	{ N is N1 + 1 },
	(
		{ Decl = yes }
	->
		(
			{ Exported = yes }
		->
			[]
		;
			io__write_string("static ")
		),
		globals__io_get_globals(Globals),
		{ globals__have_static_code_addresses(Globals, StaticCode) },
		(
				% Don't make the structure `const' 
				% if the structure will eventually include
				% code addresses but we don't have static code
				% addresses.
			{ StaticCode = no },
			{ DeclId = data_addr(data_addr(_, DataName)) },
			{ data_name_would_include_code_address(DataName, yes) }
		->
			[]
		;
			io__write_string("const ")
		)
	;
		[]
	),
	io__write_string("struct "),

	% If it's a type_ctor_info struct, use the MR_TypeCtorInfo_struct
	% type, and don't emit a definition.
	(
		{ decl_id_is_type_ctor_info(DeclId) }
	->
		io__write_string("MR_TypeCtorInfo_struct")
	;
		output_decl_id(DeclId),
		io__write_string("_struct"),
		(
			{ Def = yes }
		->
			io__write_string(" {\n"),
			output_cons_arg_types(ArgVals, CreateArgTypes, "\t", 1),
			io__write_string("} ")
		;
			[]
		)
	),
	(
		{ Decl = yes }
	->
		io__write_string(" "),
		output_decl_id(DeclId),
		(
			{ Init = yes }
		->
			io__write_string(" = {\n"),
			output_cons_args(ArgVals, CreateArgTypes, "\t"),
			io__write_string(LaterIndent),
			io__write_string("};\n")
		;
			io__write_string(";\n")
		)
	;
		io__write_string(";\n")
	).

	% Succeed if the decl_id is for a type constructor info structure.

:- pred decl_id_is_type_ctor_info(decl_id).
:- mode decl_id_is_type_ctor_info(in) is semidet.

decl_id_is_type_ctor_info(data_addr(data_addr(_, type_ctor(info, _, _)))).

	% Return true if a data structure of the given type will eventually
	% include code addresses. Note that we can't just test the data
	% structure itself, since in the absence of code addresses the earlier
	% passes will have replaced any code addresses with dummy values
	% that will have to be overridden with the real code address at
	% initialization time.

:- pred data_name_would_include_code_address(data_name, bool).
:- mode data_name_would_include_code_address(in, out) is det.

data_name_would_include_code_address(common(_), no).
data_name_would_include_code_address(type_ctor(info, _, _), yes).
data_name_would_include_code_address(type_ctor(layout, _, _), no).
data_name_would_include_code_address(type_ctor(functors, _, _), no).
data_name_would_include_code_address(base_typeclass_info(_, _), yes).
data_name_would_include_code_address(module_layout, no).
data_name_would_include_code_address(proc_layout(_), yes).
data_name_would_include_code_address(internal_layout(_), no).
data_name_would_include_code_address(tabling_pointer(_), no).

:- pred output_decl_id(decl_id, io__state, io__state).
:- mode output_decl_id(in, di, uo) is det.

output_decl_id(create_label(N)) -->
	io__write_string("mercury_const_"),
	io__write_int(N).
output_decl_id(data_addr(data_addr(ModuleName, VarName))) -->
	output_data_addr(ModuleName, VarName).
output_decl_id(code_addr(_CodeAddress)) -->
	{ error("output_decl_id: code_addr unexpected") }.
output_decl_id(float_label(_Label)) -->
	{ error("output_decl_id: float_label unexpected") }.
output_decl_id(pragma_c_struct(_Name)) -->
	{ error("output_decl_id: pragma_c_struct unexpected") }.

:- pred output_cons_arg_types(list(maybe(rval))::in, create_arg_types::in,
	string::in, int::in, io__state::di, io__state::uo) is det.

output_cons_arg_types(Args, uniform(MaybeType), Indent, ArgNum) -->
	output_uniform_cons_arg_types(Args, MaybeType, Indent, ArgNum).
output_cons_arg_types(Args, initial(InitialTypes, RestTypes),
		Indent, ArgNum) -->
	output_initial_cons_arg_types(Args, InitialTypes, RestTypes,
		Indent, ArgNum).
output_cons_arg_types(Args, none, _, _) -->
	{ require(unify(Args, []), "too many args for specified arg types") }.

:- pred output_uniform_cons_arg_types(list(maybe(rval))::in,
	maybe(llds_type)::in, string::in, int::in,
	io__state::di, io__state::uo) is det.

output_uniform_cons_arg_types([], _, _, _) --> [].
output_uniform_cons_arg_types([Arg | Args], MaybeType, Indent, ArgNum) -->
	( { Arg = yes(Rval) } ->
		io__write_string(Indent),
		llds_arg_type(Rval, MaybeType, Type),
		output_llds_type(Type),
		io__write_string(" f"),
		io__write_int(ArgNum),
		io__write_string(";\n"),
		{ ArgNum1 is ArgNum + 1 },
		output_uniform_cons_arg_types(Args, MaybeType, Indent, ArgNum1)
	;
		{ error("output_uniform_cons_arg_types: missing arg") }
	).

:- pred output_initial_cons_arg_types(list(maybe(rval))::in,
	initial_arg_types::in, create_arg_types::in, string::in, int::in,
	io__state::di, io__state::uo) is det.

output_initial_cons_arg_types(Args, [], RestTypes, Indent, ArgNum) -->
	output_cons_arg_types(Args, RestTypes, Indent, ArgNum).
output_initial_cons_arg_types(Args, [N - MaybeType | InitTypes], RestTypes,
		Indent, ArgNum) -->
	output_initial_cons_arg_types_2(Args, N, MaybeType, InitTypes,
		RestTypes, Indent, ArgNum).

:- pred output_initial_cons_arg_types_2(list(maybe(rval))::in, int::in,
	maybe(llds_type)::in, initial_arg_types::in, create_arg_types::in,
	string::in, int::in, io__state::di, io__state::uo) is det.

output_initial_cons_arg_types_2([], N, _, _, _, _, _) -->
	{ require(unify(N, 0), "not enough args for specified arg types") }.
output_initial_cons_arg_types_2([Arg | Args], N, MaybeType, InitTypes,
		RestTypes, Indent, ArgNum) -->
	( { N = 0 } ->
		output_initial_cons_arg_types([Arg | Args], InitTypes,
			RestTypes, Indent, ArgNum)
	;
		( { Arg = yes(Rval) } ->
			io__write_string(Indent),
			llds_arg_type(Rval, MaybeType, Type),
			output_llds_type(Type),
			io__write_string(" f"),
			io__write_int(ArgNum),
			io__write_string(";\n"),
			{ ArgNum1 is ArgNum + 1 },
			{ N1 is N - 1 },
			output_initial_cons_arg_types_2(Args, N1, MaybeType,
				InitTypes, RestTypes, Indent, ArgNum1)
		;
			{ error("output_initial_cons_arg_types: missing arg") }
		)
	).

	% Given an rval, figure out the type it would have as an argument,
	% if it is not explicitly specified.

:- pred llds_arg_type(rval::in, maybe(llds_type)::in, llds_type::out,
	io__state::di, io__state::uo) is det.

llds_arg_type(Rval, MaybeType, Type) -->
	( { MaybeType = yes(SpecType) } ->
		{ Type = SpecType }
	;
		llds_out__rval_type_as_arg(Rval, Type)
	).

	% Given an rval, figure out the type it would have as
	% an argument.  Normally that's the same as its usual type;
	% the exception is that for boxed floats, the type is data_ptr
	% (i.e. the type of the boxed value) rather than float
	% (the type of the unboxed value).

:- pred llds_out__rval_type_as_arg(rval::in, llds_type::out,
	io__state::di, io__state::uo) is det.

llds_out__rval_type_as_arg(Rval, ArgType) -->
	{ llds__rval_type(Rval, Type) },
	globals__io_lookup_bool_option(unboxed_float, UnboxFloat),
	( { Type = float, UnboxFloat = no } ->
		{ ArgType = data_ptr }
	;
		{ ArgType = Type }
	).

:- pred output_llds_type(llds_type::in, io__state::di, io__state::uo) is det.

output_llds_type(int_least8)   --> io__write_string("MR_int_least8_t").
output_llds_type(uint_least8)  --> io__write_string("MR_uint_least8_t").
output_llds_type(int_least16)  --> io__write_string("MR_int_least16_t").
output_llds_type(uint_least16) --> io__write_string("MR_uint_least16_t").
output_llds_type(int_least32)  --> io__write_string("MR_int_least32_t").
output_llds_type(uint_least32) --> io__write_string("MR_uint_least32_t").
output_llds_type(bool)         --> io__write_string("Integer").
output_llds_type(integer)      --> io__write_string("Integer").
output_llds_type(unsigned)     --> io__write_string("Unsigned").
output_llds_type(float)        --> io__write_string("Float").
output_llds_type(word)         --> io__write_string("Word").
output_llds_type(string)       --> io__write_string("String").
output_llds_type(data_ptr)     --> io__write_string("Word *").
output_llds_type(code_ptr)     --> io__write_string("Code *").

:- pred output_cons_arg_decls(list(maybe(rval))::in, string::in, string::in,
	int::in, int::out, decl_set::in, decl_set::out,
	io__state::di, io__state::uo) is det.

output_cons_arg_decls([], _, _, N, N, DeclSet, DeclSet) --> [].
output_cons_arg_decls([Arg | Args], FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	( { Arg = yes(Rval) } ->
		output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N1,
			DeclSet0, DeclSet1)
	;
		{ N1 = N0 },
		{ DeclSet1 = DeclSet0 }
	),
	output_cons_arg_decls(Args, FirstIndent, LaterIndent, N1, N,
		DeclSet1, DeclSet).

	% Output the arguments, each on its own line prefixing with Indent,
	% and with a cast appropriate to its type if necessary.

:- pred output_cons_args(list(maybe(rval))::in, create_arg_types::in,
	string::in, io__state::di, io__state::uo) is det.

output_cons_args(Args, uniform(MaybeType), Indent) -->
	output_uniform_cons_args(Args, MaybeType, Indent).
output_cons_args(Args, initial(InitTypes, RestTypes), Indent) -->
	output_initial_cons_args(Args, InitTypes, RestTypes, Indent).
output_cons_args(Args, none, _) -->
	{ require(unify(Args, []), "too many args for specified arg types") }.

:- pred output_uniform_cons_args(list(maybe(rval))::in, maybe(llds_type)::in,
	string::in, io__state::di, io__state::uo) is det.

output_uniform_cons_args([], _, _) --> [].
output_uniform_cons_args([Arg | Args], MaybeType, Indent) -->
	( { Arg = yes(Rval) } ->
		io__write_string(Indent),
		globals__io_get_globals(Globals),
		(
			%
			% Don't output code_addr_consts if they are not 
			% actually const; instead just output `NULL' here in
			% the static initializer.  The value will be supplied
			% by the dynamic initialization code.
			%
			{ Rval = const(code_addr_const(_)) },
			{ globals__have_static_code_addresses(Globals,
				StaticCode) },
			{ StaticCode = no }
		->
			io__write_string("NULL")
		;
			( { MaybeType = yes(_) } ->
				output_static_rval(Rval)
			;
				llds_out__rval_type_as_arg(Rval, Type),
				output_rval_as_type(Rval, Type)
			)
		),
		( { Args \= [] } ->
			io__write_string(",\n"),
			output_uniform_cons_args(Args, MaybeType, Indent)
		;
			io__write_string("\n")
		)
	;
		% `Arg = no' means the argument is uninitialized,
		% but that would mean the term isn't ground
		{ error("output_uniform_cons_args: missing argument") }
	).

:- pred output_initial_cons_args(list(maybe(rval))::in, initial_arg_types::in,
	create_arg_types::in, string::in, io__state::di, io__state::uo) is det.

output_initial_cons_args(Args, [], RestTypes, Indent) -->
	output_cons_args(Args, RestTypes, Indent).
output_initial_cons_args(Args, [N - MaybeType | InitTypes], RestTypes,
		Indent) -->
	output_initial_cons_args_2(Args, N, MaybeType, InitTypes, RestTypes,
		Indent).

:- pred output_initial_cons_args_2(list(maybe(rval))::in, int::in,
	maybe(llds_type)::in, initial_arg_types::in, create_arg_types::in,
	string::in, io__state::di, io__state::uo) is det.

output_initial_cons_args_2([], N, _, _, _, _) -->
	{ require(unify(N, 0), "not enough args for specified arg types") }.
output_initial_cons_args_2([Arg | Args], N, MaybeType, InitTypes, RestTypes,
		Indent) -->
	( { N = 0 } ->
		output_initial_cons_args([Arg | Args], InitTypes, RestTypes,
			Indent)
	;
		( { Arg = yes(Rval) } ->
			{ N1 is N - 1 },
			io__write_string(Indent),
			( { MaybeType = yes(_) } ->
				output_static_rval(Rval)
			;
				llds_out__rval_type_as_arg(Rval, Type),
				output_rval_as_type(Rval, Type)
			),
			( { Args \= [] } ->
				io__write_string(",\n"),
				output_initial_cons_args_2(Args, N1, MaybeType,
					InitTypes, RestTypes, Indent)
			;
				{ require(unify(N1, 0),
				"not enough args for specified arg types") },
				io__write_string("\n")
			)
		;
			{ error("output_initial_cons_arg: missing argument") }
		)
	).

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

% output_lval_decls(Lval, ...) outputs the declarations of any
% static constants, etc. that need to be declared before
% output_lval(Lval) is called.

:- pred output_lval_decls(lval, string, string, int, int, decl_set, decl_set,
	io__state, io__state).
:- mode output_lval_decls(in, in, in, in, out, in, out, di, uo) is det.

output_lval_decls(field(_, Rval, FieldNum), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N1,
		DeclSet0, DeclSet1),
	output_rval_decls(FieldNum, FirstIndent, LaterIndent, N1, N,
		DeclSet1, DeclSet).
output_lval_decls(reg(_, _), _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(stackvar(_), _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(framevar(_), _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(succip, _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(maxfr, _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(curfr, _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(succfr(Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_lval_decls(prevfr(Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_lval_decls(redofr(Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_lval_decls(redoip(Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_lval_decls(succip(Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).
output_lval_decls(hp, _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(sp, _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(lvar(_), _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(temp(_, _), _, _, N, N, DeclSet, DeclSet) --> [].
output_lval_decls(mem_ref(Rval), FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	output_rval_decls(Rval, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet).

% output_code_addr_decls(CodeAddr, ...) outputs the declarations of any
% extern symbols, etc. that need to be declared before
% output_code_addr(CodeAddr) is called.

:- pred output_code_addr_decls(code_addr, string, string, int, int,
	decl_set, decl_set, io__state, io__state).
:- mode output_code_addr_decls(in, in, in, in, out, in, out, di, uo) is det.

output_code_addr_decls(CodeAddress, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	( { decl_set_is_member(code_addr(CodeAddress), DeclSet0) } ->
		{ N = N0 },
		{ DeclSet = DeclSet0 }
	;
		{ decl_set_insert(DeclSet0, code_addr(CodeAddress), DeclSet) },
		need_code_addr_decls(CodeAddress, NeedDecl),
		( { NeedDecl = yes } ->
			output_indent(FirstIndent, LaterIndent, N0),
			{ N is N0 + 1 },
			output_code_addr_decls(CodeAddress)
		;
			{ N = N0 }
		)
	).

:- pred need_code_addr_decls(code_addr, bool, io__state, io__state).
:- mode need_code_addr_decls(in, out, di, uo) is det.

need_code_addr_decls(label(Label), Need) -->
	{ 
		Label = exported(_),
		Need = yes
	;
		Label = local(_),
		Need = yes
	;
		Label = c_local(_),
		Need = no
	;
		Label = local(_, _),
		Need = no
	}.
need_code_addr_decls(imported(_), yes) --> [].
need_code_addr_decls(succip, no) --> [].
need_code_addr_decls(do_succeed(_), no) --> [].
need_code_addr_decls(do_redo, NeedDecl) -->
	globals__io_lookup_bool_option(use_macro_for_redo_fail, UseMacro),
	(
		{ UseMacro = yes },
		{ NeedDecl = no }
	;
		{ UseMacro = no },
		{ NeedDecl = yes }
	).
need_code_addr_decls(do_fail, NeedDecl) -->
	globals__io_lookup_bool_option(use_macro_for_redo_fail, UseMacro),
	(
		{ UseMacro = yes },
		{ NeedDecl = no }
	;
		{ UseMacro = no },
		{ NeedDecl = yes }
	).
need_code_addr_decls(do_trace_redo_fail_shallow, yes) --> [].
need_code_addr_decls(do_trace_redo_fail_deep, yes) --> [].
need_code_addr_decls(do_call_closure, yes) --> [].
need_code_addr_decls(do_call_class_method, yes) --> [].
need_code_addr_decls(do_det_aditi_call, yes) --> [].
need_code_addr_decls(do_semidet_aditi_call, yes) --> [].
need_code_addr_decls(do_nondet_aditi_call, yes) --> [].
need_code_addr_decls(do_aditi_insert, yes) --> [].
need_code_addr_decls(do_aditi_delete, yes) --> [].
need_code_addr_decls(do_aditi_bulk_insert, yes) --> [].
need_code_addr_decls(do_aditi_bulk_delete, yes) --> [].
need_code_addr_decls(do_aditi_modify, yes) --> [].
need_code_addr_decls(do_not_reached, yes) --> [].

:- pred output_code_addr_decls(code_addr, io__state, io__state).
:- mode output_code_addr_decls(in, di, uo) is det.

output_code_addr_decls(label(Label)) -->
	output_label_as_code_addr_decls(Label).
output_code_addr_decls(imported(ProcLabel)) -->
	io__write_string("Declare_entry("),
	output_proc_label(ProcLabel),
	io__write_string(");\n").
output_code_addr_decls(succip) --> [].
output_code_addr_decls(do_succeed(_)) --> [].
output_code_addr_decls(do_redo) -->
	globals__io_lookup_bool_option(use_macro_for_redo_fail, UseMacro),
	(
		{ UseMacro = yes }
	;
		{ UseMacro = no },
		io__write_string("Declare_entry("),
		io__write_string("do_redo"),
		io__write_string(");\n")
	).
output_code_addr_decls(do_fail) -->
	globals__io_lookup_bool_option(use_macro_for_redo_fail, UseMacro),
	(
		{ UseMacro = yes }
	;
		{ UseMacro = no },
		io__write_string("Declare_entry("),
		io__write_string("do_fail"),
		io__write_string(");\n")
	).
output_code_addr_decls(do_trace_redo_fail_shallow) -->
	io__write_string("Declare_entry(MR_do_trace_redo_fail_shallow);\n").
output_code_addr_decls(do_trace_redo_fail_deep) -->
	io__write_string("Declare_entry(MR_do_trace_redo_fail_deep);\n").
output_code_addr_decls(do_call_closure) -->
	io__write_string("Declare_entry(mercury__do_call_closure);\n").
output_code_addr_decls(do_call_class_method) -->
	io__write_string("Declare_entry(mercury__do_call_class_method);\n").
output_code_addr_decls(do_det_aditi_call) -->
	io__write_string("Declare_entry(do_det_aditi_call);\n").
output_code_addr_decls(do_semidet_aditi_call) -->
	io__write_string("Declare_entry(do_semidet_aditi_call);\n").
output_code_addr_decls(do_nondet_aditi_call) -->
	io__write_string("Declare_entry(do_nondet_aditi_call);\n").
output_code_addr_decls(do_aditi_insert) -->
	io__write_string("Declare_entry(do_aditi_insert);\n").
output_code_addr_decls(do_aditi_delete) -->
	io__write_string("Declare_entry(do_aditi_delete);\n").
output_code_addr_decls(do_aditi_bulk_insert) -->
	io__write_string("Declare_entry(do_aditi_bulk_insert);\n").
output_code_addr_decls(do_aditi_bulk_delete) -->
	io__write_string("Declare_entry(do_aditi_bulk_delete);\n").
output_code_addr_decls(do_aditi_modify) -->
	io__write_string("Declare_entry(do_aditi_modify);\n").
output_code_addr_decls(do_not_reached) -->
	io__write_string("Declare_entry(do_not_reached);\n").

:- pred output_label_as_code_addr_decls(label, io__state, io__state).
:- mode output_label_as_code_addr_decls(in, di, uo) is det.

output_label_as_code_addr_decls(exported(ProcLabel)) -->
	io__write_string("Declare_entry("),
	output_label(exported(ProcLabel)),
	io__write_string(");\n").
output_label_as_code_addr_decls(local(ProcLabel)) -->
	globals__io_lookup_bool_option(split_c_files, SplitFiles),
	( { SplitFiles = no } ->
		[]
	;
		io__write_string("Declare_entry("),
		output_label(local(ProcLabel)),
		io__write_string(");\n")
	).
output_label_as_code_addr_decls(c_local(_)) --> [].
output_label_as_code_addr_decls(local(_, _)) --> [].

:- pred output_data_addr_decls(data_addr, string, string, int, int,
		decl_set, decl_set, io__state, io__state).
:- mode output_data_addr_decls(in, in, in, in, out, in, out, di, uo) is det.

output_data_addr_decls(DataAddr, FirstIndent, LaterIndent, N0, N,
		DeclSet0, DeclSet) -->
	( { decl_set_is_member(data_addr(DataAddr), DeclSet0) } ->
		{ N = N0 },
		{ DeclSet = DeclSet0 }
	;
		{ decl_set_insert(DeclSet0, data_addr(DataAddr),
			DeclSet) },
		output_data_addr_decls_2(DataAddr,
			FirstIndent, LaterIndent, N0, N)
	).

:- pred output_data_addr_decls_2(data_addr, string, string, int, int,
	io__state, io__state).
:- mode output_data_addr_decls_2(in, in, in, in, out, di, uo) is det.

output_data_addr_decls_2(data_addr(ModuleName, VarName),
		FirstIndent, LaterIndent, N0, N) -->
	output_indent(FirstIndent, LaterIndent, N0),
	{ N is N0 + 1 },

	%
	% Previously we used to always write `extern' here, but
	% declaring something `extern' and then later defining it as
	% `static' causes undefined behavior -- on many systems, it
	% works, but on some systems such as RS/6000s running AIX
	% it results in link errors.
	%
	{ linkage(VarName, Linkage) },
	globals__io_lookup_bool_option(split_c_files, SplitFiles),
	(
		( { Linkage = extern }
		; { SplitFiles = yes }
		)
	->
		io__write_string("extern ")
	;
		io__write_string("static ")
	),

	globals__io_get_globals(Globals),

		% Don't make decls of type_ctor_infos etc.
		% `const' if we don't have static code addresses.
	(
		{ data_name_would_include_code_address(VarName, yes) },
		{ globals__have_static_code_addresses(Globals, no) }
	->
		[]
	;
		io__write_string("const ")
	),
	io__write_string("struct "),

	% If it's a type_ctor_info struct, use the
	% MR_TypeCtorInfo_struct type.
	(
		{ VarName = type_ctor(info, _, _) }
	->
		io__write_string("MR_TypeCtorInfo_struct\n")
	;
		output_data_addr(ModuleName, VarName), 
		io__write_string("_struct\n")
	),
	io__write_string(LaterIndent),
	io__write_string("\t"),
	output_data_addr(ModuleName, VarName), 
	io__write_string(";\n").

%
% Note that we need to know the linkage not just at the definition,
% but also at every use, because if the use is prior to the definition,
% then we need to declare the name first, and the linkage used in that
% declaration must be consistent with the linkage in the definition.
% For this reason, the field in c_data (which holds the information about
% the definition) which says whether or not a data name is exported
% is not useful.  Instead, we need to determine whether or not something
% is exported from its `data_name'.
%

:- type linkage ---> extern ; static.

:- pred linkage(data_name::in, linkage::out) is det.
linkage(common(_),                 static).
linkage(type_ctor(info, _, _),     extern).
linkage(type_ctor(layout, _, _),   static).
linkage(type_ctor(functors, _, _), static).
linkage(base_typeclass_info(_, _), extern).
linkage(module_layout,             static).
linkage(proc_layout(_),            static).
linkage(internal_layout(_),        static).
linkage(tabling_pointer(_),        static).

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

:- pred output_indent(string, string, int, io__state, io__state).
:- mode output_indent(in, in, in, di, uo) is det.

output_indent(FirstIndent, LaterIndent, N0) -->
	( { N0 > 0 } ->
		io__write_string(LaterIndent)
	;
		io__write_string(FirstIndent)
	).

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

:- pred maybe_output_update_prof_counter(label,
	pair(label, bintree_set(label)), io__state, io__state).
:- mode maybe_output_update_prof_counter(in, in, di, uo) is det.

maybe_output_update_prof_counter(Label, CallerLabel - ContLabelSet) -->
	(
		{ bintree_set__is_member(Label, ContLabelSet) }
	->
		io__write_string("\tupdate_prof_current_proc(LABEL("),
		output_label(CallerLabel),
		io__write_string("));\n")
	;
		[]
	).

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

:- pred output_goto(code_addr, label, io__state, io__state).
:- mode output_goto(in, in, di, uo) is det.

	% Note that we do some optimization here:
	% instead of always outputting `GOTO(<label>)', we
	% output different things for each different kind of label.

output_goto(label(Label), CallerLabel) -->
	(
		{ Label = exported(_) },
		io__write_string("tailcall("),
		output_label_as_code_addr(Label),
		io__write_string(",\n\t\t"),
		output_label_as_code_addr(CallerLabel),
		io__write_string(");\n")
	;
		{ Label = local(_) },
		io__write_string("tailcall("),
		output_label_as_code_addr(Label),
		io__write_string(",\n\t\t"),
		output_label_as_code_addr(CallerLabel),
		io__write_string(");\n")
	;
		{ Label = c_local(_) },
		io__write_string("localtailcall("),
		output_label(Label),
		io__write_string(",\n\t\t"),
		output_label_as_code_addr(CallerLabel),
		io__write_string(");\n")
	;
		{ Label = local(_, _) },
		io__write_string("GOTO_LABEL("),
		output_label(Label),
		io__write_string(");\n")
	).
output_goto(imported(ProcLabel), CallerLabel) -->
	io__write_string("tailcall(ENTRY("),
	output_proc_label(ProcLabel),
	io__write_string("),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(succip, _) -->
	io__write_string("proceed();\n").
output_goto(do_succeed(Last), _) -->
	(
		{ Last = no },
		io__write_string("MR_succeed();\n")
	;
		{ Last = yes },
		io__write_string("MR_succeed_discard();\n")
	).
output_goto(do_redo, _) -->
	globals__io_lookup_bool_option(use_macro_for_redo_fail, UseMacro),
	(
		{ UseMacro = yes },
		io__write_string("MR_redo();\n")
	;
		{ UseMacro = no },
		io__write_string("GOTO(ENTRY(do_redo));\n")
	).
output_goto(do_fail, _) -->
	globals__io_lookup_bool_option(use_macro_for_redo_fail, UseMacro),
	(
		{ UseMacro = yes },
		io__write_string("MR_fail();\n")
	;
		{ UseMacro = no },
		io__write_string("GOTO(ENTRY(do_fail));\n")
	).
output_goto(do_trace_redo_fail_shallow, _) -->
	io__write_string("GOTO(ENTRY(MR_do_trace_redo_fail_shallow));\n").
output_goto(do_trace_redo_fail_deep, _) -->
	io__write_string("GOTO(ENTRY(MR_do_trace_redo_fail_deep));\n").
output_goto(do_call_closure, CallerLabel) -->
	io__write_string("tailcall(ENTRY(mercury__do_call_closure),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_call_class_method, CallerLabel) -->
	io__write_string("tailcall(ENTRY(mercury__do_call_class_method),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_det_aditi_call, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_det_aditi_call),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_semidet_aditi_call, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_semidet_aditi_call),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_nondet_aditi_call, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_nondet_aditi_call),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_aditi_insert, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_aditi_insert),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_aditi_delete, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_aditi_delete),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_aditi_bulk_insert, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_aditi_bulk_insert),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_aditi_bulk_delete, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_aditi_bulk_delete),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_aditi_modify, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_aditi_modify),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").
output_goto(do_not_reached, CallerLabel) -->
	io__write_string("tailcall(ENTRY(do_not_reached),\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").

	% Note that we also do some optimization here by
	% outputting `localcall' rather than `call' for
	% calls to local labels, or `call_localret' for
	% calls which return to local labels (i.e. most of them).

:- pred output_call(code_addr, code_addr, label, io__state, io__state).
:- mode output_call(in, in, in, di, uo) is det.

output_call(Target, Continuation, CallerLabel) -->
	(
		{ Target = label(Label) },
		% We really shouldn't be calling internal labels ...
		{ Label = c_local(_) ; Label = local(_, _) }
	->
		io__write_string("\tlocalcall("),
		output_label(Label),
		io__write_string(",\n\t\t"),
		output_code_addr(Continuation)
	;
		{ Continuation = label(ContLabel) },
		{ ContLabel = c_local(_) ; ContLabel = local(_, _) }
	->
		io__write_string("\tcall_localret("),
		output_code_addr(Target),
		io__write_string(",\n\t\t"),
		output_label(ContLabel)
	;
		io__write_string("\tcall("),
		output_code_addr(Target),
		io__write_string(",\n\t\t"),
		output_code_addr(Continuation)
	),
	io__write_string(",\n\t\t"),
	output_label_as_code_addr(CallerLabel),
	io__write_string(");\n").

:- pred output_code_addr(code_addr, io__state, io__state).
:- mode output_code_addr(in, di, uo) is det.

output_code_addr(label(Label)) -->
	output_label_as_code_addr(Label).
output_code_addr(imported(ProcLabel)) -->
	io__write_string("ENTRY("),
	output_proc_label(ProcLabel),
	io__write_string(")").
output_code_addr(succip) -->
	io__write_string("MR_succip").
output_code_addr(do_succeed(Last)) -->
	(
		{ Last = no },
		io__write_string("ENTRY(do_succeed)")
	;
		{ Last = yes },
		io__write_string("ENTRY(do_last_succeed)")
	).
output_code_addr(do_redo) -->
	io__write_string("ENTRY(do_redo)").
output_code_addr(do_fail) -->
	io__write_string("ENTRY(do_fail)").
output_code_addr(do_trace_redo_fail_shallow) -->
	io__write_string("ENTRY(MR_do_trace_redo_fail_shallow)").
output_code_addr(do_trace_redo_fail_deep) -->
	io__write_string("ENTRY(MR_do_trace_redo_fail_deep)").
output_code_addr(do_call_closure) -->
	io__write_string("ENTRY(mercury__do_call_closure)").
output_code_addr(do_call_class_method) -->
	io__write_string("ENTRY(mercury__do_call_class_method)").
output_code_addr(do_det_aditi_call) -->
	io__write_string("ENTRY(do_det_aditi_call)").
output_code_addr(do_semidet_aditi_call) -->
	io__write_string("ENTRY(do_semidet_aditi_call)").
output_code_addr(do_nondet_aditi_call) -->
	io__write_string("ENTRY(do_nondet_aditi_call)").
output_code_addr(do_aditi_insert) -->
	io__write_string("ENTRY(do_aditi_insert)").
output_code_addr(do_aditi_delete) -->
	io__write_string("ENTRY(do_aditi_delete)").
output_code_addr(do_aditi_bulk_insert) -->
	io__write_string("ENTRY(do_aditi_bulk_insert)").
output_code_addr(do_aditi_bulk_delete) -->
	io__write_string("ENTRY(do_aditi_bulk_delete)").
output_code_addr(do_aditi_modify) -->
	io__write_string("ENTRY(do_aditi_modify)").
output_code_addr(do_not_reached) -->
	io__write_string("ENTRY(do_not_reached)").

	% The code should be kept in sync with output_data_addr/2 below.
llds_out__make_stack_layout_name(Label, Name) :-
	llds_out__get_label(Label, yes, LabelName),
	string__append_list([
		"mercury_data__layout__",
		LabelName
	], Name).

	% Output a data address. 

:- pred output_data_addr(module_name, data_name, io__state, io__state).
:- mode output_data_addr(in, in, di, uo) is det.

output_data_addr(ModuleName, VarName) -->
	(
		{ VarName = common(N) },
		{ llds_out__sym_name_mangle(ModuleName, MangledModuleName) },
		io__write_string("mercury_data_"),
		io__write_string(MangledModuleName),
		io__write_string("__common_"),
		{ string__int_to_string(N, NStr) },
		io__write_string(NStr)
	;
		{ VarName = type_ctor(BaseData, TypeName0, TypeArity) },
		{ llds_out__sym_name_mangle(ModuleName, MangledModuleName) },
		io__write_string("mercury_data_"),
		io__write_string(MangledModuleName),
		{ llds_out__make_type_ctor_name(BaseData, TypeName0, TypeArity,
			Str) },
		io__write_string("__"),
		io__write_string(Str)
	;
			% We don't want to include the module name as part
			% of the name if it is a base_typeclass_info, since
			% we _want_ to cause a link error for overlapping
			% instance decls, even if they are in a different 
			% module
		{ VarName = base_typeclass_info(ClassId, TypeNames) },
		{ llds_out__make_base_typeclass_info_name(ClassId, TypeNames, 
			Str) },
		io__write_string("mercury_data___"),
		io__write_string(Str)
	;
		{ VarName = module_layout },
		io__write_string("mercury_data__module_layout_"),
		{ llds_out__sym_name_mangle(ModuleName, MangledModuleName) },
		io__write_string(MangledModuleName)
	;
		% Keep this code in sync with make_stack_layout_name/3.
		{ VarName = proc_layout(Label) },
		io__write_string("mercury_data__layout__"),
		output_label(Label)
	;
		% Keep this code in sync with make_stack_layout_name/3.
		{ VarName = internal_layout(Label) },
		io__write_string("mercury_data__layout__"),
		output_label(Label)
	;
		{ VarName = tabling_pointer(ProcLabel) },
		io__write_string("mercury_var__tabling__"),
		output_proc_label(ProcLabel)
	).

:- pred output_label_as_code_addr(label, io__state, io__state).
:- mode output_label_as_code_addr(in, di, uo) is det.

output_label_as_code_addr(exported(ProcLabel)) -->
	io__write_string("ENTRY("),
	output_label(exported(ProcLabel)),
	io__write_string(")").
output_label_as_code_addr(local(ProcLabel)) -->
	globals__io_lookup_bool_option(split_c_files, SplitFiles),
	( { SplitFiles = no } ->
		io__write_string("STATIC("),
		output_label(local(ProcLabel)),
		io__write_string(")")
	;
		io__write_string("ENTRY("),
		output_label(local(ProcLabel)),
		io__write_string(")")
	).
output_label_as_code_addr(c_local(ProcLabel)) -->
	io__write_string("LABEL("),
	output_label(c_local(ProcLabel)),
	io__write_string(")").
output_label_as_code_addr(local(ProcLabel, N)) -->
	io__write_string("LABEL("),
	output_label(local(ProcLabel, N)),
	io__write_string(")").

:- pred output_label_list(list(label), io__state, io__state).
:- mode output_label_list(in, di, uo) is det.

output_label_list([]) --> [].
output_label_list([Label | Labels]) -->
	io__write_string("LABEL("),
	output_label(Label),
	io__write_string(")"),
	output_label_list_2(Labels).

:- pred output_label_list_2(list(label), io__state, io__state).
:- mode output_label_list_2(in, di, uo) is det.

output_label_list_2([]) --> [].
output_label_list_2([Label | Labels]) -->
	io__write_string(" AND\n\t\t"),
	io__write_string("LABEL("),
	output_label(Label),
	io__write_string(")"),
	output_label_list_2(Labels).

:- pred output_label_defn(label, io__state, io__state).
:- mode output_label_defn(in, di, uo) is det.

output_label_defn(exported(ProcLabel)) -->
	io__write_string("Define_entry("),
	output_label(exported(ProcLabel)),
	io__write_string(");\n").
output_label_defn(local(ProcLabel)) -->
	% The code for procedures local to a Mercury module
	% should normally be visible only within the C file
	% generated for that module. However, if we generate
	% multiple C files, the code in each C file must be
	% visible to the other C files for that Mercury module.
	globals__io_lookup_bool_option(split_c_files, SplitFiles),
	( { SplitFiles = no } ->
		io__write_string("Define_static("),
		output_label(local(ProcLabel)),
		io__write_string(");\n")
	;
		io__write_string("Define_entry("),
		output_label(local(ProcLabel)),
		io__write_string(");\n")
	).
output_label_defn(c_local(ProcLabel)) -->
	io__write_string("Define_local("),
	output_label(c_local(ProcLabel)),
	io__write_string(");\n").
output_label_defn(local(ProcLabel, Num)) -->
	io__write_string("Define_label("),
	output_label(local(ProcLabel, Num)),
	io__write_string(");\n").

% Note that the suffixes _l and _iN used to be interpreted by mod2c,
% which generated different code depending on the suffix.
% We don't generate the _l suffix anymore, since it interferes
% with referring to a label both as local(_) and c_local(_).
% For example, the entry label of a recursive unification predicate
% is referred to as local(_) in type_info structures and as c_local(_)
% in the recursive call.

output_label(Label) -->
	{ llds_out__get_label(Label, yes, LabelStr) },
	io__write_string(LabelStr).

output_proc_label(ProcLabel) -->
	{ llds_out__get_proc_label(ProcLabel, yes, ProcLabelString) },
	io__write_string(ProcLabelString).

llds_out__get_label(exported(ProcLabel), AddPrefix, ProcLabelStr) :-
	llds_out__get_proc_label(ProcLabel, AddPrefix, ProcLabelStr).
llds_out__get_label(local(ProcLabel), AddPrefix, ProcLabelStr) :-
	llds_out__get_proc_label(ProcLabel, AddPrefix, ProcLabelStr).
llds_out__get_label(c_local(ProcLabel), AddPrefix, ProcLabelStr) :-
	llds_out__get_proc_label(ProcLabel, AddPrefix, ProcLabelStr).
llds_out__get_label(local(ProcLabel, Num), AddPrefix, LabelStr) :-
	llds_out__get_proc_label(ProcLabel, AddPrefix, ProcLabelStr),
	string__int_to_string(Num, NumStr),
	string__append("_i", NumStr, NumSuffix),
	string__append(ProcLabelStr, NumSuffix, LabelStr).

%
% Warning: any changes to the name mangling algorithm here will also
% require changes to extras/dynamic_linking/name_mangle.m,
% profiler/demangle.m and util/mdemangle.c.
%
llds_out__get_proc_label(proc(DefiningModule, PredOrFunc, PredModule,
		PredName, Arity, ModeNum0), AddPrefix, ProcLabelString) :-
	get_label_name(DefiningModule, PredOrFunc, PredModule,
		PredName, Arity, AddPrefix, LabelName),
	( PredOrFunc = function ->
		OrigArity is Arity - 1
	;
		OrigArity = Arity
	),
	string__int_to_string(OrigArity, ArityString),
	proc_id_to_int(ModeNum0, ModeInt),
	string__int_to_string(ModeInt, ModeNumString),
	string__append_list([LabelName, "_", ArityString, "_", ModeNumString], 
		ProcLabelString).

	% For a special proc, output a label of the form:
	% mercury____<PredName>___<TypeModule>__<TypeName>_<TypeArity>_<Mode>
llds_out__get_proc_label(special_proc(Module, PredName, TypeModule, 
		TypeName, TypeArity, ModeNum0), AddPrefix, ProcLabelString) :-
	% figure out the LabelName
	DummyArity = -1,	% not used by get_label_name.
	get_label_name(unqualified(""), predicate, unqualified(""),
		PredName, DummyArity, AddPrefix, LabelName),

	% figure out the ModeNumString
	string__int_to_string(TypeArity, TypeArityString),
	proc_id_to_int(ModeNum0, ModeInt),
	string__int_to_string(ModeInt, ModeNumString),

	% mangle all the relevent names
	llds_out__sym_name_mangle(Module, MangledModule),
	llds_out__sym_name_mangle(TypeModule, MangledTypeModule),
	llds_out__name_mangle(TypeName, MangledTypeName),

	% Module-qualify the type name.
	% To handle locally produced unification preds for imported types,
	% we need to qualify it with both the module name of the
	% type, and also (if it is different) the module name of the
	% current module.
	llds_out__qualify_name(MangledTypeModule, MangledTypeName,
		QualifiedMangledTypeName),
	llds_out__maybe_qualify_name(MangledModule, QualifiedMangledTypeName,
		FullyQualifiedMangledTypeName),

	% join it all together
	string__append_list( [LabelName, "_", FullyQualifiedMangledTypeName, 
		"_", TypeArityString, "_", ModeNumString], 
		ProcLabelString).

	%  get a label name, given the defining module, predicate or
	%  function indicator, declaring module, predicate name, arity,
	%  and whether or not to add a prefix.

:- pred get_label_name(module_name, pred_or_func, module_name, string, arity,
			bool, string).
:- mode get_label_name(in, in, in, in, in, in, out) is det.

%
% Warning: any changes to the name mangling algorithm here will also
% require changes to extras/dynamic_linking/name_mangle.m,
% profiler/demangle.m and util/mdemangle.c.
%
get_label_name(DefiningModule, PredOrFunc, DeclaringModule,
		Name0, Arity, AddPrefix, LabelName) :-
	llds_out__sym_name_mangle(DeclaringModule, DeclaringModuleName),
	llds_out__sym_name_mangle(DefiningModule, DefiningModuleName),
	(
		( 
			mercury_private_builtin_module(DeclaringModule)
		;
			mercury_public_builtin_module(DeclaringModule)
		;
			Name0 = "main",
			Arity = 2
		;
			string__prefix(Name0, "__")
		)
		% The conditions above define which labels are printed without
		% module qualification.  XXX Changes to runtime/* are necessary
		% to allow `builtin' or `private_builtin' labels to be
		% qualified.
	->
		LabelName0 = Name0
	;
		llds_out__qualify_name(DeclaringModuleName, Name0,
			LabelName0)
	),
	(
		% if this is a specialized version of a predicate
		% defined in some other module, then it needs both
		% module prefixes
		DefiningModule \= DeclaringModule
	->
		string__append_list([DefiningModuleName, "__", LabelName0],
			LabelName1)
	;
		LabelName1 = LabelName0
	),
	llds_out__name_mangle(LabelName1, LabelName2),
	(
		PredOrFunc = function,
		string__append("fn__", LabelName2, LabelName3)
	;
		PredOrFunc = predicate,
		LabelName3 = LabelName2
	),
	( 
		AddPrefix = yes
	->
		get_label_prefix(Prefix),
		string__append(Prefix, LabelName3, LabelName)
	;
		LabelName = LabelName3
	).

	% To ensure that Mercury labels don't clash with C symbols, we
	% prefix them with `mercury__'.

:- pred get_label_prefix(string).
:- mode get_label_prefix(out) is det.

get_label_prefix("mercury__"). 

:- pred output_reg(reg_type, int, io__state, io__state).
:- mode output_reg(in, in, di, uo) is det.

output_reg(r, N) -->
	{ llds_out__reg_to_string(r, N, RegName) },
	io__write_string(RegName).
output_reg(f, _) -->
	{ error("Floating point registers not implemented") }.

:- pred output_tag(tag, io__state, io__state).
:- mode output_tag(in, di, uo) is det.

output_tag(Tag) -->
	io__write_string("MR_mktag("),
	io__write_int(Tag),
	io__write_string(")").

	% output an rval, converted to the specified type
	%
:- pred output_rval_as_type(rval, llds_type, io__state, io__state).
:- mode output_rval_as_type(in, in, di, uo) is det.

output_rval_as_type(Rval, DesiredType) -->
	{ llds__rval_type(Rval, ActualType) },
	( { types_match(DesiredType, ActualType) } ->
		% no casting needed
		output_rval(Rval)
	; { Rval = unop(cast_to_unsigned, _) } ->
		% cast_to_unsigned overrides the ordinary type
		% XXX this is a bit of a hack; we should probably
		% eliminate cast_to_unsigned and instead use
		% special unsigned operators
		output_rval(Rval)
	;
		% We need to convert to the right type first.
		% Convertions to/from float must be treated specially;
		% for the others, we can just use a cast.
		( { DesiredType = float } ->
			io__write_string("word_to_float("),
			output_rval(Rval),
			io__write_string(")")
		; { ActualType = float } ->
			( { DesiredType = word } ->
				output_float_rval_as_word(Rval)
			; { DesiredType = data_ptr } ->
				output_float_rval_as_data_ptr(Rval)
			;
				{ error("output_rval_as_type: type error") }
			)
		;
			% cast value to desired type
			io__write_string("("),
			output_llds_type(DesiredType),
			io__write_string(") "),
			output_rval(Rval)
		)
	).
	
	% types_match(DesiredType, ActualType) is true iff
	% a value of type ActualType can be used as a value of
	% type DesiredType without casting.
	%
:- pred types_match(llds_type, llds_type).
:- mode types_match(in, in) is semidet.

types_match(Type, Type).
types_match(word, unsigned).
types_match(word, integer).
types_match(word, bool).
types_match(bool, integer).
types_match(bool, unsigned).
types_match(bool, word).
types_match(integer, bool).

	% output a float rval, converted to type `Word *'
	%
:- pred output_float_rval_as_data_ptr(rval, io__state, io__state).
:- mode output_float_rval_as_data_ptr(in, di, uo) is det.

output_float_rval_as_data_ptr(Rval) -->
	%
	% for float constant expressions, if we're using boxed
	% boxed floats and --static-ground-terms is enabled,
	% we just refer to the static const which we declared
	% earlier
	%
	globals__io_lookup_bool_option(unboxed_float, UnboxFloat),
	globals__io_lookup_bool_option(static_ground_terms, StaticGroundTerms),
	(
		{ UnboxFloat = no, StaticGroundTerms = yes },
		{ llds_out__float_const_expr_name(Rval, FloatName) }
	->
		io__write_string("(Word *) &mercury_float_const_"),
		io__write_string(FloatName)
	;
		io__write_string("(Word *) float_to_word("),
		output_rval(Rval),
		io__write_string(")")
	).

	% output a float rval, converted to type `Word'
	%
:- pred output_float_rval_as_word(rval, io__state, io__state).
:- mode output_float_rval_as_word(in, di, uo) is det.

output_float_rval_as_word(Rval) -->
	%
	% for float constant expressions, if we're using boxed
	% boxed floats and --static-ground-terms is enabled,
	% we just refer to the static const which we declared
	% earlier
	%
	globals__io_lookup_bool_option(unboxed_float, UnboxFloat),
	globals__io_lookup_bool_option(static_ground_terms, StaticGroundTerms),
	(
		{ UnboxFloat = no, StaticGroundTerms = yes },
		{ llds_out__float_const_expr_name(Rval, FloatName) }
	->
		io__write_string("(Word) &mercury_float_const_"),
		io__write_string(FloatName)
	;
		io__write_string("float_to_word("),
		output_rval(Rval),
		io__write_string(")")
	).

	% output an rval (not converted to any particular type,
	% but instead output as its "natural" type)
	%
:- pred output_rval(rval, io__state, io__state).
:- mode output_rval(in, di, uo) is det.

output_rval(const(Const)) -->
	output_rval_const(Const).
output_rval(unop(UnaryOp, Exprn)) -->
	output_unary_op(UnaryOp),
	io__write_string("("),
	{ llds__unop_arg_type(UnaryOp, ArgType) },
	output_rval_as_type(Exprn, ArgType),
	io__write_string(")").
output_rval(binop(Op, X, Y)) -->
	(
		{ Op = array_index }
	->
		io__write_string("("),
		output_rval_as_type(X, data_ptr),
		io__write_string(")["),
		output_rval_as_type(Y, integer),
		io__write_string("]")
	;
		{ c_util__string_compare_op(Op, OpStr) }
	->
		io__write_string("(strcmp((char *)"),
		output_rval_as_type(X, word),
		io__write_string(", (char *)"),
		output_rval_as_type(Y, word),
		io__write_string(")"),
		io__write_string(" "),
		io__write_string(OpStr),
		io__write_string(" "),
		io__write_string("0)")
	;
		( { c_util__float_compare_op(Op, OpStr1) } ->
			{ OpStr = OpStr1 }
		; { c_util__float_op(Op, OpStr2) } ->
			{ OpStr = OpStr2 }
		;
			{ fail }
		)
	->
		io__write_string("("),
		output_rval_as_type(X, float),
		io__write_string(" "),
		io__write_string(OpStr),
		io__write_string(" "),
		output_rval_as_type(Y, float),
		io__write_string(")")
	;
/****
XXX broken for C == minint
(since `NewC is 0 - C' overflows)
		{ Op = (+) },
		{ Y = const(int_const(C)) },
		{ C < 0 }
	->
		{ NewOp = (-) },
		{ NewC is 0 - C },
		{ NewY = const(int_const(NewC)) },
		io__write_string("("),
		output_rval(X),
		io__write_string(" "),
		output_binary_op(NewOp),
		io__write_string(" "),
		output_rval(NewY),
		io__write_string(")")
	;
******/
		% special-case equality ops to avoid some unnecessary
		% casts -- there's no difference between signed and
		% unsigned equality, so if both args are unsigned, we
		% don't need to cast them to (Integer)
		{ Op = eq ; Op = ne },
		{ llds__rval_type(X, XType) },
		{ XType = word ; XType = unsigned },
		{ llds__rval_type(Y, YType) },
		{ YType = word ; YType = unsigned }
	->
		io__write_string("("),
		output_rval(X),
		io__write_string(" "),
		output_binary_op(Op),
		io__write_string(" "),
		output_rval(Y),
		io__write_string(")")
	;
		io__write_string("("),
		output_rval_as_type(X, integer),
		io__write_string(" "),
		output_binary_op(Op),
		io__write_string(" "),
		output_rval_as_type(Y, integer),
		io__write_string(")")
	).
output_rval(mkword(Tag, Exprn)) -->
	io__write_string("MR_mkword("),
	output_tag(Tag),
	io__write_string(", "),
	output_rval_as_type(Exprn, data_ptr),
	io__write_string(")").
output_rval(lval(Lval)) -->
	% if a field is used as an rval, then we need to use
	% the MR_const_field() macro, not the MR_field() macro,
	% to avoid warnings about discarding const,
	% and similarly for MR_mask_field.
	( { Lval = field(MaybeTag, Rval, FieldNum) } ->
		( { MaybeTag = yes(Tag) } ->
			io__write_string("MR_const_field("),
			output_tag(Tag),
			io__write_string(", ")
		;
			io__write_string("MR_const_mask_field(")
		),
		output_rval(Rval),
		io__write_string(", "),
		output_rval(FieldNum),
		io__write_string(")")
	;
		output_lval(Lval)
	).
output_rval(create(Tag, _Args, _ArgTypes, _StatDyn, CellNum, _Msg)) -->
		% emit a reference to the static constant which we
		% declared in output_rval_decls.
	io__write_string("MR_mkword(MR_mktag("),
	io__write_int(Tag),
	io__write_string("), "),
	io__write_string("&mercury_const_"),
	io__write_int(CellNum),
	io__write_string(")").
output_rval(var(_)) -->
	{ error("Cannot output a var(_) expression in code") }.
output_rval(mem_addr(MemRef)) -->
	(
		{ MemRef = stackvar_ref(N) },
		io__write_string("(Word *) &MR_stackvar("),
		io__write_int(N),
		io__write_string(")")
	;
		{ MemRef = framevar_ref(N) },
		io__write_string("(Word *) &MR_framevar("),
		io__write_int(N),
		io__write_string(")")
	;
		{ MemRef = heap_ref(Rval, Tag, FieldNum) },
		io__write_string("(Word *) &MR_field("),
		output_tag(Tag),
		io__write_string(", "),
		output_rval(Rval),
		io__write_string(", "),
		io__write_int(FieldNum),
		io__write_string(")")
	).

:- pred output_unary_op(unary_op, io__state, io__state).
:- mode output_unary_op(in, di, uo) is det.

output_unary_op(Op) -->
	{ c_util__unary_prefix_op(Op, OpString) },
	io__write_string(OpString).

:- pred output_rval_const(rval_const, io__state, io__state).
:- mode output_rval_const(in, di, uo) is det.

output_rval_const(int_const(N)) -->
	% we need to cast to (Integer) to ensure
	% things like 1 << 32 work when `Integer' is 64 bits
	% but `int' is 32 bits.
	io__write_string("(Integer) "),
	io__write_int(N).
output_rval_const(float_const(FloatVal)) -->
	% the cast to (Float) here lets the C compiler
	% do arithmetic in `float' rather than `double'
	% if `Float' is `float' not `double'.
	io__write_string("(Float) "),
	io__write_float(FloatVal).
output_rval_const(string_const(String)) -->
	io__write_string("MR_string_const("""),
	output_c_quoted_string(String),
	{ string__length(String, StringLength) },
	io__write_string(""", "),
	io__write_int(StringLength),
	io__write_string(")").
output_rval_const(multi_string_const(Length, String)) -->
	io__write_string("MR_string_const("""),
	output_c_quoted_multi_string(Length, String),
	io__write_string(""", "),
	io__write_int(Length),
	io__write_string(")").
output_rval_const(true) -->
	io__write_string("TRUE").
output_rval_const(false) -->
	io__write_string("FALSE").
output_rval_const(code_addr_const(CodeAddress)) -->
	output_code_addr(CodeAddress).
output_rval_const(data_addr_const(data_addr(ModuleName, VarName))) -->
	% data addresses are all assumed to be of type `Word *';
	% we need to cast them here to avoid type errors
	io__write_string("(Word *) &"),
	output_data_addr(ModuleName, VarName).
output_rval_const(label_entry(Label)) -->
	io__write_string("ENTRY("),
	output_label(Label),
	io__write_string(")").

	% Output an rval as an initializer in a static struct.
	% Make sure it has the C type the corresponding field would have.
	% This is the "really" natural type of the rval, free of the
	% Mercury abstract engine's need to shoehorn things into Words.

:- pred output_static_rval(rval, io__state, io__state).
:- mode output_static_rval(in, di, uo) is det.

output_static_rval(const(Const)) -->
	output_rval_static_const(Const).
output_static_rval(unop(_, _)) -->
	{ error("Cannot output a unop(_, _) in a static initializer") }.
output_static_rval(binop(_, _, _)) -->
	{ error("Cannot output a binop(_, _, _) in a static initializer") }.
output_static_rval(mkword(Tag, Exprn)) -->
	io__write_string("(Word *) MR_mkword("),
	output_tag(Tag),
	io__write_string(", "),
	output_static_rval(Exprn),
	io__write_string(")").
output_static_rval(lval(_)) -->
	{ error("Cannot output an lval(_) in a static initializer") }.
output_static_rval(create(Tag, _Args, _ArgTypes, _StatDyn, CellNum, _Msg)) -->
		% emit a reference to the static constant which we
		% declared in output_rval_decls.
	io__write_string("MR_mkword(MR_mktag("),
	io__write_int(Tag),
	io__write_string("), "),
	io__write_string("&mercury_const_"),
	io__write_int(CellNum),
	io__write_string(")").
output_static_rval(var(_)) -->
	{ error("Cannot output a var(_) in a static initializer") }.
output_static_rval(mem_addr(_)) -->
	{ error("Cannot output a mem_ref(_) in a static initializer") }.

:- pred output_rval_static_const(rval_const, io__state, io__state).
:- mode output_rval_static_const(in, di, uo) is det.

output_rval_static_const(int_const(N)) -->
	io__write_int(N).
output_rval_static_const(float_const(FloatVal)) -->
	io__write_float(FloatVal).
output_rval_static_const(string_const(String)) -->
	io__write_string("MR_string_const("""),
	output_c_quoted_string(String),
	{ string__length(String, StringLength) },
	io__write_string(""", "),
	io__write_int(StringLength),
	io__write_string(")").
output_rval_static_const(multi_string_const(Length, String)) -->
	io__write_string("MR_string_const("""),
	output_c_quoted_multi_string(Length, String),
	io__write_string(""", "),
	io__write_int(Length),
	io__write_string(")").
output_rval_static_const(true) -->
	io__write_string("TRUE").
output_rval_static_const(false) -->
	io__write_string("FALSE").
output_rval_static_const(code_addr_const(CodeAddress)) -->
	output_code_addr(CodeAddress).
output_rval_static_const(data_addr_const(data_addr(ModuleName, VarName))) -->
	io__write_string("(Word *) &"),
	output_data_addr(ModuleName, VarName).
output_rval_static_const(label_entry(Label)) -->
	io__write_string("ENTRY("),
	output_label(Label),
	io__write_string(")").

:- pred output_lval_as_word(lval, io__state, io__state).
:- mode output_lval_as_word(in, di, uo) is det.

output_lval_as_word(Lval) -->
	{ llds__lval_type(Lval, ActualType) },
	( { types_match(word, ActualType) } ->
		output_lval(Lval)
	; { ActualType = float } ->
		% sanity check -- if this happens, the llds is ill-typed
		{ error("output_lval_as_word: got float") }
	;
		io__write_string("LVALUE_CAST(Word,"),
		output_lval(Lval),
		io__write_string(")")
	).

:- pred output_lval(lval, io__state, io__state).
:- mode output_lval(in, di, uo) is det.

output_lval(reg(Type, Num)) -->
	output_reg(Type, Num).
output_lval(stackvar(N)) -->
	{ (N < 0) ->
		error("stack var out of range")
	;
		true
	},
	io__write_string("MR_stackvar("),
	io__write_int(N),
	io__write_string(")").
output_lval(framevar(N)) -->
	{ (N =< 0) ->
		error("frame var out of range")
	;
		true
	},
	io__write_string("MR_framevar("),
	io__write_int(N),
	io__write_string(")").
output_lval(succip) -->
	io__write_string("MR_succip").
output_lval(sp) -->
	io__write_string("MR_sp").
output_lval(hp) -->
	io__write_string("MR_hp").
output_lval(maxfr) -->
	io__write_string("MR_maxfr").
output_lval(curfr) -->
	io__write_string("MR_curfr").
output_lval(succfr(Rval)) -->
	io__write_string("MR_succfr_slot("),
	output_rval(Rval),
	io__write_string(")").
output_lval(prevfr(Rval)) -->
	io__write_string("MR_prevfr_slot("),
	output_rval(Rval),
	io__write_string(")").
output_lval(redofr(Rval)) -->
	io__write_string("MR_redofr_slot("),
	output_rval(Rval),
	io__write_string(")").
output_lval(redoip(Rval)) -->
	io__write_string("MR_redoip_slot("),
	output_rval(Rval),
	io__write_string(")").
output_lval(succip(Rval)) -->
	io__write_string("MR_succip_slot("),
	output_rval(Rval),
	io__write_string(")").
output_lval(field(MaybeTag, Rval, FieldNum)) -->
	( { MaybeTag = yes(Tag) } ->
		io__write_string("MR_field("),
		output_tag(Tag),
		io__write_string(", ")
	;
		io__write_string("MR_mask_field(")
	),
	output_rval(Rval),
	io__write_string(", "),
	output_rval(FieldNum),
	io__write_string(")").
output_lval(lvar(_)) -->
	{ error("Illegal to output an lvar") }.
output_lval(temp(Type, Num)) -->
	(
		{ Type = r },
		io__write_string("MR_tempr"),
		io__write_int(Num)
	;
		{ Type = f },
		io__write_string("MR_tempf"),
		io__write_int(Num)
	).
output_lval(mem_ref(Rval)) -->
	io__write_string("XXX("),
	output_rval(Rval),
	io__write_string(")").

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

:- pred output_set_line_num(prog_context, io__state, io__state).
:- mode output_set_line_num(in, di, uo) is det.

output_set_line_num(Context) -->
	{ term__context_file(Context, File) },
	{ term__context_line(Context, Line) },
	c_util__set_line_num(File, Line).

:- pred output_reset_line_num(io__state, io__state).
:- mode output_reset_line_num(di, uo) is det.

output_reset_line_num -->
	c_util__reset_line_num.

output_c_quoted_string(S) -->
	c_util__output_quoted_string(S).

output_c_quoted_multi_string(Len, S) -->
	c_util__output_quoted_multi_string(Len, S).

llds_out__quote_c_string(String, QuotedString) :-
	c_util__quote_string(String, QuotedString).

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

:- pred output_binary_op(binary_op, io__state, io__state).
:- mode output_binary_op(in, di, uo) is det.

output_binary_op(Op) -->
	( { c_util__binary_infix_op(Op, String) } ->
		io__write_string(String)
	;
		{ error("llds_out.m: invalid binary operator") }
	).

llds_out__binary_op_to_string(Op, Name) :-
	( c_util__binary_infix_op(Op, Name0) ->
		Name = Name0
	;
		% The following is just for debugging purposes -
		% string operators are not output as `str_eq', etc.
		functor(Op, Name, _)
	).

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

llds_out__lval_to_string(framevar(N), Description) :-
	string__int_to_string(N, N_String),
	string__append("MR_framevar(", N_String, Tmp),
	string__append(Tmp, ")", Description).
llds_out__lval_to_string(stackvar(N), Description) :-
	string__int_to_string(N, N_String),
	string__append("MR_stackvar(", N_String, Tmp),
	string__append(Tmp, ")", Description).
llds_out__lval_to_string(reg(RegType, RegNum), Description) :-
	llds_out__reg_to_string(RegType, RegNum, Reg_String),
	string__append("reg(", Reg_String, Tmp),
	string__append(Tmp, ")", Description).

llds_out__reg_to_string(r, N, Description) :-
	( N > 32 ->
		Template = "r(%d)"
	;
		Template = "r%d"
	),
	string__format(Template, [i(N)], Description).
llds_out__reg_to_string(f, N, Description) :-
	string__int_to_string(N, N_String),
	string__append("f(", N_String, Tmp),
	string__append(Tmp, ")", Description).

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

%
% Warning: any changes to the name mangling algorithm here will also
% require changes to extras/dynamic_linking/name_mangle.m,
% profiler/demangle.m and util/mdemangle.c.
%

llds_out__sym_name_mangle(unqualified(Name), MangledName) :-
	llds_out__name_mangle(Name, MangledName).
llds_out__sym_name_mangle(qualified(ModuleName, PlainName), MangledName) :-
	llds_out__sym_name_mangle(ModuleName, MangledModuleName),
	llds_out__name_mangle(PlainName, MangledPlainName),
	llds_out__qualify_name(MangledModuleName, MangledPlainName,
			MangledName).
	
	% Convert a Mercury predicate name into something that can form
	% part of a C identifier.  This predicate is necessary because
	% quoted names such as 'name with embedded spaces' are valid
	% predicate names in Mercury.

llds_out__name_mangle(Name, MangledName) :-
	(
		string__is_alnum_or_underscore(Name)
	->
		% any names that start with `f_' are changed so that
		% they start with `f__', so that we can use names starting
		% with `f_' (followed by anything except an underscore)
		% without fear of name collisions
		(
			string__append("f_", Suffix, Name)
		->
			string__append("f__", Suffix, MangledName)
		;
			MangledName = Name
		)
	;
		llds_out__convert_to_valid_c_identifier(Name, MangledName)
	).

:- pred llds_out__convert_to_valid_c_identifier(string, string).
:- mode llds_out__convert_to_valid_c_identifier(in, out) is det.

llds_out__convert_to_valid_c_identifier(String, Name) :-	
	(
		llds_out__name_conversion_table(String, Name0)
	->
		Name = Name0
	;
		llds_out__convert_to_valid_c_identifier_2(String, Name0),
		string__append("f", Name0, Name)
	).

llds_out__qualify_name(Module0, Name0, Name) :-
	string__append_list([Module0, "__", Name0], Name).

	% Produces a string of the form Module__Name, unless Module__
	% is already a prefix of Name.

:- pred llds_out__maybe_qualify_name(string, string, string).
:- mode llds_out__maybe_qualify_name(in, in, out) is det.

llds_out__maybe_qualify_name(Module0, Name0, Name) :-
	string__append(Module0, "__", UnderscoresModule),
	( string__append(UnderscoresModule, _, Name0) ->
		Name = Name0
	;
		string__append(UnderscoresModule, Name0, Name)
	).

	% A table used to convert Mercury functors into
	% C identifiers.  Feel free to add any new translations you want.
	% The C identifiers should start with "f_",
	% to avoid introducing name clashes.
	% If the functor name is not found in the table, then
	% we use a fall-back method which produces ugly names.

:- pred llds_out__name_conversion_table(string, string).
:- mode llds_out__name_conversion_table(in, out) is semidet.

llds_out__name_conversion_table("\\=", "f_not_equal").
llds_out__name_conversion_table(">=", "f_greater_or_equal").
llds_out__name_conversion_table("=<", "f_less_or_equal").
llds_out__name_conversion_table("=", "f_equal").
llds_out__name_conversion_table("<", "f_less_than").
llds_out__name_conversion_table(">", "f_greater_than").
llds_out__name_conversion_table("-", "f_minus").
llds_out__name_conversion_table("+", "f_plus").
llds_out__name_conversion_table("*", "f_times").
llds_out__name_conversion_table("/", "f_slash").
llds_out__name_conversion_table(",", "f_comma").
llds_out__name_conversion_table(";", "f_semicolon").
llds_out__name_conversion_table("!", "f_cut").

	% This is the fall-back method.
	% Given a string, produce a C identifier
	% for that string by concatenating the decimal
	% expansions of the character codes in the string,
	% separated by underlines.
	% The C identifier will start with "f_"; this predicate
	% constructs everything except the initial "f".
	%
	% For example, given the input "\n\t" we return "_10_8".

:- pred llds_out__convert_to_valid_c_identifier_2(string, string).
:- mode llds_out__convert_to_valid_c_identifier_2(in, out) is det.

llds_out__convert_to_valid_c_identifier_2(String, Name) :-	
	(
		string__first_char(String, Char, Rest)
	->
		char__to_int(Char, Code),
		string__int_to_string(Code, CodeString),
		string__append("_", CodeString, ThisCharString),
		llds_out__convert_to_valid_c_identifier_2(Rest, Name0),
		string__append(ThisCharString, Name0, Name)
	;
		% String is the empty string
		Name = String
	).

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

llds_out__make_type_ctor_name(BaseData, TypeName0, TypeArity, Str) :-
	(
		BaseData = info,
		BaseString = "info"
	;
		BaseData = layout,
		BaseString = "layout"
	;
		BaseData = functors,
		BaseString = "functors"
	),
	llds_out__name_mangle(TypeName0, TypeName),
	string__int_to_string(TypeArity, A_str),
        string__append_list(["type_ctor_", BaseString, "_", TypeName, "_", 
		A_str], Str).


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

llds_out__make_base_typeclass_info_name(class_id(ClassSym, ClassArity),
		TypeNames, Str) :-
	llds_out__sym_name_mangle(ClassSym, MangledClassString),
	string__int_to_string(ClassArity, ArityString),
	llds_out__name_mangle(TypeNames, MangledTypeNames),
	string__append_list(["base_typeclass_info_", MangledClassString,
		"__arity", ArityString, "__", MangledTypeNames], Str).

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

:- pred gather_c_file_labels(list(comp_gen_c_module)::in, list(label)::out)
	is det.

gather_c_file_labels(Modules, Labels) :-
	gather_labels_from_c_modules(Modules, [], Labels1),
	list__reverse(Labels1, Labels).

:- pred gather_c_module_labels(list(c_procedure)::in, list(label)::out) is det.

gather_c_module_labels(Procs, Labels) :-
	gather_labels_from_c_procs(Procs, [], Labels1),
	list__reverse(Labels1, Labels).

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

:- pred gather_labels_from_c_modules(list(comp_gen_c_module)::in,
	list(label)::in, list(label)::out) is det.

gather_labels_from_c_modules([], Labels, Labels).
gather_labels_from_c_modules([Module | Modules], Labels0, Labels) :-
	gather_labels_from_c_module(Module, Labels0, Labels1),
	gather_labels_from_c_modules(Modules, Labels1, Labels).

:- pred gather_labels_from_c_module(comp_gen_c_module::in,
	list(label)::in, list(label)::out) is det.

gather_labels_from_c_module(comp_gen_c_module(_, Procs), Labels0, Labels) :-
	gather_labels_from_c_procs(Procs, Labels0, Labels).

:- pred gather_labels_from_c_procs(list(c_procedure)::in,
	list(label)::in, list(label)::out) is det.

gather_labels_from_c_procs([], Labels, Labels).
gather_labels_from_c_procs([c_procedure(_, _, _, Instrs) | Procs],
		Labels0, Labels) :-
	gather_labels_from_instrs(Instrs, Labels0, Labels1),
	gather_labels_from_c_procs(Procs, Labels1, Labels).

:- pred gather_labels_from_instrs(list(instruction)::in,
	list(label)::in, list(label)::out) is det.

gather_labels_from_instrs([], Labels, Labels).
gather_labels_from_instrs([Instr | Instrs], Labels0, Labels) :-
	( Instr = label(Label) - _ ->
		Labels1 = [Label | Labels0]
	;
		Labels1 = Labels0
	),
	gather_labels_from_instrs(Instrs, Labels1, Labels).

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

	% Currently the `.rlo' files are stored as static data in the
	% executable. It may be better to store them in separate files
	% in a known location and load them at runtime.
:- pred output_rl_file(module_name, maybe(rl_file), io__state, io__state).
:- mode output_rl_file(in, in, di, uo) is det.

output_rl_file(ModuleName, MaybeRLFile) -->
	globals__io_lookup_bool_option(aditi, Aditi),
	( { Aditi = no } ->
		[]
	;
		io__write_string("\n\n/* Aditi-RL code for this module. */\n"),
		{ llds_out__make_rl_data_name(ModuleName, RLDataConstName) },
		io__write_string("const char "),
		io__write_string(RLDataConstName),
		io__write_string("[] = {"),
		(
			{ MaybeRLFile = yes(RLFile) },
			rl_file__write_binary(output_rl_byte, RLFile, Length),
			io__write_string("0};\n")
		;
			{ MaybeRLFile = no },
			io__write_string("};\n"),
			{ Length = 0 }
		),

		% Store the length of the data in 
		% mercury__aditi_rl_data__<module>__length.

		{ string__append(RLDataConstName, "__length",
			RLDataConstLength) },
		io__write_string("const int "),
		io__write_string(RLDataConstLength),
		io__write_string(" = "),
		io__write_int(Length),
		io__write_string(";\n\n")
	).

:- pred output_rl_byte(int, io__state, io__state).
:- mode output_rl_byte(in, di, uo) is det.

output_rl_byte(Byte) -->
	io__write_int(Byte),
	io__write_string(", ").

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

:- pred make_directory(string::in, io__state::di, io__state::uo) is det.

make_directory(DirName) -->
	{ string__format("[ -d %s ] || mkdir -p %s", [s(DirName), s(DirName)],
		Command) },
	io__call_system(Command, _Result).

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