Source

gdc / d / d-codegen.cc

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
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
/* GDC -- D front-end for GCC
   Copyright (C) 2004 David Friedman

   Modified by
    Iain Buclaw, Michael Parrott, (C) 2010, 2011

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "d-gcc-includes.h"
#include "d-lang.h"
#include "d-codegen.h"

#include <math.h>
#include <limits.h>

#include "template.h"
#include "init.h"
#include "symbol.h"
#include "dt.h"
#include "id.h"

GlobalValues g;
IRState gen;
TemplateEmission IRState::emitTemplates;
bool IRState::splitDynArrayVarArgs;
bool IRState::useInlineAsm;
bool IRState::useBuiltins;

Module * IRState::builtinsModule = 0;
Module * IRState::intrinsicModule = 0;
Module * IRState::intrinsicCoreModule = 0;
Module * IRState::mathModule = 0;
Module * IRState::mathCoreModule = 0;
TemplateDeclaration * IRState::stdargTemplateDecl = 0;
TemplateDeclaration * IRState::cstdargStartTemplateDecl = 0;
TemplateDeclaration * IRState::cstdargArgTemplateDecl = 0;

#if V2
VarDeclarations * IRState::varsInScope;
#endif

bool
d_gcc_force_templates()
{
    return IRState::emitTemplates == TEprivate ||
        IRState::emitTemplates == TEall;
}

void
d_gcc_emit_local_variable(VarDeclaration * v)
{
    g.irs->emitLocalVar(v);
}

bool
d_gcc_supports_weak()
{
    return SUPPORTS_WEAK;
}

static bool
needs_expr_var(tree exp)
{
    switch (TREE_CODE(exp))
    {
        case VAR_DECL:
        case FUNCTION_DECL:
        case PARM_DECL:
        case CONST_DECL:
        case INDIRECT_REF:
        case ARRAY_REF:
            return false;

        case COMPONENT_REF:
            return needs_expr_var(TREE_OPERAND(exp,0));

        default:
            return true;
    }
}

tree
IRState::declContext(Dsymbol * d_sym)
{
    Dsymbol * orig_sym = d_sym;
    AggregateDeclaration * ad;

    while ((d_sym = d_sym->toParent2()))
    {
        if (d_sym->isFuncDeclaration())
        {   // 3.3.x (others?) dwarf2out chokes without this check... (output_pubnames)
            FuncDeclaration * f = orig_sym->isFuncDeclaration();
            if (f && ! gen.functionNeedsChain(f))
                return NULL_TREE;

            return d_sym->toSymbol()->Stree;
        }
        else if ((ad = d_sym->isAggregateDeclaration()))
        {
            tree ctx = ad->type->toCtype();
            if (ad->isClassDeclaration())
            {   // RECORD_TYPE instead of REFERENCE_TYPE
                ctx = TREE_TYPE(ctx);
            }

            return ctx;
        }
        else if (d_sym->isModule())
        {
            return d_sym->toSymbol()->ScontextDecl;
        }
    }
    return NULL_TREE;
}

void
IRState::doLineNote(const Loc & loc)
{
    ObjectFile::doLineNote(loc);
}

void
IRState::emitLocalVar(VarDeclaration * v, bool no_init)
{
    if (v->isDataseg() || v->isMember())
        return;

    Symbol * sym = v->toSymbol();
    tree var_decl = sym->Stree;

    gcc_assert(! TREE_STATIC(var_decl));
    if (TREE_CODE(var_decl) == CONST_DECL)
        return;

    DECL_CONTEXT(var_decl) = getLocalContext();

    // Compiler generated symbols
    if (v == func->vresult || v == func->v_argptr || v == func->v_arguments_var)
        DECL_ARTIFICIAL(var_decl) = 1;

    tree var_exp;
    if (sym->SframeField)
    {   // Fixes debugging local variables.
        SET_DECL_VALUE_EXPR(var_decl, var(v));
        DECL_HAS_VALUE_EXPR_P(var_decl) = 1;
    }
    var_exp = var_decl;
    pushdecl(var_decl);

    tree init_exp = NULL_TREE; // complete initializer expression (include MODIFY_EXPR, e.g.)
    tree init_val = NULL_TREE;

    if (! no_init && ! DECL_INITIAL(var_decl) && v->init)
    {
        if (! v->init->isVoidInitializer())
        {
            ExpInitializer * exp_init = v->init->isExpInitializer();
            Expression * ie = exp_init->toExpression();
            if (! (init_val = assignValue(ie, v)))
                init_exp = ie->toElem(this);
        }
        else
        {
            no_init = true;
        }
    }

    if (! no_init)
    {
        g.ofile->doLineNote(v->loc);

        if (! init_val)
        {
            init_val = DECL_INITIAL(var_decl);
            DECL_INITIAL(var_decl) = NULL_TREE; // %% from expandDecl
        }
        if (! init_exp && init_val)
            init_exp = vinit(var_exp, init_val);

        if (init_exp)
            addExp(init_exp);
        else if (! init_val && v->size(v->loc)) // Zero-length arrays do not have an initializer
            d_warning(OPT_Wuninitialized, "uninitialized variable '%s'", v->ident ? v->ident->string : "(no name)");
    }
}

tree
IRState::localVar(tree t_type)
{
    tree t_decl = build_decl(BUILTINS_LOCATION, VAR_DECL, NULL_TREE, t_type);
    DECL_CONTEXT(t_decl) = getLocalContext();
    DECL_ARTIFICIAL(t_decl) = 1;
    DECL_IGNORED_P(t_decl) = 1;
    pushdecl(t_decl);
    return t_decl;
}

tree
IRState::localVar(Type * e_type)
{
    return localVar(e_type->toCtype());
}

tree
IRState::exprVar(tree t_type)
{
    tree t_decl = build_decl(BUILTINS_LOCATION, VAR_DECL, NULL_TREE, t_type);
    DECL_CONTEXT(t_decl) = getLocalContext();
    DECL_ARTIFICIAL(t_decl) = 1;
    DECL_IGNORED_P(t_decl) = 1;
    return t_decl;
}

tree
IRState::maybeExprVar(tree exp, tree * out_var)
{
    if (needs_expr_var(exp))
    {
        *out_var = exprVar(TREE_TYPE(exp));
        DECL_INITIAL(*out_var) = exp;
        return *out_var;
    }
    else
    {
        *out_var = NULL_TREE;
        return exp;
    }
}

void
IRState::expandDecl(tree t_decl)
{
    // nothing, pushdecl will add t_decl to a BIND_EXPR
    if (DECL_INITIAL(t_decl))
    {   // void_type_node%%?
        doExp(build2(INIT_EXPR, void_type_node, t_decl, DECL_INITIAL(t_decl)));
        DECL_INITIAL(t_decl) = NULL_TREE;
    }
}

tree
IRState::var(VarDeclaration * v)
{
    bool is_frame_var = v->toSymbol()->SframeField != NULL;

    if (is_frame_var)
    {
        FuncDeclaration * f = v->toParent2()->isFuncDeclaration();

        tree cf = getFrameRef(f);
        tree field = v->toSymbol()->SframeField;
        gcc_assert(field != NULL_TREE);
        return component(indirect(cf), field);
    }
    else
    {   // Static var or auto var that the back end will handle for us
        return v->toSymbol()->Stree;
    }
}


tree
IRState::convertTo(Expression * exp, Type * target_type)
{
    return convertTo(exp->toElem(this), exp->type, target_type);
}

tree
IRState::convertTo(tree exp, Type * exp_type, Type * target_type)
{
    tree result = NULL_TREE;

    gcc_assert(exp_type && target_type);
    Type * ebtype = exp_type->toBasetype();
    Type * tbtype = target_type->toBasetype();

    if (typesSame(exp_type, target_type))
        return exp;

    if (isErrorMark(exp))
        return exp;

    switch (ebtype->ty)
    {
        case Tdelegate:
            if (tbtype->ty == Tdelegate)
            {
                exp = maybeMakeTemp(exp);
                return delegateVal(delegateMethodRef(exp), delegateObjectRef(exp),
                                   target_type);
            }
            else if (tbtype->ty == Tpointer)
            {   // The front-end converts <delegate>.ptr to cast(void*)<delegate>.
                // Maybe should only allow void*?
                exp = delegateObjectRef(exp);
            }
            else
            {
                ::error("can't convert a delegate expression to %s", target_type->toChars());
                return error_mark_node;
            }
            break;
        case Tstruct:
            if (tbtype->ty == Tstruct)
            {
                if (target_type->size() == exp_type->size())
                {   // Allowed to cast to structs with same type size.
                    result = vconvert(exp, target_type->toCtype());
                }
                else
                {
                    ::error("can't convert struct %s to %s", exp_type->toChars(), target_type->toChars());
                    return error_mark_node;
                }
            }
            // else, default conversion, which should produce an error
            break;
        case Tclass:
            if (tbtype->ty == Tclass)
            {
                ClassDeclaration * target_class_decl = ((TypeClass *) tbtype)->sym;
                ClassDeclaration * obj_class_decl = ((TypeClass *) ebtype)->sym;
                bool use_dynamic = false;
                int offset;

                if (target_class_decl->isBaseOf(obj_class_decl, & offset))
                {   // Casting up the inheritance tree: Don't do anything special.
                    // Cast to an implemented interface: Handle at compile time.
                    if (offset == OFFSET_RUNTIME)
                        use_dynamic = true;
                    else if (offset)
                    {
                        tree t = target_type->toCtype();
                        exp = maybeMakeTemp(exp);
                        return build3(COND_EXPR, t,
                                boolOp(NE_EXPR, exp, d_null_pointer),
                                nop(pointerOffset(exp, size_int(offset)), t),
                                nop(d_null_pointer, t));
                    }
                    else
                    {   // d_convert will make a NOP cast
                        break;
                    }
                }
                else if (target_class_decl == obj_class_decl)
                {   // d_convert will make a NOP cast
                    break;
                }
                else if (! obj_class_decl->isCOMclass())
                    use_dynamic = true;

                if (use_dynamic)
                {   // Otherwise, do dynamic cast
                    tree args[2] = {
                        exp,
                        addressOf(target_class_decl->toSymbol()->Stree)
                    }; // %% (and why not just addressOf(target_class_decl)
                    return libCall(obj_class_decl->isInterfaceDeclaration()
                            ? LIBCALL_INTERFACE_CAST : LIBCALL_DYNAMIC_CAST, 2, args);
                }
                else
                {
                    d_warning(0, "cast to %s will yield null result", target_type->toChars());
                    result = convert(target_type->toCtype(), d_null_pointer);
                    if (TREE_SIDE_EFFECTS(exp))
                    {   // make sure the expression is still evaluated if necessary
                        result = compound(exp, result);
                    }
                    return result;
                }
            }
            // else default conversion
            break;
        case Tsarray:
            if (tbtype->ty == Tpointer)
            {
                result = nop(addressOf(exp), target_type->toCtype());
            }
            else if (tbtype->ty == Tarray)
            {
                TypeSArray * a_type = (TypeSArray*) ebtype;

                uinteger_t array_len = a_type->dim->toUInteger();
                d_uns64 sz_a = a_type->next->size();
                d_uns64 sz_b = tbtype->nextOf()->size();

                // conversions to different sizes
                // Assumes tvoid->size() == 1
                // %% TODO: handle misalign like _d_arraycast_xxx ?
                if (sz_a != sz_b)
                    array_len = array_len * sz_a / sz_b;

                tree pointer_value = nop(addressOf(exp),
                        tbtype->nextOf()->pointerTo()->toCtype());

                // Assumes casting to dynamic array of same type or void
                return darrayVal(target_type, array_len, pointer_value);
            }
            else if (tbtype->ty == Tsarray)
            {   // DMD apparently allows casting a static array to any static array type
                return vconvert(exp, target_type->toCtype());
            }
            else if (tbtype->ty == Tstruct)
            {   // And allows casting a static array to any struct type too.
                // %% type sizes should have already been checked by the frontend.
                gcc_assert(target_type->size() == exp_type->size());
                result = vconvert(exp, target_type->toCtype());
            }
            else
            {
                ::error("cannot cast expression of type %s to type %s",
                        exp_type->toChars(), target_type->toChars());
                return error_mark_node;
            }
            break;
        case Tarray:
            if (tbtype->ty == Tpointer)
            {
                return convert(target_type->toCtype(), darrayPtrRef(exp));
            }
            else if (tbtype->ty == Tarray)
            {   // assume tvoid->size() == 1
                Type * src_elem_type = ebtype->nextOf()->toBasetype();
                Type * dst_elem_type = tbtype->nextOf()->toBasetype();
                d_uns64 sz_src = src_elem_type->size();
                d_uns64 sz_dst = dst_elem_type->size();

                if (/*src_elem_type->ty == Tvoid ||*/ sz_src == sz_dst)
                {   // Convert from void[] or elements are the same size -- don't change length
                    return vconvert(exp, target_type->toCtype());
                }
                else
                {
                    unsigned mult = 1;
#if V1
                    if (dst_elem_type->isbit())
                        mult = 8;
#endif
                    tree args[3] = {
                        // assumes Type::tbit->size() == 1
                        integerConstant(sz_dst, Type::tsize_t),
                        integerConstant(sz_src * mult, Type::tsize_t),
                        exp
                    };
                    return libCall(LIBCALL_ARRAYCAST, 3, args, target_type->toCtype());
                }
            }
#if V2
            else if (tbtype->ty == Tsarray)
            {   // %% Strings are treated as dynamic arrays D2.
                if (ebtype->isString() && tbtype->isString())
                    return indirect(darrayPtrRef(exp), target_type->toCtype());
            }
#endif
            else
            {
                ::error("cannot cast expression of type %s to %s",
                        exp_type->toChars(), target_type->toChars());
                return error_mark_node;
            }
            break;
        case Taarray:
            if (tbtype->ty == Taarray)
                return vconvert(exp, target_type->toCtype());
            // else, default conversion, which should product an error
            break;
        case Tpointer:
            /* For some reason, convert_to_integer converts pointers
               to a signed type. */
            if (tbtype->isintegral())
                exp = d_convert_basic(d_type_for_size(POINTER_SIZE, 1), exp);
            // Can convert void pointers to associative arrays too...
            else if (tbtype->ty == Taarray && ebtype == Type::tvoidptr)
                return vconvert(exp, target_type->toCtype());
            break;
#if V2
        case Tnull:
            if (tbtype->ty == Tarray)
            {
                Type * pointer_type = tbtype->nextOf()->pointerTo();
                return darrayVal(target_type, 0, nop(exp, pointer_type->toCtype()));
            }
            break;
        case Tvector:
            if (tbtype->ty == Tsarray)
            {
                if (tbtype->size() == ebtype->size())
                    return vconvert(exp, target_type->toCtype());
            }
            break;
#endif
        default:
        {
            if ((ebtype->isreal() && tbtype->isimaginary())
                || (ebtype->isimaginary() && tbtype->isreal()))
            {   // warn? handle in front end?
                result = build_real_from_int_cst(target_type->toCtype(), integer_zero_node);
                if (TREE_SIDE_EFFECTS(exp))
                    result = compound(exp, result);
                return result;
            }
            else if (ebtype->iscomplex())
            {
                Type * part_type;
                // creal.re, .im implemented by cast to real or ireal
                // Assumes target type is the same size as the original's components size
                if (tbtype->isreal())
                {   // maybe install lang_specific...
                    switch (ebtype->ty)
                    {
                        case Tcomplex32: part_type = Type::tfloat32; break;
                        case Tcomplex64: part_type = Type::tfloat64; break;
                        case Tcomplex80: part_type = Type::tfloat80; break;
                        default:
                            gcc_unreachable();
                    }
                    result = realPart(exp);
                }
                else if (tbtype->isimaginary())
                {
                    switch (ebtype->ty)
                    {
                        case Tcomplex32: part_type = Type::timaginary32; break;
                        case Tcomplex64: part_type = Type::timaginary64; break;
                        case Tcomplex80: part_type = Type::timaginary80; break;
                        default:
                            gcc_unreachable();
                    }
                    result = imagPart(exp);
                }
                else
                {   // default conversion
                    break;
                }
                result = convertTo(result, part_type, target_type);
            }
            else if (tbtype->iscomplex())
            {
                tree c1 = convert(TREE_TYPE(target_type->toCtype()), exp);
                tree c2 = build_real_from_int_cst(TREE_TYPE(target_type->toCtype()), integer_zero_node);

                if (ebtype->isreal())
                {   // nothing
                }
                else if (ebtype->isimaginary())
                {
                    tree swap = c1;
                    c1 = c2;
                    c2 = swap;
                } else
                {   // default conversion
                    break;
                }
                result = build2(COMPLEX_EXPR, target_type->toCtype(), c1, c2);
            }
            else
            {
                gcc_assert(TREE_CODE(exp) != STRING_CST);
                // default conversion
            }
        }
    }

    if (! result)
        result = d_convert_basic(target_type->toCtype(), exp);
#if ENABLE_CHECKING
    if (isErrorMark(result))
        error("type: %s, target: %s", exp_type->toChars(), target_type->toChars());
#endif
    return result;
}

// Apply semantics of assignment to a values of type <target_type> to <exp>
// (e.g., pointer = array -> pointer = & array[0])

