summaryrefslogtreecommitdiffstats
path: root/source/slang/ir.cpp
blob: 3a8aabd85cfc8231d5ce98bcbc8ade0decc62420 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
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
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
// ir.cpp
#include "ir.h"
#include "ir-insts.h"

#include "../core/basic.h"
#include "mangle.h"

namespace Slang
{

    static const IROpInfo kIROpInfos[] =
    {
#define INST(ID, MNEMONIC, ARG_COUNT, FLAGS)  \
    { #MNEMONIC, ARG_COUNT, FLAGS, },
#include "ir-inst-defs.h"
    };

    //

    IROp findIROp(char const* name)
    {
        // TODO: need to make this faster by using a dictionary...

        if (0) {}

#define INST(ID, MNEMONIC, ARG_COUNT, FLAGS)  \
    else if(strcmp(name, #MNEMONIC) == 0) return kIROp_##ID;

#define PSEUDO_INST(ID)  \
    else if(strcmp(name, #ID) == 0) return kIRPseudoOp_##ID;

#include "ir-inst-defs.h"

        return IROp(kIROp_Invalid);
    }

    IROpInfo getIROpInfo(IROp op)
    {
        return kIROpInfos[op];
    }

    //

    void IRUse::init(IRUser* u, IRValue* v)
    {
        user = u;
        usedValue = v;

        if(v)
        {
            nextUse = v->firstUse;
            prevLink = &v->firstUse;

            v->firstUse = this;
        }
    }

    void IRUse::set(IRValue* usedVal)
    {
        // clear out the old value
        if (usedVal)
        {
            *prevLink = nextUse;
        }

        init(user, usedVal);
    }

    void IRUse::clear()
    {
        if (usedValue)
        {
            *prevLink = nextUse;
        }

        user = nullptr;
        usedValue = nullptr;
    }

    //

    IRUse* IRUser::getArgs()
    {
        // We assume that *all* instructions are laid out
        // in memory such that their arguments come right
        // after the first `sizeof(IRInst)` bytes.
        //
        // TODO: we probably need to be careful and make
        // this more robust.

        return (IRUse*)(this + 1);
    }

    IRDecoration* IRValue::findDecorationImpl(IRDecorationOp decorationOp)
    {
        for( auto dd = firstDecoration; dd; dd = dd->next )
        {
            if(dd->op == decorationOp)
                return dd;
        }
        return nullptr;
    }

    // IRBlock

    void IRBlock::addParam(IRParam* param)
    {
        if (auto lp = lastParam)
        {
            lp->nextParam = param;
            param->prevParam = lp;
        }
        else
        {
            firstParam = param;
        }
        lastParam = param;
    }

    // IRFunc

    IRType* IRFunc::getResultType() { return getType()->getResultType(); }
    UInt IRFunc::getParamCount() { return getType()->getParamCount(); }
    IRType* IRFunc::getParamType(UInt index) { return getType()->getParamType(index); }

    IRParam* IRFunc::getFirstParam()
    {
        auto entryBlock = getFirstBlock();
        if(!entryBlock) return nullptr;

        return entryBlock->getFirstParam();
    }

    void IRGlobalValueWithCode::addBlock(IRBlock* block)
    {
        block->parentFunc = this;

        if (auto lb = lastBlock)
        {
            lb->nextBlock = block;
            block->prevBlock = lb;
        }
        else
        {
            firstBlock = block;
        }
        lastBlock = block;
    }

    //

    bool isTerminatorInst(IROp op)
    {
        switch (op)
        {
        default:
            return false;

        case kIROp_ReturnVal:
        case kIROp_ReturnVoid:
        case kIROp_unconditionalBranch:
        case kIROp_conditionalBranch:
        case kIROp_break:
        case kIROp_continue:
        case kIROp_loop:
        case kIROp_if:
        case kIROp_ifElse:
        case kIROp_loopTest:
        case kIROp_discard:
        case kIROp_switch:
        case kIROp_unreachable:
            return true;
        }
    }

    bool isTerminatorInst(IRInst* inst)
    {
        if (!inst) return false;
        return isTerminatorInst(inst->op);
    }

    //

    void IRValueListBase::addImpl(IRValue* parent, IRChildValue* val)
    {
        val->parent = parent;
        val->prev = last;
        val->next = nullptr;

        if (last)
        {
            last->next = val;
        }
        else
        {
            first = val;
        }

        last = val;
    }


    //

    // Add an instruction to a specific parent
    void IRBuilder::addInst(IRBlock* pblock, IRInst* inst)
    {
        inst->parent = pblock;

        if (!pblock->firstInst)
        {
            inst->prev = nullptr;
            inst->next = nullptr;

            pblock->firstInst = inst;
            pblock->lastInst = inst;
        }
        else
        {
            auto prev = pblock->lastInst;

            inst->prev = prev;
            inst->next = nullptr;

            prev->next = inst;
            pblock->lastInst = inst;
        }
    }

    // Add an instruction into the current scope
    void IRBuilder::addInst(
        IRInst*     inst)
    {
        if(insertBeforeInst)
        {
            inst->insertBefore(insertBeforeInst);
            return;
        }

        auto parent = curBlock;
        if (!parent)
            return;

        addInst(parent, inst);
    }

    static IRValue* createValueImpl(
        IRBuilder*  /*builder*/,
        UInt        size,
        IROp        op,
        IRType*     type)
    {
        IRValue* value = (IRValue*) malloc(size);
        memset(value, 0, size);
        value->op = op;
        value->type = type;
        return value;
    }

    template<typename T>
    static T* createValue(
        IRBuilder*  builder,
        IROp        op,
        IRType*     type)
    {
        return (T*) createValueImpl(builder, sizeof(T), op, type);
    }


    // Create an IR instruction/value and initialize it.
    //
    // In this case `argCount` and `args` represnt the
    // arguments *after* the type (which is a mandatory
    // argument for all instructions).
    static IRInst* createInstImpl(
        IRBuilder*      /*builder*/,
        UInt            size,
        IROp            op,
        IRType*         type,
        UInt            fixedArgCount,
        IRValue* const* fixedArgs,
        UInt            varArgCount = 0,
        IRValue* const* varArgs = nullptr)
    {
        IRInst* inst = (IRInst*) malloc(size);
        memset(inst, 0, size);

        inst->argCount = (uint32_t)(fixedArgCount + varArgCount);

        inst->op = op;

        inst->type = type;

        auto operand = inst->getArgs();

        for( UInt aa = 0; aa < fixedArgCount; ++aa )
        {
            if (fixedArgs)
            {
                operand->init(inst, fixedArgs[aa]);
            }
            operand++;
        }

        for( UInt aa = 0; aa < varArgCount; ++aa )
        {
            if (varArgs)
            {
                operand->init(inst, varArgs[aa]);
            }
            operand++;
        }

        return inst;
    }

    template<typename T>
    static T* createInst(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        UInt            argCount,
        IRValue* const* args)
    {
        return (T*)createInstImpl(
            builder,
            sizeof(T),
            op,
            type,
            argCount,
            args);
    }

    template<typename T>
    static T* createInst(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type)
    {
        return (T*)createInstImpl(
            builder,
            sizeof(T),
            op,
            type,
            0,
            nullptr);
    }

    template<typename T>
    static T* createInst(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        IRValue*        arg)
    {
        return (T*)createInstImpl(
            builder,
            sizeof(T),
            op,
            type,
            1,
            &arg);
    }

    template<typename T>
    static T* createInst(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        IRValue*        arg1,
        IRValue*        arg2)
    {
        IRValue* args[] = { arg1, arg2 };
        return (T*)createInstImpl(
            builder,
            sizeof(T),
            op,
            type,
            2,
            &args[0]);
    }

    template<typename T>
    static T* createInstWithTrailingArgs(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        UInt            argCount,
        IRValue* const* args)
    {
        return (T*)createInstImpl(
            builder,
            sizeof(T) + argCount * sizeof(IRUse),
            op,
            type,
            argCount,
            args);
    }

    template<typename T>
    static T* createInstWithTrailingArgs(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        UInt            fixedArgCount,
        IRValue* const* fixedArgs,
        UInt            varArgCount,
        IRValue* const* varArgs)
    {
        return (T*)createInstImpl(
            builder,
            sizeof(T) + varArgCount * sizeof(IRUse),
            op,
            type,
            fixedArgCount,
            fixedArgs,
            varArgCount,
            varArgs);
    }

    template<typename T>
    static T* createInstWithTrailingArgs(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        IRValue*        arg1,
        UInt            varArgCount,
        IRValue* const* varArgs)
    {
        IRValue* fixedArgs[] = { arg1 };
        UInt fixedArgCount = sizeof(fixedArgs) / sizeof(fixedArgs[0]);

        return (T*)createInstImpl(
            builder,
            sizeof(T) + varArgCount * sizeof(IRUse),
            op,
            type,
            fixedArgCount,
            fixedArgs,
            varArgCount,
            varArgs);
    }
    //

    bool operator==(IRInstKey const& left, IRInstKey const& right)
    {
        if(left.inst->op != right.inst->op) return false;
        if(left.inst->parent != right.inst->parent) return false;
        if(left.inst->argCount != right.inst->argCount) return false;

        auto argCount = left.inst->argCount;
        auto leftArgs = left.inst->getArgs();
        auto rightArgs = right.inst->getArgs();
        for( UInt aa = 0; aa < argCount; ++aa )
        {
            if(leftArgs[aa].usedValue != rightArgs[aa].usedValue)
                return false;
        }

        return true;
    }

    int IRInstKey::GetHashCode()
    {
        auto code = Slang::GetHashCode(inst->op);
        code = combineHash(code, Slang::GetHashCode(inst->parent));
        code = combineHash(code, Slang::GetHashCode(inst->argCount));

        auto argCount = inst->argCount;
        auto args = inst->getArgs();
        for( UInt aa = 0; aa < argCount; ++aa )
        {
            code = combineHash(code, Slang::GetHashCode(args[aa].usedValue));
        }
        return code;
    }

    //

    bool operator==(IRConstantKey const& left, IRConstantKey const& right)
    {
        if(left.inst->op            != right.inst->op)              return false;
        if(left.inst->type          != right.inst->type)            return false;
        if(left.inst->u.ptrData[0]  != right.inst->u.ptrData[0])    return false;
        if(left.inst->u.ptrData[1]  != right.inst->u.ptrData[1])    return false;
        return true;
    }

    int IRConstantKey::GetHashCode()
    {
        auto code = Slang::GetHashCode(inst->op);
        code = combineHash(code, Slang::GetHashCode(inst->type));
        code = combineHash(code, Slang::GetHashCode(inst->u.ptrData[0]));
        code = combineHash(code, Slang::GetHashCode(inst->u.ptrData[1]));
        return code;
    }

    static IRConstant* findOrEmitConstant(
        IRBuilder*      builder,
        IROp            op,
        IRType*         type,
        UInt            valueSize,
        void const*     value)
    {
        // First, we need to pick a good insertion point
        // for the instruction, which we do by looking
        // at its operands.
        //

        IRConstant keyInst;
        memset(&keyInst, 0, sizeof(keyInst));
        keyInst.op = op;
        keyInst.type = type;
        memcpy(&keyInst.u, value, valueSize);

        IRConstantKey key;
        key.inst = &keyInst;

        IRConstant* irValue = nullptr;
        if( builder->sharedBuilder->constantMap.TryGetValue(key, irValue) )
        {
            // We found a match, so just use that.
            return irValue;
        }

        // We now know where we want to insert, but there might
        // already be an equivalent instruction in that block.
        //
        // We will check for such an instruction in a slightly hacky
        // way: we will construct a temporary instruction and
        // then use it to look up in a cache of instructions.

        irValue = createValue<IRConstant>(builder, op, type);
        memcpy(&irValue->u, value, valueSize);

        key.inst = irValue;
        builder->sharedBuilder->constantMap.Add(key, irValue);

        return irValue;
    }


    //

    IRValue* IRBuilder::getBoolValue(bool inValue)
    {
        IRIntegerValue value = inValue;
        return findOrEmitConstant(
            this,
            kIROp_boolConst,
            getSession()->getBoolType(),
            sizeof(value),
            &value);
    }

    IRValue* IRBuilder::getIntValue(IRType* type, IRIntegerValue value)
    {
        return findOrEmitConstant(
            this,
            kIROp_IntLit,
            type,
            sizeof(value),
            &value);
    }

    IRValue* IRBuilder::getFloatValue(IRType* type, IRFloatingPointValue value)
    {
        return findOrEmitConstant(
            this,
            kIROp_FloatLit,
            type,
            sizeof(value),
            &value);
    }

    IRValue* IRBuilder::getDeclRefVal(
        DeclRefBase const&  declRef)
    {
        // TODO: we should cache these...
        auto irValue = createValue<IRDeclRef>(
            this,
            kIROp_decl_ref,
            nullptr);
        irValue->declRef = DeclRef<Decl>(declRef.decl, declRef.substitutions);
        return irValue;
    }

    IRValue * IRBuilder::getTypeVal(IRType * type)
    {
        auto irValue = createValue<IRValue>(
            this,
            kIROp_TypeType,
            nullptr);
        irValue->type = type;
        if (auto typetype = dynamic_cast<TypeType*>(type))
            irValue->type = typetype->type;
        return irValue;
    }

    IRValue* IRBuilder::emitSpecializeInst(
        Type*       type,
        IRValue*    genericVal,
        IRValue*    specDeclRef)
    {
        auto inst = createInst<IRSpecialize>(
            this,
            kIROp_specialize,
            type,
            genericVal,
            specDeclRef);
        addInst(inst);
        return inst;
    }

    IRValue* IRBuilder::emitSpecializeInst(
        Type*           type,
        IRValue*        genericVal,
        DeclRef<Decl>   specDeclRef)
    {
        auto specDeclRefVal = getDeclRefVal(specDeclRef);
        auto inst = createInst<IRSpecialize>(
            this,
            kIROp_specialize,
            type,
            genericVal,
            specDeclRefVal);
        addInst(inst);
        return inst;
    }

    IRValue* IRBuilder::emitLookupInterfaceMethodInst(
        IRType*     type,
        IRValue*    witnessTableVal,
        IRValue*    interfaceMethodVal)
    {
        auto inst = createInst<IRLookupWitnessMethod>(
            this,
            kIROp_lookup_interface_method,
            type,
            witnessTableVal,
            interfaceMethodVal);
        addInst(inst);
        return inst;
    }

    IRValue* IRBuilder::emitLookupInterfaceMethodInst(
        IRType*         type,
        DeclRef<Decl>   witnessTableDeclRef,
        DeclRef<Decl>   interfaceMethodDeclRef)
    {
        auto witnessTableVal = getDeclRefVal(witnessTableDeclRef);
        auto interfaceMethodVal = getDeclRefVal(interfaceMethodDeclRef);
        return emitLookupInterfaceMethodInst(type, witnessTableVal, interfaceMethodVal);
    }



    IRInst* IRBuilder::emitCallInst(
        IRType*         type,
        IRValue*        pFunc,
        UInt            argCount,
        IRValue* const* args)
    {
        auto inst = createInstWithTrailingArgs<IRCall>(
            this,
            kIROp_Call,
            type,
            1,
            &pFunc,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitIntrinsicInst(
        IRType*         type,
        IROp            op,
        UInt            argCount,
        IRValue* const* args)
    {
        auto inst = createInstWithTrailingArgs<IRInst>(
            this,
            op,
            type,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitConstructorInst(
        IRType*         type,
        UInt            argCount,
        IRValue* const* args)
    {
        auto inst = createInstWithTrailingArgs<IRInst>(
            this,
            kIROp_Construct,
            type,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRModule* IRBuilder::createModule()
    {
        auto module = new IRModule();
        module->session = getSession();
        return module;
    }

    void IRGlobalValue::insertBefore(IRGlobalValue* other)
    {
        assert(other);
        insertBefore(other, other->parentModule);
    }

    void IRGlobalValue::insertBefore(IRGlobalValue* other, IRModule* module)
    {
        assert(other || module);

        if(!other) other = module->firstGlobalValue;
        if(!module) module = other->parentModule;

        assert(module);

        auto nn = other;
        auto pp = other ? other->prevGlobalValue : nullptr;

        if(pp)
        {
            pp->nextGlobalValue = this;
        }
        else
        {
            module->firstGlobalValue = this;
        }

        if(nn)
        {
            nn->prevGlobalValue = this;
        }
        else
        {
            module->lastGlobalValue = this;
        }

        this->prevGlobalValue = pp;
        this->nextGlobalValue = nn;
        this->parentModule = module;
    }

    void IRGlobalValue::insertAtStart(IRModule* module)
    {
        insertBefore(module->firstGlobalValue, module);
    }

    void IRGlobalValue::insertAfter(IRGlobalValue* other)
    {
        assert(other);
        insertAfter(other, other->parentModule);
    }

    void IRGlobalValue::insertAfter(IRGlobalValue* other, IRModule* module)
    {
        assert(other || module);

        if(!other) other = module->lastGlobalValue;
        if(!module) module = other->parentModule;

        assert(module);

        auto pp = other;
        auto nn = other ? other->nextGlobalValue : nullptr;

        if(pp)
        {
            pp->nextGlobalValue = this;
        }
        else
        {
            module->firstGlobalValue = this;
        }

        if(nn)
        {
            nn->prevGlobalValue = this;
        }
        else
        {
            module->lastGlobalValue = this;
        }

        this->prevGlobalValue = pp;
        this->nextGlobalValue = nn;
        this->parentModule = module;
    }

    void IRGlobalValue::insertAtEnd(IRModule* module)
    {
        assert(module);
        insertAfter(module->lastGlobalValue, module);
    }

    void IRGlobalValue::removeFromParent()
    {
        auto module = parentModule;
        if(!module)
            return;

        auto pp = this->prevGlobalValue;
        auto nn = this->nextGlobalValue;

        if(pp)
        {
            pp->nextGlobalValue = nn;
        }
        else
        {
            module->firstGlobalValue = nn;
        }

        if( nn )
        {
            nn->prevGlobalValue = pp;
        }
        else
        {
            module->lastGlobalValue = pp;
        }
    }

    void IRGlobalValue::moveToEnd()
    {
        auto module = parentModule;
        removeFromParent();
        insertAtEnd(module);
    }



    void addGlobalValue(
        IRModule*   module,
        IRGlobalValue*  value)
    {
        if(!module)
            return;

        value->parentModule = module;
        value->insertAfter(module->lastGlobalValue, module);
    }

    IRFunc* IRBuilder::createFunc()
    {
        IRFunc* rsFunc = createValue<IRFunc>(
            this,
            kIROp_Func,
            nullptr);
        addGlobalValue(getModule(), rsFunc);
        return rsFunc;
    }

    IRGlobalVar* IRBuilder::createGlobalVar(
        IRType* valueType)
    {
        auto ptrType = getSession()->getPtrType(valueType);
        IRGlobalVar* globalVar = createValue<IRGlobalVar>(
            this,
            kIROp_global_var,
            ptrType);
        addGlobalValue(getModule(), globalVar);
        return globalVar;
    }

    IRWitnessTable* IRBuilder::createWitnessTable()
    {
        IRWitnessTable* witnessTable = createValue<IRWitnessTable>(
            this,
            kIROp_witness_table,
            nullptr);
        addGlobalValue(getModule(), witnessTable);
        return witnessTable;
    }

    IRWitnessTableEntry* IRBuilder::createWitnessTableEntry(
        IRWitnessTable* witnessTable,
        IRValue*        requirementKey,
        IRValue*        satisfyingVal)
    {
        IRWitnessTableEntry* entry = createInst<IRWitnessTableEntry>(
            this,
            kIROp_witness_table_entry,
            nullptr,
            requirementKey,
            satisfyingVal);

        if (witnessTable)
        {
            witnessTable->entries.add(witnessTable, entry);
        }

        return entry;
    }


    IRBlock* IRBuilder::createBlock()
    {
        return createValue<IRBlock>(
            this,
            kIROp_Block,
            getSession()->getIRBasicBlockType());
    }

    IRBlock* IRBuilder::emitBlock()
    {
        auto bb = createBlock();

        auto f = this->curFunc;
        if (f)
        {
            f->addBlock(bb);
            this->curBlock = bb;
        }
        return bb;
    }

    IRParam* IRBuilder::emitParam(
        IRType* type)
    {
        auto param = createValue<IRParam>(
            this,
            kIROp_Param,
            type);

        if (auto bb = curBlock)
        {
            bb->addParam(param);
        }
        return param;
    }

    IRVar* IRBuilder::emitVar(
        IRType*         type)
    {
        auto allocatedType = getSession()->getPtrType(type);
        auto inst = createInst<IRVar>(
            this,
            kIROp_Var,
            allocatedType);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitLoad(
        IRValue*    ptr)
    {
        auto ptrType = ptr->getType()->As<PtrTypeBase>();
        if( !ptrType )
        {
            // Bad!
            SLANG_ASSERT(ptrType);
            return nullptr;
        }

        auto valueType = ptrType->getValueType();

        auto inst = createInst<IRLoad>(
            this,
            kIROp_Load,
            valueType,
            ptr);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitStore(
        IRValue*    dstPtr,
        IRValue*    srcVal)
    {
        auto inst = createInst<IRStore>(
            this,
            kIROp_Store,
            nullptr,
            dstPtr,
            srcVal);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitFieldExtract(
        IRType*         type,
        IRValue*        base,
        IRValue*        field)
    {
        auto inst = createInst<IRFieldExtract>(
            this,
            kIROp_FieldExtract,
            type,
            base,
            field);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitFieldAddress(
        IRType*         type,
        IRValue*        base,
        IRValue*        field)
    {
        auto inst = createInst<IRFieldAddress>(
            this,
            kIROp_FieldAddress,
            type,
            base,
            field);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitElementExtract(
        IRType*     type,
        IRValue*    base,
        IRValue*    index)
    {
        auto inst = createInst<IRFieldAddress>(
            this,
            kIROp_getElement,
            type,
            base,
            index);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitElementAddress(
        IRType*     type,
        IRValue*    basePtr,
        IRValue*    index)
    {
        auto inst = createInst<IRFieldAddress>(
            this,
            kIROp_getElementPtr,
            type,
            basePtr,
            index);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitSwizzle(
        IRType*         type,
        IRValue*        base,
        UInt            elementCount,
        IRValue* const* elementIndices)
    {
        auto inst = createInstWithTrailingArgs<IRSwizzle>(
            this,
            kIROp_swizzle,
            type,
            base,
            elementCount,
            elementIndices);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitSwizzle(
        IRType*         type,
        IRValue*        base,
        UInt            elementCount,
        UInt const*     elementIndices)
    {
        auto intType = getSession()->getBuiltinType(BaseType::Int);

        IRValue* irElementIndices[4];
        for (UInt ii = 0; ii < elementCount; ++ii)
        {
            irElementIndices[ii] = getIntValue(intType, elementIndices[ii]);
        }

        return emitSwizzle(type, base, elementCount, irElementIndices);
    }


    IRInst* IRBuilder::emitSwizzleSet(
        IRType*         type,
        IRValue*        base,
        IRValue*        source,
        UInt            elementCount,
        IRValue* const* elementIndices)
    {
        IRValue* fixedArgs[] = { base, source };
        UInt fixedArgCount = sizeof(fixedArgs) / sizeof(fixedArgs[0]);

        auto inst = createInstWithTrailingArgs<IRSwizzleSet>(
            this,
            kIROp_swizzleSet,
            type,
            fixedArgCount,
            fixedArgs,
            elementCount,
            elementIndices);

        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitSwizzleSet(
        IRType*         type,
        IRValue*        base,
        IRValue*        source,
        UInt            elementCount,
        UInt const*     elementIndices)
    {
        auto intType = getSession()->getBuiltinType(BaseType::Int);

        IRValue* irElementIndices[4];
        for (UInt ii = 0; ii < elementCount; ++ii)
        {
            irElementIndices[ii] = getIntValue(intType, elementIndices[ii]);
        }

        return emitSwizzleSet(type, base, source, elementCount, irElementIndices);
    }

    IRInst* IRBuilder::emitReturn(
        IRValue*    val)
    {
        auto inst = createInst<IRReturnVal>(
            this,
            kIROp_ReturnVal,
            nullptr,
            val);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitReturn()
    {
        auto inst = createInst<IRReturnVoid>(
            this,
            kIROp_ReturnVoid,
            nullptr);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitUnreachable()
    {
        auto inst = createInst<IRUnreachable>(
            this,
            kIROp_unreachable,
            nullptr);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitDiscard()
    {
        auto inst = createInst<IRDiscard>(
            this,
            kIROp_discard,
            nullptr);
        addInst(inst);
        return inst;
    }


    IRInst* IRBuilder::emitBranch(
        IRBlock*    pBlock)
    {
        auto inst = createInst<IRUnconditionalBranch>(
            this,
            kIROp_unconditionalBranch,
            nullptr,
            pBlock);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitBreak(
        IRBlock*    target)
    {
        auto inst = createInst<IRBreak>(
            this,
            kIROp_break,
            nullptr,
            target);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitContinue(
        IRBlock*    target)
    {
        auto inst = createInst<IRContinue>(
            this,
            kIROp_continue,
            nullptr,
            target);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitLoop(
        IRBlock*    target,
        IRBlock*    breakBlock,
        IRBlock*    continueBlock)
    {
        IRValue* args[] = { target, breakBlock, continueBlock };
        UInt argCount = sizeof(args) / sizeof(args[0]);

        auto inst = createInst<IRLoop>(
            this,
            kIROp_loop,
            nullptr,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitBranch(
        IRValue*    val,
        IRBlock*    trueBlock,
        IRBlock*    falseBlock)
    {
        IRValue* args[] = { val, trueBlock, falseBlock };
        UInt argCount = sizeof(args) / sizeof(args[0]);

        auto inst = createInst<IRConditionalBranch>(
            this,
            kIROp_conditionalBranch,
            nullptr,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitIf(
        IRValue*    val,
        IRBlock*    trueBlock,
        IRBlock*    afterBlock)
    {
        IRValue* args[] = { val, trueBlock, afterBlock };
        UInt argCount = sizeof(args) / sizeof(args[0]);

        auto inst = createInst<IRIf>(
            this,
            kIROp_if,
            nullptr,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitIfElse(
        IRValue*    val,
        IRBlock*    trueBlock,
        IRBlock*    falseBlock,
        IRBlock*    afterBlock)
    {
        IRValue* args[] = { val, trueBlock, falseBlock, afterBlock };
        UInt argCount = sizeof(args) / sizeof(args[0]);

        auto inst = createInst<IRIfElse>(
            this,
            kIROp_ifElse,
            nullptr,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitLoopTest(
        IRValue*    val,
        IRBlock*    bodyBlock,
        IRBlock*    breakBlock)
    {
        IRValue* args[] = { val, bodyBlock, breakBlock };
        UInt argCount = sizeof(args) / sizeof(args[0]);

        auto inst = createInst<IRLoopTest>(
            this,
            kIROp_loopTest,
            nullptr,
            argCount,
            args);
        addInst(inst);
        return inst;
    }

    IRInst* IRBuilder::emitSwitch(
        IRValue*        val,
        IRBlock*        breakLabel,
        IRBlock*        defaultLabel,
        UInt            caseArgCount,
        IRValue* const* caseArgs)
    {
        IRValue* fixedArgs[] = { val, breakLabel, defaultLabel };
        UInt fixedArgCount = sizeof(fixedArgs) / sizeof(fixedArgs[0]);

        auto inst = createInstWithTrailingArgs<IRSwitch>(
            this,
            kIROp_switch,
            nullptr,
            fixedArgCount,
            fixedArgs,
            caseArgCount,
            caseArgs);
        addInst(inst);
        return inst;
    }

    IRDecoration* IRBuilder::addDecorationImpl(
        IRValue*        inst,
        UInt            decorationSize,
        IRDecorationOp  op)
    {
        auto decoration = (IRDecoration*) malloc(decorationSize);
        memset(decoration, 0, decorationSize);

        decoration->op = op;

        decoration->next = inst->firstDecoration;
        inst->firstDecoration = decoration;

        return decoration;
    }

    IRHighLevelDeclDecoration* IRBuilder::addHighLevelDeclDecoration(IRValue* inst, Decl* decl)
    {
        auto decoration = addDecoration<IRHighLevelDeclDecoration>(inst, kIRDecorationOp_HighLevelDecl);
        decoration->decl = decl;
        return decoration;
    }

    IRLayoutDecoration* IRBuilder::addLayoutDecoration(IRValue* inst, Layout* layout)
    {
        auto decoration = addDecoration<IRLayoutDecoration>(inst);
        decoration->layout = layout;
        return decoration;
    }

    //


    struct IRDumpContext
    {
        StringBuilder* builder;
        int     indent;

        UInt                        idCounter = 1;
        Dictionary<IRValue*, UInt>  mapValueToID;
    };

    static void dump(
        IRDumpContext*  context,
        char const*     text)
    {
        context->builder->append(text);
    }

    static void dump(
        IRDumpContext*  context,
        UInt            val)
    {
        context->builder->append(val);

//        fprintf(context->file, "%llu", (unsigned long long)val);
    }

    static void dump(
        IRDumpContext*          context,
        IntegerLiteralValue     val)
    {
        context->builder->append(val);

//        fprintf(context->file, "%llu", (unsigned long long)val);
    }

    static void dump(
        IRDumpContext*              context,
        FloatingPointLiteralValue   val)
    {
        context->builder->append(val);

//        fprintf(context->file, "%llu", (unsigned long long)val);
    }

    static void dumpIndent(
        IRDumpContext*  context)
    {
        for (int ii = 0; ii < context->indent; ++ii)
        {
            dump(context, "\t");
        }
    }

    bool opHasResult(IRValue* inst);

    static UInt getID(
        IRDumpContext*  context,
        IRValue*        value)
    {
        UInt id = 0;
        if (context->mapValueToID.TryGetValue(value, id))
            return id;

        if (opHasResult(value))
        {
            id = context->idCounter++;
        }

        context->mapValueToID.Add(value, id);
        return id;
    }

    static void dumpID(
        IRDumpContext* context,
        IRValue*        inst)
    {
        if (!inst)
        {
            dump(context, "<null>");
            return;
        }

        switch(inst->op)
        {
        case kIROp_Func:
        case kIROp_global_var:
        case kIROp_witness_table:
            {
                auto irFunc = (IRFunc*) inst;
                dump(context, "@");
                dump(context, irFunc->mangledName.Buffer());
            }
            break;

        default:
            {
                UInt id = getID(context, inst);
                if (id)
                {
                    dump(context, "%");
                    dump(context, id);
                }
                else
                {
                    dump(context, "_");
                }
            }
            break;
        }
    }

    static void dumpType(
        IRDumpContext*  context,
        IRType*         type);

    static void dumpDeclRef(
        IRDumpContext*          context,
        DeclRef<Decl> const&    declRef);

    static void dumpOperand(
        IRDumpContext*  context,
        IRValue*        inst)
    {
        // TODO: we should have a dedicated value for the `undef` case
        if (!inst)
        {
            dump(context, "undef");
            return;
        }

        switch (inst->op)
        {
        case kIROp_IntLit:
            dump(context, ((IRConstant*)inst)->u.intVal);
            return;

        case kIROp_FloatLit:
            dump(context, ((IRConstant*)inst)->u.floatVal);
            return;

        case kIROp_boolConst:
            dump(context, ((IRConstant*)inst)->u.intVal ? "true" : "false");
            return;

        case kIROp_TypeType:
            dumpType(context, (IRType*)inst);
            return;

        case kIROp_decl_ref:
            dump(context, "$\"");
            dumpDeclRef(context, ((IRDeclRef*)inst)->declRef);
            dump(context, "\"");
            return;

        default:
            break;
        }

        dumpID(context, inst);
    }

    static void dump(
        IRDumpContext*  context,
        Name*           name)
    {
        dump(context, getText(name).Buffer());
    }

    static void dumpVal(
        IRDumpContext*  context,
        Val*            val)
    {
        if(auto type = dynamic_cast<Type*>(val))
        {
            dumpType(context, type);
        }
        else if(auto constIntVal = dynamic_cast<ConstantIntVal*>(val))
        {
            dump(context, constIntVal->value);
        }
        else if(auto genericParamVal = dynamic_cast<GenericParamIntVal*>(val))
        {
            dumpDeclRef(context, genericParamVal->declRef);
        }
        else if(auto declaredSubtypeWitness = dynamic_cast<DeclaredSubtypeWitness*>(val))
        {
            dump(context, "DeclaredSubtypeWitness(");
            dumpType(context, declaredSubtypeWitness->sub);
            dump(context, ", ");
            dumpType(context, declaredSubtypeWitness->sup);
            dump(context, ", ");
            dumpDeclRef(context, declaredSubtypeWitness->declRef);
            dump(context, ")");
        }
        else if (auto proxyVal = dynamic_cast<IRProxyVal*>(val))
        {
            dumpOperand(context, proxyVal->inst);
        }
        else
        {
            dump(context, "???");
        }
    }

    static void dumpDeclRef(
        IRDumpContext*          context,
        DeclRef<Decl> const&    declRef)
    {
        auto decl = declRef.getDecl();

        auto parentDeclRef = declRef.GetParent();
        auto genericParentDeclRef = parentDeclRef.As<GenericDecl>();
        if (genericParentDeclRef)
        {
            if (genericParentDeclRef.getDecl()->inner.Ptr() == decl)
            {
                parentDeclRef = genericParentDeclRef.GetParent();
            }
            else
            {
                genericParentDeclRef = DeclRef<GenericDecl>();
            }
        }

        if(parentDeclRef.As<ModuleDecl>())
        {
            parentDeclRef = DeclRef<ContainerDecl>();
        }
        else if(parentDeclRef.As<GenericDecl>())
        {
            parentDeclRef = DeclRef<ContainerDecl>();
        }

        if(parentDeclRef)
        {
            dumpDeclRef(context, parentDeclRef);
            dump(context, ".");
        }
        dump(context, decl->getName());
        if (auto genericTypeConstraintDecl = dynamic_cast<GenericTypeConstraintDecl*>(decl))
        {
            dump(context, "{");
            dumpType(context, genericTypeConstraintDecl->sub);
            dump(context, " : ");
            dumpType(context, genericTypeConstraintDecl->sup);
            dump(context, "}");
        }
        else if (auto inheritanceDecl = dynamic_cast<InheritanceDecl*>(decl))
        {
            dump(context, "{ _ : ");
            dumpType(context, inheritanceDecl->base);
            dump(context, "}");
        }

        if(genericParentDeclRef)
        {
            auto subst = declRef.substitutions.As<GenericSubstitution>();
            if( !subst || subst->genericDecl != genericParentDeclRef.getDecl() )
            {
                // No actual substitutions in place here
                dump(context, "<>");
            }
            else
            {
                auto args = subst->args;
                bool first = true;
                dump(context, "<");
                for(auto aa : args)
                {
                    if(!first) dump(context, ",");
                    dumpVal(context, aa);
                    first = false;
                }
                dump(context, ">");
            }
        }
    }

    static void dumpType(
        IRDumpContext*  context,
        IRType*         type)
    {
        if (!type)
        {
            dump(context, "_");
            return;
        }

        if(auto funcType = type->As<FuncType>())
        {
            UInt paramCount = funcType->getParamCount();
            dump(context, "(");
            for( UInt pp = 0; pp < paramCount; ++pp )
            {
                if(pp != 0) dump(context, ", ");
                dumpType(context, funcType->getParamType(pp));
            }
            dump(context, ") -> ");
            dumpType(context, funcType->getResultType());
        }
        else if(auto arrayType = type->As<ArrayExpressionType>())
        {
            dumpType(context, arrayType->baseType);
            dump(context, "[");
            if(auto elementCount = arrayType->ArrayLength)
            {
                dumpVal(context, elementCount);
            }
            dump(context, "]");
        }
        else if(auto declRefType = type->As<DeclRefType>())
        {
            dumpDeclRef(context, declRefType->declRef);
        }
        else if(auto groupSharedType = type->As<GroupSharedType>())
        {
            dump(context, "@ThreadGroup ");
            dumpType(context, groupSharedType->valueType);
        }
        else
        {
            // Need a default case here
            dump(context, "???");
        }

#if 0
        auto op = type->op;
        auto opInfo = kIROpInfos[op];

        switch (op)
        {
        case kIROp_StructType:
            dumpID(context, type);
            break;

        default:
            {
                dump(context, opInfo.name);
                UInt argCount = type->getArgCount();

                if (argCount > 1)
                {
                    dump(context, "<");
                    for (UInt aa = 1; aa < argCount; ++aa)
                    {
                        if (aa != 1) dump(context, ",");
                        dumpOperand(context, type->getArg(aa));

                    }
                    dump(context, ">");
                }
            }
            break;
        }
#endif
    }

    static void dumpInstTypeClause(
        IRDumpContext*  context,
        IRType*         type)
    {
        dump(context, "\t: ");
        dumpType(context, type);

    }

    static void dumpInst(
        IRDumpContext*  context,
        IRInst*         inst);

    static void dumpChildrenRaw(
        IRDumpContext*  context,
        IRBlock*        block)
    {
        for (auto ii = block->firstInst; ii; ii = ii->getNextInst())
        {
            dumpInst(context, ii);
        }
    }

    static void dumpBlock(
        IRDumpContext*  context,
        IRBlock*        block)
    {
        context->indent--;
        dump(context, "block ");
        dumpID(context, block);

        if( block->getFirstParam() )
        {
            dump(context, "(\n");
            context->indent += 2;
            for (auto pp = block->getFirstParam(); pp; pp = pp->getNextParam())
            {
                if (pp != block->getFirstParam())
                    dump(context, ",\n");

                dumpIndent(context);
                dump(context, "param ");
                dumpID(context, pp);
                dumpInstTypeClause(context, pp->getType());
            }
            context->indent -= 2;
            dump(context, ")");
        }
        dump(context, ":\n");
        context->indent++;

        dumpChildrenRaw(context, block);
    }
#if 0
    static void dumpChildrenRaw(
        IRDumpContext*  context,
        IRFunc*         func)
    {
        for (auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock())
        {
            dumpBlock(context, bb);
        }
    }

    static void dumpChildren(
        IRDumpContext*  context,
        IRFunc*         func)
    {
        dumpIndent(context);
        dump(context, "{\n");
        context->indent++;
        dumpChildrenRaw(context, func);
        context->indent--;
        dumpIndent(context);
        dump(context, "}\n");
    }
#endif
    static void dumpInst(
        IRDumpContext*  context,
        IRInst*         inst)
    {
        if (!inst)
        {
            dumpIndent(context);
            dump(context, "<null>");
            return;
        }

        auto op = inst->op;

        // There are several ops we want to special-case here,
        // so that they will be more pleasant to look at.
        //
#if 0
        switch (op)
        {
        case kIROp_Module:
            dumpIndent(context);
            dump(context, "module\n");
            dumpChildren(context, inst);
            return;

        case kIROp_Func:
            {
                IRFunc* func = (IRFunc*)inst;
                dump(context, "\n");
                dumpIndent(context);
                dump(context, "func ");
                dumpID(context, func);
                dumpInstTypeClause(context, func->getType());
                dump(context, "\n");

                dumpIndent(context);
                dump(context, "{\n");
                context->indent++;

                for (auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock())
                {
                    if (bb != func->getFirstBlock())
                        dump(context, "\n");
                    dumpInst(context, bb);
                }

                context->indent--;
                dump(context, "}\n");
            }
            return;

        case kIROp_TypeType:
        case kIROp_Param:
        case kIROp_IntLit:
        case kIROp_FloatLit:
        case kIROp_boolConst:
            // Don't dump here
            return;

        case kIROp_Block:
            {
                IRBlock* block = (IRBlock*)inst;

                context->indent--;
                dump(context, "block ");
                dumpID(context, block);

                if( block->getFirstParam() )
                {
                    dump(context, "(");
                    context->indent++;
                    for (auto pp = block->getFirstParam(); pp; pp = pp->getNextParam())
                    {
                        if (pp != block->getFirstParam())
                            dump(context, ",\n");

                        dumpIndent(context);
                        dump(context, "param ");
                        dumpID(context, pp);
                        dumpInstTypeClause(context, pp->getType());
                    }
                    context->indent--;
                    dump(context, ")\n");
                }
                dump(context, ":\n");
                context->indent++;

                dumpChildrenRaw(context, block);
            }
            return;

        default:
            break;
        }
#endif

#if 0
        // We also want to special-case based on the *type*
        // of the instruction
        auto type = inst->getType();
        if (type && type->op == kIROp_TypeType)
        {
            // We probably don't want to print most types
            // when producing "friendly" output.
            switch (type->op)
            {
            case kIROp_StructType:
                break;

            default:
                return;
            }
        }
#endif


        // Okay, we have a seemingly "ordinary" op now
        dumpIndent(context);

        auto opInfo = &kIROpInfos[op];
        auto type = inst->getType();

        if (!type)
        {
            // No result, okay...
        }
        else
        {
            auto basicType = type->As<BasicExpressionType>();
            if (basicType && basicType->baseType == BaseType::Void)
            {
                // No result, okay...
            }
            else
            {
                dump(context, "let  ");
                dumpID(context, inst);
                dumpInstTypeClause(context, type);
                dump(context, "\t= ");
            }
        }

        dump(context, opInfo->name);

        uint32_t argCount = inst->argCount;
        dump(context, "(");
        for (uint32_t ii = 0; ii < argCount; ++ii)
        {
            if (ii != 0)
                dump(context, ", ");

            auto argVal = inst->getArgs()[ii].usedValue;

            dumpOperand(context, argVal);
        }
        dump(context, ")");

        dump(context, "\n");
    }

    void dumpGenericSignature(
        IRDumpContext*  context,
        GenericDecl*    genericDecl)
    {
        for( auto pp = genericDecl->ParentDecl; pp; pp = pp->ParentDecl )
        {
            if( auto genericAncestor = dynamic_cast<GenericDecl*>(pp) )
            {
                dumpGenericSignature(context, genericAncestor);
                break;
            }
        }

        dump(context, " <");
        bool first = true;
        for (auto mm : genericDecl->Members)
        {

            if( auto typeParamDecl = mm.As<GenericTypeParamDecl>() )
            {
                if (!first) dump(context, ", ");
                dumpDeclRef(context, makeDeclRef(typeParamDecl.Ptr()));
                first = false;
            }
            else if( auto valueParamDecl = mm.As<GenericTypeParamDecl>() )
            {
                if (!first) dump(context, ", ");
                dumpDeclRef(context, makeDeclRef(valueParamDecl.Ptr()));
                first = false;
            }
        }
        first = true;
        for (auto mm : genericDecl->Members)
        {
            if( auto constraintDecl = mm.As<GenericTypeConstraintDecl>() )
            {
                if (!first) dump(context, ", ");
                else dump(context, " where ");

                dumpType(context, constraintDecl->sub);
                dump(context, " : ");
                dumpType(context, constraintDecl->sup);
                first = false;
            }
        }
        dump(context, ">");
    }

    void dumpIRFunc(
        IRDumpContext*  context,
        IRFunc*         func)
    {

        for( auto dd = func->firstDecoration; dd; dd = dd->next )
        {
            switch( dd->op )
            {
            case kIRDecorationOp_Target:
                {
                    auto decoration = (IRTargetDecoration*) dd;

                    dump(context, "\n");
                    dumpIndent(context);
                    dump(context, "[target(");
                    dump(context, decoration->targetName.Buffer());
                    dump(context, ")]");
                }
                break;

            }
        }

        dump(context, "\n");
        dumpIndent(context);
        dump(context, "ir_func ");
        dumpID(context, func);

        if (func->genericDecl)
        {
            dump(context, " ");
            dumpGenericSignature(context, func->genericDecl);
        }

        dumpInstTypeClause(context, func->getType());

        if (!func->getFirstBlock())
        {
            // Just a declaration.
            dump(context, ";\n");
            return;
        }

        dump(context, "\n");

        dumpIndent(context);
        dump(context, "{\n");
        context->indent++;

        for (auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock())
        {
            if (bb != func->getFirstBlock())
                dump(context, "\n");
            dumpBlock(context, bb);
        }

        context->indent--;
        dump(context, "}\n");
    }

    void dumpIRGlobalVar(
        IRDumpContext*  context,
        IRGlobalVar*    var)
    {
        dump(context, "\n");
        dumpIndent(context);
        dump(context, "ir_global_var ");
        dumpID(context, var);
        dumpInstTypeClause(context, var->getType());

        // TODO: deal with the case where a global
        // might have embedded initialization logic.

        dump(context, ";\n");
    }

    void dumpIRWitnessTableEntry(
        IRDumpContext*          context,
        IRWitnessTableEntry*    entry)
    {
        dump(context, "witness_table_entry(");
        dumpOperand(context, entry->requirementKey.usedValue);
        dump(context, ",");
        dumpOperand(context, entry->satisfyingVal.usedValue);
        dump(context, ")\n");
    }

    void dumpIRWitnessTable(
        IRDumpContext*  context,
        IRWitnessTable* witnessTable)
    {
        dump(context, "\n");
        dumpIndent(context);
        dump(context, "ir_witness_table ");
        dumpID(context, witnessTable);
        dump(context, "\n{\n");
        context->indent++;

        for (auto entry : witnessTable->entries)
        {
            dumpIRWitnessTableEntry(context, entry);
        }

        context->indent--;
        dump(context, "}\n");
    }

    void dumpIRGlobalValue(
        IRDumpContext*  context,
        IRGlobalValue*  value)
    {
        switch (value->op)
        {
        case kIROp_Func:
            dumpIRFunc(context, (IRFunc*)value);
            break;

        case kIROp_global_var:
            dumpIRGlobalVar(context, (IRGlobalVar*)value);
            break;

        case kIROp_witness_table:
            dumpIRWitnessTable(context, (IRWitnessTable*)value);
            break;

        default:
            dump(context, "???\n");
            break;
        }
    }

    void dumpIRModule(
        IRDumpContext*  context,
        IRModule*       module)
    {
        for( auto gv = module->getFirstGlobalValue(); gv; gv = gv->getNextValue() )
        {
            dumpIRGlobalValue(context, gv);
        }
    }

    void printSlangIRAssembly(StringBuilder& builder, IRModule* module)
    {
        IRDumpContext context;
        context.builder = &builder;
        context.indent = 0;

        dumpIRModule(&context, module);
    }

    String getSlangIRAssembly(IRModule* module)
    {
        StringBuilder sb;
        printSlangIRAssembly(sb, module);
        return sb;
    }

    void dumpIR(IRModule* module)
    {
        String ir = getSlangIRAssembly(module);
        fprintf(stderr, "%s\n", ir.Buffer());
        fflush(stderr);
    }


    //
    //
    //

    void IRValue::replaceUsesWith(IRValue* other)
    {
        // We will walk through the list of uses for the current
        // instruction, and make them point to the other inst.
        IRUse* ff = firstUse;

        // No uses? Nothing to do.
        if(!ff)
            return;

        IRUse* uu = ff;
        for(;;)
        {
            // The uses had better all be uses of this
            // instruction, or invariants are broken.
            assert(uu->usedValue == this);

            // Swap this use over to use the other value.
            uu->usedValue = other;

            // Try to move to the next use, but bail
            // out if we are at the last one.
            IRUse* next = uu->nextUse;
            if( !next )
                break;

            uu = next;
        }

        // We are at the last use (and there must
        // be at least one, because we handled
        // the case of an empty list earlier).
        assert(uu);

        // Our job at this point is to splice
        // our list of uses onto the other
        // value's uses.
        //
        // If the value already had uses, then
        // we need to patch our new list onto
        // the front.
        if( auto nn = other->firstUse )
        {
            uu->nextUse = nn;
            nn->prevLink = &uu->nextUse;
        }

        // No matter what, our list of
        // uses will become the start
        // of the list of uses for
        // `other`
        other->firstUse = ff;
        ff->prevLink = &other->firstUse;

        // And `this` will have no uses any more.
        this->firstUse = nullptr;
    }

    void IRValue::deallocate()
    {
#if 0
        // I'm going to intentionally leak here,
        // just to test that this is the source
        // of my heap-corruption crashes.
#else
        // Run destructor to be sure...
        this->~IRValue();

        // And then free the memory
        free((void*) this);
#endif
    }

    // Insert this instruction into the same basic block
    // as `other`, right before it.
    void IRInst::insertBefore(IRInst* other)
    {
        // Make sure this instruction has been removed from any previous parent
        this->removeFromParent();

        auto bb = other->getParentBlock();
        assert(bb);

        auto pp = other->getPrevInst();
        if( pp )
        {
            pp->next = this;
        }
        else
        {
            bb->firstInst = this;
        }

        this->prev = pp;
        this->next = other;
        this->parent = bb;

        other->prev = this;
    }

    // Remove this instruction from its parent block,
    // and then destroy it (it had better have no uses!)
    void IRInst::removeFromParent()
    {
        // If we don't currently have a parent, then
        // we are doing fine.
        if(!getParentBlock())
            return;

        auto bb = getParentBlock();
        auto pp = getPrevInst();
        auto nn = getNextInst();

        if(pp)
        {
            SLANG_ASSERT(pp->getParentBlock() == bb);
            pp->next = nn;
        }
        else
        {
            bb->firstInst = nn;
        }

        if(nn)
        {
            SLANG_ASSERT(nn->getParentBlock() == bb);
            nn->prev = pp;
        }
        else
        {
            bb->lastInst = pp;
        }

        prev = nullptr;
        next = nullptr;
        parent = nullptr;
    }

    void IRInst::removeArguments()
    {
        for( UInt aa = 0; aa < argCount; ++aa )
        {
            IRUse& use = getArgs()[aa];

            if(!use.usedValue)
                continue;

            // Need to unlink this use from the appropriate linked list.
            use.usedValue = nullptr;
            *use.prevLink = use.nextUse;
            use.prevLink = nullptr;
            use.nextUse = nullptr;
        }
    }

    // Remove this instruction from its parent block,
    // and then destroy it (it had better have no uses!)
    void IRInst::removeAndDeallocate()
    {
        removeFromParent();
        removeArguments();
        deallocate();
    }


    //
    // Legalization of entry points for GLSL:
    //

    IRGlobalVar* addGlobalVariable(
        IRModule*   module,
        Type*       valueType)
    {
        auto session = module->session;

        SharedIRBuilder shared;
        shared.module = module;
        shared.session = session;

        IRBuilder builder;
        builder.sharedBuilder = &shared;

        RefPtr<PtrType> ptrType = session->getPtrType(valueType);

        return builder.createGlobalVar(valueType);
    }

    void moveValueBefore(
        IRGlobalValue*  valueToMove,
        IRGlobalValue*  placeBefore)
    {
        valueToMove->removeFromParent();
        valueToMove->insertBefore(placeBefore);
    }

    // When scalarizing shader inputs/outputs for GLSL, we need a way
    // to refer to a conceptual "value" that might comprise multiple
    // IR-level values. We could in principle introduce tuple types
    // into the IR so that everything stays at the IR level, but
    // it seems easier to just layer it over the top for now.
    //
    // The `ScalarizedVal` type deals with the "tuple or single value?"
    // question, and also the "l-value or r-value?" question.
    struct ScalarizedValImpl : RefObject
    {};
    struct ScalarizedTupleValImpl;
    struct ScalarizedVal
    {
        enum class Flavor
        {
            // no value (null pointer)
            none,

            // A simple `IRValue*` that represents the actual value
            value,

            // An `IRValue*` that represents the address of the actual value
            address,

            // A `TupleValImpl` that represents zero or more `ScalarizedVal`s
            tuple,
        };

        // Create a value representing a simple value
        static ScalarizedVal value(IRValue* irValue)
        {
            ScalarizedVal result;
            result.flavor = Flavor::value;
            result.irValue = irValue;
            return result;
        }


        // Create a value representing an address
        static ScalarizedVal address(IRValue* irValue)
        {
            ScalarizedVal result;
            result.flavor = Flavor::address;
            result.irValue = irValue;
            return result;
        }

        static ScalarizedVal tuple(ScalarizedTupleValImpl* impl)
        {
            ScalarizedVal result;
            result.flavor = Flavor::tuple;
            result.impl = (ScalarizedValImpl*)impl;
            return result;
        }

        Flavor                      flavor = Flavor::none;
        IRValue*                    irValue = nullptr;
        RefPtr<ScalarizedValImpl>   impl;
    };

    // This is the case for a value that is a "tuple" of other values
    struct ScalarizedTupleValImpl : ScalarizedValImpl
    {
        struct Element
        {
            ScalarizedVal   val;
            DeclRef<Decl>   declRef;
        };

        RefPtr<Type>    type;
        List<Element>   elements;
    };

    struct GlobalVaryingDeclarator
    {
        enum class Flavor
        {
            array,
        };

        Flavor                      flavor;
        Val*                        elementCount;
        GlobalVaryingDeclarator*    next;
    };

    ScalarizedVal createSimpleGLSLGlobalVarying(
        IRBuilder*                  builder,
        Type*                       type,
        VarLayout*                  varLayout,
        TypeLayout*                 /*typeLayout*/,
        LayoutResourceKind          /*kind*/,
        GlobalVaryingDeclarator*    /*declarator*/)
    {
        // TODO: We might be creating an `in` or `out` variable based on
        // an `in out` function parameter. In this case we should
        // rewrite the `typeLayout` to only include the information
        // for the appropriate `kind`.
        //
        // TODO: actually, we should *always* be re-creating the layout,
        // because we need to apply any offsets from the parent...

        // TODO: If there are any `declarator`s, we need to unwrap
        // them here, and allow them to modify the type of the
        // variable that we declare.
        //
        // They should probably also affect how we return the
        // `ScalarizedVal`, since we need to reflect the AOS->SOA conversion.

        // TODO: detect when the layout represents a system input/output
        if( varLayout->systemValueSemantic.Length() != 0 )
        {
            // This variable represents a system input/output,
            // and we should probably handle that differently, right?
        }

        // Simple case: just create a global variable of the matching type,
        // and then use the value of the global as a replacement for the
        // value of the original parameter.
        //
        auto globalVariable = addGlobalVariable(builder->getModule(), type);
        moveValueBefore(globalVariable, builder->getFunc());
        builder->addLayoutDecoration(globalVariable, varLayout);
        return ScalarizedVal::address(globalVariable);
    }

    ScalarizedVal createGLSLGlobalVaryingsImpl(
        IRBuilder*                  builder,
        Type*                       type,
        VarLayout*                  varLayout,
        TypeLayout*                 typeLayout,
        LayoutResourceKind          kind,
        GlobalVaryingDeclarator*    declarator)
    {
        if( type->As<BasicExpressionType>() )
        {
            return createSimpleGLSLGlobalVarying(builder, type, varLayout, typeLayout, kind, declarator);
        }
        else if( type->As<VectorExpressionType>() )
        {
            return createSimpleGLSLGlobalVarying(builder, type, varLayout, typeLayout, kind, declarator);
        }
        else if( type->As<MatrixExpressionType>() )
        {
            // TODO: a matrix-type varying should probably be handled like an array of rows
            return createSimpleGLSLGlobalVarying(builder, type, varLayout, typeLayout, kind, declarator);
        }
        else if( auto arrayType = type->As<ArrayExpressionType>() )
        {
            // We will need to SOA-ize any nested types.

            auto elementType = arrayType->baseType;
            auto elementCount = arrayType->ArrayLength;
            auto arrayLayout = dynamic_cast<ArrayTypeLayout*>(typeLayout);
            SLANG_ASSERT(arrayLayout);
            auto elementTypeLayout = arrayLayout->elementTypeLayout;

            GlobalVaryingDeclarator arrayDeclarator;
            arrayDeclarator.flavor = GlobalVaryingDeclarator::Flavor::array;
            arrayDeclarator.elementCount = elementCount;
            arrayDeclarator.next = declarator;

            return createGLSLGlobalVaryingsImpl(
                builder,
                elementType,
                varLayout,
                elementTypeLayout,
                kind,
                &arrayDeclarator);
        }
        else if( auto declRefType = type->As<DeclRefType>() )
        {
            auto declRef = declRefType->declRef;
            if( auto structDeclRef = declRef.As<StructDecl>() )
            {
                // This is either a user-defined struct, or a builtin type.
                // TODO: exclude resource types here.

                // We need to recurse down into the individual fields,
                // and generate a variable for each of them.

                // Note: we can use the presence of a `StructTypeLayout` as
                // a quick way to reject a bunch of types that aren't actually `struct`s
                auto structTypeLayout = dynamic_cast<StructTypeLayout*>(typeLayout);
                if( structTypeLayout )
                {
                    RefPtr<ScalarizedTupleValImpl> tupleValImpl = new ScalarizedTupleValImpl();
                    tupleValImpl->type = type;

                    // Okay, we want to walk through the fields here, and
                    // generate one variable for each.
                    for( auto ff : structTypeLayout->fields )
                    {
                        auto fieldVal = createGLSLGlobalVaryingsImpl(
                            builder,
                            ff->typeLayout->type,
                            ff,
                            ff->typeLayout,
                            kind,
                            declarator);

                        ScalarizedTupleValImpl::Element element;
                        element.val = fieldVal;
                        element.declRef = ff->varDecl;

                        tupleValImpl->elements.Add(element);
                    }

                    return ScalarizedVal::tuple(tupleValImpl);
                }
            }
        }

        // Default case is to fall back on the simple behavior
        return createSimpleGLSLGlobalVarying(builder, type, varLayout, typeLayout, kind, declarator);
    }

    ScalarizedVal createGLSLGlobalVaryings(
        IRBuilder*          builder,
        Type*               type,
        VarLayout*          layout,
        LayoutResourceKind  kind)
    {
        return createGLSLGlobalVaryingsImpl(builder, type, layout, layout->typeLayout, kind, nullptr);
    }

    ScalarizedVal extractField(
        IRBuilder*              builder,
        ScalarizedVal const&    val,
        UInt                    fieldIndex,
        DeclRef<Decl>           fieldDeclRef)
    {
        switch( val.flavor )
        {
        case ScalarizedVal::Flavor::value:
            return ScalarizedVal::value(
                builder->emitFieldExtract(
                    GetType(fieldDeclRef.As<VarDeclBase>()),
                    val.irValue,
                    builder->getDeclRefVal(fieldDeclRef)));

        case ScalarizedVal::Flavor::address:
            return ScalarizedVal::address(
                builder->emitFieldAddress(
                    GetType(fieldDeclRef.As<VarDeclBase>()),
                    val.irValue,
                    builder->getDeclRefVal(fieldDeclRef)));

        case ScalarizedVal::Flavor::tuple:
            {
                auto tupleVal = val.impl.As<ScalarizedTupleValImpl>();
                return tupleVal->elements[fieldIndex].val;
            }

        default:
            SLANG_UNEXPECTED("unimplemented");
            UNREACHABLE_RETURN(ScalarizedVal());
        }

    }

    void assign(
        IRBuilder*              builder,
        ScalarizedVal const&    left,
        ScalarizedVal const&    right)
    {
        switch( left.flavor )
        {
        case ScalarizedVal::Flavor::address:
            switch( right.flavor )
            {
            case ScalarizedVal::Flavor::value:
                {
                    builder->emitStore(left.irValue, right.irValue);
                }
                break;

            default:
                SLANG_UNEXPECTED("unimplemented");
                break;
            }
            break;

        case ScalarizedVal::Flavor::tuple:
            {
                // We have a tuple, so we are going to need to try and assign
                // to each of its constituent fields.
                auto leftTupleVal = left.impl.As<ScalarizedTupleValImpl>();
                UInt elementCount = leftTupleVal->elements.Count();

                for( UInt ee = 0; ee < elementCount; ++ee )
                {
                    auto rightElementVal = extractField(
                        builder,
                        right,
                        ee,
                        leftTupleVal->elements[ee].declRef);
                    assign(builder, leftTupleVal->elements[ee].val, rightElementVal);
                }
            }
            break;

        default:
            SLANG_UNEXPECTED("unimplemented");
            break;
        }
    }

    IRValue* materializeValue(
        IRBuilder*              builder,
        ScalarizedVal const&    val)
    {
        switch( val.flavor )
        {
        case ScalarizedVal::Flavor::value:
            return val.irValue;

        case ScalarizedVal::Flavor::address:
            {
                auto loadInst = builder->emitLoad(val.irValue);
                return loadInst;
            }
            break;

        case ScalarizedVal::Flavor::tuple:
            {
                auto tupleVal = val.impl.As<ScalarizedTupleValImpl>();
                UInt elementCount = tupleVal->elements.Count();

                List<IRValue*> elementVals;
                for( UInt ee = 0; ee < elementCount; ++ee )
                {
                    auto elementVal = materializeValue(builder, tupleVal->elements[ee].val);
                    elementVals.Add(elementVal);
                }

                return builder->emitConstructorInst(
                    tupleVal->type,
                    elementVals.Count(),
                    elementVals.Buffer());
            }
            break;

        default:
            SLANG_UNEXPECTED("unimplemented");
            break;
        }
    }

    void legalizeEntryPointForGLSL(
        Session*                session,
        IRFunc*                 func,
        EntryPointLayout*       entryPointLayout)
    {
        auto module = func->parentModule;

        // We require that the entry-point function has no uses,
        // because otherwise we'd invalidate the signature
        // at all existing call sites.
        //
        // TODO: the right thing to do here is to split any
        // function that both gets called as an entry point
        // and as an ordinary function.
        assert(!func->firstUse);

        // We create a dummy IR builder, since some of
        // the functions require it.
        //
        // TODO: make some of these free functions...
        //
        SharedIRBuilder shared;
        shared.module = module;
        shared.session = session;
        IRBuilder builder;
        builder.sharedBuilder = &shared;
        builder.curFunc = func;

        // We will start by looking at the return type of the
        // function, because that will enable us to do an
        // early-out check to avoid more work.
        //
        // Specifically, we need to check if the function has
        // a `void` return type, because there is no work
        // to be done on its return value in that case.
        auto resultType = func->getResultType();
        if( resultType->Equals(session->getVoidType()) )
        {
            // In this case, the function doesn't return a value
            // so we don't need to transform its `return` sites.
            //
            // We can also use this opportunity to quickly
            // check if the function has any parameters, and if
            // it doesn't use the chance to bail out immediately.
            if( func->getParamCount() == 0 )
            {
                // This function is already legal for GLSL
                // (at least in terms of parameter/result signature),
                // so we won't bother doing anything at all.
                return;
            }

            // If the function does have parameters, then we need
            // to let the logic later in this function handle them.
        }
        else
        {
            // Function returns a value, so we need
            // to introduce a new global variable
            // to hold that value, and then replace
            // any `returnVal` instructions with
            // code to write to that variable.

            auto resultGlobal = createGLSLGlobalVaryings(
                &builder,
                resultType,
                entryPointLayout->resultLayout,
                LayoutResourceKind::FragmentOutput);

            for( auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock() )
            {
                // TODO: This is silly, because we are looking at every instruction,
                // when we know that a `returnVal` should only ever appear as a
                // terminator...
                for( auto ii = bb->getFirstInst(); ii; ii = ii->getNextInst() )
                {
                    if(ii->op != kIROp_ReturnVal)
                        continue;

                    IRReturnVal* returnInst = (IRReturnVal*) ii;
                    IRValue* returnValue = returnInst->getVal();

                    // Make sure we add these instructions to the right block
                    builder.curBlock = bb;

                    // Write to our global variable(s) from the value being returned.
                    assign(&builder, resultGlobal, ScalarizedVal::value(returnValue));

                    // Emit a `returnVoid` to end the block
                    auto returnVoid = builder.emitReturn();

                    // Remove the old `returnVal` instruction.
                    returnInst->removeAndDeallocate();

                    // Make sure to resume our iteration at an
                    // appropriate instruciton, since we deleted
                    // the one we had been using.
                    ii = returnVoid;
                }
            }
        }

        // Next we will walk through any parameters of the entry-point function,
        // and turn them into global variables.
        if( auto firstBlock = func->getFirstBlock() )
        {
            UInt paramCounter = 0;
            for( auto pp = firstBlock->getFirstParam(); pp; pp = pp->getNextParam() )
            {
                UInt paramIndex = paramCounter++;

                // We assume that the entry-point layout includes information
                // on each parameter, and that these arrays are kept aligned.
                // Note that this means that any transformations that mess
                // with function signatures will need to also update layout info...
                //
                assert(entryPointLayout->fields.Count() > paramIndex);
                auto paramLayout = entryPointLayout->fields[paramIndex];

                // We need to create a global variable that will replace the parameter.
                // It seems superficially obvious that the variable should have
                // the same type as the parameter.
                // However, if the parameter was a pointer, in order to
                // support `out` or `in out` parameter passing, we need
                // to be sure to allocate a variable of the pointed-to
                // type instead.
                //
                // We also need to replace uses of the parameter with
                // uses of the variable, and the exact logic there
                // will differ a bit between the pointer and non-pointer
                // cases.
                auto paramType = pp->getType();

                // Any initialization code we insert nees to be at the start
                // of the block:
                builder.curBlock = firstBlock;
                builder.insertBeforeInst = firstBlock->getFirstInst();

                // Is the parameter type a special pointer type
                // that indicates the parameter is used for `out`
                // or `inout` access?
                if(auto paramPtrType = paramType->As<OutTypeBase>() )
                {
                    // Okay, we have the more interesting case here,
                    // where the parameter was being passed by reference.
                    // We are going to create a local variable of the appropriate
                    // type, which will replace the parameter, along with
                    // one or more global variables for the actual input/output.

                    auto valueType = paramPtrType->getValueType();

                    auto localVariable = builder.emitVar(valueType);
                    auto localVal = ScalarizedVal::address(localVariable);

                    if( auto inOutType = paramPtrType->As<InOutType>() )
                    {
                        // In the `in out` case we need to declare two
                        // sets of global variables: one for the `in`
                        // side and one for the `out` side.
                        auto globalInputVal = createGLSLGlobalVaryings(&builder, valueType, paramLayout, LayoutResourceKind::VertexInput);

                        assign(&builder, localVal, globalInputVal);
                    }

                    // Any places where the original parameter was used inside
                    // the function body should instead use the new local variable.
                    // Since the parameter was a pointer, we use the variable instruction
                    // itself (which is an `alloca`d pointer) directly:
                    pp->replaceUsesWith(localVariable);

                    // We also need one or more global variabels to write the output to
                    // when the function is done. We create them here.
                    auto globalOutputVal = createGLSLGlobalVaryings(&builder, valueType, paramLayout, LayoutResourceKind::FragmentOutput);

                    // Now we need to iterate over all the blocks in the function looking
                    // for any `return*` instructions, so that we can write to the output variable
                    for( auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock() )
                    {
                        auto terminatorInst = bb->getLastInst();
                        if(!terminatorInst)
                            continue;

                        switch( terminatorInst->op )
                        {
                        default:
                            continue;

                        case kIROp_ReturnVal:
                        case kIROp_ReturnVoid:
                            break;
                        }

                        builder.curBlock = bb;
                        builder.insertBeforeInst = terminatorInst;

                        assign(&builder, globalOutputVal, localVal);
                    }
                }
                else
                {
                    // This is the "easy" case where the parameter wasn't
                    // being passed by reference. We start by just creating
                    // one or more global variables to represent the parameter,
                    // and attach the required layout information to it along
                    // the way.

                    auto globalValue = createGLSLGlobalVaryings(&builder, paramType, paramLayout, LayoutResourceKind::VertexInput);

                    // Next we need to replace uses of the parameter with
                    // references to the variable(s). We are going to do that
                    // somewhat naively, by simply materializing the
                    // variables at the start.
                    IRValue* materialized = materializeValue(&builder, globalValue);

                    pp->replaceUsesWith(materialized);
                }
            }

            // At this point we should have eliminated all uses of the
            // parameters of the entry block. Also, our control-flow
            // rules mean that the entry block cannot be the target
            // of any branches in the code, so there can't be
            // any control-flow ops that try to match the parameter
            // list.
            //
            // We can safely go through and destroy the parameters
            // themselves, and then clear out the parameter list.
            for( auto pp = firstBlock->getFirstParam(); pp; )
            {
                auto next = pp->getNextParam();
                pp->deallocate();
                pp = next;
            }
            firstBlock->firstParam = nullptr;
            firstBlock->lastParam = nullptr;
        }

        // Finally, we need to patch up the type of the entry point,
        // because it is no longer accurate.

        RefPtr<FuncType> voidFuncType = new FuncType();
        voidFuncType->setSession(session);
        voidFuncType->resultType = session->getVoidType();
        func->type = voidFuncType;

        // TODO: we should technically be constructing
        // a new `EntryPointLayout` here to reflect
        // the way that things have been moved around.
    }

    // Needed for lookup up entry-point layouts.
    //
    // TODO: maybe arrange so that codegen is driven from the layout layer
    // instead of the input/request layer.
    EntryPointLayout* findEntryPointLayout(
        ProgramLayout*      programLayout,
        EntryPointRequest*  entryPointRequest);

    struct IRSpecSymbol : RefObject
    {
        IRGlobalValue*          irGlobalValue;
        RefPtr<IRSpecSymbol>    nextWithSameName;
    };

    struct IRSharedSpecContext
    {
        // The specialized module we are building
        IRModule*   module;

        // The original, unspecialized module we are copying
        IRModule*   originalModule;

        // A map from mangled symbol names to zero or
        // more global IR values that have that name,
        // in the *original* module.
        typedef Dictionary<String, RefPtr<IRSpecSymbol>> SymbolDictionary;
        SymbolDictionary symbols;

        // A map from values in the original IR module
        // to their equivalent in the cloned module.
        typedef Dictionary<IRValue*, IRValue*> ClonedValueDictionary;
        ClonedValueDictionary clonedValues;

        SharedIRBuilder sharedBuilderStorage;
        IRBuilder builderStorage;
    };

    struct IRSpecContextBase
    {
        IRSharedSpecContext* shared;

        IRSharedSpecContext* getShared() { return shared; }

        IRModule* getModule() { return getShared()->module; }

        IRModule* getOriginalModule() { return getShared()->originalModule; }

        IRSharedSpecContext::SymbolDictionary& getSymbols() { return getShared()->symbols; }

        IRSharedSpecContext::ClonedValueDictionary& getClonedValues() { return getShared()->clonedValues; }

        // The IR builder to use for creating nodes
        IRBuilder*  builder;

        // A callback to be used when a value that is not registerd in `clonedValues`
        // is needed during cloning. This gives the subtype a chance to intercept
        // the operation and clone (or not) as needed.
        virtual IRValue* maybeCloneValue(IRValue* originalVal)
        {
            return originalVal;
        }

        // A callback used to clone (or not) types.
        virtual RefPtr<Type> maybeCloneType(Type* originalType)
        {
            return originalType;
        }

        // A callback used to clone (or not) a declaration reference
        virtual DeclRef<Decl> maybeCloneDeclRef(DeclRef<Decl> const& declRef)
        {
            return declRef;
        }
    };

    void registerClonedValue(
        IRSpecContextBase*  context,
        IRValue*    clonedValue,
        IRValue*    originalValue)
    {
        if(!originalValue)
            return;
        context->getClonedValues().Add(originalValue, clonedValue);
    }

    // Information on values to use when registering a cloned value
    struct IROriginalValuesForClone
    {
        IRValue*        originalVal = nullptr;
        IRSpecSymbol*   sym = nullptr;

        IROriginalValuesForClone() {}

        IROriginalValuesForClone(IRValue* originalValue)
            : originalVal(originalValue)
        {}

        IROriginalValuesForClone(IRSpecSymbol* symbol)
            : sym(symbol)
        {}
    };

    void registerClonedValue(
        IRSpecContextBase*              context,
        IRValue*                        clonedValue,
        IROriginalValuesForClone const& originalValues)
    {
        registerClonedValue(context, clonedValue, originalValues.originalVal);
        for( auto s = originalValues.sym; s; s = s->nextWithSameName )
        {
            registerClonedValue(context, clonedValue, s->irGlobalValue);
        }
    }

    void cloneDecorations(
        IRSpecContextBase*  context,
        IRValue*        clonedValue,
        IRValue*        originalValue)
    {
        for (auto dd = originalValue->firstDecoration; dd; dd = dd->next)
        {
            switch (dd->op)
            {
            case kIRDecorationOp_HighLevelDecl:
                {
                    auto originalDecoration = (IRHighLevelDeclDecoration*)dd;

                    context->builder->addHighLevelDeclDecoration(clonedValue, originalDecoration->decl);
                }
                break;

            case kIRDecorationOp_LoopControl:
                {
                    auto originalDecoration = (IRLoopControlDecoration*)dd;
                    auto newDecoration = context->builder->addDecoration<IRLoopControlDecoration>(clonedValue);
                    newDecoration->mode = originalDecoration->mode;
                }
                break;

            default:
                // Don't clone any decorations we don't understand.
                break;
            }
        }

        // TODO: implement this
    }

    struct IRSpecContext : IRSpecContextBase
    {
        // The code-generation target in use
        CodeGenTarget target;

        // A map from the mangled name of a global variable
        // to the layout to use for it.
        Dictionary<String, VarLayout*> globalVarLayouts;

        RefPtr<GlobalGenericParamSubstitution> subst;

        // Override the "maybe clone" logic so that we always clone
        virtual IRValue* maybeCloneValue(IRValue* originalVal) override;

        // Override teh "maybe clone" logic so that we carefully
        // clone any IR proxy values inside substitutions
        virtual DeclRef<Decl> maybeCloneDeclRef(DeclRef<Decl> const& declRef) override;

        virtual RefPtr<Type> maybeCloneType(Type* originalType) override;
    };


    IRGlobalValue* cloneGlobalValue(IRSpecContext* context, IRGlobalValue* originalVal);
    RefPtr<Substitutions> cloneSubstitutions(
        IRSpecContext*  context,
        Substitutions*  subst);

    RefPtr<Type> IRSpecContext::maybeCloneType(Type* originalType)
    {
        return originalType->Substitute(subst).As<Type>();
    }

    IRValue* IRSpecContext::maybeCloneValue(IRValue* originalValue)
    {
        switch (originalValue->op)
        {
        case kIROp_global_var:
        case kIROp_Func:
        case kIROp_witness_table:
            return cloneGlobalValue(this, (IRGlobalValue*) originalValue);

        case kIROp_boolConst:
            {
                IRConstant* c = (IRConstant*)originalValue;
                return builder->getBoolValue(c->u.intVal != 0);
            }
            break;


        case kIROp_IntLit:
            {
                IRConstant* c = (IRConstant*)originalValue;
                return builder->getIntValue(c->type, c->u.intVal);
            }
            break;

        case kIROp_FloatLit:
            {
                IRConstant* c = (IRConstant*)originalValue;
                return builder->getFloatValue(c->type, c->u.floatVal);
            }
            break;

        case kIROp_decl_ref:
            {
                IRDeclRef* od = (IRDeclRef*)originalValue;

                // if the declRef is one of the __generic_param decl being substituted by subst
                // return the substituted decl
                if (subst)
                {
                    if (od->declRef.getDecl() == subst->paramDecl)
                        return builder->getTypeVal(subst->actualType.As<Type>());
                    else if (auto genConstraint = od->declRef.As<GenericTypeConstraintDecl>())
                    {
                        // a decl-ref to GenericTypeConstraintDecl as a result of
                        // referencing a generic parameter type should be replaced with
                        // the actual witness table
                        if (genConstraint.getDecl()->ParentDecl == subst->paramDecl)
                        {
                            // find the witness table from subst
                            for (auto witness : subst->witnessTables)
                            {
                                if (witness.Key->EqualsVal(GetSup(genConstraint)))
                                {
                                    auto proxyVal = witness.Value.As<IRProxyVal>();
                                    SLANG_ASSERT(proxyVal);
                                    return proxyVal->inst;
                                }
                            }
                        }
                    }
                }
                auto declRef = maybeCloneDeclRef(od->declRef);
                return builder->getDeclRefVal(declRef);
            }
            break;
        case kIROp_TypeType:
            {
                IRValue* od = (IRValue*)originalValue;
                int ioDiff = 0;
                auto newType = od->type->SubstituteImpl(subst, &ioDiff);
                return builder->getTypeVal(newType.As<Type>());
            }
            break;
        default:
            SLANG_UNEXPECTED("no value registered for IR value");
            UNREACHABLE_RETURN(nullptr);
        }
    }

    RefPtr<Val> cloneSubstitutionArg(
        IRSpecContext*  context,
        Val*            val)
    {
        if (auto proxyVal = dynamic_cast<IRProxyVal*>(val))
        {
            auto newIRVal = context->maybeCloneValue(proxyVal->inst);

            RefPtr<IRProxyVal> newProxyVal = new IRProxyVal();
            newProxyVal->inst = newIRVal;
            return newProxyVal;
        }
        else if (auto type = dynamic_cast<Type*>(val))
        {
            return context->maybeCloneType(type);
        }
        else
        {
            return val;
        }
    }

    RefPtr<Substitutions> cloneSubstitutions(
        IRSpecContext*  context,
        Substitutions*  subst)
    {
        if (!subst)
            return nullptr;
        if (auto genSubst = dynamic_cast<GenericSubstitution*>(subst))
        {
            RefPtr<GenericSubstitution> newSubst = new GenericSubstitution();
            newSubst->outer = cloneSubstitutions(context, subst->outer);
            newSubst->genericDecl = genSubst->genericDecl;

            for (auto arg : genSubst->args)
            {
                auto newArg = cloneSubstitutionArg(context, arg);
                newSubst->args.Add(arg);
            }
            return newSubst;
        }
        else if (auto thisSubst = dynamic_cast<ThisTypeSubstitution*>(subst))
        {
            RefPtr<ThisTypeSubstitution> newSubst = new ThisTypeSubstitution();
            newSubst->sourceType = thisSubst->sourceType;
            newSubst->outer = cloneSubstitutions(context, subst->outer);
            return newSubst;
        }
        else if (auto genTypeSubst = dynamic_cast<GlobalGenericParamSubstitution*>(subst))
        {
            RefPtr<GlobalGenericParamSubstitution> newSubst = new GlobalGenericParamSubstitution();
            newSubst->actualType = genTypeSubst->actualType;
            newSubst->paramDecl = genTypeSubst->paramDecl;
            newSubst->witnessTables = genTypeSubst->witnessTables;
            newSubst->outer = cloneSubstitutions(context, subst->outer);
            return newSubst;
        }
        else
            SLANG_UNREACHABLE("unimplemented cloneSubstitution");
        UNREACHABLE_RETURN(nullptr);
    }

    DeclRef<Decl> IRSpecContext::maybeCloneDeclRef(DeclRef<Decl> const& declRef)
    {
        // Un-specialized decl? Nothing to do.
        if (!declRef.substitutions)
            return declRef;

        DeclRef<Decl> newDeclRef = declRef;

        // Scan through substitutions and clone as needed.
        //
        // TODO: this is wasteful since we clone *everything*
        newDeclRef.substitutions = cloneSubstitutions(this, declRef.substitutions);

        return newDeclRef;

    }


    IRValue* cloneValue(
        IRSpecContextBase*  context,
        IRValue*        originalValue)
    {
        IRValue* clonedValue = nullptr;
        if (context->getClonedValues().TryGetValue(originalValue, clonedValue))
            return clonedValue;

        return context->maybeCloneValue(originalValue);
    }

    void cloneInst(
        IRSpecContextBase*  context,
        IRBuilder*      builder,
        IRInst*         originalInst)
    {
        switch (originalInst->op)
        {
        // TODO: are there any instruction types that need to be handled
        // specially here? That would be anything that has more state
        // than is visible in its operand list...
        case 0: // nothing yet
        default:
            {
                // The common case is that we just need to construct a cloned
                // instruction with the right number of operands, intialize
                // it, and then add it to the sequence.
                UInt argCount = originalInst->getArgCount();
                IRInst* clonedInst = createInstWithTrailingArgs<IRInst>(
                    builder, originalInst->op,
                    context->maybeCloneType(originalInst->type),
                    0, nullptr,
                    argCount, nullptr);
                builder->addInst(clonedInst);
                registerClonedValue(context, clonedInst, originalInst);

                cloneDecorations(context, clonedInst, originalInst);

                for (UInt aa = 0; aa < argCount; ++aa)
                {
                    IRValue* originalArg = originalInst->getArg(aa);
                    IRValue* clonedArg = cloneValue(context, originalArg);

                    clonedInst->getArgs()[aa].init(clonedInst, clonedArg);
                }
            }

            break;
        }
    }

    void cloneGlobalValueWithCodeCommon(
        IRSpecContextBase*      context,
        IRGlobalValueWithCode*  clonedValue,
        IRGlobalValueWithCode*  originalValue);

    IRGlobalVar* cloneGlobalVarImpl(
        IRSpecContext*  context,
        IRGlobalVar*    originalVar,
        IROriginalValuesForClone const& originalValues)
    {
        auto clonedVar = context->builder->createGlobalVar(context->maybeCloneType(originalVar->getType()->getValueType()));
        registerClonedValue(context, clonedVar, originalValues);

        auto mangledName = originalVar->mangledName;
        clonedVar->mangledName = mangledName;

        cloneDecorations(context, clonedVar, originalVar);

        VarLayout* layout = nullptr;
        if (context->globalVarLayouts.TryGetValue(mangledName, layout))
        {
            context->builder->addLayoutDecoration(clonedVar, layout);
        }

        // Clone any code in the body of the variable, since this
        // represents the initializer.
        cloneGlobalValueWithCodeCommon(
            context,
            clonedVar,
            originalVar);

        return clonedVar;
    }

    IRWitnessTable* cloneWitnessTableImpl(
        IRSpecContext*  context,
        IRWitnessTable* originalTable,
        IROriginalValuesForClone const& originalValues)
    {
        auto clonedTable = context->builder->createWitnessTable();
        registerClonedValue(context, clonedTable, originalValues);

        auto mangledName = originalTable->mangledName;
        clonedTable->mangledName = mangledName;

        cloneDecorations(context, clonedTable, originalTable);

        // Clone the entries in the witness table as well
        for( auto originalEntry : originalTable->entries )
        {
            auto clonedKey = context->maybeCloneValue(originalEntry->requirementKey.usedValue);
            auto clonedVal = context->maybeCloneValue(originalEntry->satisfyingVal.usedValue);
            /*auto clonedEntry = */context->builder->createWitnessTableEntry(
                clonedTable,
                clonedKey,
                clonedVal);
        }

        return clonedTable;
    }

    IRWitnessTable* cloneWitnessTableWithoutRegistering(
        IRSpecContext*  context,
        IRWitnessTable* originalTable)
    {
        return cloneWitnessTableImpl(context, originalTable, IROriginalValuesForClone());
    }

    void cloneGlobalValueWithCodeCommon(
        IRSpecContextBase*      context,
        IRGlobalValueWithCode*  clonedValue,
        IRGlobalValueWithCode*  originalValue)
    {
        // Next we are going to clone the actual code.
        IRBuilder builderStorage = *context->builder;
        IRBuilder* builder = &builderStorage;
        builder->curFunc = clonedValue;


        // We will walk through the blocks of the function, and clone each of them.
        //
        // We need to create the cloned blocks first, and then walk through them,
        // because blocks might be forward referenced (this is not possible
        // for other cases of instructions).
        for (auto originalBlock = originalValue->getFirstBlock();
            originalBlock;
            originalBlock = originalBlock->getNextBlock())
        {
            IRBlock* clonedBlock = builder->createBlock();
            clonedValue->addBlock(clonedBlock);
            registerClonedValue(context, clonedBlock, originalBlock);

            // We can go ahead and clone parameters here, while we are at it.
            builder->curBlock = clonedBlock;
            for (auto originalParam = originalBlock->getFirstParam();
                originalParam;
                originalParam = originalParam->getNextParam())
            {
                IRParam* clonedParam = builder->emitParam(
                    context->maybeCloneType(
                        originalParam->getType()));
                registerClonedValue(context, clonedParam, originalParam);
            }
        }

        // Okay, now we are in a good position to start cloning
        // the instructions inside the blocks.
        {
            IRBlock* ob = originalValue->getFirstBlock();
            IRBlock* cb = clonedValue->getFirstBlock();
            while (ob)
            {
                assert(cb);

                builder->curBlock = cb;
                for (auto oi = ob->getFirstInst(); oi; oi = oi->getNextInst())
                {
                    cloneInst(context, builder, oi);
                }

                ob = ob->getNextBlock();
                cb = cb->getNextBlock();
            }
        }

    }

    void cloneFunctionCommon(
        IRSpecContextBase*  context,
        IRFunc*         clonedFunc,
        IRFunc*         originalFunc)
    {
        // First clone all the simple properties.
        clonedFunc->mangledName = originalFunc->mangledName;
        clonedFunc->genericDecl = originalFunc->genericDecl;
        clonedFunc->type = context->maybeCloneType(originalFunc->type);

        cloneDecorations(context, clonedFunc, originalFunc);

        cloneGlobalValueWithCodeCommon(
            context,
            clonedFunc,
            originalFunc);

        // Shuffle the function to the end of the list, because
        // it needs to follow its dependencies.
        //
        // TODO: This isn't really a good requirement to place on the IR...
        clonedFunc->removeFromParent();
        clonedFunc->insertAtEnd(context->getModule());
    }

    IRFunc* specializeIRForEntryPoint(
        IRSpecContext*  context,
        EntryPointRequest*  entryPointRequest,
        EntryPointLayout*   entryPointLayout)
    {
        // Look up the IR symbol by name
        String mangledName = getMangledName(entryPointRequest->decl);
        RefPtr<IRSpecSymbol> sym;
        if (!context->getSymbols().TryGetValue(mangledName, sym))
        {
            SLANG_UNEXPECTED("no matching IR symbol");
            return nullptr;
        }

        // TODO: deal with the case where we might
        // have multiple versions...

        auto globalValue = sym->irGlobalValue;
        if (globalValue->op != kIROp_Func)
        {
            SLANG_UNEXPECTED("expected an IR function");
            return nullptr;
        }
        auto originalFunc = (IRFunc*)globalValue;

        // Create a clone for the IR function
        auto clonedFunc = context->builder->createFunc();

        // Note: we do *not* register this cloned declaration
        // as the cloned value for the original symbol.
        // This is kind of a kludge, but it ensures that
        // in the unlikely case that the function is both
        // used as an entry point and a callable function
        // (yes, this would imply recursion...) we actually
        // have two copies, which lets us arbitrarily
        // transform the entry point to meet target requirements.
        //
        // TODO: The above statement is kind of bunk, though,
        // because both versions of the function would have
        // the same mangled name... :(

        // We need to clone all the properties of the original
        // function, including any blocks, their parameters,
        // and their instructions.
        cloneFunctionCommon(context, clonedFunc, originalFunc);

        // We need to attach the layout information for
        // the entry point to this declaration, so that
        // we can use it to inform downstream code emit.
        context->builder->addLayoutDecoration(
            clonedFunc,
            entryPointLayout);

        // We will also go on and attach layout information
        // to the function parameters, so that we have it
        // available directly on the parameters, rather
        // than having to look it up on the original entry-point layout.
        if( auto firstBlock = clonedFunc->getFirstBlock() )
        {
            UInt paramLayoutCount = entryPointLayout->fields.Count();
            UInt paramCounter = 0;
            for( auto pp = firstBlock->getFirstParam(); pp; pp = pp->getNextParam() )
            {
                UInt paramIndex = paramCounter++;
                if( paramIndex < paramLayoutCount )
                {
                    auto paramLayout = entryPointLayout->fields[paramIndex];
                    context->builder->addLayoutDecoration(
                        pp,
                        paramLayout);
                }
                else
                {
                    SLANG_UNEXPECTED("too many parameters");
                }
            }
        }

        return clonedFunc;
    }

    IRFunc* cloneSimpleFuncWithoutRegistering(IRSpecContextBase* context, IRFunc* originalFunc)
    {
        auto clonedFunc = context->builder->createFunc();
        cloneFunctionCommon(context, clonedFunc, originalFunc);
        return clonedFunc;
    }

    // Get a string form of the target so that we can
    // use it to match against target-specialization modifiers
    //
    // TODO: We shouldn't be using strings for this.
    String getTargetName(IRSpecContext* context)
    {
        switch( context->target )
        {
        case CodeGenTarget::HLSL:
            return "hlsl";

        case CodeGenTarget::GLSL:
            return "glsl";

        default:
            SLANG_UNEXPECTED("unhandled case");
            UNREACHABLE_RETURN("unknown");
        }
    }

    // How specialized is a given declaration for the chosen target?
    enum class TargetSpecializationLevel
    {
        specializedForOtherTarget = 0,
        notSpecialized,
        specializedForTarget,
    };

    TargetSpecializationLevel getTargetSpecialiationLevel(
        IRGlobalValue*  val,
        String const&   targetName)
    {
        TargetSpecializationLevel result = TargetSpecializationLevel::notSpecialized;
        for( auto dd = val->firstDecoration; dd; dd = dd->next )
        {
            if(dd->op != kIRDecorationOp_Target)
                continue;

            auto decoration = (IRTargetDecoration*) dd;
            if(decoration->targetName == targetName)
                return TargetSpecializationLevel::specializedForTarget;

            result = TargetSpecializationLevel::specializedForOtherTarget;
        }

        return result;
    }

    bool isDefinition(
        IRGlobalValue* val)
    {
        switch (val->op)
        {
        case kIROp_witness_table:
            return ((IRWitnessTable*)val)->entries.first != nullptr;

        case kIROp_global_var:
        case kIROp_Func:
            return ((IRGlobalValueWithCode*)val)->firstBlock != nullptr;

        default:
            return false;
        }
    }

    // Is `newVal` marked as being a better match for our
    // chosen code-generation target?
    //
    // TODO: there is a missing step here where we need
    // to check if things are even available in the first place...
    bool isBetterForTarget(
        IRSpecContext*  context,
        IRGlobalValue*  newVal,
        IRGlobalValue*  oldVal)
    {
        String targetName = getTargetName(context);

        // For right now every declaration might have zero or more
        // modifiers, representing the targets for which it is specialized.
        // Each modifier has a single string "tag" to represent a target.
        // We thus decide that a declaration is "more specialized" by:
        //
        // - Does it have a modifier with a tag with the string for the current target?
        //   If yes, it is the most specialized it can be.
        //
        // - Does it have a no tags? Then it is "unspecialized" and that is okay.
        //
        // - Does it have a modifier with a tag for a *different* target?
        //   If yes, then it shouldn't even be usable on this target.
        //
        // Longer term a better approach is to think of this in terms
        // of a "disjunction of conjunctions" that is:
        //
        //     (A and B and C) or (A and D) or (E) or (F and G) ...
        //
        // A code generation target would then consist of a
        // conjunction of invidual tags:
        //
        //    (HLSL and SM_4_0 and Vertex and ...)
        //
        // A declaration is *applicable* on a target if one of
        // its conjunctions of tags is a subset of the target's.
        //
        // One declaration is *better* than another on a target
        // if it is applicable and its tags are a superset
        // of the other's.

        auto newLevel = getTargetSpecialiationLevel(newVal, targetName);
        auto oldLevel = getTargetSpecialiationLevel(oldVal, targetName);
        if(newLevel != oldLevel)
            return UInt(newLevel) > UInt(oldLevel);

        // All other factors being equal, a definition is
        // better than a declaration.
        auto newIsDef = isDefinition(newVal);
        auto oldIsDef = isDefinition(oldVal);
        if (newIsDef != oldIsDef)
            return newIsDef;

        return false;
    }

    IRFunc* cloneFuncImpl(
        IRSpecContext*  context,
        IRFunc*         originalFunc,
        IROriginalValuesForClone const& originalValues)
    {
        auto clonedFunc = context->builder->createFunc();
        registerClonedValue(context, clonedFunc, originalValues);
        cloneFunctionCommon(context, clonedFunc, originalFunc);
        return clonedFunc;
    }

    // Directly clone a global value, based on a single definition/declaration, `originalVal`.
    // The symbol `sym` will thread together other declarations of the same value, and
    // we will register the new value as the cloned version of all of those.
    IRGlobalValue* cloneGlobalValueImpl(
        IRSpecContext*  context,
        IRGlobalValue*  originalVal,
        IRSpecSymbol*   sym)
    {
        if( !originalVal )
        {
            SLANG_UNEXPECTED("cloning a null value");
            UNREACHABLE_RETURN(nullptr);
        }

        switch( originalVal->op )
        {
        case kIROp_Func:
            return cloneFuncImpl(context, (IRFunc*) originalVal, sym);

        case kIROp_global_var:
            return cloneGlobalVarImpl(context, (IRGlobalVar*)originalVal, sym);

        case kIROp_witness_table:
            return cloneWitnessTableImpl(context, (IRWitnessTable*)originalVal, sym);

        default:
            SLANG_UNEXPECTED("unknown global value kind");
            UNREACHABLE_RETURN(nullptr);
        }

    }

    // Clone a global value, which has the given `mangledName`.
    // The `originalVal` is a known global IR value with that name, if one is available.
    // (It is okay for this parameter to be null).
    IRGlobalValue* cloneGlobalValueWithMangledName(
        IRSpecContext*  context,
        String const&   mangledName,
        IRGlobalValue*  originalVal)
    {
        if(mangledName.Length() == 0)
        {
            // If there is no mangled name, then we assume this is a local symbol,
            // and it can't possibly have multiple declarations.
            return cloneGlobalValueImpl(context, originalVal, nullptr);
        }

        //
        // We will scan through all of the available declarations
        // with the same mangled name as `originalVal` and try
        // to pick the "best" one for our target.

        RefPtr<IRSpecSymbol> sym;
        if( !context->getSymbols().TryGetValue(mangledName, sym) )
        {
            // This shouldn't happen!
            SLANG_UNEXPECTED("no matching values registered");
            UNREACHABLE_RETURN(cloneGlobalValueImpl(context, originalVal, nullptr));
        }

        // We will try to track the "best" declaration we can find.
        //
        // Generally, one declaration wil lbe better than another if it is
        // more specialized for the chosen target. Otherwise, we simply favor
        // definitions over declarations.
        //
        IRGlobalValue* bestVal = sym->irGlobalValue;
        for( auto ss = sym->nextWithSameName; ss; ss = ss->nextWithSameName )
        {
            IRGlobalValue* newVal = ss->irGlobalValue;
            if(isBetterForTarget(context, newVal, bestVal))
                bestVal = newVal;
        }

        return cloneGlobalValueImpl(context, bestVal, sym);
    }

    IRGlobalValue* cloneGlobalValueWithMangledName(IRSpecContext* context, String const& mangledName)
    {
        return cloneGlobalValueWithMangledName(context, mangledName, nullptr);
    }

    // Clone a global value, where `originalVal` is one declaration/definition, but we might
    // have to consider others, in order to find the "best" version of the symbol.
    IRGlobalValue* cloneGlobalValue(IRSpecContext* context, IRGlobalValue* originalVal)
    {
        // We are being asked to clone a particular global value, but in
        // the IR that comes out of the front-end there could still
        // be multiple, target-specific, declarations of any given
        // global value, all of which share the same mangled name.
        return cloneGlobalValueWithMangledName(
            context,
            originalVal->mangledName,
            originalVal);
    }

    StructTypeLayout* getGlobalStructLayout(
        ProgramLayout*  programLayout);

    void insertGlobalValueSymbol(
        IRSharedSpecContext*    sharedContext,
        IRGlobalValue*          gv)
    {
        String mangledName = gv->mangledName;

        // Don't try to register a symbol for global values
        // with no mangled name, since these represent symbols
        // that shouldn't get "linkage"
        if (mangledName == "")
            return;

        RefPtr<IRSpecSymbol> sym = new IRSpecSymbol();
        sym->irGlobalValue = gv;

        RefPtr<IRSpecSymbol> prev;
        if (sharedContext->symbols.TryGetValue(mangledName, prev))
        {
            sym->nextWithSameName = prev->nextWithSameName;
            prev->nextWithSameName = sym;
        }
        else
        {
            sharedContext->symbols.Add(mangledName, sym);
        }
    }

    void insertGlobalValueSymbols(
        IRSharedSpecContext*    sharedContext,
        IRModule*               originalModule)
    {
        if (!originalModule)
            return;

        for (auto gv = originalModule->firstGlobalValue; gv; gv = gv->nextGlobalValue)
        {
            insertGlobalValueSymbol(sharedContext, gv);
        }
    }

    void initializeSharedSpecContext(
        IRSharedSpecContext*    sharedContext,
        Session*                session,
        IRModule*               module,
        IRModule*               originalModule)
    {

        SharedIRBuilder* sharedBuilder = &sharedContext->sharedBuilderStorage;
        sharedBuilder->module = nullptr;
        sharedBuilder->session = session;

        IRBuilder* builder = &sharedContext->builderStorage;
        builder->sharedBuilder = sharedBuilder;

        if( !module )
        {
            module = builder->createModule();
            sharedBuilder->module = module;
        }

        sharedContext->module = module;
        sharedContext->originalModule = originalModule;

        // We will populate a map with all of the IR values
        // that use the same mangled name, to make lookup easier
        // in other steps.
        insertGlobalValueSymbols(sharedContext, originalModule);
    }

    // implementation provided in parameter-binding.cpp
    RefPtr<ProgramLayout> specializeProgramLayout(
        TargetRequest * targetReq,
        ProgramLayout* programLayout,
        Substitutions * typeSubst);

    RefPtr<GlobalGenericParamSubstitution> createGlobalGenericParamSubstitution(
        EntryPointRequest * entryPointRequest, 
        ProgramLayout * programLayout,
        IRSpecContext*  context,
        IRModule* originalIRModule)
    {
        RefPtr<GlobalGenericParamSubstitution> globalParamSubst;
        Substitutions * curTailSubst = nullptr;
        for (auto param : programLayout->globalGenericParams)
        {
            auto paramSubst = new GlobalGenericParamSubstitution();
            if (!globalParamSubst)
                globalParamSubst = paramSubst;
            if (curTailSubst)
                curTailSubst->outer = paramSubst;
            curTailSubst = paramSubst;
            paramSubst->paramDecl = param->decl;
            SLANG_ASSERT((UInt)param->index < entryPointRequest->genericParameterTypes.Count());
            paramSubst->actualType = entryPointRequest->genericParameterTypes[param->index];
            // find witness tables
            for (auto witness : entryPointRequest->genericParameterWitnesses)
            {
                if (auto subtypeWitness = witness.As<SubtypeWitness>())
                {
                    if (subtypeWitness->sub->EqualsVal(paramSubst->actualType))
                    {
                        auto witnessTableName = getMangledNameForConformanceWitness(subtypeWitness->sub, subtypeWitness->sup);
                        auto globalVar = originalIRModule->getFirstGlobalValue();
                        IRGlobalValue * table = nullptr;
                        while (globalVar)
                        {
                            if (globalVar->mangledName == witnessTableName)
                            {
                                table = globalVar;
                                break;
                            }
                            globalVar = globalVar->getNextValue();
                        }
                        SLANG_ASSERT(table);
                        table = cloneWitnessTableWithoutRegistering(context, (IRWitnessTable*)(table));
                        IRProxyVal * tableVal = new IRProxyVal();
                        tableVal->inst = table;
                        paramSubst->witnessTables.Add(KeyValuePair<RefPtr<Type>, RefPtr<Val>>(subtypeWitness->sup, tableVal));
                    }
                }
            }
        }
        return globalParamSubst;
    }

    struct IRSpecializationState
    {
        ProgramLayout*      programLayout;
        CodeGenTarget       target;
        TargetRequest*      targetReq;

        IRModule* irModule = nullptr;
        RefPtr<ProgramLayout> newProgramLayout;

        IRSharedSpecContext sharedContextStorage;
        IRSpecContext contextStorage;

        IRSharedSpecContext* getSharedContext() { return &sharedContextStorage; }
        IRSpecContext* getContext() { return &contextStorage; }
    };

    IRSpecializationState* createIRSpecializationState(
        EntryPointRequest*  entryPointRequest,
        ProgramLayout*      programLayout,
        CodeGenTarget       target,
        TargetRequest*      targetReq)
    {
        IRSpecializationState* state = new IRSpecializationState();

        state->programLayout = programLayout;
        state->target = target;
        state->targetReq = targetReq;


        auto compileRequest = entryPointRequest->compileRequest;
        auto translationUnit = entryPointRequest->getTranslationUnit();
        auto originalIRModule = translationUnit->irModule;

        auto sharedContext = state->getSharedContext();
        initializeSharedSpecContext(
            sharedContext,
            compileRequest->mSession,
            nullptr,
            originalIRModule);
        state->irModule = sharedContext->module;

        // We also need to attach the IR definitions for symbols from
        // any loaded modules:
        for (auto loadedModule : compileRequest->loadedModulesList)
        {
            insertGlobalValueSymbols(sharedContext, loadedModule->irModule);
        }

        auto context = state->getContext();
        context->shared = sharedContext;
        context->builder = &sharedContext->builderStorage;
        context->target = target;

        // Create the GlobalGenericParamSubstitution for substituting global generic types
        // into user-provided type arguments
        auto globalParamSubst = createGlobalGenericParamSubstitution(entryPointRequest, programLayout, context, originalIRModule);

        context->subst = globalParamSubst;
        
        // now specailize the program layout using the substitution
        RefPtr<ProgramLayout> newProgramLayout = specializeProgramLayout(targetReq, programLayout, globalParamSubst);

        state->newProgramLayout = newProgramLayout;

        // Next, we want to optimize lookup for layout infromation
        // associated with global declarations, so that we can 
        // look things up based on the IR values (using mangled names)
        auto globalStructLayout = getGlobalStructLayout(newProgramLayout);
        for (auto globalVarLayout : globalStructLayout->fields)
        {
            String mangledName = getMangledName(globalVarLayout->varDecl);
            context->globalVarLayouts.AddIfNotExists(mangledName, globalVarLayout);
        }

        return state;
    }

    void destroyIRSpecializationState(IRSpecializationState* state)
    {
        delete state;
    }

    IRModule* getIRModule(IRSpecializationState* state)
    {
        return state->irModule;
    }

    IRGlobalValue* getSpecializedGlobalValueForDeclRef(
        IRSpecializationState*  state,
        DeclRef<Decl> const&    declRef)
    {
        // We will start be ensuring that we have code for
        // the declaration itself.
        auto decl = declRef.getDecl();
        auto mangledDeclName = getMangledName(decl);

        IRGlobalValue* irDeclVal = cloneGlobalValueWithMangledName(
            state->getContext(),
            mangledDeclName);
        if(!irDeclVal)
            return nullptr;

        // Now we need to deal with specializing the given
        // IR value based on the substitutions applied to
        // our declaration reference.

        if(!declRef.substitutions)
            return irDeclVal;

        SLANG_UNEXPECTED("unhandled");
        UNREACHABLE_RETURN(nullptr);
    }

    void specializeIRForEntryPoint(
        IRSpecializationState*  state,
        EntryPointRequest*  entryPointRequest)
    {
        auto target = state->target;

        auto compileRequest = entryPointRequest->compileRequest;
        auto session = compileRequest->mSession;
        auto translationUnit = entryPointRequest->getTranslationUnit();
        auto originalIRModule = translationUnit->irModule;
        if (!originalIRModule)
        {
            // We should already have emitted IR for the original
            // translation unit, and it we don't have it, then
            // we are now in trouble.
            return;
        }

        auto context = state->getContext();
        auto newProgramLayout = state->newProgramLayout;

        auto entryPointLayout = findEntryPointLayout(newProgramLayout, entryPointRequest);


        // Next, we make sure to clone the global value for
        // the entry point function itself, and rely on
        // this step to recursively copy over anything else
        // it might reference.
        auto irEntryPoint = specializeIRForEntryPoint(context, entryPointRequest, entryPointLayout);

        // TODO: *technically* we should consider the case where
        // we have global variables with initializers, since
        // these should get run whether or not the entry point
        // references them.

        // For GLSL only, we will need to perform "legalization" of
        // the entry point and any entry-point parameters.
        switch (target)
        {
        case CodeGenTarget::GLSL:
            {
                legalizeEntryPointForGLSL(session, irEntryPoint, entryPointLayout);
            }
            break;

        default:
            break;
        }
    }

    //

    struct IRSharedGenericSpecContext : IRSharedSpecContext
    {
        // Non-generic functions to be processed
        List<IRFunc*> workList;
    };

    struct IRGenericSpecContext : IRSpecContextBase
    {
        IRSharedGenericSpecContext* getShared() { return (IRSharedGenericSpecContext*) shared; }

        // The substutions to apply
        RefPtr<Substitutions>   subst;

        // Override the "maybe clone" logic so that we always clone
        virtual IRValue* maybeCloneValue(IRValue* originalVal) override;

        virtual RefPtr<Type> maybeCloneType(Type* originalType) override;
    };

    // Convert a type-level value into an IR-level equivalent.
    IRValue* getIRValue(
        IRGenericSpecContext*   context,
        Val*                    val)
    {
        if( auto subtypeWitness = dynamic_cast<SubtypeWitness*>(val) )
        {
            String mangledName = getMangledNameForConformanceWitness(
                subtypeWitness->sub,
                subtypeWitness->sup);
            RefPtr<IRSpecSymbol> symbol;

            if( !context->getSymbols().TryGetValue(mangledName, symbol) )
            {
                SLANG_UNEXPECTED("couldn't find symbol for conformance!");
                return nullptr;
            }

            return symbol->irGlobalValue;
        }
        else if (auto proxyVal = dynamic_cast<IRProxyVal*>(val))
        {
            // The type-level value actually references an IR-level value,
            // so we need to make sure to emit as if we were referencing
            // the pointed-to value and not the proxy type-level `Val`
            // instead.

            return context->maybeCloneValue(proxyVal->inst);
        }
        else
        {
            SLANG_UNEXPECTED("unimplemented");
            UNREACHABLE_RETURN(nullptr);
        }
    }

    IRValue* getSubstValue(
        IRGenericSpecContext*   context,
        DeclRef<Decl>           declRef)
    {
        auto subst = context->subst.As<GenericSubstitution>();
        SLANG_ASSERT(subst);
        auto genericDecl = subst->genericDecl;

        UInt orinaryParamCount = 0;
        for( auto mm : genericDecl->Members )
        {
            if(mm.As<GenericTypeParamDecl>())
                orinaryParamCount++;
            else if(mm.As<GenericValueParamDecl>())
                orinaryParamCount++;
        }

        if( auto constraintDeclRef = declRef.As<GenericTypeConstraintDecl>() )
        {
            // We have a constraint, but we need to find its index in the
            // argument list of the substitutions.
            UInt constraintIndex = 0;
            bool found = false;
            for( auto cd : genericDecl->getMembersOfType<GenericTypeConstraintDecl>() )
            {
                if( cd.Ptr() == constraintDeclRef.getDecl() )
                {
                    found = true;
                    break;
                }

                constraintIndex++;
            }
            assert(found);

            UInt argIndex = orinaryParamCount + constraintIndex;
            assert(argIndex < subst->args.Count());

            return getIRValue(context, subst->args[argIndex]);
        }
        else
        {
            SLANG_UNEXPECTED("unhandled case");
            return nullptr;
        }
    }

    IRValue* IRGenericSpecContext::maybeCloneValue(IRValue* originalVal)
    {
        switch( originalVal->op )
        {
        case kIROp_decl_ref:
            {
                auto declRefVal = (IRDeclRef*) originalVal;
                auto declRef = declRefVal->declRef;
                auto genSubst = subst.As<GenericSubstitution>();
                SLANG_ASSERT(genSubst);
                // We may have a direct reference to one of the parameters
                // of the generic we are specializing, and in that case
                // we nee to translate it over to the equiavalent of
                // the `Val` we have been given.
                if(declRef.getDecl()->ParentDecl == genSubst->genericDecl)
                {
                    return getSubstValue(this, declRef);
                }

                int diff = 0;
                auto substDeclRef = declRefVal->declRef.SubstituteImpl(subst, &diff);
                if(!diff)
                    return originalVal;

                return builder->getDeclRefVal(substDeclRef);
            }
            break;

        default:
            return originalVal;
        }
    }

    RefPtr<Type> IRGenericSpecContext::maybeCloneType(Type* originalType)
    {
        return originalType->Substitute(subst).As<Type>();
    }

    // Given a list of substitutions, return the inner-most
    // generic substitution in the list, or NULL if there
    // are no generic substitutions.
    RefPtr<GenericSubstitution> getInnermostGenericSubst(
        Substitutions*  inSubst)
    {
        auto subst = inSubst;
        while( subst )
        {
            GenericSubstitution* genericSubst = dynamic_cast<GenericSubstitution*>(subst);
            if(genericSubst)
                return genericSubst;

            subst = subst->outer;
        }
        return nullptr;
    }

    RefPtr<GenericDecl> getInnermostGenericDecl(
        Decl*   inDecl)
    {
        auto decl = inDecl;
        while( decl )
        {
            GenericDecl* genericDecl = dynamic_cast<GenericDecl*>(decl);
            if(genericDecl)
                return genericDecl;

            decl = decl->ParentDecl;
        }
        return nullptr;
    }

    // This function takes a list of substitutions that we'd
    // like to apply, but which (1) might apply to a different
    // declaration in cases where we have got target-specific
    // overloads in the mix, and (2) might include some `ThisType`
    // substitutions, which we don't care about in this context,
    // and produces a new set of substitutiosn without these
    // two issues.
    RefPtr<Substitutions> cloneSubstitutionsForSpecialization(
        IRSharedGenericSpecContext* sharedContext,
        Substitutions*              oldSubst,
        Decl*                       newDecl)
    {
        // We will "peel back" layers of substitutions until
        // we find our first generic subsitution.
        auto oldGenericSubst = getInnermostGenericSubst(oldSubst);
        if(!oldGenericSubst)
            return nullptr;

        // We will also peel back layers of declarations until
        // we find our first generic decl.
        auto newGenericDecl = getInnermostGenericDecl(newDecl);
        if( !newGenericDecl )
        {
//            SLANG_UNEXPECTED("generic subst without generic decl");
            return nullptr;
        }

        RefPtr<GenericSubstitution> newSubst = new GenericSubstitution();
        newSubst->genericDecl = newGenericDecl;
        newSubst->args = oldGenericSubst->args;

        newSubst->outer = cloneSubstitutionsForSpecialization(
            sharedContext,
            oldGenericSubst->outer,
            newGenericDecl->ParentDecl);

        return newSubst;
    }


    IRFunc* getSpecializedFunc(
        IRSharedGenericSpecContext* sharedContext,
        IRFunc*                     genericFunc,
        DeclRef<Decl>               specDeclRef)
    {
        // First, we want to see if an existing specialization
        // has already been made. To do that we will need to
        // compute the mangled name of the specialized function,
        // so that we can look for existing declarations.
        String specMangledName;
        if (genericFunc->genericDecl == specDeclRef.decl)
            specMangledName = getMangledName(specDeclRef);
        else
            specMangledName = mangleSpecializedFuncName(genericFunc->mangledName, specDeclRef.substitutions);

        // TODO: This is a terrible linear search, and we should
        // avoid it by building a dictionary ahead of time,
        // as is being done for the `IRSpecContext` used above.
        // We can probalby use the same basic context, actually.
        auto module = genericFunc->parentModule;
        for(auto gv = module->getFirstGlobalValue(); gv; gv = gv->getNextValue())
        {
            if(gv->mangledName == specMangledName)
                return (IRFunc*) gv;
        }

        // If we get to this point, then we need to construct a
        // new `IRFunc` to represent the result of specialization.

        // The substitutions we are applying might have been created
        // using a different overload of a target-specific function,
        // so we need to create a dummy substitution here, to make
        // sure it used the correct generic.
        RefPtr<Substitutions> newSubst = cloneSubstitutionsForSpecialization(
            sharedContext,
            specDeclRef.substitutions,
            genericFunc->genericDecl);

        IRGenericSpecContext context;
        context.shared = sharedContext;
        context.builder = &sharedContext->builderStorage;
        context.subst = newSubst;

        // TODO: other initialization is needed here...

        auto specFunc = cloneSimpleFuncWithoutRegistering(&context, genericFunc);

        // Set up the clone to recognize that it is no longer generic
        specFunc->mangledName = specMangledName;
        specFunc->genericDecl = nullptr;

        // Put the function into the global sequence right after
        // the function it specializes.
        //
        // TODO: This shouldn't be needed, if we introduce a sorting
        // step before we emit code.
        //specFunc->removeFromParent();
        //specFunc->insertAfter(genericFunc);

        // At this point we've created a new non-generic function,
        // which means we should add it to our work list for
        // subsequent processing.
        sharedContext->workList.Add(specFunc);

        // We also need to make sure that we register this specialized
        // function under its mangled name, so that later lookup
        // steps will find it.
        insertGlobalValueSymbol(sharedContext, specFunc);

        return specFunc;
    }

    // Find the value in the given witness table that
    // satisfies the given requirement (or return
    // null if not found).
    IRValue* findWitnessVal(
        IRWitnessTable*         witnessTable,
        DeclRef<Decl> const&    requirementDeclRef)
    {
        // For now we will do a dumb linear search
        for( auto entry : witnessTable->entries )
        {
            // We expect the key on the entry to be a decl-ref,
            // but lets go ahead and check, just to be sure.
            auto requirementKey = entry->requirementKey.usedValue;
            if(requirementKey->op != kIROp_decl_ref)
                continue;
            auto keyDeclRef = ((IRDeclRef*) requirementKey)->declRef;

            // If the keys don't match, continue with the next entry.
            if (!keyDeclRef.Equals(requirementDeclRef))
            {
                // requirementDeclRef may be pointing to the inner decl of a generic decl
                // in this case we compare keyDeclRef against the parent decl of requiredDeclRef
                if (auto genRequiredDeclRef = requirementDeclRef.GetParent().As<GenericDecl>())
                {
                    if (!keyDeclRef.Equals(genRequiredDeclRef))
                    {
                        continue;
                    }
                }
                else
                    continue;
            }

            // If the keys matched, then we use the value from
            // this entry.
            auto satisfyingVal = entry->satisfyingVal.usedValue;
            return satisfyingVal;
        }

        // No matching entry found.
        return nullptr;
    }

    // Go through the code in the module and try to identify
    // calls to generic functions where the generic arguments
    // are known, and specialize the callee based on those
    // known values.
    void specializeGenerics(
        IRModule*   module)
    {
        IRSharedGenericSpecContext sharedContextStorage;
        auto sharedContext = &sharedContextStorage;

        initializeSharedSpecContext(
            sharedContext,
            module->session,
            module,
            module);

        // Our goal here is to find `specialize` instructions that
        // can be replaced with references to a suitably sepcialized
        // funciton. As a simplification, we will only consider `specialize`
        // calls that are inside of non-generic functions, since we assume
        // that these will allow us to fully specialize the referenced
        // function.
        //
        // We start by building up a work list of non-generic functions.
        for( auto gv = module->getFirstGlobalValue();
            gv;
            gv = gv->getNextValue() )
        {
            // Is it a function? If not, skip.
            if(gv->op != kIROp_Func)
                continue;
            auto func = (IRFunc*) gv;

            // Is it generic? If so, skip.
            if(func->genericDecl)
                continue;

            sharedContext->workList.Add(func);
        }

        // Now that we have our work list, we are going to
        // process it until it goes empty. Along the way
        // we may specialize a function and thus create
        // a new non-generic function, and in that case
        // we will add the new function to the work list.
        auto& workList = sharedContext->workList;
        while( auto count = workList.Count() )
        {
            // We will process the last entry in the
            // work list, which amounts to treating
            // it like a stack when we have recursive
            // specialization to perform.
            auto func = workList[count-1];
            workList.RemoveAt(count-1);

            // We are going to go ahead and walk through
            // all the instructions in this function,
            // and look for `specialize` operations.
            for( auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock() )
            {
                // We need to be careful when iterating over the instructions,
                // because we might end up removing the "current" instruction,
                // so that accessing `ii->next` would crash.
                IRInst* nextInst = nullptr;
                for( auto ii = bb->getFirstInst(); ii; ii = nextInst )
                {
                    nextInst = ii->getNextInst();

                    // We want to handle both `specialize` instructions,
                    // which trigger specialization, and also `lookup_interface_method`
                    // instructions, which may allow us to "de-virtualize"
                    // calls.

                    switch( ii->op )
                    {
                    default:
                        // Most instructions are ones we don't care about here.
                        continue;

                    case kIROp_specialize:
                        {
                            // We have a `specialize` instruction, so lets see
                            // whether we have an opportunity to perform the
                            // specialization here and now.
                            IRSpecialize* specInst = (IRSpecialize*) ii;

                            // We need to check that the value being specialized is
                            // a generic function.
                            auto genericVal = specInst->genericVal.usedValue;
                            if(genericVal->op != kIROp_Func)
                                continue;
                            auto genericFunc = (IRFunc*) genericVal;
                            if(!genericFunc->genericDecl)
                                continue;

                            // Now we extract the specialized decl-ref that will
                            // tell us how to specialize things.
                            auto specDeclRefVal = (IRDeclRef*) specInst->specDeclRefVal.usedValue;
                            auto specDeclRef = specDeclRefVal->declRef;

                            // Okay, we have a candidate for specialization here.
                            //
                            // We will first find or construct a specialized version
                            // of the callee funciton/
                            auto specFunc = getSpecializedFunc(sharedContext, genericFunc, specDeclRef);
                            //
                            // Then we will replace the use sites for the `specialize`
                            // instruction with uses of the specialized function.
                            //
                            specInst->replaceUsesWith(specFunc);

                            specInst->removeAndDeallocate();
                        }
                        break;

                    case kIROp_lookup_interface_method:
                        {
                            // We have a `lookup_interface_method` instruction,
                            // so let's see whether it is a lookup in a known
                            // witness table.
                            IRLookupWitnessMethod* lookupInst = (IRLookupWitnessMethod*) ii;

                            // We only want to deal with the case where the witness-table
                            // argument points to a concrete global table.
                            auto witnessTableArg = lookupInst->witnessTable.usedValue;
                            if(witnessTableArg->op != kIROp_witness_table)
                                continue;
                            IRWitnessTable* witnessTable = (IRWitnessTable*)witnessTableArg;

                            // We also need to be sure that the requirement we
                            // are trying to look up is identified via a decl-ref:
                            auto requirementArg = lookupInst->requirementDeclRef.usedValue;
                            if(requirementArg->op != kIROp_decl_ref)
                                continue;
                            auto requirementDeclRef = ((IRDeclRef*) requirementArg)->declRef;

                            // Use the witness table to look up the value that
                            // satisfies the requirement.
                            auto satisfyingVal = findWitnessVal(witnessTable, requirementDeclRef);
                            // We expect to always find something, but lets just
                            // be careful here.
                            if(!satisfyingVal)
                                continue;

                            // If we get through all of the above checks, then we
                            // have a (more) concrete method that implements the interface,
                            // and so we should dispatch to that directly, rather than
                            // use the `lookup_interface_method` instruction.
                            lookupInst->replaceUsesWith(satisfyingVal);
                            lookupInst->removeAndDeallocate();
                        }
                        break;
                    }


                    // We only care about `specialize` instructions.
                    if(ii->op != kIROp_specialize)
                        continue;

                }
            }
        }

        // Once the work list has gone dry, we should have the invariant
        // that there are no `specialize` instructions inside of non-generic
        // functions that in turn reference a generic function.
    }

    //

}