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
|
// 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(IRInst* u, IRValue* v)
{
user = u;
usedValue = v;
if(v)
{
nextUse = v->firstUse;
prevLink = &v->firstUse;
v->firstUse = this;
}
}
//
IRUse* IRInst::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 IRFunc::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:
return true;
}
}
bool isTerminatorInst(IRInst* inst)
{
if (!inst) return false;
return isTerminatorInst(inst->op);
}
//
// Add an instruction to a specific parent
void IRBuilder::addInst(IRBlock* block, IRInst* inst)
{
inst->parentBlock = block;
if (!block->firstInst)
{
inst->prevInst = nullptr;
inst->nextInst = nullptr;
block->firstInst = inst;
block->lastInst = inst;
}
else
{
auto prev = block->lastInst;
inst->prevInst = prev;
inst->nextInst = nullptr;
prev->nextInst = inst;
block->lastInst = inst;
}
}
// Add an instruction into the current scope
void IRBuilder::addInst(
IRInst* inst)
{
auto parent = block;
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);
auto module = builder->getModule();
inst->argCount = 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->parentBlock != right.inst->parentBlock) 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->parentBlock));
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->shared->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 = createInst<IRConstant>(builder, op, type);
memcpy(&irValue->u, value, valueSize);
key.inst = irValue;
builder->shared->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 = createInst<IRDeclRef>(
this,
kIROp_decl_ref,
nullptr);
irValue->declRef = declRef;
return irValue;
}
IRInst* IRBuilder::emitCallInst(
IRType* type,
IRValue* func,
UInt argCount,
IRValue* const* args)
{
auto inst = createInstWithTrailingArgs<IRCall>(
this,
kIROp_Call,
type,
1,
&func,
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* func = createValue<IRFunc>(
this,
kIROp_Func,
nullptr);
addGlobalValue(getModule(), func);
return func;
}
IRGlobalVar* IRBuilder::createGlobalVar(
IRType* valueType)
{
auto ptrType = getSession()->getPtrType(valueType);
IRGlobalVar* globalVar = createValue<IRGlobalVar>(
this,
kIROp_global_var,
ptrType);
addGlobalValue(getModule(), globalVar);
return globalVar;
}
IRBlock* IRBuilder::createBlock()
{
return createValue<IRBlock>(
this,
kIROp_Block,
getSession()->getIRBasicBlockType());
}
IRBlock* IRBuilder::emitBlock()
{
auto bb = createBlock();
auto f = this->func;
if (f)
{
f->addBlock(bb);
this->block = bb;
}
return bb;
}
IRParam* IRBuilder::emitParam(
IRType* type)
{
auto param = createValue<IRParam>(
this,
kIROp_Param,
type);
if (auto bb = block)
{
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<PtrType>();
if( !ptrType )
{
// Bad!
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::emitBranch(
IRBlock* block)
{
auto inst = createInst<IRUnconditionalBranch>(
this,
kIROp_unconditionalBranch,
nullptr,
block);
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;
}
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:
{
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 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;
default:
break;
}
dumpID(context, inst);
}
static void dump(
IRDumpContext* context,
Name* name)
{
dump(context, getText(name).Buffer());
}
static void dumpDeclRef(
IRDumpContext* context,
DeclRef<Decl> const& declRef);
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
{
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)
{
parentDeclRef = genericParentDeclRef.GetParent();
}
if(parentDeclRef.As<ModuleDecl>())
{
parentDeclRef = DeclRef<ContainerDecl>();
}
if(parentDeclRef)
{
dumpDeclRef(context, parentDeclRef);
dump(context, ".");
}
dump(context, decl->getName());
if(genericParentDeclRef)
{
auto subst = declRef.substitutions;
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->nextInst)
{
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);
}
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");
}
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.
//
switch (op)
{
#if 0
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;
#endif
default:
break;
}
#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 dumpIRFunc(
IRDumpContext* context,
IRFunc* func)
{
dump(context, "\n");
dumpIndent(context);
dump(context, "ir_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");
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 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;
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()
{
// Run destructor to be sure...
this->~IRValue();
// And then free the memory
free((void*) this);
}
// 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->parentBlock;
assert(bb);
auto pp = other->prevInst;
if( pp )
{
pp->nextInst = this;
}
else
{
bb->firstInst = this;
}
this->prevInst = pp;
this->nextInst = other;
this->parentBlock = bb;
other->prevInst = 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(!parentBlock)
return;
auto bb = parentBlock;
auto pp = prevInst;
auto nn = nextInst;
if(pp)
{
SLANG_ASSERT(pp->parentBlock == bb);
pp->nextInst = nn;
}
else
{
bb->firstInst = nn;
}
if(nn)
{
SLANG_ASSERT(nn->parentBlock == bb);
nn->prevInst = pp;
}
else
{
bb->lastInst = pp;
}
prevInst = nullptr;
nextInst = nullptr;
parentBlock = nullptr;
}
// Remove this instruction from its parent block,
// and then destroy it (it had better have no uses!)
void IRInst::removeAndDeallocate()
{
removeFromParent();
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.shared = &shared;
RefPtr<PtrType> ptrType = session->getPtrType(valueType);
return builder.createGlobalVar(valueType);
}
void moveValueBefore(
IRGlobalValue* valueToMove,
IRGlobalValue* placeBefore)
{
valueToMove->removeFromParent();
valueToMove->insertBefore(placeBefore);
}
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.shared = &shared;
// 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 resultVariable = addGlobalVariable(module, resultType);
moveValueBefore(resultVariable, func);
// We need to transfer layout information from the entry point
// down to the variable:
builder.addLayoutDecoration(resultVariable, entryPointLayout->resultLayout);
for( auto bb = func->getFirstBlock(); bb; bb = bb->getNextBlock() )
{
for( auto ii = bb->getFirstInst(); ii; ii = ii->nextInst )
{
if(ii->op != kIROp_ReturnVal)
continue;
IRReturnVal* returnInst = (IRReturnVal*) ii;
IRValue* resultValue = returnInst->getVal();
// `store <resultVariable> <resultValue>`
IRStore* storeInst = createInst<IRStore>(
&builder,
kIROp_Store,
nullptr,
resultVariable,
resultValue);
// `returnVoid`
IRReturnVoid* returnVoid = createInst<IRReturnVoid>(
&builder,
kIROp_ReturnVoid,
nullptr);
// Put the two new instructions before the old one
storeInst->insertBefore(returnInst);
returnVoid->insertBefore(returnInst);
// and then remove the old one.
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() )
{
IRInst* insertBeforeInst = firstBlock->getFirstInst();
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();
// TODO: We need to distinguish any true pointers in the
// user's code from pointers that only exist for
// parameter-passing. This `PtrType` here should actually
// be `OutTypeBase`, but I'm not confident that all
// the other code is handling that correctly...
if(auto paramPtrType = paramType->As<PtrType>() )
{
// Okay, we have the more interesting case here,
// where the parameter was being passed by reference.
// This actually makes our life pretty easy, though,
// since we can simply replace any uses of the existing
// pointer with the global variable (since it will
// be a pointer to storage).
// We start by creating the global variable, using
// the pointed-to type:
auto valueType = paramPtrType->getValueType();
auto paramVariable = addGlobalVariable(module, paramType);
moveValueBefore(paramVariable, func);
// TODO: We need to special-case `in out` variables here,
// because they actually need to be lowered to *two*
// global variables, not just one. We then need
// to emit logic to initialize the output variable
// based on the input at the start of the entry point,
// and then use the output variable thereafter.
//
// TODO: Actually, I need to double-check that it is
// legal in GLSL to use shader input/output parameters
// as temporaries in general; if not then we'd need
// to introduce a temporary no matter what.
// Next we attach the layout information from the
// original parameter to the new global variable,
// so that we can lay it out correctly when generating
// target code:
builder.addLayoutDecoration(paramVariable, paramLayout);
// And finally, we go ahead and replace all the
// uses of the parameter (which was a pointer) with
// uses of the new global variable's address.
pp->replaceUsesWith(paramVariable);
}
else
{
// This is the "easy" case where the parameter wasn't
// being passed by reference. We start by just creating
// a variable of the appropriate type, and attaching
// the required layout information to it.
auto paramVariable = addGlobalVariable(module, paramType);
moveValueBefore(paramVariable, func);
builder.addLayoutDecoration(paramVariable, paramLayout);
// Next we need to replace uses of the parameter with
// references to the variable. We are going to do that
// somewhat naively, by simply loading the variable
// at the start.
IRInst* loadInst = builder.emitLoad(paramVariable);
loadInst->insertBefore(insertBeforeInst);
pp->replaceUsesWith(loadInst);
}
}
// 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.
auto voidFuncType = new FuncType();
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 IRSpecContext
{
// The specialized module we are building
IRModule* module;
// The original, unspecialized module we are copying
IRModule* originalModule;
// The IR builder to use for creating nodes
IRBuilder* builder;
// A map from mangled symbol names to zero or
// more global IR values that have that name,
// in the *original* module.
Dictionary<String, RefPtr<IRSpecSymbol>> symbols;
// A map from the mangled name of a global variable
// to the layout to use for it.
Dictionary<String, VarLayout*> globalVarLayouts;
// A map from values in the original IR module
// to their equivalent in the cloned module.
Dictionary<IRValue*, IRValue*> clonedValues;
};
void registerClonedValue(
IRSpecContext* context,
IRValue* clonedValue,
IRValue* originalValue)
{
context->clonedValues.Add(originalValue, clonedValue);
}
void cloneDecorations(
IRSpecContext* 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;
default:
// Don't clone any decorations we don't understand.
break;
}
}
// TODO: implement this
}
IRGlobalVar* cloneGlobalVar(IRSpecContext* context, IRGlobalVar* originalVar);
IRFunc* cloneFunc(IRSpecContext* context, IRFunc* originalFunc);
IRValue* cloneValue(
IRSpecContext* context,
IRValue* originalValue)
{
IRValue* clonedValue = nullptr;
if (context->clonedValues.TryGetValue(originalValue, clonedValue))
return clonedValue;
switch (originalValue->op)
{
case kIROp_global_var:
return cloneGlobalVar(context, (IRGlobalVar*)originalValue);
break;
case kIROp_Func:
return cloneFunc(context, (IRFunc*)originalValue);
break;
case kIROp_boolConst:
{
IRConstant* c = (IRConstant*)originalValue;
return context->builder->getBoolValue(c->u.intVal != 0);
}
break;
case kIROp_IntLit:
{
IRConstant* c = (IRConstant*)originalValue;
return context->builder->getIntValue(c->type, c->u.intVal);
}
break;
case kIROp_FloatLit:
{
IRConstant* c = (IRConstant*)originalValue;
return context->builder->getFloatValue(c->type, c->u.floatVal);
}
break;
case kIROp_decl_ref:
{
IRDeclRef* od = (IRDeclRef*)originalValue;
return context->builder->getDeclRefVal(od->declRef);
}
break;
default:
SLANG_UNEXPECTED("no value registered for IR value");
return nullptr;
}
}
void cloneInst(
IRSpecContext* 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...
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, 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;
}
}
IRGlobalVar* cloneGlobalVar(IRSpecContext* context, IRGlobalVar* originalVar)
{
auto clonedVar = context->builder->createGlobalVar(originalVar->getType()->getValueType());
registerClonedValue(context, clonedVar, originalVar);
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);
}
// TODO: once we support initializers on global variables,
// we'll need to handle cloning it here.
return clonedVar;
}
void cloneFunctionCommon(
IRSpecContext* context,
IRFunc* clonedFunc,
IRFunc* originalFunc)
{
// First clone all the simple properties.
clonedFunc->mangledName = originalFunc->mangledName;
clonedFunc->genericParams = originalFunc->genericParams;
clonedFunc->type = originalFunc->type;
cloneDecorations(context, clonedFunc, originalFunc);
// Next we are going to clone the actual code.
IRBuilder builderStorage = *context->builder;
IRBuilder* builder = &builderStorage;
builder->func = clonedFunc;
// 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 = originalFunc->getFirstBlock();
originalBlock;
originalBlock = originalBlock->getNextBlock())
{
IRBlock* clonedBlock = builder->createBlock();
clonedFunc->addBlock(clonedBlock);
registerClonedValue(context, clonedBlock, originalBlock);
// We can go ahead and clone parameters here, while we are at it.
builder->block = clonedBlock;
for (auto originalParam = originalBlock->getFirstParam();
originalParam;
originalParam = originalParam->getNextParam())
{
IRParam* clonedParam = builder->emitParam(originalParam->getType());
registerClonedValue(context, clonedParam, originalParam);
}
}
// Okay, now we are in a good position to start cloning
// the instructions inside the blocks.
{
IRBlock* ob = originalFunc->getFirstBlock();
IRBlock* cb = clonedFunc->getFirstBlock();
while (ob)
{
assert(cb);
builder->block = cb;
for (auto oi = ob->getFirstInst(); oi; oi = oi->nextInst)
{
cloneInst(context, builder, oi);
}
ob = ob->getNextBlock();
cb = cb->getNextBlock();
}
}
// 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->module);
}
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->symbols.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);
return clonedFunc;
}
// The case for functions that are not the entry point is
// strictly simpler, so that is nice.
IRFunc* cloneFunc(IRSpecContext* context, IRFunc* originalFunc)
{
// TODO: We really need to scan through all the various
// global function symbols that have the same mangled name,
// and pick the correct one to lower for the target.
auto clonedFunc = context->builder->createFunc();
registerClonedValue(context, clonedFunc, originalFunc);
cloneFunctionCommon(context, clonedFunc, originalFunc);
return clonedFunc;
}
StructTypeLayout* getGlobalStructLayout(
ProgramLayout* programLayout);
IRModule* specializeIRForEntryPoint(
EntryPointRequest* entryPointRequest,
ProgramLayout* programLayout,
CodeGenTarget 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 nullptr;
}
auto entryPointLayout = findEntryPointLayout(programLayout, entryPointRequest);
// We now need to start cloning IR symbols from `originalIRModule`
// into a fresh IR module for this entry point. Along the way we need to:
//
// 1. Attach layout information from `programLayout` and/or `entryPointLayout`
// onto the cloned IR symbols, to drive later code generation.
//
// 2. In cases where a function might have multiple target-specific definitions,
// we need to pick the "best" one for the chosen code generation target.
//
SharedIRBuilder sharedBuilderStorage;
SharedIRBuilder* sharedBuilder = &sharedBuilderStorage;
sharedBuilder->module = nullptr;
sharedBuilder->session = compileRequest->mSession;
IRBuilder builderStorage;
IRBuilder* builder = &builderStorage;
builder->shared = sharedBuilder;
IRModule* module = builder->createModule();
sharedBuilder->module = module;
//
IRSpecContext contextStorage;
IRSpecContext* context = &contextStorage;
context->builder = builder;
context->module = module;
context->originalModule = originalIRModule;
// First, we will populate a map with all of the IR values
// that use the same mangled name, to make lookup easier
// in other steps.
for (auto gv = originalIRModule->firstGlobalValue; gv; gv = gv->nextGlobalValue)
{
String mangledName = gv->mangledName;
if (mangledName == "")
continue;
RefPtr<IRSpecSymbol> sym = new IRSpecSymbol();
sym->irGlobalValue = gv;
RefPtr<IRSpecSymbol> prev;
if (context->symbols.TryGetValue(mangledName, prev))
{
sym->nextWithSameName = prev->nextWithSameName;
prev->nextWithSameName = sym;
}
else
{
context->symbols.Add(mangledName, sym);
}
}
// Next, we want to optimize lookup over
auto globalStructLayout = getGlobalStructLayout(programLayout);
for (auto globalVarLayout : globalStructLayout->fields)
{
String mangledName = getMangledName(globalVarLayout->varDecl);
context->globalVarLayouts.AddIfNotExists(mangledName, globalVarLayout);
}
// 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.
// Depending on the downstream target, we may need to apply some
// guaranteed transformations to legalize things. We will go
// ahead and apply there here for now.
switch (target)
{
case CodeGenTarget::GLSL:
{
legalizeEntryPointForGLSL(session, irEntryPoint, entryPointLayout);
}
break;
default:
break;
}
return module;
}
}
|