// Expects base type to be passed
static Type *
final_sa_elem_type(Type * type)
{
    while (type->ty == Tsarray)
        type = type->nextOf()->toBasetype();

    return type;
}

tree
IRState::convertForAssignment(Expression * exp, Type * target_type)
{
    Type * exp_base_type = exp->type->toBasetype();
    Type * target_base_type = target_type->toBasetype();
    tree exp_tree = NULL_TREE;

    // Assuming this only has to handle converting a non Tsarray type to
    // arbitrarily dimensioned Tsarrays.
    if (target_base_type->ty == Tsarray &&
        typesCompatible(final_sa_elem_type(target_base_type), exp_base_type))
    {   // %% what about implicit converions...?
        TypeSArray * sa_type = (TypeSArray *) target_base_type;
        uinteger_t count = sa_type->dim->toUInteger();

        tree ctor = build_constructor(target_type->toCtype(), 0);
        if (count)
        {
            CtorEltMaker ce;
            ce.cons(build2(RANGE_EXPR, Type::tsize_t->toCtype(),
                    integer_zero_node, integerConstant(count - 1)),
                g.ofile->stripVarDecl(convertForAssignment(exp, sa_type->next)));
            CONSTRUCTOR_ELTS(ctor) = ce.head;
        }
        TREE_READONLY(ctor) = 1;
        TREE_CONSTANT(ctor) = 1;
        return ctor;
    }
    else if (! target_type->isscalar() && exp_base_type->isintegral())
    {   // D Front end uses IntegerExp(0) to mean zero-init a structure
        // This could go in convert for assignment, but we only see this for
        // internal init code -- this also includes default init for _d_newarrayi...
        if (exp->toInteger() == 0)
        {
            CtorEltMaker ce;
            tree empty = build_constructor(target_type->toCtype(), ce.head); // %% will this zero init?
            TREE_CONSTANT(empty) = 1;
            TREE_STATIC(empty) = 1;
            return empty;
            // %%TODO: Use a code (lang_specific in decl or flag) to memset instead?
        }
        else
        {
            gcc_unreachable();
        }
    }

    exp_tree = exp->toElem(this);
    return convertForAssignment(exp_tree, exp->type, target_type);
}

tree
IRState::convertForAssignment(tree expr, Type * expr_type, Type * target_type)
{
    return convertTo(expr, expr_type, target_type);
}

tree
IRState::convertForArgument(Expression * exp, Parameter * arg)
{
    if (isArgumentReferenceType(arg))
    {
        tree exp_tree = this->toElemLvalue(exp);
        // front-end already sometimes automatically takes the address
        // TODO: Make this safer?  Can this be confused by a non-zero SymOff?
        if (exp->op != TOKaddress && exp->op != TOKsymoff && exp->op != TOKadd)
            return addressOf(exp_tree);
        else
            return exp_tree;
    }
    else
    {   // Lazy arguments: exp should already be a delegate
        tree exp_tree = exp->toElem(this);
        return exp_tree;
    }
}

// could be like C c-typeck.c:default_conversion
// todo:

/* Perform default promotions for C data used in expressions.
   Arrays and functions are converted to pointers;
   enumeral types or short or char, to int.
   In addition, manifest constants symbols are replaced by their values.  */

// what about float->double?

tree
IRState::convertForCondition(Expression * exp)
{
    return convertForCondition(exp->toElem(this), exp->type);
}

tree
IRState::convertForCondition(tree exp_tree, Type * exp_type)
{
    tree result = NULL_TREE;
    tree obj, func, tmp;

    switch (exp_type->toBasetype()->ty)
    {
        case Taarray:
            // Shouldn't this be...
            //  result = libCall(LIBCALL_AALEN, 1, & exp_tree);
            result = component(exp_tree, TYPE_FIELDS(TREE_TYPE(exp_tree)));
            break;

        case Tarray:
            // DMD checks (length || ptr) (i.e ary !is null)
            tmp = maybeMakeTemp(exp_tree);
            obj = delegateObjectRef(tmp);
            func = delegateMethodRef(tmp);
            if (TYPE_MODE(TREE_TYPE(obj)) == TYPE_MODE(TREE_TYPE(func)))
            {
                result = build2(BIT_IOR_EXPR, TREE_TYPE(obj), obj,
                                convert(TREE_TYPE(obj), func));
            }
            else
            {
                obj = d_truthvalue_conversion(obj);
                func = d_truthvalue_conversion(func);
                // probably not worth TRUTH_OROR ...
                result = build2(TRUTH_OR_EXPR, TREE_TYPE(obj), obj, func);
            }
            break;

        case Tdelegate:
            // DMD checks (function || object), but what good
            // is if if there is a null function pointer?
            if (D_IS_METHOD_CALL_EXPR(exp_tree))
            {
                extractMethodCallExpr(exp_tree, obj, func);
            }
            else
            {
                tmp = maybeMakeTemp(exp_tree);
                obj = delegateObjectRef(tmp);
                func = delegateMethodRef(tmp);
            }
            obj = d_truthvalue_conversion(obj);
            func = d_truthvalue_conversion(func);
            // not worth using  or TRUTH_ORIF...
            // %%TODO: Is this okay for all targets?
            result = build2(BIT_IOR_EXPR, TREE_TYPE(obj), obj, func);
            break;

        default:
            result = exp_tree;
            break;
    }
    // see expr.c:do_jump for the types of trees that can be passed to expand_start_cond
    //TREE_USED(<result>) = 1; // %% maybe not.. expr optimized away because constant expression?
    return d_truthvalue_conversion(result);
}


/* Convert EXP to a dynamic array.  EXP must be a static array or
   dynamic array. */
tree
IRState::toDArray(Expression * exp)
{
    TY ty = exp->type->toBasetype()->ty;
    tree val;
    if (ty == Tsarray)
        val = convertTo(exp, exp->type->toBasetype()->nextOf()->arrayOf());
    else if (ty == Tarray)
        val = exp->toElem(this);
    else
    {
        gcc_assert(ty == Tsarray || ty == Tarray);
        return NULL_TREE;
    }
    return val;
}


/* Type management for D frontend types.  */
bool
IRState::typesSame(Type * t1, Type * t2)
{
#if V2
    return t1->mutableOf()->equals(t2->mutableOf());
#else
    return t1->equals(t2);
#endif
}

bool
IRState::typesCompatible(Type * t1, Type * t2)
{
#if V2
    return t1->implicitConvTo(t2) >= MATCHconst;
#else
    return t1->equals(t2);
#endif
}

Type *
IRState::getDType(tree t)
{
    // %% TODO: assert that its a type node..
    struct lang_type * l = TYPE_LANG_SPECIFIC(t);
    return l ? l->d_type : 0;
}

Type *
IRState::getObjectType()
{
    if (ClassDeclaration::object)
        return ClassDeclaration::object->type;
    //error("missing or corrupt object.d");
    // %% apparently this isn't an error, so special-case in outdata.
    return Type::terror;
}


bool
IRState::isDeclarationReferenceType(Declaration * decl)
{
    Type * base_type = decl->type->toBasetype();
    // D doesn't do this now..
    if (base_type->ty == Treference)
        return true;

    if (decl->isOut() || decl->isRef())
        return true;

#if !SARRAYVALUE
    if (decl->isParameter() && base_type->ty == Tsarray)
        return true;
#endif
    return false;
}

tree
IRState::trueDeclarationType(Declaration * decl)
{
    // If D supported references, we would have to check twice for
    //   (out T &) -- disallow, maybe or make isDeclarationReferenceType return
    //   the number of levels to reference
    tree decl_type = decl->type->toCtype();
    if (isDeclarationReferenceType(decl))
    {
        decl_type = build_reference_type(decl_type);
        if (decl->isParameter())
            D_TYPE_ADDRESSABLE(decl_type) = 1;
    }
    else if (decl->storage_class & STClazy)
    {
        TypeFunction *tf = new TypeFunction(NULL, decl->type, 0, LINKd);
        TypeDelegate *t = new TypeDelegate(tf);
        decl_type = t->merge()->toCtype();
    }
    return decl_type;
}

// These should match the Declaration versions above
bool
IRState::isArgumentReferenceType(Parameter * arg)
{
    Type * base_type = arg->type->toBasetype();

    if (base_type->ty == Treference)
        return true;

    if (arg->storageClass & (STCout | STCref))
        return true;

#if !SARRAYVALUE
    if (base_type->ty == Tsarray)
        return true;
#endif
    return false;
}

tree
IRState::trueArgumentType(Parameter * arg)
{
    tree arg_type = arg->type->toCtype();
    if (isArgumentReferenceType(arg))
    {
        arg_type = build_reference_type(arg_type);
    }
    else if (arg->storageClass & STClazy)
    {
        TypeFunction *tf = new TypeFunction(NULL, arg->type, 0, LINKd);
        TypeDelegate *t = new TypeDelegate(tf);
        arg_type = t->merge()->toCtype();
    }
    return arg_type;
}

tree
IRState::arrayType(Type * d_type, uinteger_t size) // %% use of dinteger_t
{
    return arrayType(d_type->toCtype(), size);
}

tree
IRState::arrayType(tree type_node, uinteger_t size)
{
    tree index_type_node;
    if (size > 0)
    {
        index_type_node = size_int(size - 1);
        index_type_node = build_index_type(index_type_node);
    }
    else
    {   // See c-decl.c grokdeclarator for zero-length arrays
        index_type_node = build_range_type (sizetype, size_zero_node,
                NULL_TREE);
    }

    tree array_type = build_array_type(type_node, index_type_node);
    if (size == 0)
    {
        TYPE_SIZE(array_type) = bitsize_zero_node;
        TYPE_SIZE_UNIT(array_type) = size_zero_node;
    }
    return array_type;
}

// Can't call this until common types have been built
bool
IRState::haveLongDouble()
{
    return TYPE_MODE(long_double_type_node) != TYPE_MODE(double_type_node);
}

tree
IRState::addTypeAttribute(tree type, const char * attrname, tree value)
{
    // use build_variant_type_copy / build_type_attribute_variant

    // types built by functions in tree.c need to be treated as immutable
    if (! TYPE_ATTRIBUTES(type))
    {   // ! TYPE_ATTRIBUTES -- need a better check
        type = build_variant_type_copy(type);
        // TYPE_STUB_DECL(type) = .. if we need this for structs, etc.. since
        // TREE_CHAIN is cleared by COPY_NODE
    }
    if (value)
    {
        value = tree_cons(NULL_TREE, value, NULL_TREE);
    }
    TYPE_ATTRIBUTES(type) = tree_cons(get_identifier(attrname), value,
            TYPE_ATTRIBUTES(type));
    return type;
}

void
IRState::addDeclAttribute(tree type, const char * attrname, tree value)
{
    tree ident = get_identifier(attrname);
    if (value)
        value = tree_cons(NULL_TREE, value, NULL_TREE);

    DECL_ATTRIBUTES(type) = tree_cons(ident, value, DECL_ATTRIBUTES(type));
}

tree
IRState::attributes(Expressions * in_attrs)
{
    if (! in_attrs)
        return NULL_TREE;

    ListMaker out_attrs;

    for (size_t i = 0; i < in_attrs->dim; i++)
    {
        Expression * e = in_attrs->tdata()[i];
        IdentifierExp * ident_e = NULL;

        ListMaker args;

        if (e->op == TOKidentifier)
            ident_e = (IdentifierExp *) e;
        else if (e->op == TOKcall)
        {
            CallExp * c = (CallExp *) e;
            gcc_assert(c->e1->op == TOKidentifier);
            ident_e = (IdentifierExp *) c->e1;

            if (c->arguments)
            {
                for (size_t ai = 0; ai < c->arguments->dim; ai++)
                {
                    Expression * ae = c->arguments->tdata()[ai];
                    tree aet;
                    if (ae->op == TOKstring && ((StringExp *) ae)->sz == 1)
                    {
                        StringExp * s = (StringExp *) ae;
                        aet = build_string(s->len, (const char*) s->string);
                    }
                    else
                        aet = ae->toElem(&gen);
                    args.cons(aet);
                }
            }
        }
        else
        {
            gcc_unreachable();
            continue;
        }
        out_attrs.cons(get_identifier(ident_e->ident->string), args.head);
    }

    return out_attrs.head;
}

tree
IRState::addTypeModifiers(tree type, unsigned mod)
{
    int quals = 0;
    gcc_assert(type);

    switch (mod)
    {
        case 0:
            break;

        case MODconst:
        case MODwild:
        case MODimmutable:
            quals |= TYPE_QUAL_CONST;
            break;

        case MODshared:
            quals |= TYPE_QUAL_VOLATILE;
            break;

        case MODshared | MODwild:
        case MODshared | MODconst:
            quals |= TYPE_QUAL_CONST;
            quals |= TYPE_QUAL_VOLATILE;
            break;

        default:
            gcc_unreachable();
    }

    return build_qualified_type(type, quals);
}


tree
IRState::integerConstant(dinteger_t value, Type * type)
{
    return integerConstant(value, type->toCtype());
}

tree
IRState::integerConstant(dinteger_t value, tree type)
{
    // The type is error_mark_node, we can't do anything.
    if (isErrorMark(type))
        return type;

    tree tree_value = NULL_TREE;

#if HOST_BITS_PER_WIDE_INT == 32
    double_int cst = { value & 0xffffffff, (value >> 32) & 0xffffffff };
    tree_value = double_int_to_tree(type, cst);
#elif HOST_BITS_PER_WIDE_INT == 64
    tree_value = build_int_cst_type(type, value);
#else
#  error Fix This
#endif

    return tree_value;
}

tree
IRState::floatConstant(const real_t & value, Type * target_type)
{
    real_t new_value;
    TypeBasic * tb = target_type->isTypeBasic();

    gcc_assert(tb != NULL);

    tree type_node = tb->toCtype();
    real_convert(& new_value.rv(), TYPE_MODE(type_node), & value.rv());

    if (new_value > value)
    {   // value grew as a result of the conversion. %% precision bug ??
        // For now just revert back to original.
        new_value = value;
    }

    return build_real(type_node, new_value.rv());
}

dinteger_t
IRState::hwi2toli(HOST_WIDE_INT low, HOST_WIDE_INT high)
{
    dinteger_t result;

    if (high == 0 || sizeof(HOST_WIDE_INT) >= sizeof(dinteger_t))
        result = low;
    else
    {
        gcc_assert(sizeof(HOST_WIDE_INT) * 2 == sizeof(dinteger_t));
        result = (unsigned HOST_WIDE_INT) low;
        result += ((uinteger_t) (unsigned HOST_WIDE_INT) high) << HOST_BITS_PER_WIDE_INT;
    }
    return result;
}

dinteger_t
IRState::hwi2toli(double_int cst)
{
    return hwi2toli(cst.low, cst.high);
}


tree
IRState::realPart(tree c)
{
    return build1(REALPART_EXPR, TREE_TYPE(TREE_TYPE(c)), c);
}

tree
IRState::imagPart(tree c)
{
    return build1(IMAGPART_EXPR, TREE_TYPE(TREE_TYPE(c)), c);
}


tree
IRState::darrayLenRef(tree exp)
{
    if (isErrorMark(exp))
    {   // backend will ICE otherwise
        return exp;
    }
    // Get the backend type for the array and pick out the array length
    // field (assumed to be the first field.)
    tree len_field = TYPE_FIELDS(TREE_TYPE(exp));
    return component(exp, len_field);
}

tree
IRState::darrayPtrRef(tree exp)
{
    if (isErrorMark(exp))
    {   // backend will ICE otherwise
        return exp;
    }
    // Get the backend type for the array and pick out the array data
    // pointer field (assumed to be the second field.)
    tree ptr_field = TREE_CHAIN(TYPE_FIELDS(TREE_TYPE(exp)));
    //return build2(COMPONENT_REF, TREE_TYPE(ptr_field), exp, ptr_field);
    return component(exp, ptr_field);
}

tree
IRState::darrayPtrRef(Expression * e)
{
    return darrayPtrRef(e->toElem(this));
}


tree
IRState::darrayVal(tree type, tree len, tree data)
{
    // %% assert type is a darray
    tree len_field, ptr_field;
    CtorEltMaker ce;

    len_field = TYPE_FIELDS(type);
    ptr_field = TREE_CHAIN(len_field);

    ce.cons(len_field, len);
    ce.cons(ptr_field, data); // shouldn't need to convert the pointer...

    tree ctor = build_constructor(type, ce.head);
    TREE_STATIC(ctor) = 0;   // can be set by caller if needed
    TREE_CONSTANT(ctor) = 0; // "

    return ctor;
}

tree
IRState::darrayVal(Type * type, uinteger_t len, tree data)
{
    return darrayVal(type->toCtype(), len, data);
}

tree
IRState::darrayVal(tree type, uinteger_t len, tree data)
{
    // %% assert type is a darray
    tree len_value, ptr_value, len_field, ptr_field;
    CtorEltMaker ce;

    len_field = TYPE_FIELDS(type);
    ptr_field = TREE_CHAIN(len_field);

    if (data)
    {
        gcc_assert(POINTER_TYPE_P(TREE_TYPE(data)));
        ptr_value = data;
    }
    else
    {
        ptr_value = convert(TREE_TYPE(ptr_field), d_null_pointer);
    }

    len_value = integerConstant(len, TREE_TYPE(len_field));
    ce.cons(len_field, len_value);
    ce.cons(ptr_field, ptr_value); // shouldn't need to convert the pointer...

    tree ctor = build_constructor(type, ce.head);
    TREE_STATIC(ctor) = 0;   // can be set by caller if needed
    TREE_CONSTANT(ctor) = 0; // "

    return ctor;
}


tree
IRState::darrayString(const char * str)
{
    unsigned len = strlen(str);
    // %% assumes str is null-terminated
    tree str_tree = build_string(len + 1, str);

    TREE_TYPE(str_tree) = arrayType(Type::tchar, len);
    return darrayVal(Type::tchar->arrayOf()->toCtype(), len, addressOf(str_tree));
}

char *
IRState::hostToTargetString(char * str, size_t length, unsigned unit_size)
{
    if (unit_size == 1)
        return str;
    gcc_assert(unit_size == 2 || unit_size == 4);

    bool flip;
    if (WORDS_BIG_ENDIAN)
        flip = (bool) ! BYTES_BIG_ENDIAN;
    else
        flip = (bool) BYTES_BIG_ENDIAN;

    if (flip)
    {
        char * out_str = (char *) xmalloc(length * unit_size);
        const d_uns8 * p_src = (const d_uns8 *) str;
        d_uns8 * p_out = (d_uns8 *) out_str;

        while (length--)
        {
            if (unit_size == 2)
            {
                p_out[0] = p_src[1];
                p_out[1] = p_src[0];
            } else
            {   /* unit_size == 4 */
                p_out[0] = p_src[3];
                p_out[1] = p_src[2];
                p_out[2] = p_src[1];
                p_out[3] = p_src[0];
            }
            p_src += unit_size;
            p_out += unit_size;
        }
        return out_str;
    }
    // else
    return str;
}


tree
IRState::arrayLength(Expression * exp)
{
    return arrayLength(exp->toElem(this), exp->type);
}

tree
IRState::arrayLength(tree exp, Type * exp_type)
{
    Type * base_type = exp_type->toBasetype();
    switch (base_type->ty)
    {
        case Tsarray:
            return size_int(((TypeSArray *) base_type)->dim->toUInteger());
        case Tarray:
            return darrayLenRef(exp);
        default:
            ::error("can't determine the length of a %s", exp_type->toChars());
            return error_mark_node;
    }
}

// delegate is
// struct delegate {
//   void * frame_or_object;
//   void * function;
// }

tree
IRState::delegateMethodRef(tree exp)
{
    // Get the backend type for the array and pick out the array length
    // field (assumed to be the second field.)
    tree method_field = TREE_CHAIN(TYPE_FIELDS(TREE_TYPE(exp)));
    //return build2(COMPONENT_REF, TREE_TYPE(method_field), exp, method_field);
    return component(exp, method_field);
}

tree
IRState::delegateObjectRef(tree exp)
{
    // Get the backend type for the array and pick out the array data
    // pointer field (assumed to be the first field.)
    tree obj_field = TYPE_FIELDS(TREE_TYPE(exp));
    //return build2(COMPONENT_REF, TREE_TYPE(obj_field), exp, obj_field);
    return component(exp, obj_field);
}

// Converts pointer types of method_exp and object_exp to match d_type
tree
IRState::delegateVal(tree method_exp, tree object_exp, Type * d_type)
{
    Type * base_type = d_type->toBasetype();
    if (base_type->ty == Tfunction)
    {   // Called from DotVarExp.  These are just used to
        // make function calls and not to make Tdelegate variables.
        // Clearing the type makes sure of this.
        base_type = 0;
    }
    else
    {
        gcc_assert(base_type->ty == Tdelegate);
    }

    tree type = base_type ? base_type->toCtype() : NULL_TREE;
    tree ctor = make_node(CONSTRUCTOR);
    tree obj_field = NULL_TREE;
    tree func_field = NULL_TREE;
    CtorEltMaker ce;

    if (type)
    {
        TREE_TYPE(ctor) = type;
        obj_field = TYPE_FIELDS(type);
        func_field = TREE_CHAIN(obj_field);
    }
#if ENABLE_CHECKING
    if (obj_field)
        ce.cons(obj_field, convert (TREE_TYPE(obj_field), object_exp));
    else
        ce.cons(obj_field, object_exp);

    if (func_field)
        ce.cons(func_field, convert (TREE_TYPE(func_field), method_exp));
    else
        ce.cons(func_field, method_exp);
#else
    ce.cons(obj_field, object_exp);
    ce.cons(func_field, method_exp);
#endif
    CONSTRUCTOR_ELTS(ctor) = ce.head;
    return ctor;
}

tree
IRState::methodCallExpr(tree callee, tree object, Type * d_type)
{
    tree t = delegateVal(callee, object, d_type);
    D_IS_METHOD_CALL_EXPR(t) = 1;
    return t;
}

void
IRState::extractMethodCallExpr(tree mcr, tree & callee_out, tree & object_out)
{
    gcc_assert(D_IS_METHOD_CALL_EXPR(mcr));

    VEC(constructor_elt,gc) *elts = CONSTRUCTOR_ELTS(mcr);
    object_out = VEC_index(constructor_elt, elts, 0)->value;
    callee_out = VEC_index(constructor_elt, elts, 1)->value;
}

tree
IRState::objectInstanceMethod(Expression * obj_exp, FuncDeclaration * func, Type * d_type)
{
    Type * obj_type = obj_exp->type->toBasetype();
    if (func->isThis())
    {
        bool is_dottype;
        tree this_expr;

        // DotTypeExp cannot be evaluated
        if (obj_exp->op == TOKdottype)
        {
            is_dottype = true;
            this_expr = ((DotTypeExp *) obj_exp)->e1->toElem(this);
        }
        else if (obj_exp->op == TOKcast &&
                ((CastExp*) obj_exp)->e1->op == TOKdottype)
        {
            is_dottype = true;
            // see expression.c:"See if we need to adjust the 'this' pointer"
            this_expr = ((DotTypeExp *) ((CastExp*) obj_exp)->e1)->e1->toElem(this);
        }
        else
        {
            is_dottype = false;
            this_expr = obj_exp->toElem(this);
        }

        // Calls to super are static (func is the super's method)
        // Structs don't have vtables.
        // Final and non-virtual methods can be called directly.
        // DotTypeExp means non-virtual

        if (obj_exp->op == TOKsuper ||
                obj_type->ty == Tstruct || obj_type->ty == Tpointer ||
                func->isFinal() || ! func->isVirtual() || is_dottype)
        {
            if (obj_type->ty == Tstruct)
                this_expr = addressOf(this_expr);
            return methodCallExpr(functionPointer(func), this_expr, d_type);
        }
        else
        {   // Interface methods are also in the class's vtable, so we don't
            // need to convert from a class pointer to an interface pointer.
            this_expr = maybeMakeTemp(this_expr);

            tree vtbl_ref;
            /* Folding of *&<static var> fails because of the type of the
               address expression is 'Object' while the type of the static
               var is a particular class (why?). This prevents gimplification
               of the expression.
            */
            if (TREE_CODE(this_expr) == ADDR_EXPR /*&&
                // can't use this check
                TREE_TYPE(TREE_OPERAND(this_expr, 0)) ==
                TREE_TYPE(TREE_TYPE(this_expr))*/)
            {
                vtbl_ref = TREE_OPERAND(this_expr, 0);
            }
            else
            {
                vtbl_ref = indirect(this_expr);
            }

            tree field = TYPE_FIELDS(TREE_TYPE(vtbl_ref)); // the vtbl is the first field
            //vtbl_ref = build2(COMPONENT_REF, TREE_TYPE(field), vtbl_ref, field); // vtbl field (a pointer)
            vtbl_ref = component(vtbl_ref, field); // vtbl field (a pointer)
            // %% better to do with array ref?
            vtbl_ref = pointerOffset(vtbl_ref,
                    size_int(PTRSIZE * func->vtblIndex));
            vtbl_ref = indirect(vtbl_ref, TREE_TYPE(functionPointer(func)));

            return methodCallExpr(vtbl_ref, this_expr, d_type);
        }
    }
    else
    {   // Static method; ignore the object instance
        return addressOf(func);
    }
}


tree
IRState::twoFieldType(tree rec_type, tree ft1, tree ft2, Type * d_type, const char * n1, const char * n2)
{
    tree f0 = build_decl(BUILTINS_LOCATION, FIELD_DECL, get_identifier(n1), ft1);
    tree f1 = build_decl(BUILTINS_LOCATION, FIELD_DECL, get_identifier(n2), ft2);
    DECL_CONTEXT(f0) = rec_type;
    DECL_CONTEXT(f1) = rec_type;
    TYPE_FIELDS(rec_type) = chainon(f0, f1);
    layout_type(rec_type);
    if (d_type)
    {   /* This is needed so that maybeExpandSpecialCall knows to
           split dynamic array varargs. */
        TYPE_LANG_SPECIFIC(rec_type) = build_d_type_lang_specific(d_type);

        /* ObjectFile::declareType will try to declare it as top-level type
           which can break debugging info for element types. */
        tree stub_decl = build_decl(BUILTINS_LOCATION, TYPE_DECL,
                                    get_identifier(d_type->toChars()), rec_type);
        TYPE_STUB_DECL(rec_type) = stub_decl;
        TYPE_NAME(rec_type) = stub_decl;
        DECL_ARTIFICIAL(stub_decl) = 1;
        g.ofile->rodc(stub_decl, 0);
    }
    return rec_type;
}

// Create a record type from two field types
tree
IRState::twoFieldType(Type * ft1, Type * ft2, Type * d_type, const char * n1, const char * n2)
{
    return twoFieldType(make_node(RECORD_TYPE), ft1->toCtype(), ft2->toCtype(), d_type, n1, n2);
}

tree
IRState::twoFieldCtor(tree rec_type, tree f1, tree f2, int storage_class)
{
    CtorEltMaker ce;
    ce.cons(TYPE_FIELDS(rec_type), f1);
    ce.cons(TREE_CHAIN(TYPE_FIELDS(rec_type)), f2);

    tree ctor = build_constructor(rec_type, ce.head);
    TREE_STATIC(ctor) = (storage_class & STCstatic) != 0;
    TREE_CONSTANT(ctor) = (storage_class & STCconst) != 0;
    TREE_READONLY(ctor) = (storage_class & STCconst) != 0;

    return ctor;
}

// This could be made more lax to allow better CSE (?)
bool
needs_temp(tree t)
{
    // %%TODO: check for anything with TREE_SIDE_EFFECTS?
    switch (TREE_CODE(t))
    {
        case VAR_DECL:
        case FUNCTION_DECL:
        case PARM_DECL:
        case CONST_DECL:
        case SAVE_EXPR:
            return false;

        case ADDR_EXPR:
            /* This check is needed for 4.0.  Without it, typeinfo.methodCall may not be
             */
            return ! (DECL_P(TREE_OPERAND(t, 0)));

        case INDIRECT_REF:
        case COMPONENT_REF:
        case NOP_EXPR:
        case NON_LVALUE_EXPR:
        case VIEW_CONVERT_EXPR:
            return needs_temp(TREE_OPERAND(t, 0));

        case ARRAY_REF:
            return true;

        default:
        {
            if (TREE_CODE_CLASS(TREE_CODE(t)) == tcc_constant)
                return false;
            else
                return true;
        }
    }
}

tree
IRState::maybeMakeTemp(tree t)
{
    if (needs_temp(t))
    {
        if (TREE_CODE(TREE_TYPE(t)) != ARRAY_TYPE)
            return save_expr(t);
        else
            return stabilize_reference(t);
    }
    else
    {
        return t;
    }
}

bool
IRState::isFreeOfSideEffects(tree t)
{
    // SAVE_EXPR is safe to reference more than once, but not to
    // expand in a loop.
    return TREE_CODE(t) != SAVE_EXPR && ! needs_temp(t);
}

tree
IRState::toElemLvalue(Expression * e)
{
    /*
    if (e->op == TOKcast)
        fprintf(stderr, "IRState::toElemLvalue TOKcast\n");
    else
    */
    if (e->op == TOKindex)
    {
        IndexExp * ie = (IndexExp *) e;
        Expression * e1 = ie->e1;
        Expression * e2 = ie->e2;
        Type * type = e->type;
        Type * array_type = e1->type->toBasetype();

        if (array_type->ty == Taarray)
        {
            Type * key_type = ((TypeAArray *) array_type)->index->toBasetype();
            AddrOfExpr aoe;

            tree args[4];
            args[0] = this->addressOf(this->toElemLvalue(e1));
            args[1] = this->typeinfoReference(key_type);
            args[2] = this->integerConstant(array_type->nextOf()->size(), Type::tsize_t);
            args[3] = aoe.set(this, this->convertTo(e2, key_type));
            return build1(INDIRECT_REF, type->toCtype(),
                aoe.finish(this,
                    this->libCall(LIBCALL_AAGETP, 4, args, type->pointerTo()->toCtype())));
        }
    }
    return e->toElem(this);
}


tree
IRState::addressOf(Dsymbol *d)
{
    return addressOf(d->toSymbol()->Stree);
}

tree
IRState::addressOf(tree exp)
{
    tree t, ptrtype;
    tree exp_type = TREE_TYPE(exp);
    d_mark_addressable(exp);

    // Gimplify doesn't like &(*(ptr-to-array-type)) with static arrays
    if (TREE_CODE(exp) == INDIRECT_REF)
    {
        t = TREE_OPERAND(exp, 0);
        ptrtype = build_pointer_type(exp_type);
        t = nop(t, ptrtype);
    }
    else
    {   /* Just convert string literals (char[]) to C-style strings (char *), otherwise
           the latter method (char[]*) causes conversion problems during gimplification. */
        if (TREE_CODE (exp) == STRING_CST)
        {
            ptrtype = build_pointer_type(TREE_TYPE(exp_type));
        }
        /* Special case for va_list. The backends will be expecting a pointer to vatype,
         * but some targets use an array. So fix it.  */
        else if (TYPE_MAIN_VARIANT(exp_type) == TYPE_MAIN_VARIANT(va_list_type_node))
        {
            if (TREE_CODE(TYPE_MAIN_VARIANT(exp_type)) == ARRAY_TYPE)
                ptrtype = build_pointer_type(TREE_TYPE(exp_type));
            else
                ptrtype = build_pointer_type(exp_type);
        }
        else
            ptrtype = build_pointer_type(exp_type);

        t = build1(ADDR_EXPR, ptrtype, exp);
    }
    if (TREE_CODE(exp) == FUNCTION_DECL)
        TREE_NO_TRAMPOLINE(t) = 1;

    return t;
}

/* Cast exp (which should be a pointer) to TYPE* and then indirect.  The
   back-end requires this cast in many cases. */
tree
IRState::indirect(tree exp, tree type)
{
    if (TREE_CODE(TREE_TYPE(exp)) == REFERENCE_TYPE)
        return build1(INDIRECT_REF, type, exp);

    return build1(INDIRECT_REF, type,
                  nop(exp, build_pointer_type(type)));
}

tree
IRState::indirect(tree exp)
{
    return indirect(exp, TREE_TYPE(TREE_TYPE(exp)));
}

tree
IRState::vmodify(tree dst, tree src)
{
    return build2(MODIFY_EXPR, void_type_node, dst, src);
}

tree
IRState::vinit(tree dst, tree src)
{
    return build2(INIT_EXPR, void_type_node, dst, src);
}

tree
IRState::pointerIntSum(Expression * ptr_exp, Expression * idx_exp)
{
    return pointerIntSum(ptr_exp->toElem(this), idx_exp->toElem(this));
}

tree
IRState::pointerIntSum(tree ptr_node, tree idx_exp)
{
    tree result_type_node = TREE_TYPE(ptr_node);
    tree elem_type_node = TREE_TYPE(result_type_node);
    tree intop = idx_exp;
    tree size_exp;

    tree prod_result_type;
    prod_result_type = sizetype;

    // %% TODO: real-not-long-double issues...

    size_exp = size_in_bytes(elem_type_node); // array element size

    if (integer_zerop(size_exp))
    {   // Test for void case...
        if (TYPE_MODE(elem_type_node) == TYPE_MODE(void_type_node))
            intop = fold_convert(prod_result_type, intop);
        else
        {   // FIXME: should catch this earlier.
            error("invalid use of incomplete type %qD", TYPE_NAME(elem_type_node));
            result_type_node = error_mark_node;
        }
    }
    else if (integer_onep(size_exp))
    {   // ...or byte case -- No need to multiply.
        intop = fold_convert(prod_result_type, intop);
    }
    else
    {
        if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
            || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
        {
            intop = convert (d_type_for_size (TYPE_PRECISION (sizetype),
                                 TYPE_UNSIGNED (sizetype)), intop);
        }
        intop = fold_convert (prod_result_type,
                              fold_build2 (MULT_EXPR, TREE_TYPE(size_exp), // the type here may be wrong %%
                                           intop, convert (TREE_TYPE (intop), size_exp)));
    }

    if (isErrorMark(result_type_node))
        return result_type_node; // backend will ICE otherwise

    if (integer_zerop(intop))
        return ptr_node;
    
    return build2(POINTER_PLUS_EXPR, result_type_node, ptr_node, intop);
}

// %% op should be tree_code
tree
IRState::pointerOffsetOp(int op, tree ptr, tree idx)
{
    if (op == MINUS_EXPR)
    {   // %% sign extension...
        idx = fold_build1(NEGATE_EXPR, sizetype, idx);
    }
    else
    {
        gcc_assert(op == PLUS_EXPR);
        /* nothing */
    }
    return build2(POINTER_PLUS_EXPR, TREE_TYPE(ptr), ptr,
                  convert(sizetype, idx));
}

tree
IRState::pointerOffset(tree ptr_node, tree byte_offset)
{
    tree ofs = fold_convert(sizetype, byte_offset);
    return fold_build2(POINTER_PLUS_EXPR, TREE_TYPE(ptr_node), ptr_node, ofs);
}

tree
IRState::nop(tree e, tree t)
{
    return build1(NOP_EXPR, t, e);
}

tree
IRState::vconvert(tree e, tree t)
{
    return build1(VIEW_CONVERT_EXPR, t, e);
}

// DMD allows { void[] a; & a[3]; }
tree
IRState::pvoidOkay(tree t)
{
    if (VOID_TYPE_P(TREE_TYPE(TREE_TYPE(t))))
    {   // ::warning("indexing array of void");
        return convert(Type::tuns8->pointerTo()->toCtype(), t);
    }
    return t;
}

tree
IRState::boolOp(enum tree_code code, tree a, tree b)
{
    return build2(code, boolean_type_node, a, b);
}


// Doesn't do some of the optimizations in ::makeArrayElemRef
tree
IRState::checkedIndex(Loc loc, tree index, tree upper_bound, bool inclusive)
{
    if (arrayBoundsCheck())
    {
        return build3(COND_EXPR, TREE_TYPE(index),
                boundsCond(index, upper_bound, inclusive),
                index,
                assertCall(loc, LIBCALL_ARRAY_BOUNDS));
    }
    else
    {
        return index;
    }
}


// index must be wrapped in a SAVE_EXPR to prevent multiple evaluation...
tree
IRState::boundsCond(tree index, tree upper_bound, bool inclusive)
{
    tree bound_check;

    bound_check = build2(inclusive ? LE_EXPR : LT_EXPR, boolean_type_node,
            convert(d_unsigned_type(TREE_TYPE(index)), index),
            upper_bound);

    if (! TYPE_UNSIGNED(TREE_TYPE(index)))
    {
        bound_check = build2(TRUTH_ANDIF_EXPR, boolean_type_node, bound_check,
                // %% conversions
                build2(GE_EXPR, boolean_type_node, index, integer_zero_node));
    }
    return bound_check;
}

// Return != 0 if do array bounds checking
int
IRState::arrayBoundsCheck()
{
    int result = global.params.useArrayBounds;
#if V2
    if (result == 1)
    {
        // For D2 safe functions only
        result = 0;
        if (func && func->type->ty == Tfunction)
        {
            TypeFunction * tf = (TypeFunction *)func->type;
            if (tf->trust == TRUSTsafe)
                result = 1;
        }
    }
#endif
    return result;
}

tree
IRState::arrayElemRef(IndexExp * aer_exp, ArrayScope * aryscp)
{
    Expression * e1 = aer_exp->e1;
    Expression * e2 = aer_exp->e2;

    Type * base_type = e1->type->toBasetype();
    TY base_type_ty = base_type->ty;
    tree index_expr; // logical index
    tree subscript_expr; // expr that indexes the array data
    tree ptr_exp;  // base pointer to the elements
    tree elem_ref; // reference the the element

    index_expr = e2->toElem(this);
    subscript_expr = index_expr;

    switch (base_type_ty)
    {
        case Tarray:
        case Tsarray:
        {
            tree e1_tree = e1->toElem(this);
            e1_tree = aryscp->setArrayExp(e1_tree, e1->type);

            // If it's a static array and the index is constant,
            // the front end has already checked the bounds.
            if (arrayBoundsCheck() &&
                ! (base_type_ty == Tsarray && e2->isConst()))
            {
                tree array_len_expr, throw_expr, oob_cond;
                // implement bounds check as a conditional expression:
                // a[ inbounds(index) ? index : { throw ArrayBoundsError } ]
                //
                // First, set up the index expression to only be evaluated
                // once.
                // %% save_expr does this check: if (! TREE_CONSTANT(index_expr))
                //   %% so we don't do a <0 check for a[2]...
                index_expr = maybeMakeTemp(index_expr);

                if (base_type_ty == Tarray)
                {
                    e1_tree = maybeMakeTemp(e1_tree);
                    array_len_expr = darrayLenRef(e1_tree);
                }
                else
                    array_len_expr = ((TypeSArray *) base_type)->dim->toElem(this);

                oob_cond = boundsCond(index_expr, array_len_expr, false);
                throw_expr = assertCall(aer_exp->loc, LIBCALL_ARRAY_BOUNDS);

                subscript_expr = build3(COND_EXPR, TREE_TYPE(index_expr),
                        oob_cond, index_expr, throw_expr);
            }

            // %% TODO: make this an ARRAY_REF?
            if (base_type_ty == Tarray)
                ptr_exp = darrayPtrRef(e1_tree); // %% do convert in darrayPtrRef?
            else
                ptr_exp = addressOf(e1_tree);
            // This conversion is required for static arrays and is just-to-be-safe
            // for dynamic arrays
            ptr_exp = d_convert_basic(base_type->nextOf()->pointerTo()->toCtype(), ptr_exp);
            break;
        }
        case Tpointer:
        {   // Ignores aryscp
            ptr_exp = e1->toElem(this);
            break;
        }
        default:
            gcc_unreachable();
    }

    ptr_exp = pvoidOkay(ptr_exp);
    subscript_expr = aryscp->finish(subscript_expr);
    elem_ref = indirect(pointerIntSum(ptr_exp, subscript_expr),
            TREE_TYPE(TREE_TYPE(ptr_exp)));

    return elem_ref;
}

tree
IRState::binding(tree var_chain, tree body)
{
    // BIND_EXPR/DECL_INITIAL not supported in 4.0?
    gcc_assert(TREE_CHAIN(var_chain) == NULL_TREE); // TODO: only handles one var

    // %%EXPER -- if a BIND_EXPR is an a SAVE_EXPR, gimplify dies
    // in mostly_copy_tree_r.  prevent the latter from seeing
    // our shameful BIND_EXPR by wrapping it in a TARGET_EXPR
    if (DECL_INITIAL(var_chain))
    {
        tree ini = build2(INIT_EXPR, void_type_node, var_chain, DECL_INITIAL(var_chain));
        DECL_INITIAL(var_chain) = NULL_TREE;
        body = compound(ini, body);
    }
    return save_expr(build3(BIND_EXPR, TREE_TYPE(body), var_chain, body, NULL_TREE));
}

tree
IRState::compound(tree a, tree b, tree type)
{
    return build2(COMPOUND_EXPR, type ? type : TREE_TYPE(b), a, b);
}

tree
IRState::voidCompound(tree a, tree b)
{
    return compound(a, b, void_type_node);
}

tree
IRState::maybeCompound(tree a, tree b)
{
    if (a == NULL_TREE)
        return b;
    else if (b == NULL_TREE)
        return a;
    else
        return build2(COMPOUND_EXPR, TREE_TYPE(b), a, b);
}

tree
IRState::maybeVoidCompound(tree a, tree b)
{
    if (a == NULL_TREE)
        return b;
    else if (b == NULL_TREE)
        return a;
    else
        return build2(COMPOUND_EXPR, void_type_node, a, b);
}

tree
IRState::component(tree v, tree f)
{
    return build3(COMPONENT_REF, TREE_TYPE(f), v, f, NULL_TREE);
}

tree
IRState::errorMark(Type * t)
{
    return nop(error_mark_node, t->toCtype());
}

bool
IRState::isErrorMark(tree t)
{
    return (t == error_mark_node
            || (t && TREE_TYPE(t) == error_mark_node)
            || (t && TREE_CODE(t) == NOP_EXPR &&
                TREE_OPERAND(t, 0) == error_mark_node));
}

// Assumes T is already ->toBasetype()
TypeFunction *
IRState::getFuncType(Type * t)
{
    TypeFunction* tf = NULL;
    if (t->ty == Tpointer)
        t = t->nextOf()->toBasetype();
    if (t->ty == Tfunction)
        tf = (TypeFunction *) t;
    else if (t->ty == Tdelegate)
        tf = (TypeFunction *) ((TypeDelegate *) t)->next;

    return tf;
}

bool
IRState::isFuncType(tree t)
{
    return (TREE_CODE(t) == FUNCTION_TYPE
            || TREE_CODE(t) == METHOD_TYPE);
}

tree
IRState::call(Expression * expr, Expressions * arguments)
{
    // Calls to delegates can sometimes look like this:
    if (expr->op == TOKcomma)
    {
        CommaExp * ce = (CommaExp *) expr;
        expr = ce->e2;

        VarExp * ve;
        gcc_assert(ce->e2->op == TOKvar);
        ve = (VarExp *) ce->e2;
        gcc_assert(ve->var->isFuncDeclaration() && ! ve->var->needThis());
    }

    Type* t = expr->type->toBasetype();
    TypeFunction* tf = NULL;
    tree callee = expr->toElem(this);
    tree object = NULL_TREE;

    if (D_IS_METHOD_CALL_EXPR(callee))
    {
        /* This could be a delegate expression (TY == Tdelegate), but not
           actually a delegate variable. */
        // %% Is this ever not a DotVarExp ?
        if (expr->op == TOKdotvar)
        {   /* This gets the true function type, the latter way can sometimes
               be incorrect. Example: ref functions in D2. */
            tf = getFuncType(((DotVarExp *)expr)->var->type);
        }
        else
            tf = getFuncType(t);

        extractMethodCallExpr(callee, callee, object);
    }
    else if (t->ty == Tdelegate)
    {
        tf = (TypeFunction*) ((TypeDelegate *) t)->next;
        callee = maybeMakeTemp(callee);
        object = delegateObjectRef(callee);
        callee = delegateMethodRef(callee);
    }
    else if (expr->op == TOKvar)
    {
        FuncDeclaration * fd = ((VarExp *) expr)->var->isFuncDeclaration();
        gcc_assert(fd);
        tf = (TypeFunction *) fd->type;
        if (fd->isNested())
        {
            object = getFrameForFunction(fd);
        }
        else if (fd->needThis())
        {
            expr->error("need 'this' to access member %s", fd->toChars());
            object = d_null_pointer; // continue processing...
        }
    }
    else
    {
        tf = getFuncType(t);
    }
    return call(tf, callee, object, arguments);
}

tree
IRState::call(FuncDeclaration * func_decl, Expressions * args)
{
    gcc_assert(! func_decl->isNested()); // Otherwise need to copy code from above
    return call(getFuncType(func_decl->type), func_decl->toSymbol()->Stree, NULL_TREE, args);
}

tree
IRState::call(FuncDeclaration * func_decl, tree object, Expressions * args)
{
    return call(getFuncType(func_decl->type), functionPointer(func_decl), object, args);
}

tree
IRState::call(TypeFunction *func_type, tree callable, tree object, Expressions * arguments)
{
    // Using TREE_TYPE(callable) instead of func_type->toCtype can save a build_method_type
    tree func_type_node = TREE_TYPE(callable);
    tree actual_callee  = callable;
    tree saved_args = NULL_TREE;

    ListMaker actual_arg_list;

    if (POINTER_TYPE_P(func_type_node))
        func_type_node = TREE_TYPE(func_type_node);
    else
        actual_callee = addressOf(callable);

    gcc_assert(isFuncType(func_type_node));
    gcc_assert(func_type != NULL);
    gcc_assert(func_type->ty == Tfunction);

    bool is_d_vararg = func_type->varargs == 1 && func_type->linkage == LINKd;

    // Account for the hidden object/frame pointer argument

    if (TREE_CODE(func_type_node) == FUNCTION_TYPE)
    {
        if (object != NULL_TREE)
        {   // Happens when a delegate value is called
            tree method_type = build_method_type(TREE_TYPE(object), func_type_node);
            TYPE_ATTRIBUTES(method_type) = TYPE_ATTRIBUTES(func_type_node);
            func_type_node = method_type;
        }
    }
    else
    {   /* METHOD_TYPE */
        if (! object)
        {   // Front-end apparently doesn't check this.
            if (TREE_CODE(callable) == FUNCTION_DECL)
            {
                error("need 'this' to access member %s", IDENTIFIER_POINTER(DECL_NAME(callable)));
                return error_mark_node;
            }
            else
            {   // Probably an internal error
                gcc_unreachable();
            }
        }
    }
    /* If this is a delegate call or a nested function being called as
       a delegate, the object should not be NULL. */
    if (object != NULL_TREE)
        actual_arg_list.cons(object);

    Parameters * formal_args = func_type->parameters; // can be NULL for genCfunc decls
    size_t n_formal_args = formal_args ? (int) Parameter::dim(formal_args) : 0;
    size_t n_actual_args = arguments ? arguments->dim : 0;
    size_t fi = 0;

    // assumes arguments->dim <= formal_args->dim if (! this->varargs)
    for (size_t ai = 0; ai < n_actual_args; ++ai)
    {
        tree actual_arg_tree;
        Expression * actual_arg_exp = arguments->tdata()[ai];

        if (ai == 0 && is_d_vararg)
        {   // The hidden _arguments parameter
            actual_arg_tree = actual_arg_exp->toElem(this);
        }
        else if (fi < n_formal_args)
        {   // Actual arguments for declared formal arguments
            Parameter * formal_arg = Parameter::getNth(formal_args, fi);
            actual_arg_tree = convertForArgument(actual_arg_exp, formal_arg);
            actual_arg_tree = d_convert_basic(trueArgumentType(formal_arg), actual_arg_tree);
            ++fi;
        }
        else
        {
            if (splitDynArrayVarArgs && actual_arg_exp->type->toBasetype()->ty == Tarray)
            {
                tree da_exp = maybeMakeTemp(actual_arg_exp->toElem(this));
                actual_arg_list.cons(darrayLenRef(da_exp));
                actual_arg_list.cons(darrayPtrRef(da_exp));
                continue;
            }
            else
            {
                actual_arg_tree = actual_arg_exp->toElem(this);
                /* Not all targets support passing unpromoted types, so
                   promote anyway. */
                tree prom_type = d_type_promotes_to(TREE_TYPE(actual_arg_tree));
                if (prom_type != TREE_TYPE(actual_arg_tree))
                    actual_arg_tree = d_convert_basic(prom_type, actual_arg_tree);
            }
        }
        /* Evaluate the argument before passing to the function.
           Needed for left to right evaluation.  */
        if (func_type->linkage == LINKd && !isFreeOfSideEffects(actual_arg_tree))
        {
            actual_arg_tree = maybeMakeTemp(actual_arg_tree);
            saved_args = maybeVoidCompound(saved_args, actual_arg_tree);
        }

        actual_arg_list.cons(actual_arg_tree);
    }

    tree result = buildCall(TREE_TYPE(func_type_node), actual_callee, actual_arg_list.head);
    result = maybeExpandSpecialCall(result);

    return maybeCompound(saved_args, result);
}

tree
IRState::assertCall(Loc loc, LibCall libcall)
{
    tree args[2] = {
        darrayString(loc.filename ? loc.filename : ""),
        integerConstant(loc.linnum, Type::tuns32)
    };
#if V2
    if (libcall == LIBCALL_ASSERT && func->isUnitTestDeclaration())
        libcall = LIBCALL_UNITTEST;
#endif
    return libCall(libcall, 2, args);
}

tree
IRState::assertCall(Loc loc, Expression * msg)
{
    tree args[3] = {
        msg->toElem(this),
        darrayString(loc.filename ? loc.filename : ""),
        integerConstant(loc.linnum, Type::tuns32)
    };
#if V2
    LibCall libcall = func->isUnitTestDeclaration() ?
        LIBCALL_UNITTEST_MSG : LIBCALL_ASSERT_MSG;
#else
    LibCall libcall = LIBCALL_ASSERT_MSG;
#endif
    return libCall(libcall, 3, args);
}

static const char * libcall_ids[LIBCALL_count] = {
    "_d_assert", "_d_assert_msg", "_d_array_bounds", "_d_switch_error",
    /*"_d_invariant",*/ "_D9invariant12_d_invariantFC6ObjectZv",
    "_d_newclass", "_d_newarrayT",
    "_d_newarrayiT",
    "_d_newarraymTp", "_d_newarraymiTp",
#if V2
    "_d_allocmemory",
#endif
    "_d_delclass", "_d_delinterface", "_d_delarray",
    "_d_delmemory", "_d_callfinalizer", "_d_callinterfacefinalizer",
    "_d_arraysetlengthT", "_d_arraysetlengthiT",
    "_d_dynamic_cast", "_d_interface_cast",
    "_adEq", "_adEq2", "_adCmp", "_adCmp2", "_adCmpChar",
    "_aaEqual", "_aaLen",
    //"_aaIn", "_aaGet", "_aaGetRvalue", "_aaDel",
    "_aaInp", "_aaGetp", "_aaGetRvaluep", "_aaDelp",
    "_d_arraycast",
    "_d_arraycopy",
    "_d_arraycatT", "_d_arraycatnT",
    "_d_arrayappendT",
    /*"_d_arrayappendc", */"_d_arrayappendcTp",
    "_d_arrayappendcd", "_d_arrayappendwd",
#if V2
    "_d_arrayassign", "_d_arrayctor", "_d_arraysetassign",
    "_d_arraysetctor", "_d_delarray_t",
#endif
    "_d_monitorenter", "_d_monitorexit",
    "_d_criticalenter", "_d_criticalexit",
    "_d_throw",
    "_d_switch_string", "_d_switch_ustring", "_d_switch_dstring",
    "_d_assocarrayliteralTp",
    "_d_arrayliteralTp"
#if V2
        ,
    "_d_unittest", "_d_unittest_msg",
    "_d_hidden_func"
#endif
};

static FuncDeclaration * libcall_decls[LIBCALL_count];

FuncDeclaration *
IRState::getLibCallDecl(LibCall lib_call)
{
    FuncDeclaration * decl = libcall_decls[lib_call];
    Types arg_types;
    bool varargs = false;

    if (! decl)
    {
        Type * return_type = Type::tvoid;

        switch (lib_call)
        {
            case LIBCALL_ASSERT:
            case LIBCALL_ARRAY_BOUNDS:
            case LIBCALL_SWITCH_ERROR:
                // need to spec chararray/string because internal code passes string constants
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tuns32);
                break;

            case LIBCALL_ASSERT_MSG:
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tuns32);
                break;
#if V2
            case LIBCALL_UNITTEST:
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tuns32);
                break;

            case LIBCALL_UNITTEST_MSG:
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tuns32);
                break;
#endif
            case LIBCALL_NEWCLASS:
                arg_types.push(ClassDeclaration::classinfo->type);
                return_type = getObjectType();
                break;

            case LIBCALL_NEWARRAYT:
            case LIBCALL_NEWARRAYIT:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tsize_t);
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_NEWARRAYMTP:
            case LIBCALL_NEWARRAYMITP:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tsize_t);
                arg_types.push(Type::tsize_t);
                return_type = Type::tvoid->arrayOf();
                break;
#if V2
            case LIBCALL_ALLOCMEMORY:
                arg_types.push(Type::tsize_t);
                return_type = Type::tvoidptr;
                break;
#endif
            case LIBCALL_DELCLASS:
            case LIBCALL_DELINTERFACE:
                arg_types.push(Type::tvoidptr);
                break;

            case LIBCALL_DELARRAY:
                arg_types.push(Type::tvoid->arrayOf()->pointerTo());
                break;
#if V2
            case LIBCALL_DELARRAYT:
                arg_types.push(Type::tvoid->arrayOf()->pointerTo());
                arg_types.push(Type::typeinfo->type);
                break;
#endif
            case LIBCALL_DELMEMORY:
                arg_types.push(Type::tvoidptr->pointerTo());
                break;

            case LIBCALL_CALLFINALIZER:
            case LIBCALL_CALLINTERFACEFINALIZER:
                arg_types.push(Type::tvoidptr);
                break;

            case LIBCALL_ARRAYSETLENGTHT:
            case LIBCALL_ARRAYSETLENGTHIT:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tsize_t);
                arg_types.push(Type::tvoid->arrayOf()->pointerTo());
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_DYNAMIC_CAST:
            case LIBCALL_INTERFACE_CAST:
                arg_types.push(getObjectType());
                arg_types.push(ClassDeclaration::classinfo->type);
                return_type = getObjectType();
                break;

            case LIBCALL_ADEQ:
            case LIBCALL_ADEQ2:
            case LIBCALL_ADCMP:
            case LIBCALL_ADCMP2:
                arg_types.push(Type::tvoid->arrayOf());
                arg_types.push(Type::tvoid->arrayOf());
                arg_types.push(Type::typeinfo->type);
                return_type = Type::tint32;
                break;

            case LIBCALL_ADCMPCHAR:
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tchar->arrayOf());
                return_type = Type::tint32;
                break;
//          case LIBCALL_AAIN:
//          case LIBCALL_AAGET:
//          case LIBCALL_AAGETRVALUE:
//          case LIBCALL_AADEL:
            case LIBCALL_AAEQUAL:
            case LIBCALL_AALEN:
            case LIBCALL_AAINP:
            case LIBCALL_AAGETP:
            case LIBCALL_AAGETRVALUEP:
            case LIBCALL_AADELP:
            {
                static Type * aa_type = NULL;
                if (! aa_type)
                    aa_type = new TypeAArray(Type::tvoidptr, Type::tvoidptr);

                if (lib_call == LIBCALL_AAEQUAL)
                {
                    arg_types.push(Type::typeinfo->type);
                    arg_types.push(aa_type);
                    arg_types.push(aa_type);
                    return_type = Type::tint32;
                    break;
                }

                if (lib_call == LIBCALL_AALEN)
                {
                    arg_types.push(aa_type);
                    return_type = Type::tsize_t;
                    break;
                }

                if (lib_call == LIBCALL_AAGETP)
                    aa_type = aa_type->pointerTo();

                arg_types.push(aa_type);
                arg_types.push(Type::typeinfo->type); // typeinfo reference
                if (lib_call == LIBCALL_AAGETP || lib_call == LIBCALL_AAGETRVALUEP)
                    arg_types.push(Type::tsize_t);

                arg_types.push(Type::tvoidptr);

                switch (lib_call)
                {
                    case LIBCALL_AAINP:
                    case LIBCALL_AAGETP:
                    case LIBCALL_AAGETRVALUEP:
                        return_type = Type::tvoidptr;
                        break;
                    case LIBCALL_AADELP:
                        return_type = Type::tvoid;
                        break;
                    default:
                        gcc_unreachable();
                }
                break;
            }

            case LIBCALL_ARRAYCAST:
                arg_types.push(Type::tsize_t);
                arg_types.push(Type::tsize_t);
                arg_types.push(Type::tvoid->arrayOf());
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_ARRAYCOPY:
                arg_types.push(Type::tsize_t);
                arg_types.push(Type::tvoid->arrayOf());
                arg_types.push(Type::tvoid->arrayOf());
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_ARRAYCATT:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tvoid->arrayOf());
                arg_types.push(Type::tvoid->arrayOf());
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_ARRAYCATNT:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tuns32); // Currently 'uint', even if 64-bit
                varargs = true;
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_ARRAYAPPENDT:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tuns8->arrayOf()->pointerTo());
                arg_types.push(Type::tuns8->arrayOf());
                return_type = Type::tvoid->arrayOf();
                break;

//          case LIBCALL_ARRAYAPPENDCT:
            case LIBCALL_ARRAYAPPENDCTP:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tuns8->arrayOf()->pointerTo());
                arg_types.push(Type::tsize_t);
                return_type = Type::tuns8->arrayOf();
                break;

            case LIBCALL_ARRAYAPPENDCD:
                arg_types.push(Type::tchar->arrayOf());
                arg_types.push(Type::tdchar);
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_ARRAYAPPENDWD:
                arg_types.push(Type::twchar->arrayOf());
                arg_types.push(Type::tdchar);
                return_type = Type::tvoid->arrayOf();
                break;
#if V2
            case LIBCALL_ARRAYASSIGN:
            case LIBCALL_ARRAYCTOR:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tvoid->arrayOf());
                arg_types.push(Type::tvoid->arrayOf());
                return_type = Type::tvoid->arrayOf();
                break;

            case LIBCALL_ARRAYSETASSIGN:
            case LIBCALL_ARRAYSETCTOR:
                arg_types.push(Type::tvoidptr);
                arg_types.push(Type::tvoidptr);
                arg_types.push(Type::tsize_t);
                arg_types.push(Type::typeinfo->type);
                return_type = Type::tvoidptr;
                break;
#endif
            case LIBCALL_MONITORENTER:
            case LIBCALL_MONITOREXIT:
            case LIBCALL_THROW:
            case LIBCALL_INVARIANT:
                arg_types.push(getObjectType());
                break;

            case LIBCALL_CRITICALENTER:
            case LIBCALL_CRITICALEXIT:
                arg_types.push(Type::tvoidptr);
                break;

            case LIBCALL_SWITCH_USTRING:
                arg_types.push(Type::twchar->arrayOf()->arrayOf());
                arg_types.push(Type::twchar->arrayOf());
                return_type = Type::tint32;
                break;

            case LIBCALL_SWITCH_DSTRING:
                arg_types.push(Type::tdchar->arrayOf()->arrayOf());
                arg_types.push(Type::tdchar->arrayOf());
                return_type = Type::tint32;
                break;

            case LIBCALL_SWITCH_STRING:
                arg_types.push(Type::tchar->arrayOf()->arrayOf());
                arg_types.push(Type::tchar->arrayOf());
                return_type = Type::tint32;
                break;
            case LIBCALL_ASSOCARRAYLITERALTP:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tvoid->arrayOf());
                arg_types.push(Type::tvoid->arrayOf());
                return_type = Type::tvoidptr;
                break;

            case LIBCALL_ARRAYLITERALTP:
                arg_types.push(Type::typeinfo->type);
                arg_types.push(Type::tsize_t);
                return_type = Type::tvoidptr;
                break;
#if V2
            case LIBCALL_HIDDEN_FUNC:
                /* Argument is an Object, but can't use that as
                   LIBCALL_HIDDEN_FUNC is needed before the Object type is
                   created. */
                arg_types.push(Type::tvoidptr);
                break;
#endif
            default:
                gcc_unreachable();
        }
        decl = FuncDeclaration::genCfunc(return_type, libcall_ids[lib_call]);
        {
            TypeFunction * tf = (TypeFunction *) decl->type;
            tf->varargs = varargs ? 1 : 0;
            Parameters * args = new Parameters;
            args->setDim(arg_types.dim);
            for (size_t i = 0; i < arg_types.dim; i++)
                args->tdata()[i] = new Parameter(STCin, arg_types[i], NULL, NULL);

            tf->parameters = args;
        }
        libcall_decls[lib_call] = decl;
    }
    return decl;
}

void
IRState::replaceLibCallDecl(FuncDeclaration * d_decl)
{
    if (! d_decl->ident)
        return;
    for (size_t i = 0; i < LIBCALL_count; i++)
    {
        if (strcmp(d_decl->ident->string, libcall_ids[i]) == 0)
        {   // %% warn if libcall already set?
            // Only do this for the libcalls where it's a problem, otherwise
            // it causes other problems...
            switch ((LibCall) i)
            {
                // case LIBCALL_GNU_BITARRAYSLICEP:
                case LIBCALL_ARRAYCOPY: // this could be solved by turning copy of char into memcpy
                case LIBCALL_ARRAYCAST:
                    // replace the function declaration
                    break;
                default:
                    // don't replace
                    return;
            }
            libcall_decls[i] = d_decl;
            break;
        }
    }
}


tree
IRState::libCall(LibCall lib_call, unsigned n_args, tree *args, tree force_result_type)
{
    FuncDeclaration * lib_decl = getLibCallDecl(lib_call);
    Type * type = lib_decl->type->nextOf();
    tree callee = functionPointer(lib_decl);
    tree arg_list = NULL_TREE;

    for (int i = n_args - 1; i >= 0; i--)
        arg_list = tree_cons(NULL_TREE, args[i], arg_list);

    tree result = buildCall(type->toCtype(), callee, arg_list);

    // for force_result_type, assumes caller knows what it is doing %%
    if (force_result_type != NULL_TREE)
        return d_convert_basic(force_result_type, result);

    return result;
}

// GCC 3.3 does not set TREE_SIDE_EFFECTS call by default. GCC 3.4
// sets it depending on the const/pure attributes of the funcion
// and the SIDE_EFFECTS flags of the arguments.
tree
IRState::buildCall(tree type, tree callee, tree args)
{
    int nargs = list_length(args);
    tree * pargs = new tree[nargs];
    for (size_t i = 0; args; args = TREE_CHAIN(args), i++)
        pargs[i] = TREE_VALUE(args);
    
    return build_call_array(type, callee, nargs, pargs);
}

// Conveniently construct the function arguments for passing
// to the real buildCall function.
tree
IRState::buildCall(tree callee, int n_args, ...)
{
    va_list ap;
    tree arg_list = NULL_TREE;
    tree fntype = TREE_TYPE(callee);

    va_start (ap, n_args);
    for (int i = n_args - 1; i >= 0; i--)
        arg_list = tree_cons(NULL_TREE, va_arg(ap, tree), arg_list);
    va_end (ap);

    return buildCall(TREE_TYPE(fntype), addressOf(callee), nreverse(arg_list));
}


tree
IRState::assignValue(Expression * e, VarDeclaration * v)
{
    if (e->op == TOKassign || e->op == TOKblit)
    {
        AssignExp * a_exp = (AssignExp *) e;
        if (a_exp->e1->op == TOKvar && ((VarExp *) a_exp->e1)->var == v)
        {
            tree a_val = convertForAssignment(a_exp->e2, v->type);
            return a_val;
        }
        //else
            //return e->toElem(this);
    }
    return NULL_TREE;
}


static tree
fix_d_va_list_type(tree val)
{
    if (POINTER_TYPE_P(va_list_type_node)
            || INTEGRAL_TYPE_P(va_list_type_node))
        return build1(NOP_EXPR, va_list_type_node, val);
    else
        return val;
}

tree
IRState::maybeExpandSpecialCall(tree call_exp)
{
    // More code duplication from C
    CallExpr ce(call_exp);
    tree callee = ce.callee();
    tree exp = NULL_TREE, op1, op2;

    if (POINTER_TYPE_P(TREE_TYPE(callee)))
        callee = TREE_OPERAND(callee, 0);

    if (TREE_CODE(callee) == FUNCTION_DECL
        && DECL_BUILT_IN_CLASS(callee) == BUILT_IN_FRONTEND)
    {
        Intrinsic intrinsic = (Intrinsic) DECL_FUNCTION_CODE(callee);
        tree type;
        Type *d_type;
        switch (intrinsic)
        {
            case INTRINSIC_BSF:
                /* builtin count_trailing_zeros matches behaviour of bsf.
                   %% TODO: The return value is supposed to be undefined if op1 is zero. */
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_CTZL), 1, op1);

            case INTRINSIC_BSR:
                /* bsr becomes 31-(clz), but parameter passed to bsf may not be a 32bit type!!
                   %% TODO: The return value is supposed to be undefined if op1 is zero. */
                op1 = ce.nextArg();
                type = TREE_TYPE(op1);

                op2 = integerConstant(tree_low_cst(TYPE_SIZE(type), 1) - 1, type);
                exp = buildCall(d_built_in_decls(BUILT_IN_CLZL), 1, op1);

                // Handle int -> long conversions.
                if (TREE_TYPE(exp) != type)
                    exp = fold_convert (type, exp);

                return fold_build2(MINUS_EXPR, type, op2, exp);

            case INTRINSIC_BT:
            case INTRINSIC_BTC:
            case INTRINSIC_BTR:
            case INTRINSIC_BTS:
                op1 = ce.nextArg();
                op2 = ce.nextArg();
                type = TREE_TYPE(TREE_TYPE(op1));

                exp = integerConstant(tree_low_cst(TYPE_SIZE(type), 1), type);

                // op1[op2 / exp]
                op1 = pointerIntSum(op1, fold_build2(TRUNC_DIV_EXPR, type, op2, exp));
                op1 = indirect(op1, type);

                // mask = 1 << (op2 % exp);
                op2 = fold_build2(TRUNC_MOD_EXPR, type, op2, exp);
                op2 = fold_build2(LSHIFT_EXPR, type, size_one_node, op2);

                // cond = op1[op2 / size] & mask;
                exp = fold_build2(BIT_AND_EXPR, type, op1, op2);

                // cond ? -1 : 0;
                exp = build3(COND_EXPR, TREE_TYPE(call_exp), d_truthvalue_conversion(exp),
                             integer_minus_one_node, integer_zero_node);

                if (intrinsic == INTRINSIC_BT)
                {   // Only testing the bit.
                    return exp;
                }
                else
                {   // Update the bit as needed.
                    tree result = localVar(TREE_TYPE(call_exp));
                    enum tree_code code = (intrinsic == INTRINSIC_BTC) ? BIT_XOR_EXPR :
                                          (intrinsic == INTRINSIC_BTR) ? BIT_AND_EXPR :
                                          (intrinsic == INTRINSIC_BTS) ? BIT_IOR_EXPR : ERROR_MARK;
                    gcc_assert(code != ERROR_MARK);

                    // op1[op2 / size] op= mask
                    if (intrinsic == INTRINSIC_BTR)
                        op2 = build1(BIT_NOT_EXPR, TREE_TYPE(op2), op2);

                    exp = vmodify(result, exp);
                    op1 = vmodify(op1, fold_build2(code, TREE_TYPE(op1), op1, op2));
                    op1 = compound(op1, result);
                    return compound(exp, op1);
                }

            case INTRINSIC_BSWAP:
                /* Backend provides builtin bswap32.
                   Assumes first argument and return type is uint. */
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_BSWAP32), 1, op1);

            case INTRINSIC_INP:
            case INTRINSIC_INPL:
            case INTRINSIC_INPW:
#ifdef TARGET_386
                type = TREE_TYPE(call_exp);
                d_type = Type::tuns16;

                op1 = ce.nextArg();
                // %% Port is always cast to ushort
                op1 = d_convert_basic(d_type->toCtype(), op1);
                op2 = localVar(type);
                return expandPortIntrinsic(intrinsic, op1, op2, 0);
#endif
                // else fall through to error below.
            case INTRINSIC_OUTP:
            case INTRINSIC_OUTPL:
            case INTRINSIC_OUTPW:
#ifdef TARGET_386
                type = TREE_TYPE(call_exp);
                d_type = Type::tuns16;

                op1 = ce.nextArg();
                op2 = ce.nextArg();
                // %% Port is always cast to ushort
                op1 = d_convert_basic(d_type->toCtype(), op1);
                return expandPortIntrinsic(intrinsic, op1, op2, 1);
#else
                ::error("Port I/O intrinsic '%s' is only available on ix86 targets",
                        IDENTIFIER_POINTER(DECL_NAME(callee)));
                break;
#endif

            case INTRINSIC_COS:
                // Math intrinsics just map to their GCC equivalents.
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_COSL), 1, op1);

            case INTRINSIC_SIN:
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_SINL), 1, op1);

            case INTRINSIC_RNDTOL:
                // %% not sure if llroundl stands as a good replacement
                // for the expected behaviour of rndtol.
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_LLROUNDL), 1, op1);

            case INTRINSIC_SQRT:
                // Have float, double and real variants of sqrt.
                op1 = ce.nextArg();
                type = TREE_TYPE(op1);
                // Could have used mathfn_built_in, but that only returns
                // implicit built in decls.
                if (TYPE_MAIN_VARIANT(type) == double_type_node)
                    exp = d_built_in_decls(BUILT_IN_SQRT);
                else if (TYPE_MAIN_VARIANT(type) == float_type_node)
                    exp = d_built_in_decls(BUILT_IN_SQRTF);
                else if (TYPE_MAIN_VARIANT(type) == long_double_type_node)
                    exp = d_built_in_decls(BUILT_IN_SQRTL);
                // op1 is an integral type - use double precision.
                else if (INTEGRAL_TYPE_P(TYPE_MAIN_VARIANT(type)))
                {
                    op1 = d_convert_basic(double_type_node, op1);
                    exp = d_built_in_decls(BUILT_IN_SQRT);
                }

                gcc_assert(exp);    // Should never trigger.
                return buildCall(exp, 1, op1);

            case INTRINSIC_LDEXP:
                op1 = ce.nextArg();
                op2 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_LDEXPL), 2, op1, op2);

            case INTRINSIC_FABS:
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_FABSL), 1, op1);

            case INTRINSIC_RINT:
                op1 = ce.nextArg();
                return buildCall(d_built_in_decls(BUILT_IN_RINTL), 1, op1);


            case INTRINSIC_C_VA_ARG:
                // %% should_check c_promotes_to as in va_arg now
                // just drop though for now...
            case INTRINSIC_STD_VA_ARG:
                op1 = ce.nextArg();
                /* signature is (inout va_list), but VA_ARG_EXPR expects the
                   list itself... but not if the va_list type is an array.  In that
                   case, it should be a pointer.  */
                if (TREE_CODE(d_va_list_type_node) != ARRAY_TYPE)
                {
                    if (TREE_CODE(op1) == ADDR_EXPR)
                    {
                        op1 = TREE_OPERAND(op1, 0);
                    }
                    else
                    {   /* this probably doesn't happen... passing an inout va_list argument,
                           but again,  it's probably { & (* inout_arg) }  */
                        op1 = indirect(op1);
                    }
                }
#if SARRAYVALUE
                else
                {   // list would be passed by value, convert to reference.
                    tree t = TREE_TYPE(op1);
                    gcc_assert(TREE_CODE(t) == ARRAY_TYPE);
                    op1 = addressOf(op1);
                }
#endif
                op1 = fix_d_va_list_type(op1);
                type = TREE_TYPE(TREE_TYPE(callee));
                if (splitDynArrayVarArgs && (d_type = getDType(type)) &&
                        d_type->toBasetype()->ty == Tarray)
                {   /* should create a temp var of type TYPE and move the binding
                       to outside this expression.  */
                    op1 = stabilize_reference(op1);
                    tree ltype = TREE_TYPE(TYPE_FIELDS(type));
                    tree ptype = TREE_TYPE(TREE_CHAIN(TYPE_FIELDS(type)));
                    tree lvar = exprVar(ltype);
                    tree pvar = exprVar(ptype);
                    tree e1 = vmodify(lvar, build1(VA_ARG_EXPR, ltype, op1));
                    tree e2 = vmodify(pvar, build1(VA_ARG_EXPR, ptype, op1));
                    tree b = compound(compound(e1, e2), darrayVal(type, lvar, pvar));
                    return binding(lvar, binding(pvar, b));
                }
                else
                {
                    tree type2 = d_type_promotes_to(type);
                    op1 = build1(VA_ARG_EXPR, type2, op1);
                    if (type != type2)
                    {   // silently convert promoted type...
                        op1 = d_convert_basic(type, op1);
                    }
                    return op1;
                }
                break;

            case INTRINSIC_C_VA_START:
                /* The va_list argument should already have its
                   address taken.  The second argument, however, is
                   inout and that needs to be fixed to prevent a warning.  */
                op1 = ce.nextArg();
                op2 = ce.nextArg();
                type = TREE_TYPE(op1);

                // could be casting... so need to check type too?
                STRIP_TYPE_NOPS(op1);
                if (TREE_CODE(op1) == ADDR_EXPR)
                {
                    op1 = TREE_OPERAND(op1, 0);
                    op1 = fix_d_va_list_type(op1);
                    op1 = addressOf(op1);
                }
#if SARRAYVALUE
                else if (TREE_CODE(type) == ARRAY_TYPE)
                {   // pass list by reference.
                    op1 = fix_d_va_list_type(op1);
                    op1 = addressOf(op1);
                }
#endif
                else
                {
                    op1 = fix_d_va_list_type(op1);
                }

                STRIP_NOPS(op2);
                if (TREE_CODE(op2) == ADDR_EXPR)
                    op2 = TREE_OPERAND(op2, 0);
                // assuming nobody tries to change the return type
                return buildCall(d_built_in_decls(BUILT_IN_VA_START), 2, op1, op2);

            default:
                gcc_unreachable();
        }
    }

    return call_exp;
}


/* Expand a call to inp or outp with argument 'port' and return value 'value'.
 */
tree
IRState::expandPortIntrinsic(Intrinsic code, tree port, tree value, int outp)
{
    const char * insn_string;
    tree insn_tmpl;
    ListMaker outputs;
    ListMaker inputs;

    if (outp)
    {   /* Writing outport operand:
            asm ("op %[value], %[port]" :: "a" value, "Nd" port);
         */
        const char * valconstr = "a";
        tree val = tree_cons(NULL_TREE, build_string(strlen(valconstr), valconstr), NULL_TREE);
        inputs.cons(val, value);
    }
    else
    {   /* Writing inport operand:
            asm ("op %[port], %[value]" : "=a" value : "Nd" port);
         */
        const char * outconstr = "=a";
        tree out = tree_cons(NULL_TREE, build_string(strlen(outconstr), outconstr), NULL_TREE);
        outputs.cons(out, value);
    }

    const char * inconstr = "Nd";
    tree in = tree_cons(NULL_TREE, build_string(strlen(inconstr), inconstr), NULL_TREE);
    inputs.cons(in, port);

    switch(code)
    {
        case INTRINSIC_INP:     insn_string = "inb %w1, %0"; break;
        case INTRINSIC_INPL:    insn_string = "inl %w1, %0"; break;
        case INTRINSIC_INPW:    insn_string = "inw %w1, %0"; break;
        case INTRINSIC_OUTP:    insn_string = "outb %b0, %w1"; break;
        case INTRINSIC_OUTPL:   insn_string = "outl %0, %w1";  break;
        case INTRINSIC_OUTPW:   insn_string = "outw %w0, %w1"; break;
        default:
            gcc_unreachable();
    }
    insn_tmpl = build_string(strlen(insn_string), insn_string);

    // ::doAsm
    tree exp = d_build_asm_stmt(insn_tmpl, outputs.head, inputs.head,
                                NULL_TREE, NULL_TREE);
    ASM_VOLATILE_P(exp) = 1;

    // These functions always return the contents of 'value'
    return build2(COMPOUND_EXPR, TREE_TYPE(value), exp, value);
}


tree
IRState::floatMod(tree a, tree b, tree type)
{
    tree fmodfn = NULL_TREE;
    tree basetype = type;

    if (COMPLEX_FLOAT_TYPE_P(basetype))
        basetype = TREE_TYPE(basetype);

    if (TYPE_MAIN_VARIANT(basetype) == double_type_node)
        fmodfn = d_built_in_decls(BUILT_IN_FMOD);
    else if (TYPE_MAIN_VARIANT(basetype) == float_type_node)
        fmodfn = d_built_in_decls(BUILT_IN_FMODF);
    else if (TYPE_MAIN_VARIANT(basetype) == long_double_type_node)
        fmodfn = d_built_in_decls(BUILT_IN_FMODL);

    if (! fmodfn)
    {   // %qT pretty prints the tree type.
        ::error("tried to perform floating-point modulo division on %qT",
                type);
        return error_mark_node;
    }

    if (COMPLEX_FLOAT_TYPE_P(type))
    {
        return build2(COMPLEX_EXPR, type,
                      buildCall(fmodfn, 2, realPart(a), b),
                      buildCall(fmodfn, 2, imagPart(a), b));
    }
    else if (SCALAR_FLOAT_TYPE_P(type))
    {   // %% assuming no arg conversion needed
        // %% bypassing buildCall since this shouldn't have
        // side effects
        return buildCall(fmodfn, 2, a, b);
    }
    else
    {   // Should have caught this above.
        gcc_unreachable();
    }
}

tree
IRState::typeinfoReference(Type * t)
{
    tree ti_ref = t->getInternalTypeInfo(NULL)->toElem(this);
    gcc_assert(POINTER_TYPE_P(TREE_TYPE(ti_ref)));
    return ti_ref;
}

dinteger_t
IRState::getTargetSizeConst(tree t)
{
    dinteger_t result;
    if (sizeof(HOST_WIDE_INT) >= sizeof(dinteger_t))
        result = tree_low_cst(t, 1);
    else
    {
        gcc_assert(sizeof(HOST_WIDE_INT) * 2 == sizeof(dinteger_t));
        result = (unsigned HOST_WIDE_INT) TREE_INT_CST_LOW(t);
        result += ((dinteger_t) (unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH(t))
            << HOST_BITS_PER_WIDE_INT;
    }
    return result;
}


bool
IRState::maybeSetUpBuiltin(Declaration * decl)
{
    Dsymbol * dsym;
    TemplateInstance * ti;

    // Don't use toParent2.  We are looking for a template below.
    dsym = decl->toParent();

    if (! dsym)
        return false;

    if ((intrinsicModule && dsym->getModule() == intrinsicModule) ||
        (intrinsicCoreModule && dsym->getModule() == intrinsicCoreModule))
    {   // Matches order of Intrinsic enum
        static const char * intrinsic_names[] = {
            "bsf", "bsr",
            "bswap",
            "bt", "btc", "btr", "bts",
            "inp", "inpl", "inpw",
            "outp", "outpl", "outpw",
        };
        const size_t sz = sizeof(intrinsic_names) / sizeof(char *);
        int i = binary(decl->ident->string, intrinsic_names, sz);
        if (i == -1)
            return false;

        // Make sure 'i' is within the range we require.
        gcc_assert(i >= INTRINSIC_BSF && i <= INTRINSIC_OUTPW);
        tree t = decl->toSymbol()->Stree;

        DECL_BUILT_IN_CLASS(t) = BUILT_IN_FRONTEND;
        DECL_FUNCTION_CODE(t) = (built_in_function) i;
        return true;
    }
    else if ((mathModule && dsym->getModule() == mathModule) ||
             (mathCoreModule && dsym->getModule() == mathCoreModule))
    {   // Matches order of Intrinsic enum
        static const char * math_names[] = {
            "cos", "fabs", "ldexp",
            "rint", "rndtol", "sin",
            "sqrt",
        };
        const size_t sz = sizeof(math_names) / sizeof(char *);
        int i = binary(decl->ident->string, math_names, sz);
        if (i == -1)
            return false;

        // Adjust 'i' for this range of enums
        i += INTRINSIC_COS;
        gcc_assert(i >= INTRINSIC_COS && i <= INTRINSIC_SQRT);
        tree t = decl->toSymbol()->Stree;

        // rndtol returns a long, sqrt any real value,
        // every other math builtin returns an 80bit float.
        Type * tf = decl->type->nextOf();
        if ((i == INTRINSIC_RNDTOL && tf->ty == Tint64)
            || (i == INTRINSIC_SQRT && tf->isreal())
            || (i != INTRINSIC_RNDTOL && tf->ty == Tfloat80))
        {
            DECL_BUILT_IN_CLASS(t) = BUILT_IN_FRONTEND;
            DECL_FUNCTION_CODE(t) = (built_in_function) i;
            return true;
        }
        return false;
    }
    else
    {
        ti = dsym->isTemplateInstance();
        if (ti)
        {
            tree t = decl->toSymbol()->Stree;
            if (ti->tempdecl == stdargTemplateDecl)
            {
                DECL_BUILT_IN_CLASS(t) = BUILT_IN_FRONTEND;
                DECL_FUNCTION_CODE(t) = (built_in_function) INTRINSIC_STD_VA_ARG;
                return true;
            }
            else if (ti->tempdecl == cstdargArgTemplateDecl)
            {
                DECL_BUILT_IN_CLASS(t) = BUILT_IN_FRONTEND;
                DECL_FUNCTION_CODE(t) = (built_in_function) INTRINSIC_C_VA_ARG;
                return true;
            }
            else if (ti->tempdecl == cstdargStartTemplateDecl)
            {
                DECL_BUILT_IN_CLASS(t) = BUILT_IN_FRONTEND;
                DECL_FUNCTION_CODE(t) = (built_in_function) INTRINSIC_C_VA_START;
                return true;
            }
        }
    }
    return false;
}

tree
IRState::functionPointer(FuncDeclaration * func_decl)
{
    return addressOf(func_decl);
}

tree
IRState::exceptionObject()
{
    tree obj_type = getObjectType()->toCtype();
    if (TREE_CODE(TREE_TYPE(obj_type)) == REFERENCE_TYPE)
        obj_type = TREE_TYPE(obj_type);
    // Like gjc, the actual D exception object is one
    // pointer behind the exception header
    tree t = buildCall(d_built_in_decls(BUILT_IN_EH_POINTER),
                       1, integer_zero_node);
    t = build1(NOP_EXPR, build_pointer_type(obj_type), t); // treat exception header as (Object*)
    t = pointerOffsetOp(MINUS_EXPR, t, TYPE_SIZE_UNIT(TREE_TYPE(t)));
    t = build1(INDIRECT_REF, obj_type, t);
    return t;
}

tree
IRState::label(Loc loc, Identifier * ident)
{
    tree t_label = build_decl(UNKNOWN_LOCATION, LABEL_DECL,
                              ident ? get_identifier(ident->string) : NULL_TREE, void_type_node);
    DECL_CONTEXT(t_label) = current_function_decl;
    DECL_MODE(t_label) = VOIDmode;
    if (loc.filename)
        g.ofile->setDeclLoc(t_label, loc);
    return t_label;
}

tree
IRState::getFrameForFunction(FuncDeclaration * f)
{
    if (f->fbody)
    {
        return getFrameForSymbol(f);
    }
    else
    {   // Should error on line that references f
        f->error("nested function missing body");
        return d_null_pointer;
    }
}

tree
IRState::getFrameForNestedClass(ClassDeclaration *c)
{
    return getFrameForSymbol(c);
}

#if V2
tree
IRState::getFrameForNestedStruct(StructDeclaration *s)
{
    return getFrameForSymbol(s);
}
#endif

/* If nested_sym is a nested function, return the static chain to be
   used when invoking that function.

   If nested_sym is a nested class, return the static chain to be used
   when creating an instance of the class.

   This method is protected to enforce the type checking of
   getFrameForFunction and getFrameForNestedClass.
   getFrameForFunction also checks that the nestd function is properly
   defined.
*/

tree
IRState::getFrameForSymbol(Dsymbol * nested_sym)
{
    FuncDeclaration * nested_func = 0;
    FuncDeclaration * outer_func = 0;

    if ((nested_func = nested_sym->isFuncDeclaration()))
    {
        // gcc_assert(nested_func->isNested())
        outer_func = nested_func->toParent2()->isFuncDeclaration();
        gcc_assert(outer_func != NULL);

        if (func != outer_func)
        {
            Dsymbol * this_func = func;
            if (!func->vthis) // if no frame pointer for this function
            {
                nested_sym->error("is a nested function and cannot be accessed from %s", func->toChars());
                return d_null_pointer;
            }
            /* Make sure we can get the frame pointer to the outer function,
               else we'll ICE later in tree-ssa.  */
            while (nested_func != this_func)
            {
                FuncDeclaration * fd;
                ClassDeclaration * cd;
                StructDeclaration * sd;

                // Special case for __ensure and __require.
                if (nested_func->ident == Id::ensure || nested_func->ident == Id::require)
                {
                    outer_func = func;
                    break;
                }

                if ((fd = this_func->isFuncDeclaration()))
                {
                    if (outer_func == fd->toParent2())
                        break;
                    gcc_assert(fd->isNested() || fd->vthis);
                }
                else if ((cd = this_func->isClassDeclaration()))
                {
                    if (!cd->isNested() || !cd->vthis)
                        goto cannot_get_frame;
                    if (outer_func == cd->toParent2())
                        break;
                }
#if V2
                else if ((sd = this_func->isStructDeclaration()))
                {
                    if (!sd->isNested() || !sd->vthis)
                        goto cannot_get_frame;
                    if (outer_func == sd->toParent2())
                        break;
                }
#endif
                else
                {
                  cannot_get_frame:
                    func->error("cannot get frame pointer to %s", nested_sym->toChars());
                    return d_null_pointer;
                }
                this_func = this_func->toParent2();
            }
        }
    }
    else
    {
        /* It's a class (or struct).  NewExp::toElem has already determined its
           outer scope is not another class, so it must be a function. */

        Dsymbol * sym = nested_sym;

        while (sym && ! (outer_func = sym->isFuncDeclaration()))
            sym = sym->toParent2();

        /* Make sure we can access the frame of outer_func.

           For GCC < 4.0:

            f() {
              class X {
                m() { }
              }
              g() {
                h() {
                   new X // <-- you are here
                }
              }
            }

           In order to get the static chain we must know a
           function nested in F.  If we are currently in such a
           nested function, use that.

           f() {
               class X { m() { } }
               new X // <-- you are here
           }

           If we are at the level of the function containing the
           class, the answer is just 'virtual_stack_vars_rtx'.
        */

        if (outer_func != func)
        {
            Dsymbol * o = nested_func = func;
            do {
                if (! nested_func->isNested())
                {
#if V2
                    if (! nested_func->isMember2())
#endif
                    goto cannot_access_frame;
                }
                while ((o = o->toParent2()))
                {
                    if ((nested_func = o->isFuncDeclaration()))
                        break;
                }
            } while (o && o != outer_func);

            if (! o)
            {
              cannot_access_frame:
                error("cannot access frame of function '%s' from '%s'",
                      outer_func->toChars(), func->toChars());
                return d_null_pointer;
            }
        }
        // else, the answer is 'virtual_stack_vars_rtx'
    }

    if (! outer_func)
        outer_func = nested_func->toParent2()->isFuncDeclaration();
    gcc_assert(outer_func != NULL);

    FuncFrameInfo * ffo = getFrameInfo(outer_func);
    if (ffo->creates_frame || ffo->static_chain)
        return getFrameRef(outer_func);

    return d_null_pointer;
}

/* For the purposes this is used, inner is assumed to be a nested
   function or a method of a class or struct that is (eventually) nested in a
   function.
*/
bool
IRState::isFuncNestedIn(FuncDeclaration * inner, FuncDeclaration * outer)
{
    if (inner == outer)
        return false;

    while (inner)
    {
        AggregateDeclaration * ad;
        ClassDeclaration * cd;
        StructDeclaration * sd;

        if (inner == outer)
        {   //fprintf(stderr, "%s is nested in %s\n", inner->toChars(), outer->toChars());
            return true;
        }
        else if (inner->isNested())
        {
            inner = inner->toParent2()->isFuncDeclaration();
        }
        else if ((ad = inner->isThis()) && (cd = ad->isClassDeclaration()))
        {
            inner = isClassNestedInFunction(cd);
        }
#if V2
        else if ((ad = inner->isThis()) && (sd = ad->isStructDeclaration()))
        {
            inner = isStructNestedInFunction(sd);
        }
#endif
        else
        {
            break;
        }
    }
    //fprintf(stderr, "%s is NOT nested in %s\n", inner->toChars(), outer->toChars());
    return false;
}


/*
  findThis

  Starting from the current function, try to find a suitable value of
  'this' in nested functions and (not implemented yet:) nested class
  instances.

  A suitable 'this' value is an instance of target_cd or a class that
  has target_cd as a base.
*/

static tree
findThis(IRState * irs, ClassDeclaration * target_cd)
{
    FuncDeclaration * fd = irs->func;

    while (fd)
    {
        AggregateDeclaration * fd_ad;
        ClassDeclaration * fd_cd;

        if ((fd_ad = fd->isThis()) &&
            (fd_cd = fd_ad->isClassDeclaration()))
        {
            if (target_cd == fd_cd)
            {
                return irs->var(fd->vthis);
            }
            else if (target_cd->isBaseOf(fd_cd, NULL))
            {
                gcc_assert(fd->vthis); // && fd->vthis->csym->Stree
                return irs->convertTo(irs->var(fd->vthis),
                        fd_cd->type, target_cd->type);
            }
            else
            {
                fd = irs->isClassNestedInFunction(fd_cd);
            }
        }
        else if (fd->isNested())
        {
            fd = fd->toParent2()->isFuncDeclaration();
        }
        else
        {
            fd = NULL;
        }
    }
    return NULL_TREE;
}

/* Return the outer class/struct 'this' value.
   This is here mostly due to removing duplicate code,
   and clean implementation purposes.  */
tree
IRState::getVThis(Dsymbol * decl, Expression * e)
{
    tree vthis_value = NULL_TREE;

    ClassDeclaration * class_decl;
    StructDeclaration * struct_decl;

    if ((class_decl = decl->isClassDeclaration()))
    {
        Dsymbol * outer = class_decl->toParent2();
        ClassDeclaration * cd_outer = outer->isClassDeclaration();
        FuncDeclaration * fd_outer = outer->isFuncDeclaration();

        if (cd_outer)
        {
            vthis_value = findThis(this, cd_outer);
            if (vthis_value == NULL_TREE)
            {
                e->error("outer class %s 'this' needed to 'new' nested class %s",
                        cd_outer->toChars(), class_decl->toChars());
            }
        }
        else if (fd_outer)
        {   /* If a class nested in a function has no methods
               and there are no other nested functions,
               lower_nested_functions is never called and any
               STATIC_CHAIN_EXPR created here will never be
               translated. Use a null pointer for the link in
               this case. */
            FuncFrameInfo * ffo = getFrameInfo(fd_outer);
            if (ffo->creates_frame || ffo->static_chain ||
#if V2
                fd_outer->closureVars.dim
#else
                fd_outer->nestedFrameRef
#endif
               )
            {   // %% V2: rec_type->class_type
                vthis_value = getFrameForNestedClass(class_decl);
            }
            else if (fd_outer->vthis)
                vthis_value = var(fd_outer->vthis);
            else
                vthis_value = d_null_pointer;
        }
        else
            gcc_unreachable();
    }
#if V2
    else if ((struct_decl = decl->isStructDeclaration()))
    {
        Dsymbol *outer = struct_decl->toParent2();
        FuncDeclaration *fd_outer = outer->isFuncDeclaration();
        // Assuming this is kept as trivial as possible.
        // NOTE: what about structs nested in structs nested in functions?
        if (fd_outer)
        {
            FuncFrameInfo * ffo = getFrameInfo(fd_outer);
            if (ffo->creates_frame || ffo->static_chain ||
                fd_outer->closureVars.dim)
            {
                vthis_value = getFrameForNestedStruct(struct_decl);
            }
            else if (fd_outer->vthis)
                vthis_value = var(fd_outer->vthis);
            else
                vthis_value = d_null_pointer;
        }
        else
            gcc_unreachable();
    }
#endif
    return vthis_value;
}


/* Return the parent function of a nested class. */
FuncDeclaration *
IRState::isClassNestedInFunction(ClassDeclaration * cd)
{
    FuncDeclaration * fd = NULL;
    while (cd && cd->isNested())
    {
        Dsymbol * dsym = cd->toParent2();
        if ((fd = dsym->isFuncDeclaration()))
            return fd;
        else
            cd = dsym->isClassDeclaration();
    }
    return NULL;
}

#if V2
/* Return the parent function of a nested struct. */
FuncDeclaration *
IRState::isStructNestedInFunction(StructDeclaration * sd)
{
    FuncDeclaration * fd = NULL;
    while (sd && sd->isNested())
    {
        Dsymbol * dsym = sd->toParent2();
        if ((fd = dsym->isFuncDeclaration()))
            return fd;
        else
            sd = dsym->isStructDeclaration();
    }
    return NULL;
}
#endif


// Build static chain decl to be passed to nested functions in D.
void
IRState::buildChain(FuncDeclaration * func)
{
    FuncFrameInfo * ffi = getFrameInfo(func);

#if V2
    if (ffi->is_closure)
    {   // Build closure pointer, which is initialised on heap.
        func->buildClosure(this);
        return;
    }
#endif

    if (! ffi->creates_frame)
    {
        // %% TODO: Implement static chain passing this way?
        gcc_assert(! ffi->static_chain);
        return;
    }

#if V2
    VarDeclarations * nestedVars = & func->closureVars;
#else
    VarDeclarations * nestedVars = & func->frameVars;
#endif

    tree frame_rec_type = ffi->frame_rec;
    tree chain_link = chainLink();
    tree ptr_field;
    ListMaker fields;

    ptr_field = build_decl(BUILTINS_LOCATION, FIELD_DECL,
                           get_identifier("__chain"), ptr_type_node);
    DECL_CONTEXT(ptr_field) = frame_rec_type;
    fields.chain(ptr_field);

    /* __ensure never becomes a closure, but could still be referencing parameters
       of the calling function.  So we add all parameters as nested refs. This is
       written as such so that all parameters appear at the front of the frame so
       that overriding methods match the same layout when inheriting a contract.  */
    if (global.params.useOut && func->fensure)
    {
        for (size_t i = 0; func->parameters && i < func->parameters->dim; i++)
        {
            VarDeclaration * v = (*func->parameters)[i];
            // Remove if already in nestedVars so can push to front.
            for (size_t j = i; j < nestedVars->dim; j++)
            {
                Dsymbol * s = (*nestedVars)[j];
                if (s == v)
                {
                    nestedVars->remove(j);
                    break;
                }
            }
            nestedVars->insert(i, v);
        }

        // Also add hidden 'this' to outer context.
        if (func->vthis)
        {
            for (size_t i = 0; i < nestedVars->dim; i++)
            {
                Dsymbol * s = (*nestedVars)[i];
                if (s == func->vthis)
                {
                    nestedVars->remove(i);
                    break;
                }
            }
            nestedVars->insert(0, func->vthis);
        }
    }

    for (size_t i = 0; i < nestedVars->dim; i++)
    {
        VarDeclaration * v = (*nestedVars)[i];
        Symbol * s = v->toSymbol();
        tree field = build_decl(UNKNOWN_LOCATION, FIELD_DECL,
                                v->ident ? get_identifier(v->ident->string) : NULL_TREE,
                                gen.trueDeclarationType(v));
        s->SframeField = field;
        g.ofile->setDeclLoc(field, v);
        DECL_CONTEXT(field) = frame_rec_type;
        fields.chain(field);
        TREE_USED(s->Stree) = 1;

        /* Can't do nrvo if the variable is put in a frame.  */
        if (func->nrvo_can && func->nrvo_var == v)
            func->nrvo_can = 0;
    }

    TYPE_FIELDS(frame_rec_type) = fields.head;
    layout_type(frame_rec_type);

    tree frame_decl = localVar(frame_rec_type);
    tree frame_ptr = addressOf(frame_decl);
    DECL_IGNORED_P(frame_decl) = 0;
    expandDecl(frame_decl);

    // set the first entry to the parent frame, if any
    if (chain_link != NULL_TREE)
    {
        doExp(vmodify(component(indirect(frame_ptr), ptr_field),
                      chain_link));
    }

    // copy parameters that are referenced nonlocally
    for (size_t i = 0; i < nestedVars->dim; i++)
    {
        VarDeclaration * v = (*nestedVars)[i];
        if (! v->isParameter())
            continue;

        Symbol * vsym = v->toSymbol();
        doExp(vmodify(component(indirect(frame_ptr), vsym->SframeField),
                      vsym->Stree));
    }

    useChain(func, frame_ptr);
}

FuncFrameInfo *
IRState::getFrameInfo(FuncDeclaration *fd)
{
    Symbol * fds = fd->toSymbol();
    if (fds->frameInfo)
        return fds->frameInfo;

    FuncFrameInfo * ffi = new FuncFrameInfo;
    ffi->creates_frame = false;
    ffi->static_chain = false;
    ffi->is_closure = false;
    ffi->frame_rec = NULL_TREE;

    fds->frameInfo = ffi;

#if V2
    VarDeclarations * nestedVars = & fd->closureVars;
#else
    VarDeclarations * nestedVars = & fd->frameVars;
#endif

    // Nested functions, or functions with nested refs must create
    // a static frame for local variables to be referenced from.
    if (nestedVars->dim != 0 || fd->isNested())
    {
        ffi->creates_frame = true;
    }
    else
    {
        AggregateDeclaration * ad = fd->isThis();
#if V2
        if (ad && ad->isNested())
        {
            ffi->creates_frame = true;
        }
#else
        ClassDeclaration * cd = ad ? ad->isClassDeclaration() : NULL;
        if (cd && cd->isNested())
        {
            ffi->creates_frame = true;
        }
#endif
    }

    // Functions with In/Out contracts pass parameters to nested frame.
    if (fd->fensure || fd->frequire)
        ffi->creates_frame = true;

#if V2
    // D2 maybe setup closure instead.
    if (fd->needsClosure())
    {
        ffi->creates_frame = true;
        ffi->is_closure = true;
    }
    else if (nestedVars->dim == 0)
    {   /* If fd is nested (deeply) in a function that creates a closure,
           then fd inherits that closure via hidden vthis pointer, and
           doesn't create a stack frame at all.  */
        FuncDeclaration * ff = fd;

        while (ff)
        {
            FuncFrameInfo * ffo = getFrameInfo(ff);

            if (ff != fd && ffo->is_closure)
            {
                gcc_assert(ffo->frame_rec);
                ffi->creates_frame = false;
                ffi->static_chain = true;
                ffi->is_closure = true;
                gcc_assert(COMPLETE_TYPE_P(ffo->frame_rec));
                ffi->frame_rec = copy_node(ffo->frame_rec);
                break;
            }

            // Stop looking if no frame pointer for this function.
            if (ff->vthis == NULL)
                break;

            ff = ff->toParent2()->isFuncDeclaration();
        }
    }
#endif

    // Build type now as may be referenced from another module.
    if (ffi->creates_frame)
    {
        tree frame_rec = make_node(RECORD_TYPE);
        char * name = concat(ffi->is_closure ? "CLOSURE." : "FRAME.",
                             fd->toPrettyChars(), NULL);
        TYPE_NAME(frame_rec) = get_identifier(name);
        free(name);

        d_keep(frame_rec);
        ffi->frame_rec = frame_rec;
    }

    return ffi;
}

// Return a pointer to the frame/closure block of outer_func
tree
IRState::getFrameRef(FuncDeclaration * outer_func)
{
    tree result = chainLink();
    FuncDeclaration * fd = chainFunc();

    while (fd && fd != outer_func)
    {
        AggregateDeclaration * ad;
        ClassDeclaration * cd;
        StructDeclaration * sd;

        if (getFrameInfo(fd)->creates_frame)
        {
            // like compon(indirect, field0) parent frame link is the first field;
            result = indirect(result, ptr_type_node);
        }
#if V1
        else
        {   // We should only get here for D2 only.
            gcc_unreachable();
        }
#endif

        if (fd->isNested())
            fd = fd->toParent2()->isFuncDeclaration();
        /* getFrameRef is only used to get the pointer to a function's frame
           (not a class instances.)  With the current implementation, the link
           the frame/closure record always points to the outer function's frame even
           if there are intervening nested classes or structs.
           So, we can just skip over those... */
        else if ((ad = fd->isThis()) && (cd = ad->isClassDeclaration()))
            fd = isClassNestedInFunction(cd);
#if V2
        else if ((ad = fd->isThis()) && (sd = ad->isStructDeclaration()))
            fd = isStructNestedInFunction(sd);
#endif
        else
            break;
    }

    if (fd == outer_func)
    {
        tree frame_rec = getFrameInfo(outer_func)->frame_rec;

        if (frame_rec != NULL_TREE)
        {
            result = nop(result, build_pointer_type(frame_rec));
            return result;
        }
        else
        {
            func->error("forward reference to frame of %s", outer_func->toChars());
            return d_null_pointer;
        }
    }
    else
    {
        func->error("cannot access frame of %s", outer_func->toChars());
        return d_null_pointer;
    }
}


/* Return true if function F needs to have the static chain passed to
   it.  This only applies to nested function handling provided by the
   GCC back end (not D closures.)
*/
bool
IRState::functionNeedsChain(FuncDeclaration *f)
{
    Dsymbol * s;
    ClassDeclaration * a;
    FuncDeclaration * pf = NULL;
    TemplateInstance * ti = NULL;

    if (f->isNested())
    {
        s = f->toParent();
        ti = s->isTemplateInstance();
        if (ti && ti->isnested == NULL)
            return false;

#if V2
        pf = f->toParent2()->isFuncDeclaration();
        if (pf && ! getFrameInfo(pf)->is_closure)
            return true;
#else
        return true;
#endif
    }
    if (f->isStatic())
    {
        return false;
    }

    s = f->toParent2();

    while (s && (a = s->isClassDeclaration()) && a->isNested())
    {
        s = s->toParent2();
        if ((pf = s->isFuncDeclaration())
#if V2
            && ! getFrameInfo(pf)->is_closure
#endif
           )
        {
            return true;
        }
    }

    return false;
}


void
IRState::startCond(Statement * stmt, tree t_cond)
{
    Flow * f = beginFlow(stmt);
    f->condition = t_cond;
}

void
IRState::startCond(Statement * stmt, Expression * e_cond)
{
#if V2
    tree t_cond = e_cond->toElemDtor(this);
    startCond(stmt, convertForCondition(t_cond, e_cond->type));
#else
    startCond(stmt, convertForCondition(e_cond));
#endif
}


void
IRState::startElse()
{
    currentFlow()->trueBranch = popStatementList();
    pushStatementList();
}

void
IRState::endCond()
{
    Flow * f = currentFlow();
    tree t_brnch = popStatementList(); // endFlow(); -- can't pop -- need the info?
    tree t_false_brnch = NULL_TREE;

    if (f->trueBranch == NULL_TREE)
        f->trueBranch = t_brnch;
    else
        t_false_brnch = t_brnch;

    g.ofile->doLineNote(f->statement->loc);
    tree t_stmt = build3(COND_EXPR, void_type_node,
            f->condition, f->trueBranch, t_false_brnch);
    endFlow();
    addExp(t_stmt);
}

void
IRState::startLoop(Statement * stmt)
{
    Flow * f = beginFlow(stmt);
    f->continueLabel = label(stmt ? stmt->loc : 0); // should be end for 'do' loop
}

void
IRState::continueHere()
{
    doLabel(currentFlow()->continueLabel);
}

void
IRState::setContinueLabel(tree lbl)
{
    currentFlow()->continueLabel = lbl;
}

void
IRState::exitIfFalse(tree t_cond, bool /*unused*/)
{
    addExp(build1(EXIT_EXPR, void_type_node,
               build1(TRUTH_NOT_EXPR, TREE_TYPE(t_cond), t_cond)));
}

void
IRState::exitIfFalse(Expression * e_cond, bool is_top_cond)
{
#if V2
    tree t_cond = e_cond->toElemDtor(this);
    exitIfFalse(convertForCondition(t_cond, e_cond->type), is_top_cond);
#else
    exitIfFalse(convertForCondition(e_cond), is_top_cond);
#endif
}

void
IRState::endLoop()
{
    // says must contain an EXIT_EXPR -- what about while(1)..goto;? something other thand LOOP_EXPR?
    tree t_body = popStatementList();
    tree t_loop = build1(LOOP_EXPR, void_type_node, t_body);
    addExp(t_loop);
    endFlow();
}


void
IRState::startCase(Statement * stmt, tree t_cond, int has_vars)
{
    Flow * f = beginFlow(stmt);
    f->condition = t_cond;
    f->kind = level_switch;
#if V2
    if (has_vars)
    {   // %% dummy value so the tree is not NULL
        f->hasVars = integer_one_node;
    }
#endif
}

void
IRState::doCase(tree t_value, tree t_label)
{
#if V2
    if (currentFlow()->hasVars)
    {   // SwitchStatement has already taken care of label jumps.
        doLabel(t_label);
    }
    else
#endif
    {
#if D_GCC_VER >= 47
        tree t_case = build_case_label(t_value, NULL_TREE, t_label);
        addExp(t_case);
#else
        addExp(build3(CASE_LABEL_EXPR, void_type_node,
                    t_value, NULL_TREE, t_label));
#endif
    }
}

void
IRState::endCase(tree /*t_cond*/)
{
    Flow * f = currentFlow();
    tree t_body = popStatementList();
#if V2
    if (f->hasVars)
    {   // %% switch was converted to if-then-else expression
        addExp(t_body);
    }
    else
#endif
    {
        tree t_stmt = build3(SWITCH_EXPR, void_type_node, f->condition,
                t_body, NULL_TREE);
        addExp(t_stmt);
    }
    endFlow();
}

void
IRState::continueLoop(Identifier * ident)
{
    //doFlowLabel(stmt, ident, Continue);
    doJump(NULL, getLoopForLabel(ident, true)->continueLabel);
}

void
IRState::exitLoop(Identifier * ident)
{
    Flow * flow = getLoopForLabel(ident);
    if (! flow->exitLabel)
        flow->exitLabel = label(flow->statement->loc);
    doJump(NULL, flow->exitLabel);
}


void
IRState::startTry(Statement * stmt)
{
    beginFlow(stmt);
    currentFlow()->kind = level_try;
}

void
IRState::startCatches()
{
    currentFlow()->tryBody = popStatementList();
    currentFlow()->kind = level_catch;
    pushStatementList();
}

void
IRState::startCatch(tree t_type)
{
    currentFlow()->catchType = t_type;
    pushStatementList();
}

void
IRState::endCatch()
{
    tree t_body = popStatementList();
    // % wrong loc.. can set pass statement to startCatch, set
    // the loc on t_type and then use it here..
    // may not be important?
    doExp(build2(CATCH_EXPR, void_type_node,
              currentFlow()->catchType, t_body));
}

void
IRState::endCatches()
{
    tree t_catches = popStatementList();
    g.ofile->doLineNote(currentFlow()->statement->loc);
    doExp(build2(TRY_CATCH_EXPR, void_type_node,
                currentFlow()->tryBody, t_catches));
    endFlow();
}

void
IRState::startFinally()
{
    currentFlow()->tryBody = popStatementList();
    currentFlow()->kind = level_finally;
    pushStatementList();
}

void
IRState::endFinally()
{
    tree t_finally = popStatementList();
    g.ofile->doLineNote(currentFlow()->statement->loc);
    doExp(build2(TRY_FINALLY_EXPR, void_type_node,
                currentFlow()->tryBody, t_finally));
    endFlow();
}

void
IRState::doReturn(tree t_value)
{
    addExp(build1(RETURN_EXPR, void_type_node, t_value));
}

void
IRState::doJump(Statement * stmt, tree t_label)
{
    if (stmt)
        g.ofile->doLineNote(stmt->loc);
    addExp(build1(GOTO_EXPR, void_type_node, t_label));
    TREE_USED(t_label) = 1;
}

void
IRState::doExp(tree t)
{
    addExp(t);
}

void
IRState::doExp(Expression * e)
{
    // %% should handle volatile...?
    addExp(e->toElem(this));
}

void
IRState::doAsm(tree insn_tmpl, tree outputs, tree inputs, tree clobbers)
{
    tree t = d_build_asm_stmt(insn_tmpl, outputs, inputs, clobbers, NULL_TREE);
    ASM_VOLATILE_P(t) = 1;
    addExp(t);
}


void
IRState::pushLabel(LabelDsymbol * l)
{
    labels.push(getLabelBlock(l));
}

void
IRState::checkSwitchCase(Statement * stmt, int default_flag)
{
    Flow * flow = currentFlow();

    gcc_assert(flow);
    if (flow->kind != level_switch && flow->kind != level_block)
    {
        stmt->error("%s cannot be in different try block level from switch",
                    default_flag ? "default" : "case");
    }
}

void
IRState::checkGoto(Statement * stmt, LabelDsymbol * label)
{
    Statement * curBlock = NULL;
    unsigned curLevel = loops.dim;
    int found = 0;

    if (curLevel)
        curBlock = currentFlow()->statement;

    for (size_t i = 0; i < labels.dim; i++)
    {
        Label * linfo = labels[i];
        gcc_assert(linfo);

        if (label == linfo->label)
        {
            // No need checking for finally, should have already been handled.
            if (linfo->kind == level_try &&
                curLevel <= linfo->level && curBlock != linfo->block)
            {
                stmt->error("cannot goto into try block");
            }
            // %% doc: It is illegal for goto to be used to skip initializations,
            // %%      so this should include all gotos into catches...
            if (linfo->kind == level_catch && curBlock != linfo->block)
                stmt->error("cannot goto into catch block");

            found = 1;
            break;
        }
    }
    // Push forward referenced gotos.
    if (! found)
    {
        if (! label->statement->fwdrefs)
            label->statement->fwdrefs = new Array();
        label->statement->fwdrefs->push(getLabelBlock(label, stmt));
    }
}

void
IRState::checkPreviousGoto(Array * refs)
{
    Statement * stmt; // Our forward reference.

    for (size_t i = 0; i < refs->dim; i++)
    {
        Label * ref = (Label *) refs->data[i];
        int found = 0;

        gcc_assert(ref && ref->from);
        stmt = ref->from;

        for (size_t i = 0; i < labels.dim; i++)
        {
            Label * linfo = labels[i];
            gcc_assert(linfo);

            if (ref->label == linfo->label)
            {
                // No need checking for finally, should have already been handled.
                if (linfo->kind == level_try &&
                    ref->level <= linfo->level && ref->block != linfo->block)
                {
                    stmt->error("cannot goto into try block");
                }
                // %% doc: It is illegal for goto to be used to skip initializations,
                // %%      so this should include all gotos into catches...
                if (linfo->kind == level_catch &&
                    (ref->block != linfo->block || ref->kind != linfo->kind))
                    stmt->error("cannot goto into catch block");

                found = 1;
                break;
            }
        }
        gcc_assert(found);
    }
}


WrappedExp::WrappedExp(Loc loc, enum TOK op, tree exp_node, Type * type)
    : Expression(loc, op, sizeof(WrappedExp))
{
    this->exp_node = exp_node;
    this->type = type;
}

void
WrappedExp::toCBuffer(OutBuffer *buf)
{
    buf->printf("< wrapped exprission >");
}

elem *
WrappedExp::toElem(IRState *)
{
    return exp_node;
}


void
FieldVisitor::visit(AggregateDeclaration * decl)
{
    ClassDeclaration * class_decl = decl->isClassDeclaration();

    if (class_decl && class_decl->baseClass)
        FieldVisitor::visit(class_decl->baseClass);

    if (decl->fields.dim)
        doFields(& decl->fields, decl);

    if (class_decl && class_decl->vtblInterfaces)
        doInterfaces(class_decl->vtblInterfaces, decl);
}


void
AggLayout::doFields(VarDeclarations * fields, AggregateDeclaration * agg)
{
    bool inherited = agg != this->aggDecl;
    tree fcontext;

    fcontext = agg->type->toCtype();
    if (POINTER_TYPE_P(fcontext))
        fcontext = TREE_TYPE(fcontext);

    // tree new_field_chain = NULL_TREE;
    for (size_t i = 0; i < fields->dim; i++)
    {   // %% D anonymous unions just put the fields into the outer struct...
        // does this cause problems?
        VarDeclaration * var_decl = fields->tdata()[i];
        gcc_assert(var_decl && var_decl->storage_class & STCfield);

        tree ident = var_decl->ident ? get_identifier(var_decl->ident->string) : NULL_TREE;
        tree field_decl = build_decl(UNKNOWN_LOCATION, FIELD_DECL, ident,
                                     gen.trueDeclarationType(var_decl));
        g.ofile->setDeclLoc(field_decl, var_decl);
        var_decl->csym = new Symbol;
        var_decl->csym->Stree = field_decl;

        DECL_CONTEXT(field_decl) = aggType;
        DECL_FCONTEXT(field_decl) = fcontext;
        DECL_FIELD_OFFSET (field_decl) = size_int(var_decl->offset);
        DECL_FIELD_BIT_OFFSET (field_decl) = bitsize_zero_node;

        DECL_ARTIFICIAL(field_decl) = DECL_IGNORED_P(field_decl) = inherited;

        // GCC 4.0 requires DECL_OFFSET_ALIGN to be set
        // %% .. using TYPE_ALIGN may not be same as DMD..
        SET_DECL_OFFSET_ALIGN(field_decl, TYPE_ALIGN(TREE_TYPE(field_decl)));

        //SET_DECL_OFFSET_ALIGN (field_decl, BIGGEST_ALIGNMENT); // ?
        layout_decl(field_decl, 0);

        // get_inner_reference doesn't check these, leaves a variable unitialized
        // DECL_SIZE is NULL if size is zero.
        if (var_decl->size(var_decl->loc))
        {
            gcc_assert(DECL_MODE(field_decl) != VOIDmode);
            gcc_assert(DECL_SIZE(field_decl) != NULL_TREE);
        }
        fieldList.chain(field_decl);
    }
}

void
AggLayout::doInterfaces(BaseClasses * bases, AggregateDeclaration * /*agg*/)
{
    //tree fcontext = TREE_TYPE(agg->type->toCtype());
    for (size_t i = 0; i < bases->dim; i++)
    {
        BaseClass * bc = bases->tdata()[i];
        tree decl = build_decl(UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE,
                               Type::tvoidptr->pointerTo()->toCtype() /* %% better */);
        //DECL_VIRTUAL_P(decl) = 1; %% nobody cares, boo hoo
        DECL_ARTIFICIAL(decl) = DECL_IGNORED_P(decl) = 1;
        // DECL_FCONTEXT(decl) = fcontext; // shouldn't be needed since it's ignored
        addField(decl, bc->offset);
    }
}

void
AggLayout::addField(tree field_decl, size_t offset)
{
    DECL_CONTEXT(field_decl) = aggType;
    // DECL_FCONTEXT(field_decl) = aggType; // caller needs to set this
    SET_DECL_OFFSET_ALIGN(field_decl, TYPE_ALIGN(TREE_TYPE(field_decl)));
    DECL_FIELD_OFFSET (field_decl) = size_int(offset);
    DECL_FIELD_BIT_OFFSET (field_decl) = bitsize_zero_node;
    Loc l(aggDecl->getModule(), 1); // Must set this or we crash with DWARF debugging
    // gen.setDeclLoc(field_decl, aggDecl->loc); // aggDecl->loc isn't set
    g.ofile->setDeclLoc(field_decl, l);

    layout_decl(field_decl, 0);
    fieldList.chain(field_decl);
}

void
AggLayout::finish(Expressions * attrs)
{
    unsigned size_to_use = aggDecl->structsize;
    unsigned align_to_use = aggDecl->alignsize;

    /* probably doesn't do anything */
    /*
    if (aggDecl->structsize == 0 && aggDecl->isInterfaceDeclaration())
        size_to_use = Type::tvoid->pointerTo()->size();
    */

    TYPE_SIZE(aggType) = bitsize_int(size_to_use * BITS_PER_UNIT);
    TYPE_SIZE_UNIT(aggType) = size_int(size_to_use);
    TYPE_ALIGN(aggType) = align_to_use * BITS_PER_UNIT;
    // TYPE_ALIGN_UNIT is not an lvalue
    TYPE_PACKED (aggType) = TYPE_PACKED (aggType); // %% todo

    if (attrs)
    {
        decl_attributes(& aggType, gen.attributes(attrs),
                        ATTR_FLAG_TYPE_IN_PLACE);
    }

    compute_record_mode (aggType);
    // %%  stor-layout.c:finalize_type_size ... it's private to that file
    // c-decl.c -- set up variants ? %%
    for (tree x = TYPE_MAIN_VARIANT(aggType); x; x = TYPE_NEXT_VARIANT(x))
    {
        TYPE_FIELDS (x) = TYPE_FIELDS (aggType);
        TYPE_LANG_SPECIFIC (x) = TYPE_LANG_SPECIFIC (aggType);
        TYPE_ALIGN (x) = TYPE_ALIGN (aggType);
        TYPE_USER_ALIGN (x) = TYPE_USER_ALIGN (aggType);
    }
}


ArrayScope::ArrayScope(IRState * ini_irs, VarDeclaration * ini_v, const Loc & loc) :
    v(ini_v), irs(ini_irs)
{
    if (v)
    {   /* Need to set the location or the expand_decl in the BIND_EXPR will
           cause the line numbering for the statement to be incorrect. */
        /* The variable itself is not included in the debugging information. */
        v->loc = loc;
        Symbol * s = v->toSymbol();
        tree decl = s->Stree;
        DECL_CONTEXT(decl) = irs->getLocalContext();
    }
}

tree
ArrayScope::setArrayExp(tree e, Type * t)
{
    /* If STCconst, the value will be assigned in d-decls.cc
       of the runtime length of the array expression. */
    if (v && ! (v->storage_class & STCconst))
    {
        if (t->toBasetype()->ty != Tsarray)  // %%
            e = irs->maybeMakeTemp(e);
        DECL_INITIAL(v->toSymbol()->Stree) = irs->arrayLength(e, t);
    }
    return e;
}

tree
ArrayScope::finish(tree e)
{
    if (v)
    {
        Symbol * s = v->toSymbol();
        tree t = s->Stree;
        if (TREE_CODE(t) == VAR_DECL)
        {
            if (s->SframeField)
            {
                return irs->compound(irs->vmodify(irs->var(v), DECL_INITIAL(t)), e);
            }
            else
            {
                return gen.binding(v->toSymbol()->Stree, e);
            }
        }
    }
    return e;
}