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
|
// TypeLayout.cpp
#include "type-layout.h"
#include "syntax.h"
#include <assert.h>
namespace Slang {
size_t RoundToAlignment(size_t offset, size_t alignment)
{
size_t remainder = offset % alignment;
if (remainder == 0)
return offset;
else
return offset + (alignment - remainder);
}
LayoutSize RoundToAlignment(LayoutSize offset, size_t alignment)
{
// An infinite size is assumed to be maximally aligned.
if(offset.isInfinite())
return LayoutSize::infinite();
return RoundToAlignment(offset.getFiniteValue(), alignment);
}
static size_t RoundUpToPowerOfTwo( size_t value )
{
// TODO(tfoley): I know this isn't a fast approach
size_t result = 1;
while (result < value)
result *= 2;
return result;
}
//
struct DefaultLayoutRulesImpl : SimpleLayoutRulesImpl
{
// Get size and alignment for a single value of base type.
SimpleLayoutInfo GetScalarLayout(BaseType baseType) override
{
switch (baseType)
{
case BaseType::Void: return SimpleLayoutInfo();
// Note: By convention, a `bool` in a constant buffer is stored as an `int.
// This default may eventually change, at which point this logic will need
// to be updated.
//
// TODO: We should probably warn in this case, since storing a `bool` in
// a constant buffer seems like a Bad Idea anyway.
//
case BaseType::Bool: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4, 4 );
case BaseType::Int8: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 1,1);
case BaseType::Int16: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 2,2);
case BaseType::Int: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4);
case BaseType::Int64: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 8,8);
case BaseType::UInt8: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 1,1);
case BaseType::UInt16: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 2,2);
case BaseType::UInt: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4);
case BaseType::UInt64: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 8,8);
case BaseType::Half: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 2,2);
case BaseType::Float: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 4,4);
case BaseType::Double: return SimpleLayoutInfo( LayoutResourceKind::Uniform, 8,8);
default:
SLANG_UNEXPECTED("uhandled scalar type");
UNREACHABLE_RETURN(SimpleLayoutInfo( LayoutResourceKind::Uniform, 0, 1 ));
}
}
SimpleArrayLayoutInfo GetArrayLayout( SimpleLayoutInfo elementInfo, LayoutSize elementCount) override
{
SLANG_RELEASE_ASSERT(elementInfo.size.isFinite());
auto elementSize = elementInfo.size.getFiniteValue();
auto elementAlignment = elementInfo.alignment;
auto elementStride = RoundToAlignment(elementSize, elementAlignment);
// An array with no elements will have zero size.
//
LayoutSize arraySize = 0;
//
// Any array with a non-zero number of elements will need
// to have space for N elements of size `elementSize`, with
// the constraints that there must be `elementStride` bytes
// between consecutive elements.
//
if( elementCount > 0 )
{
// We can think of this as either allocating (N-1)
// chunks of size `elementStride` (for most of the elements)
// and then one final chunk of size `elementSize` for
// the last element, or equivalently as allocating
// N chunks of size `elementStride` and then "giving back"
// the final `elementStride - elementSize` bytes.
//
arraySize = (elementStride * (elementCount-1)) + elementSize;
}
SimpleArrayLayoutInfo arrayInfo;
arrayInfo.kind = elementInfo.kind;
arrayInfo.size = arraySize;
arrayInfo.alignment = elementAlignment;
arrayInfo.elementStride = elementStride;
return arrayInfo;
}
SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override
{
SimpleLayoutInfo vectorInfo;
vectorInfo.kind = elementInfo.kind;
vectorInfo.size = elementInfo.size * elementCount;
vectorInfo.alignment = elementInfo.alignment;
return vectorInfo;
}
SimpleArrayLayoutInfo GetMatrixLayout(SimpleLayoutInfo elementInfo, size_t rowCount, size_t columnCount) override
{
// The default behavior here is to lay out a matrix
// as an array of row vectors (that is row-major).
//
// In practice, the code that calls `GetMatrixLayout` will
// potentially transpose the row/column counts in order
// to get layouts with a different convention.
//
return GetArrayLayout(
GetVectorLayout(elementInfo, columnCount),
rowCount);
}
UniformLayoutInfo BeginStructLayout() override
{
UniformLayoutInfo structInfo(0, 1);
return structInfo;
}
LayoutSize AddStructField(UniformLayoutInfo* ioStructInfo, UniformLayoutInfo fieldInfo) override
{
// Skip zero-size fields
if(fieldInfo.size == 0)
return ioStructInfo->size;
// A struct type must be at least as aligned as its most-aligned field.
ioStructInfo->alignment = std::max(ioStructInfo->alignment, fieldInfo.alignment);
// The new field will be added to the end of the struct.
auto fieldBaseOffset = ioStructInfo->size;
// We need to ensure that the offset for the field will respect its alignment
auto fieldOffset = RoundToAlignment(fieldBaseOffset, fieldInfo.alignment);
// The size of the struct must be adjusted to cover the bytes consumed
// by this field.
ioStructInfo->size = fieldOffset + fieldInfo.size;
return fieldOffset;
}
void EndStructLayout(UniformLayoutInfo* ioStructInfo) override
{
SLANG_UNUSED(ioStructInfo);
// Note: A traditional C layout algorithm would adjust the size
// of a struct type so that it is a multiple of the alignment.
// This is a parsimonious design choice because it means that
// `sizeof(T)` can both be used when copying/allocating a single
// value of type `T` or an array of N values, without having to
// consider more details.
//
// Of course the choice also has down-sides in that wrapping things
// into a `struct` can affect layout in ways that waste space. E.g.,
// the following two cases don't lay out the same:
//
// struct S0 { double d; float f; float g; };
//
// struct X { double d; float f; }
// struct S1 { X x; float g; }
//
// Even though `S0::g` and `S1::g` have the same amount of useful
// data in front of them, they will not land at the same offset,
// and the resulting struct sizes will differ (`sizeof(S0)` will be
// 16 while `sizeof(S1)` will be 24).
//
// Slang doesn't get to be opinionated about this stuff because
// there is already precedent in both HLSL and GLSL for types
// that have a size that is not rounded up to their alignment.
//
// Our default layout rules won't implement the C-like policy,
// and instead it will be injected in the concrete implementations
// that require it.
}
};
/// Common behavior for GLSL-family layout.
struct GLSLBaseLayoutRulesImpl : DefaultLayoutRulesImpl
{
typedef DefaultLayoutRulesImpl Super;
SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo elementInfo, size_t elementCount) override
{
// The `std140` and `std430` rules require vectors to be aligned to the next power of
// two up from their size (so a `float2` is 8-byte aligned, and a `float3` is
// 16-byte aligned).
//
// Note that in this case we have a type layout where the size is *not* a multiple
// of the alignment, so it should be possible to pack a scalar after a `float3`.
//
SLANG_RELEASE_ASSERT(elementInfo.kind == LayoutResourceKind::Uniform);
SLANG_RELEASE_ASSERT(elementInfo.size.isFinite());
auto size = elementInfo.size.getFiniteValue() * elementCount;
SimpleLayoutInfo vectorInfo(
LayoutResourceKind::Uniform,
size,
RoundUpToPowerOfTwo(size));
return vectorInfo;
}
SimpleArrayLayoutInfo GetArrayLayout( SimpleLayoutInfo elementInfo, LayoutSize elementCount) override
{
// The size of an array must be rounded up to be a multiple of its alignment.
//
auto info = Super::GetArrayLayout(elementInfo, elementCount);
info.size = RoundToAlignment(info.size, info.alignment);
return info;
}
void EndStructLayout(UniformLayoutInfo* ioStructInfo) override
{
// The size of a `struct` must be rounded up to be a multiple of its alignment.
//
ioStructInfo->size = RoundToAlignment(ioStructInfo->size, ioStructInfo->alignment);
}
};
/// The GLSL `std430` layout rules.
struct Std430LayoutRulesImpl : GLSLBaseLayoutRulesImpl
{
// These rules don't actually need any differences from our
// base/common GLSL layout rules.
};
/// The GLSL `std430` layout rules.
struct Std140LayoutRulesImpl : GLSLBaseLayoutRulesImpl
{
typedef GLSLBaseLayoutRulesImpl Super;
SimpleArrayLayoutInfo GetArrayLayout(SimpleLayoutInfo elementInfo, LayoutSize elementCount) override
{
// The `std140` rules require that array elements
// be aligned on 16-byte boundaries.
//
if(elementInfo.kind == LayoutResourceKind::Uniform)
{
if (elementInfo.alignment < 16)
elementInfo.alignment = 16;
}
return Super::GetArrayLayout(elementInfo, elementCount);
}
UniformLayoutInfo BeginStructLayout() override
{
// The `std140` rules require that a `struct` type
// be at least 16-byte aligned.
//
return UniformLayoutInfo(0, 16);
}
};
struct HLSLConstantBufferLayoutRulesImpl : DefaultLayoutRulesImpl
{
typedef DefaultLayoutRulesImpl Super;
// Similar to GLSL `std140` rules, an HLSL constant buffer requires that
// `struct` and array types have 16-byte alignement.
//
// Unlike GLSL `std140`, the overall size of an array or `struct` type
// is *not* rounded up to the alignment, so it is possible for later
// fields to sneak into the "tail space" left behind by a preceding
// structure or array. E.g., in this example:
//
// struct S { float3 a[2]; float b; };
//
// The stride of the array `a` is 16 bytes per element, but the size
// of `a` will only be 28 bytes (not 32), so that `b` can fit into
// the space after the last array element and the overall structure
// will have a size of 32 bytes.
SimpleArrayLayoutInfo GetArrayLayout(SimpleLayoutInfo elementInfo, LayoutSize elementCount) override
{
if(elementInfo.kind == LayoutResourceKind::Uniform)
{
if (elementInfo.alignment < 16)
elementInfo.alignment = 16;
}
return Super::GetArrayLayout(elementInfo, elementCount);
}
UniformLayoutInfo BeginStructLayout() override
{
return UniformLayoutInfo(0, 16);
}
// HLSL layout rules do *not* impose additional alignment
// constraints on vectors (e.g., all of `float`, `float2`,
// `float3`, and `float4` have 4-byte alignment), but instead
// they impose a rule that any `struct` field must not
// "straddle" a 16-byte boundary.
//
// This has the effect of making it *look* like `float4`
// values have 16-byte alignment in practice, but the
// effects on `float2` and `float3` are more nuanched and
// lead to different result than the GLSL rules.
//
LayoutSize AddStructField(UniformLayoutInfo* ioStructInfo, UniformLayoutInfo fieldInfo) override
{
// Skip zero-size fields
if(fieldInfo.size == 0)
return ioStructInfo->size;
ioStructInfo->alignment = std::max(ioStructInfo->alignment, fieldInfo.alignment);
ioStructInfo->size = RoundToAlignment(ioStructInfo->size, fieldInfo.alignment);
LayoutSize fieldOffset = ioStructInfo->size;
LayoutSize fieldSize = fieldInfo.size;
// Would this field cross a 16-byte boundary?
auto registerSize = 16;
auto startRegister = fieldOffset / registerSize;
auto endRegister = (fieldOffset + fieldSize - 1) / registerSize;
if (startRegister != endRegister)
{
ioStructInfo->size = RoundToAlignment(ioStructInfo->size, size_t(registerSize));
fieldOffset = ioStructInfo->size;
}
ioStructInfo->size += fieldInfo.size;
return fieldOffset;
}
};
struct HLSLStructuredBufferLayoutRulesImpl : DefaultLayoutRulesImpl
{
// HLSL structured buffers drop the restrictions added for constant buffers,
// but retain the rules around not adjusting the size of an array or
// structure to its alignment. In this way they should match our
// default layout rules.
};
struct DefaultVaryingLayoutRulesImpl : DefaultLayoutRulesImpl
{
LayoutResourceKind kind;
DefaultVaryingLayoutRulesImpl(LayoutResourceKind kind)
: kind(kind)
{}
// hook to allow differentiating for input/output
virtual LayoutResourceKind getKind()
{
return kind;
}
SimpleLayoutInfo GetScalarLayout(BaseType) override
{
// Assume that all scalars take up one "slot"
return SimpleLayoutInfo(
getKind(),
1);
}
SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo, size_t) override
{
// Vectors take up one slot by default
//
// TODO: some platforms may decide that vectors of `double` need
// special handling
return SimpleLayoutInfo(
getKind(),
1);
}
};
struct GLSLVaryingLayoutRulesImpl : DefaultVaryingLayoutRulesImpl
{
GLSLVaryingLayoutRulesImpl(LayoutResourceKind kind)
: DefaultVaryingLayoutRulesImpl(kind)
{}
};
struct HLSLVaryingLayoutRulesImpl : DefaultVaryingLayoutRulesImpl
{
HLSLVaryingLayoutRulesImpl(LayoutResourceKind kind)
: DefaultVaryingLayoutRulesImpl(kind)
{}
};
//
struct GLSLSpecializationConstantLayoutRulesImpl : DefaultLayoutRulesImpl
{
LayoutResourceKind getKind()
{
return LayoutResourceKind::SpecializationConstant;
}
SimpleLayoutInfo GetScalarLayout(BaseType) override
{
// Assume that all scalars take up one "slot"
return SimpleLayoutInfo(
getKind(),
1);
}
SimpleLayoutInfo GetVectorLayout(SimpleLayoutInfo, size_t elementCount) override
{
// GLSL doesn't support vectors of specialization constants,
// but we will assume that, if supported, they would use one slot per element.
return SimpleLayoutInfo(
getKind(),
elementCount);
}
};
GLSLSpecializationConstantLayoutRulesImpl kGLSLSpecializationConstantLayoutRulesImpl;
//
struct GLSLObjectLayoutRulesImpl : ObjectLayoutRulesImpl
{
virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind) override
{
// In Vulkan GLSL, pretty much every object is just a descriptor-table slot.
// We can refine this method once we support a case where this isn't true.
return SimpleLayoutInfo(LayoutResourceKind::DescriptorTableSlot, 1);
}
};
GLSLObjectLayoutRulesImpl kGLSLObjectLayoutRulesImpl;
struct GLSLPushConstantBufferObjectLayoutRulesImpl : GLSLObjectLayoutRulesImpl
{
virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind /*kind*/) override
{
// Special-case the layout for a constant-buffer, because we don't
// want it to allocate a descriptor-table slot
return SimpleLayoutInfo(LayoutResourceKind::PushConstantBuffer, 1);
}
};
GLSLPushConstantBufferObjectLayoutRulesImpl kGLSLPushConstantBufferObjectLayoutRulesImpl_;
struct GLSLShaderRecordConstantBufferObjectLayoutRulesImpl : GLSLObjectLayoutRulesImpl
{
virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind /*kind*/) override
{
// Special-case the layout for a constant-buffer, because we don't
// want it to allocate a descriptor-table slot
return SimpleLayoutInfo(LayoutResourceKind::ShaderRecord, 1);
}
};
GLSLShaderRecordConstantBufferObjectLayoutRulesImpl kGLSLShaderRecordConstantBufferObjectLayoutRulesImpl_;
struct HLSLObjectLayoutRulesImpl : ObjectLayoutRulesImpl
{
virtual SimpleLayoutInfo GetObjectLayout(ShaderParameterKind kind) override
{
switch( kind )
{
case ShaderParameterKind::ConstantBuffer:
return SimpleLayoutInfo(LayoutResourceKind::ConstantBuffer, 1);
case ShaderParameterKind::TextureUniformBuffer:
case ShaderParameterKind::StructuredBuffer:
case ShaderParameterKind::RawBuffer:
case ShaderParameterKind::Buffer:
case ShaderParameterKind::Texture:
return SimpleLayoutInfo(LayoutResourceKind::ShaderResource, 1);
case ShaderParameterKind::MutableStructuredBuffer:
case ShaderParameterKind::MutableRawBuffer:
case ShaderParameterKind::MutableBuffer:
case ShaderParameterKind::MutableTexture:
return SimpleLayoutInfo(LayoutResourceKind::UnorderedAccess, 1);
case ShaderParameterKind::SamplerState:
return SimpleLayoutInfo(LayoutResourceKind::SamplerState, 1);
case ShaderParameterKind::TextureSampler:
case ShaderParameterKind::MutableTextureSampler:
case ShaderParameterKind::InputRenderTarget:
// TODO: how to handle these?
default:
SLANG_UNEXPECTED("unhandled shader parameter kind");
UNREACHABLE_RETURN(SimpleLayoutInfo());
}
}
};
HLSLObjectLayoutRulesImpl kHLSLObjectLayoutRulesImpl;
// HACK: Treating ray-tracing input/output as if it was another
// case of varying input/output when it really needs to be
// based on byte storage/layout.
//
struct GLSLRayTracingLayoutRulesImpl : DefaultVaryingLayoutRulesImpl
{
GLSLRayTracingLayoutRulesImpl(LayoutResourceKind kind)
: DefaultVaryingLayoutRulesImpl(kind)
{}
};
struct HLSLRayTracingLayoutRulesImpl : DefaultVaryingLayoutRulesImpl
{
HLSLRayTracingLayoutRulesImpl(LayoutResourceKind kind)
: DefaultVaryingLayoutRulesImpl(kind)
{}
};
Std140LayoutRulesImpl kStd140LayoutRulesImpl;
Std430LayoutRulesImpl kStd430LayoutRulesImpl;
HLSLConstantBufferLayoutRulesImpl kHLSLConstantBufferLayoutRulesImpl;
HLSLStructuredBufferLayoutRulesImpl kHLSLStructuredBufferLayoutRulesImpl;
GLSLVaryingLayoutRulesImpl kGLSLVaryingInputLayoutRulesImpl(LayoutResourceKind::VertexInput);
GLSLVaryingLayoutRulesImpl kGLSLVaryingOutputLayoutRulesImpl(LayoutResourceKind::FragmentOutput);
GLSLRayTracingLayoutRulesImpl kGLSLRayPayloadParameterLayoutRulesImpl(LayoutResourceKind::RayPayload);
GLSLRayTracingLayoutRulesImpl kGLSLCallablePayloadParameterLayoutRulesImpl(LayoutResourceKind::CallablePayload);
GLSLRayTracingLayoutRulesImpl kGLSLHitAttributesParameterLayoutRulesImpl(LayoutResourceKind::HitAttributes);
HLSLVaryingLayoutRulesImpl kHLSLVaryingInputLayoutRulesImpl(LayoutResourceKind::VertexInput);
HLSLVaryingLayoutRulesImpl kHLSLVaryingOutputLayoutRulesImpl(LayoutResourceKind::FragmentOutput);
HLSLRayTracingLayoutRulesImpl kHLSLRayPayloadParameterLayoutRulesImpl(LayoutResourceKind::RayPayload);
HLSLRayTracingLayoutRulesImpl kHLSLCallablePayloadParameterLayoutRulesImpl(LayoutResourceKind::CallablePayload);
HLSLRayTracingLayoutRulesImpl kHLSLHitAttributesParameterLayoutRulesImpl(LayoutResourceKind::HitAttributes);
//
struct GLSLLayoutRulesFamilyImpl : LayoutRulesFamilyImpl
{
virtual LayoutRulesImpl* getConstantBufferRules() override;
virtual LayoutRulesImpl* getPushConstantBufferRules() override;
virtual LayoutRulesImpl* getTextureBufferRules() override;
virtual LayoutRulesImpl* getVaryingInputRules() override;
virtual LayoutRulesImpl* getVaryingOutputRules() override;
virtual LayoutRulesImpl* getSpecializationConstantRules() override;
virtual LayoutRulesImpl* getShaderStorageBufferRules() override;
virtual LayoutRulesImpl* getParameterBlockRules() override;
LayoutRulesImpl* getRayPayloadParameterRules() override;
LayoutRulesImpl* getCallablePayloadParameterRules() override;
LayoutRulesImpl* getHitAttributesParameterRules() override;
LayoutRulesImpl* getShaderRecordConstantBufferRules() override;
};
struct HLSLLayoutRulesFamilyImpl : LayoutRulesFamilyImpl
{
virtual LayoutRulesImpl* getConstantBufferRules() override;
virtual LayoutRulesImpl* getPushConstantBufferRules() override;
virtual LayoutRulesImpl* getTextureBufferRules() override;
virtual LayoutRulesImpl* getVaryingInputRules() override;
virtual LayoutRulesImpl* getVaryingOutputRules() override;
virtual LayoutRulesImpl* getSpecializationConstantRules() override;
virtual LayoutRulesImpl* getShaderStorageBufferRules() override;
virtual LayoutRulesImpl* getParameterBlockRules() override;
LayoutRulesImpl* getRayPayloadParameterRules() override;
LayoutRulesImpl* getCallablePayloadParameterRules() override;
LayoutRulesImpl* getHitAttributesParameterRules() override;
LayoutRulesImpl* getShaderRecordConstantBufferRules() override;
};
GLSLLayoutRulesFamilyImpl kGLSLLayoutRulesFamilyImpl;
HLSLLayoutRulesFamilyImpl kHLSLLayoutRulesFamilyImpl;
// GLSL cases
LayoutRulesImpl kStd140LayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kStd140LayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kStd430LayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kStd430LayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kGLSLPushConstantLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kStd430LayoutRulesImpl, &kGLSLPushConstantBufferObjectLayoutRulesImpl_,
};
LayoutRulesImpl kGLSLShaderRecordLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kStd430LayoutRulesImpl, &kGLSLShaderRecordConstantBufferObjectLayoutRulesImpl_,
};
LayoutRulesImpl kGLSLVaryingInputLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kGLSLVaryingInputLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kGLSLVaryingOutputLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kGLSLVaryingOutputLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kGLSLSpecializationConstantLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kGLSLSpecializationConstantLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kGLSLRayPayloadParameterLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kGLSLRayPayloadParameterLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kGLSLCallablePayloadParameterLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kGLSLCallablePayloadParameterLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kGLSLHitAttributesParameterLayoutRulesImpl_ = {
&kGLSLLayoutRulesFamilyImpl, &kGLSLHitAttributesParameterLayoutRulesImpl, &kGLSLObjectLayoutRulesImpl,
};
// HLSL cases
LayoutRulesImpl kHLSLConstantBufferLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLConstantBufferLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kHLSLStructuredBufferLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLStructuredBufferLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kHLSLVaryingInputLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLVaryingInputLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kHLSLVaryingOutputLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLVaryingOutputLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kHLSLRayPayloadParameterLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLRayPayloadParameterLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kHLSLCallablePayloadParameterLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLCallablePayloadParameterLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
LayoutRulesImpl kHLSLHitAttributesParameterLayoutRulesImpl_ = {
&kHLSLLayoutRulesFamilyImpl, &kHLSLHitAttributesParameterLayoutRulesImpl, &kHLSLObjectLayoutRulesImpl,
};
//
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getConstantBufferRules()
{
return &kStd140LayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getParameterBlockRules()
{
// TODO: actually pick something appropriate
return &kStd140LayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getPushConstantBufferRules()
{
return &kGLSLPushConstantLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getShaderRecordConstantBufferRules()
{
return &kGLSLShaderRecordLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getTextureBufferRules()
{
return nullptr;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getVaryingInputRules()
{
return &kGLSLVaryingInputLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getVaryingOutputRules()
{
return &kGLSLVaryingOutputLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getSpecializationConstantRules()
{
return &kGLSLSpecializationConstantLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getShaderStorageBufferRules()
{
return &kStd430LayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getRayPayloadParameterRules()
{
return &kGLSLRayPayloadParameterLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getCallablePayloadParameterRules()
{
return &kGLSLCallablePayloadParameterLayoutRulesImpl_;
}
LayoutRulesImpl* GLSLLayoutRulesFamilyImpl::getHitAttributesParameterRules()
{
return &kGLSLHitAttributesParameterLayoutRulesImpl_;
}
//
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getConstantBufferRules()
{
return &kHLSLConstantBufferLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getParameterBlockRules()
{
// TODO: actually pick something appropriate...
return &kHLSLConstantBufferLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getPushConstantBufferRules()
{
return &kHLSLConstantBufferLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getShaderRecordConstantBufferRules()
{
return &kHLSLConstantBufferLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getTextureBufferRules()
{
return nullptr;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getVaryingInputRules()
{
return &kHLSLVaryingInputLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getVaryingOutputRules()
{
return &kHLSLVaryingOutputLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getSpecializationConstantRules()
{
return nullptr;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getShaderStorageBufferRules()
{
return nullptr;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getRayPayloadParameterRules()
{
return &kHLSLRayPayloadParameterLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getCallablePayloadParameterRules()
{
return &kHLSLCallablePayloadParameterLayoutRulesImpl_;
}
LayoutRulesImpl* HLSLLayoutRulesFamilyImpl::getHitAttributesParameterRules()
{
return &kHLSLHitAttributesParameterLayoutRulesImpl_;
}
//
LayoutRulesImpl* GetLayoutRulesImpl(LayoutRule rule)
{
switch (rule)
{
case LayoutRule::Std140: return &kStd140LayoutRulesImpl_;
case LayoutRule::Std430: return &kStd430LayoutRulesImpl_;
case LayoutRule::HLSLConstantBuffer: return &kHLSLConstantBufferLayoutRulesImpl_;
case LayoutRule::HLSLStructuredBuffer: return &kHLSLStructuredBufferLayoutRulesImpl_;
default:
return nullptr;
}
}
LayoutRulesFamilyImpl* getDefaultLayoutRulesFamilyForTarget(TargetRequest* targetReq)
{
switch (targetReq->getTarget())
{
case CodeGenTarget::HLSL:
case CodeGenTarget::DXBytecode:
case CodeGenTarget::DXBytecodeAssembly:
case CodeGenTarget::DXIL:
case CodeGenTarget::DXILAssembly:
return &kHLSLLayoutRulesFamilyImpl;
case CodeGenTarget::GLSL:
case CodeGenTarget::SPIRV:
case CodeGenTarget::SPIRVAssembly:
return &kGLSLLayoutRulesFamilyImpl;
default:
return nullptr;
}
}
TypeLayoutContext getInitialLayoutContextForTarget(TargetRequest* targetReq, ProgramLayout* programLayout)
{
LayoutRulesFamilyImpl* rulesFamily = getDefaultLayoutRulesFamilyForTarget(targetReq);
TypeLayoutContext context;
context.targetReq = targetReq;
context.programLayout = programLayout;
context.rules = nullptr;
context.matrixLayoutMode = targetReq->getDefaultMatrixLayoutMode();
if( rulesFamily )
{
context.rules = rulesFamily->getConstantBufferRules();
}
return context;
}
static LayoutSize GetElementCount(RefPtr<IntVal> val)
{
// Lack of a size indicates an unbounded array.
if(!val)
return LayoutSize::infinite();
if (auto constantVal = as<ConstantIntVal>(val))
{
return LayoutSize(LayoutSize::RawValue(constantVal->value));
}
else if( auto varRefVal = as<GenericParamIntVal>(val) )
{
// TODO: We want to treat the case where the number of
// elements in an array depends on a generic parameter
// much like the case where the number of elements is
// unbounded, *but* we can't just blindly do that because
// an API might disallow unbounded arrays in various
// cases where a generic bound might work (because
// any concrete specialization will have a finite bound...)
//
return 0;
}
SLANG_UNEXPECTED("unhandled integer literal kind");
UNREACHABLE_RETURN(LayoutSize(0));
}
bool IsResourceKind(LayoutResourceKind kind)
{
switch (kind)
{
case LayoutResourceKind::None:
case LayoutResourceKind::Uniform:
return false;
default:
return true;
}
}
/// A custom tuple to capture the outputs of type layout
struct TypeLayoutResult
{
/// The actual heap-allocated layout object with all the details
RefPtr<TypeLayout> layout;
/// A simplified representation of layout information.
///
/// This information is suitable for the case where a type only
/// consumes a single resource.
///
SimpleLayoutInfo info;
/// Default constructor.
TypeLayoutResult()
{}
/// Construct a result from the given layout object and simple layout info.
TypeLayoutResult(RefPtr<TypeLayout> inLayout, SimpleLayoutInfo const& inInfo)
: layout(inLayout)
, info(inInfo)
{}
};
/// Create a type layout for a type that has simple layout needs.
///
/// This handles any type that can express its layout in `SimpleLayoutInfo`,
/// and that only needs a `TypeLayout` and not a refined subclass.
///
static TypeLayoutResult createSimpleTypeLayout(
SimpleLayoutInfo info,
RefPtr<Type> type,
LayoutRulesImpl* rules)
{
RefPtr<TypeLayout> typeLayout = new TypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
typeLayout->uniformAlignment = info.alignment;
typeLayout->addResourceUsage(info.kind, info.size);
return TypeLayoutResult(typeLayout, info);
}
static SimpleLayoutInfo getParameterGroupLayoutInfo(
RefPtr<ParameterGroupType> type,
LayoutRulesImpl* rules)
{
if( as<ConstantBufferType>(type) )
{
return rules->GetObjectLayout(ShaderParameterKind::ConstantBuffer);
}
else if( as<TextureBufferType>(type) )
{
return rules->GetObjectLayout(ShaderParameterKind::TextureUniformBuffer);
}
else if( as<GLSLShaderStorageBufferType>(type) )
{
return rules->GetObjectLayout(ShaderParameterKind::ShaderStorageBuffer);
}
else if (as<ParameterBlockType>(type))
{
// Note: we default to consuming zero register spces here, because
// a parameter block might not contain anything (or all it contains
// is other blocks), and so it won't get a space allocated.
//
// This choice *also* means that in the case where we don't actually
// want to allocate register spaces to blocks at all, we haven't
// committed to that choice here.
//
// TODO: wouldn't it be any different to just allocate this
// as an empty `SimpleLayoutInfo` of any other kind?
return SimpleLayoutInfo(LayoutResourceKind::RegisterSpace, 0);
}
// TODO: the vertex-input and fragment-output cases should
// only actually apply when we are at the appropriate stage in
// the pipeline...
else if( as<GLSLInputParameterGroupType>(type) )
{
return SimpleLayoutInfo(LayoutResourceKind::VertexInput, 0);
}
else if( as<GLSLOutputParameterGroupType>(type) )
{
return SimpleLayoutInfo(LayoutResourceKind::FragmentOutput, 0);
}
else
{
SLANG_UNEXPECTED("unhandled parameter block type");
UNREACHABLE_RETURN(SimpleLayoutInfo());
}
}
static bool isOpenGLTarget(TargetRequest*)
{
// We aren't officially supporting OpenGL right now
return false;
}
bool isD3DTarget(TargetRequest* targetReq)
{
switch( targetReq->getTarget() )
{
case CodeGenTarget::HLSL:
case CodeGenTarget::DXBytecode:
case CodeGenTarget::DXBytecodeAssembly:
case CodeGenTarget::DXIL:
case CodeGenTarget::DXILAssembly:
return true;
default:
return false;
}
}
bool isKhronosTarget(TargetRequest* targetReq)
{
switch( targetReq->getTarget() )
{
default:
return false;
case CodeGenTarget::GLSL:
case CodeGenTarget::SPIRV:
case CodeGenTarget::SPIRVAssembly:
return true;
}
}
static bool isD3D11Target(TargetRequest*)
{
// We aren't officially supporting D3D11 right now
return false;
}
static bool isD3D12Target(TargetRequest* targetReq)
{
// We are currently only officially supporting D3D12
return isD3DTarget(targetReq);
}
static bool isSM5OrEarlier(TargetRequest* targetReq)
{
if(!isD3DTarget(targetReq))
return false;
auto profile = targetReq->getTargetProfile();
if(profile.getFamily() == ProfileFamily::DX)
{
if(profile.GetVersion() <= ProfileVersion::DX_5_0)
return true;
}
return false;
}
static bool isSM5_1OrLater(TargetRequest* targetReq)
{
if(!isD3DTarget(targetReq))
return false;
auto profile = targetReq->getTargetProfile();
if(profile.getFamily() == ProfileFamily::DX)
{
if(profile.GetVersion() >= ProfileVersion::DX_5_1)
return true;
}
return false;
}
static bool isVulkanTarget(TargetRequest* targetReq)
{
// For right now, any Khronos-related target is assumed
// to be a Vulkan target.
return isKhronosTarget(targetReq);
}
static bool shouldAllocateRegisterSpaceForParameterBlock(
TypeLayoutContext const& context)
{
auto targetReq = context.targetReq;
// We *never* want to use register spaces/sets under
// OpenGL, D3D11, or for Shader Model 5.0 or earlier.
if(isOpenGLTarget(targetReq) || isD3D11Target(targetReq) || isSM5OrEarlier(targetReq))
return false;
// If we know that we are targetting Vulkan, then
// the only way to effectively use parameter blocks
// is by using descriptor sets.
if(isVulkanTarget(targetReq))
return true;
// If none of the above passed, then it seems like we
// are generating code for D3D12, and using SM5.1 or later.
// We will use a register space for parameter blocks *if*
// the target options tell us to:
if( isD3D12Target(targetReq) && isSM5_1OrLater(targetReq) )
{
return true;
}
return false;
}
// Given an existing type layout `oldTypeLayout`, apply offsets
// to any contained fields based on the resource infos in `offsetTypeLayout`
// *and* the usage implied by `offsetLayout`
RefPtr<TypeLayout> applyOffsetToTypeLayout(
RefPtr<TypeLayout> oldTypeLayout,
RefPtr<TypeLayout> offsetTypeLayout)
{
// There is no need to apply offsets if the old type and the offset
// don't share any resource infos in common.
bool anyHit = false;
for (auto oldResInfo : oldTypeLayout->resourceInfos)
{
if (auto offsetResInfo = offsetTypeLayout->FindResourceInfo(oldResInfo.kind))
{
anyHit = true;
break;
}
}
if (!anyHit)
return oldTypeLayout;
RefPtr<TypeLayout> newTypeLayout;
if (auto oldStructTypeLayout = oldTypeLayout.as<StructTypeLayout>())
{
RefPtr<StructTypeLayout> newStructTypeLayout = new StructTypeLayout();
newStructTypeLayout->type = oldStructTypeLayout->type;
newStructTypeLayout->uniformAlignment = oldStructTypeLayout->uniformAlignment;
Dictionary<VarLayout*, VarLayout*> mapOldFieldToNew;
for (auto oldField : oldStructTypeLayout->fields)
{
RefPtr<VarLayout> newField = new VarLayout();
newField->varDecl = oldField->varDecl;
newField->typeLayout = oldField->typeLayout;
newField->flags = oldField->flags;
newField->semanticIndex = oldField->semanticIndex;
newField->semanticName = oldField->semanticName;
newField->stage = oldField->stage;
newField->systemValueSemantic = oldField->systemValueSemantic;
newField->systemValueSemanticIndex = oldField->systemValueSemanticIndex;
for (auto oldResInfo : oldField->resourceInfos)
{
auto newResInfo = newField->findOrAddResourceInfo(oldResInfo.kind);
newResInfo->index = oldResInfo.index;
newResInfo->space = oldResInfo.space;
if (auto offsetResInfo = offsetTypeLayout->FindResourceInfo(oldResInfo.kind))
{
// We should not be trying to offset things by an infinite amount,
// since that would leave all the indices undefined.
SLANG_RELEASE_ASSERT(offsetResInfo->count.isFinite());
newResInfo->index += offsetResInfo->count.getFiniteValue();
}
}
newStructTypeLayout->fields.Add(newField);
mapOldFieldToNew.Add(oldField.Ptr(), newField.Ptr());
}
for (auto entry : oldStructTypeLayout->mapVarToLayout)
{
VarLayout* newFieldLayout = nullptr;
if (mapOldFieldToNew.TryGetValue(entry.Value.Ptr(), newFieldLayout))
{
newStructTypeLayout->mapVarToLayout.Add(entry.Key, newFieldLayout);
}
}
newTypeLayout = newStructTypeLayout;
}
else
{
// TODO: need to handle other cases here
return oldTypeLayout;
}
// No matter what replacement we plug in for the element type, we need to copy
// over its resource usage:
for (auto oldResInfo : oldTypeLayout->resourceInfos)
{
auto newResInfo = newTypeLayout->findOrAddResourceInfo(oldResInfo.kind);
newResInfo->count = oldResInfo.count;
}
return newTypeLayout;
}
/// Take a type layout that might include pending items and fold them into the layout.
static RefPtr<TypeLayout> flushPendingItems(
TypeLayoutContext const& context,
RefPtr<TypeLayout> layout)
{
SLANG_UNUSED(context);
// If there are no pending items on the layout,
// then there is nothing to be done.
//
if(layout->pendingItems.Count() == 0)
return layout;
// We need to compute a new type layout that reflects
// the resource usage of the provided `layout`, plus
// any resource usage for the pending items.
//
// TODO: To be correct we should construct a new `TypeLayout`
// of the same class, but that would take more work, so
// we'll re-use the one we already have... kind of gross...
//
for( auto pendingItem : layout->pendingItems )
{
auto itemTypeLayout = pendingItem.getTypeLayout();
// Any resources used by a pending item should be
// billed against the flushed layout we are computing.
//
// TODO: We need to make this handlde ordinary/uniform
// data carefully, so that it respects alignment and
// other layout rules for the target.
//
// TODO: We should only be adding in resource usage
// that can be "hidden" by the type of parameter block
// being built (e.g., only a `ParameterBlock` that allocates
// full `set`s/`space`s can hide the `register`s/`binding`s
// used by resource fields).
//
// TODO: we need to write something back to the item,
// which should have a `VarLayout` or something like
// that attached to it!
//
for( auto resInfo : itemTypeLayout->resourceInfos )
{
layout->addResourceUsage(resInfo);
}
}
layout->pendingItems.Clear();
return layout;
}
static RefPtr<ParameterGroupTypeLayout> _createParameterGroupTypeLayout(
TypeLayoutContext const& context,
RefPtr<ParameterGroupType> parameterGroupType,
SimpleLayoutInfo parameterGroupInfo,
RefPtr<TypeLayout> rawElementTypeLayout)
{
// If there are any "pending" items that need to be laid out in
// the element type of the parameter group, then we want to flush
// them here.
//
// TODO: We might need to make this only flush *parts* of the pending
// items, based on what the parameter group can absorb, and leave
// other parts still pending in the type layout we return...
//
rawElementTypeLayout = flushPendingItems(
context.with(context.getRulesFamily()->getConstantBufferRules()),
rawElementTypeLayout);
auto parameterGroupRules = context.rules;
RefPtr<ParameterGroupTypeLayout> typeLayout = new ParameterGroupTypeLayout();
typeLayout->type = parameterGroupType;
typeLayout->rules = parameterGroupRules;
RefPtr<TypeLayout> containerTypeLayout = new TypeLayout();
containerTypeLayout->type = parameterGroupType;
containerTypeLayout->rules = parameterGroupRules;
// The layout of the constant buffer if it gets stored
// in another constant buffer is just what we computed
// originally (which should be a single binding "slot"
// and hence no uniform data).
//
SLANG_RELEASE_ASSERT(parameterGroupInfo.kind != LayoutResourceKind::Uniform);
typeLayout->uniformAlignment = 1;
containerTypeLayout->uniformAlignment = 1;
// TODO(tfoley): There is a subtle question here of whether
// a constant buffer declaration that then contains zero
// bytes of uniform data should actually allocate a CB
// binding slot. For now I'm going to try to ignore it,
// but handling this robustly could let other code
// simply handle the "global scope" as a giant outer
// CB declaration...
// Make sure that we allocate resource usage for the
// parameter block itself.
if( parameterGroupInfo.size != 0 )
{
containerTypeLayout->addResourceUsage(
parameterGroupInfo.kind,
parameterGroupInfo.size);
}
// There are several different cases that need to be handled here,
// depending on whether we have a `ParameterBlock`, a `ConstantBuffer`,
// or some other kind of parameter group. Furthermore, in the
// `ParameterBlock` case, we need to deal with different layout
// rules depending on whether a block should map to a register `space`
// in HLSL or not.
// Check if we are working with a parameter block...
auto parameterBlockType = as<ParameterBlockType>(parameterGroupType);
// Check if we have a parameter block *and* it should be
// allocated into its own register space(s)
bool ownRegisterSpace = false;
if (parameterBlockType)
{
// Should we allocate this block its own register space?
if( shouldAllocateRegisterSpaceForParameterBlock(context) )
{
ownRegisterSpace = true;
}
// If we need a register space, then maybe allocate one.
if( ownRegisterSpace )
{
// The basic logic here is that if the parameter block only
// contains other parameter blocks (which themselves have
// their own register spaces), then we don't need to
// allocate *yet another* register space for the block.
bool needsARegisterSpace = false;
for( auto elementResourceInfo : rawElementTypeLayout->resourceInfos )
{
if(elementResourceInfo.kind != LayoutResourceKind::RegisterSpace)
{
needsARegisterSpace = true;
break;
}
}
// If we determine that a register space is needed, then add one here.
if( needsARegisterSpace )
{
typeLayout->addResourceUsage(LayoutResourceKind::RegisterSpace, 1);
}
}
// Next, we check if the parameter block has any uniform data, since
// that means we need to allocate a constant-buffer binding for it.
bool anyUniformData = false;
if(auto elementUniformInfo = rawElementTypeLayout->FindResourceInfo(LayoutResourceKind::Uniform) )
{
if( elementUniformInfo->count != 0 )
{
// We have a non-zero number of bytes of uniform data here.
anyUniformData = true;
}
}
if( anyUniformData )
{
// We need to ensure that the block itself consumes at least one "register" for its
// constant buffer part.
auto cbUsage = parameterGroupRules->GetObjectLayout(ShaderParameterKind::ConstantBuffer);
containerTypeLayout->addResourceUsage(cbUsage.kind, cbUsage.size);
}
}
// The layout for the element type was computed without any knowledge
// of what resources the parent type was going to consume; we now
// need to go through and offset that any starting locations (e.g.,
// in nested `StructTypeLayout`s) based on what we allocated to
// the parent.
//
// Note: at the moment, constant buffers apply their own offsetting
// logic elsewhere, so we need to only do this logic for parameter blocks
RefPtr<TypeLayout> offsetTypeLayout = applyOffsetToTypeLayout(rawElementTypeLayout, containerTypeLayout);
typeLayout->offsetElementTypeLayout = offsetTypeLayout;
RefPtr<VarLayout> containerVarLayout = new VarLayout();
containerVarLayout->typeLayout = containerTypeLayout;
for( auto typeResInfo : containerTypeLayout->resourceInfos )
{
containerVarLayout->findOrAddResourceInfo(typeResInfo.kind);
}
typeLayout->containerVarLayout = containerVarLayout;
// We will construct a dummy variable layout to represent the offsettting
// that needs to be applied to the element type to put it after the
// container.
RefPtr<VarLayout> elementVarLayout = new VarLayout();
elementVarLayout->typeLayout = rawElementTypeLayout;
for( auto elementTypeResInfo : rawElementTypeLayout->resourceInfos )
{
auto kind = elementTypeResInfo.kind;
auto elementVarResInfo = elementVarLayout->findOrAddResourceInfo(kind);
if( auto containerTypeResInfo = containerTypeLayout->FindResourceInfo(kind) )
{
SLANG_RELEASE_ASSERT(containerTypeResInfo->count.isFinite());
elementVarResInfo->index += containerTypeResInfo->count.getFiniteValue();
}
}
typeLayout->elementVarLayout = elementVarLayout;
if (ownRegisterSpace)
{
// A parameter block type that gets its own register space will only
// include resource usage from the element type when it itself consumes
// whole register spaces.
if (auto elementResInfo = rawElementTypeLayout->FindResourceInfo(LayoutResourceKind::RegisterSpace))
{
typeLayout->addResourceUsage(*elementResInfo);
}
}
else
{
// If the parameter block is *not* getting its own regsiter space, then
// it needs to include the resource usage from the "container" type, plus
// any relevant resource usage for the element type.
// We start by accumulating any resource usage from the container.
for (auto containerResourceInfo : containerTypeLayout->resourceInfos)
{
typeLayout->addResourceUsage(containerResourceInfo);
}
// Now we will (possibly) accumulate the resources used by the element
// type into the resources used by the parameter group. The reason
// this is "possibly" is because, e.g., a `ConstantBuffer<Foo>` should
// not report itself as consuming `sizeof(Foo)` bytes of uniform data,
// or else it would mess up layout for any type that contains the
// constant buffer.
for( auto elementResourceInfo : rawElementTypeLayout->resourceInfos )
{
switch( elementResourceInfo.kind )
{
case LayoutResourceKind::Uniform:
// Uniform resource usages will always be hidden.
break;
default:
// All other register types will not be hidden,
// since we aren't in the case where the parameter group
// gets its own register space.
typeLayout->addResourceUsage(elementResourceInfo);
break;
}
}
}
return typeLayout;
}
static bool usesResourceKind(RefPtr<TypeLayout> typeLayout, LayoutResourceKind kind)
{
auto resInfo = typeLayout->FindResourceInfo(kind);
return resInfo && resInfo->count != 0;
}
static bool usesOrdinaryData(RefPtr<TypeLayout> typeLayout)
{
return usesResourceKind(typeLayout, LayoutResourceKind::Uniform);
}
/// Do we need to wrap the given element type in a constant buffer layout?
static bool needsConstantBuffer(RefPtr<TypeLayout> elementTypeLayout)
{
// We need a constant buffer if the element type has ordinary/uniform data.
//
if(usesOrdinaryData(elementTypeLayout))
return true;
// We also need a constant buffer if there are any "pending"
// items that need ordinary/uniform data allocated to them.
//
for( auto pendingItem : elementTypeLayout->pendingItems )
{
if(usesOrdinaryData(pendingItem.getTypeLayout()))
return true;
}
return false;
}
RefPtr<TypeLayout> createConstantBufferTypeLayoutIfNeeded(
TypeLayoutContext const& context,
RefPtr<TypeLayout> elementTypeLayout)
{
// First things first, we need to check whether the element type
// we are trying to lay out even needs a constant buffer allocated
// for it.
//
if(!needsConstantBuffer(elementTypeLayout))
return elementTypeLayout;
auto parameterGroupRules = context.getRulesFamily()->getConstantBufferRules();
return _createParameterGroupTypeLayout(
context
.with(parameterGroupRules)
.with(context.targetReq->getDefaultMatrixLayoutMode()),
nullptr,
parameterGroupRules->GetObjectLayout(ShaderParameterKind::ConstantBuffer),
elementTypeLayout);
}
static RefPtr<ParameterGroupTypeLayout> _createParameterGroupTypeLayout(
TypeLayoutContext const& context,
RefPtr<ParameterGroupType> parameterGroupType,
RefPtr<Type> elementType,
LayoutRulesImpl* elementTypeRules)
{
auto parameterGroupRules = context.rules;
// First compute resource usage of the block itself.
// For now we assume that the layout of the block can
// always be described in a `SimpleLayoutInfo` (only
// a single resource kind consumed).
SimpleLayoutInfo info;
if (parameterGroupType)
{
info = getParameterGroupLayoutInfo(
parameterGroupType,
parameterGroupRules);
}
else
{
// If there is no concrete type, then it seems like we are
// being asked to compute layout for the global scope
info = parameterGroupRules->GetObjectLayout(ShaderParameterKind::ConstantBuffer);
}
// Now compute a layout for the elements of the parameter block.
// Note that we need to be careful and deal with the case where
// the elements of the block use the same resource kind consumed
// by the block itself.
auto elementTypeLayout = createTypeLayout(
context.with(elementTypeRules),
elementType);
return _createParameterGroupTypeLayout(
context,
parameterGroupType,
info,
elementTypeLayout);
}
LayoutRulesImpl* getParameterBufferElementTypeLayoutRules(
RefPtr<ParameterGroupType> parameterGroupType,
LayoutRulesImpl* rules)
{
if( as<ConstantBufferType>(parameterGroupType) )
{
return rules->getLayoutRulesFamily()->getConstantBufferRules();
}
else if( as<TextureBufferType>(parameterGroupType) )
{
return rules->getLayoutRulesFamily()->getTextureBufferRules();
}
else if( as<GLSLInputParameterGroupType>(parameterGroupType) )
{
return rules->getLayoutRulesFamily()->getVaryingInputRules();
}
else if( as<GLSLOutputParameterGroupType>(parameterGroupType) )
{
return rules->getLayoutRulesFamily()->getVaryingOutputRules();
}
else if( as<GLSLShaderStorageBufferType>(parameterGroupType) )
{
return rules->getLayoutRulesFamily()->getShaderStorageBufferRules();
}
else if (as<ParameterBlockType>(parameterGroupType))
{
return rules->getLayoutRulesFamily()->getParameterBlockRules();
}
else
{
SLANG_UNEXPECTED("uhandled parameter block type");
return nullptr;
}
}
RefPtr<ParameterGroupTypeLayout> createParameterGroupTypeLayout(
TypeLayoutContext const& context,
RefPtr<ParameterGroupType> parameterGroupType)
{
auto parameterGroupRules = context.rules;
// Determine the layout rules to use for the contents of the block
auto elementTypeRules = getParameterBufferElementTypeLayoutRules(
parameterGroupType,
parameterGroupRules);
auto elementType = parameterGroupType->elementType;
return _createParameterGroupTypeLayout(
context,
parameterGroupType,
elementType,
elementTypeRules);
}
// Create a type layout for a structured buffer type.
RefPtr<StructuredBufferTypeLayout>
createStructuredBufferTypeLayout(
TypeLayoutContext const& context,
ShaderParameterKind kind,
RefPtr<Type> structuredBufferType,
RefPtr<TypeLayout> elementTypeLayout)
{
auto rules = context.rules;
auto info = rules->GetObjectLayout(kind);
auto typeLayout = new StructuredBufferTypeLayout();
typeLayout->type = structuredBufferType;
typeLayout->rules = rules;
typeLayout->elementTypeLayout = elementTypeLayout;
typeLayout->uniformAlignment = info.alignment;
SLANG_RELEASE_ASSERT(!typeLayout->FindResourceInfo(LayoutResourceKind::Uniform));
SLANG_RELEASE_ASSERT(typeLayout->uniformAlignment == 1);
if( info.size != 0 )
{
typeLayout->addResourceUsage(info.kind, info.size);
}
// Note: for now we don't deal with the case of a structured
// buffer that might contain anything other than "uniform" data,
// because there really isn't a way to implement that.
return typeLayout;
}
// Create a type layout for a structured buffer type.
RefPtr<StructuredBufferTypeLayout>
createStructuredBufferTypeLayout(
TypeLayoutContext const& context,
ShaderParameterKind kind,
RefPtr<Type> structuredBufferType,
RefPtr<Type> elementType)
{
// TODO(tfoley): we should be looking up the appropriate rules
// via the `LayoutRulesFamily` in use here...
auto structuredBufferLayoutRules = GetLayoutRulesImpl(
LayoutRule::HLSLStructuredBuffer);
// Create and save type layout for the buffer contents.
auto elementTypeLayout = createTypeLayout(
context.with(structuredBufferLayoutRules),
elementType.Ptr());
return createStructuredBufferTypeLayout(
context,
kind,
structuredBufferType,
elementTypeLayout);
}
/// Create layout information for the given `type`.
///
/// This internal routine returns both the constructed type
/// layout object and the simple layout info, encapsulated
/// together as a `TypeLayoutResult`.
///
static TypeLayoutResult _createTypeLayout(
TypeLayoutContext const& context,
Type* type);
/// Create layout information for the given `type`, obeying any layout modifiers on the given declaration.
///
/// If `declForModifiers` has any matrix layout modifiers associated with it, then
/// the resulting type layout will respect those modifiers.
///
static TypeLayoutResult _createTypeLayout(
TypeLayoutContext const& context,
Type* type,
Decl* declForModifiers)
{
TypeLayoutContext subContext = context;
if (declForModifiers)
{
// TODO: The approach implemented here has a row/column-major
// layout model recursively affect any sub-fields (so that
// the layout of a nested struct depends on the context where
// it is nested). This is consistent with the GLSL behavior
// for these modifiers, but it is *not* how HLSL is supposed
// to work.
//
// In the trivial case where `row_major` and `column_major`
// are only applied to leaf fields/variables of matrix type
// the difference should be immaterial.
if (declForModifiers->HasModifier<RowMajorLayoutModifier>())
subContext.matrixLayoutMode = kMatrixLayoutMode_RowMajor;
if (declForModifiers->HasModifier<ColumnMajorLayoutModifier>())
subContext.matrixLayoutMode = kMatrixLayoutMode_ColumnMajor;
// TODO: really need to look for other modifiers that affect
// layout, such as GLSL `std140`.
}
return _createTypeLayout(subContext, type);
}
int findGenericParam(List<RefPtr<GenericParamLayout>> & genericParameters, GlobalGenericParamDecl * decl)
{
return (int)genericParameters.FindFirst([=](RefPtr<GenericParamLayout> & x) {return x->decl.Ptr() == decl; });
}
// When constructing a new var layout from an existing one,
// copy fields to the new var from the old.
void copyVarLayoutFields(
VarLayout* dstVarLayout,
VarLayout* srcVarLayout)
{
dstVarLayout->varDecl = srcVarLayout->varDecl;
dstVarLayout->typeLayout = srcVarLayout->typeLayout;
dstVarLayout->flags = srcVarLayout->flags;
dstVarLayout->systemValueSemantic = srcVarLayout->systemValueSemantic;
dstVarLayout->systemValueSemanticIndex = srcVarLayout->systemValueSemanticIndex;
dstVarLayout->semanticName = srcVarLayout->semanticName;
dstVarLayout->semanticIndex = srcVarLayout->semanticIndex;
dstVarLayout->stage = srcVarLayout->stage;
dstVarLayout->resourceInfos = srcVarLayout->resourceInfos;
}
// When constructing a new type layout from an existing one,
// copy fields to the new type from the old.
void copyTypeLayoutFields(
TypeLayout* dstTypeLayout,
TypeLayout* srcTypeLayout)
{
dstTypeLayout->type = srcTypeLayout->type;
dstTypeLayout->rules = srcTypeLayout->rules;
dstTypeLayout->uniformAlignment = srcTypeLayout->uniformAlignment;
dstTypeLayout->resourceInfos = srcTypeLayout->resourceInfos;
}
// Does this layout resource kind require adjustment when used in
// an array-of-structs fashion?
bool doesResourceRequireAdjustmentForArrayOfStructs(LayoutResourceKind kind)
{
switch( kind )
{
case LayoutResourceKind::ConstantBuffer:
case LayoutResourceKind::ShaderResource:
case LayoutResourceKind::UnorderedAccess:
case LayoutResourceKind::SamplerState:
return true;
default:
return false;
}
}
// Given the type layout for an element of an array, apply any adjustments required
// based on the element count of the array.
//
// The particular case where this matters is when we have an array of an aggregate
// type that contains resources, since each resource field might need to be at
// a different offset than we would otherwise expect.
//
// For example, given:
//
// struct Foo { Texture2D a; Texture2D b; }
//
// if we just write:
//
// Foo foo;
//
// it gets split into:
//
// Texture2D foo_a;
// Texture2D foo_b;
//
// we expect `foo_a` to get `register(t0)` and
// `foo_b` to get `register(t1)`. However, if we instead have an array:
//
// Foo foo[10];
//
// then we expect it to be split into:
//
// Texture2D foo_a[8];
// Texture2D foo_b[8];
//
// and then we expect `foo_b` to get `register(t8)`, rather
// than `register(t1)`.
//
static RefPtr<TypeLayout> maybeAdjustLayoutForArrayElementType(
RefPtr<TypeLayout> originalTypeLayout,
LayoutSize elementCount,
UInt& ioAdditionalSpacesNeeded)
{
// We will start by looking for cases that we can reject out
// of hand.
// If the original element type layout doesn't use any
// resource registers, then we are fine.
bool anyResource = false;
for( auto resInfo : originalTypeLayout->resourceInfos )
{
if( doesResourceRequireAdjustmentForArrayOfStructs(resInfo.kind) )
{
anyResource = true;
break;
}
}
if(!anyResource)
return originalTypeLayout;
// Let's look at the type layout we have, and see if there is anything
// that we need to do with it.
//
if( auto originalArrayTypeLayout = originalTypeLayout.as<ArrayTypeLayout>() )
{
// The element type is itself an array, so we'll need to adjust
// *its* element type accordingly.
//
// We adjust the already-adjusted element type of the inner
// array type, so that we pick up adjustments already made:
auto originalInnerElementTypeLayout = originalArrayTypeLayout->elementTypeLayout;
auto adjustedInnerElementTypeLayout = maybeAdjustLayoutForArrayElementType(
originalInnerElementTypeLayout,
elementCount,
ioAdditionalSpacesNeeded);
// If nothing needed to be changed on the inner element type,
// then we are done.
if(adjustedInnerElementTypeLayout == originalInnerElementTypeLayout)
return originalTypeLayout;
// Otherwise, we need to construct a new array type layout
RefPtr<ArrayTypeLayout> adjustedArrayTypeLayout = new ArrayTypeLayout();
adjustedArrayTypeLayout->originalElementTypeLayout = originalInnerElementTypeLayout;
adjustedArrayTypeLayout->elementTypeLayout = adjustedInnerElementTypeLayout;
adjustedArrayTypeLayout->uniformStride = originalArrayTypeLayout->uniformStride;
copyTypeLayoutFields(adjustedArrayTypeLayout, originalArrayTypeLayout);
return adjustedArrayTypeLayout;
}
else if(auto originalParameterGroupTypeLayout = originalTypeLayout.as<ParameterGroupTypeLayout>() )
{
auto originalInnerElementTypeLayout = originalParameterGroupTypeLayout->elementVarLayout->typeLayout;
auto adjustedInnerElementTypeLayout = maybeAdjustLayoutForArrayElementType(
originalInnerElementTypeLayout,
elementCount,
ioAdditionalSpacesNeeded);
// If nothing needed to be changed on the inner element type,
// then we are done.
if(adjustedInnerElementTypeLayout == originalInnerElementTypeLayout)
return originalTypeLayout;
// TODO: actually adjust the element type, and create all the required bits and
// pieces of layout.
SLANG_UNIMPLEMENTED_X("array of parameter group");
UNREACHABLE_RETURN(originalTypeLayout);
}
else if(auto originalStructTypeLayout = originalTypeLayout.as<StructTypeLayout>() )
{
UInt fieldCount = originalStructTypeLayout->fields.Count();
// Empty struct? Bail out.
if(fieldCount == 0)
return originalTypeLayout;
RefPtr<StructTypeLayout> adjustedStructTypeLayout = new StructTypeLayout();
copyTypeLayoutFields(adjustedStructTypeLayout, originalStructTypeLayout);
// If the array type adjustment forces us to give a whole space to
// one or more fields, then we'll need to carefully compute the space
// index for each field as we go.
//
LayoutSize nextSpaceIndex = 0;
Dictionary<RefPtr<VarLayout>, RefPtr<VarLayout>> mapOriginalFieldToAdjusted;
for( auto originalField : originalStructTypeLayout->fields )
{
auto originalFieldTypeLayout = originalField->typeLayout;
LayoutSize originalFieldSpaceCount = 0;
if(auto resInfo = originalFieldTypeLayout->FindResourceInfo(LayoutResourceKind::RegisterSpace))
originalFieldSpaceCount = resInfo->count;
// Compute the adjusted type for the field
UInt fieldAdditionalSpaces = 0;
auto adjustedFieldTypeLayout = maybeAdjustLayoutForArrayElementType(
originalFieldTypeLayout,
elementCount,
fieldAdditionalSpaces);
LayoutSize adjustedFieldSpaceCount = originalFieldSpaceCount + fieldAdditionalSpaces;
LayoutSize spaceOffsetForField = nextSpaceIndex;
nextSpaceIndex += adjustedFieldSpaceCount;
ioAdditionalSpacesNeeded += fieldAdditionalSpaces;
// Create an adjusted field variable, that is mostly
// a clone of the original field (just with our
// adjusted type in place).
RefPtr<VarLayout> adjustedField = new VarLayout();
copyVarLayoutFields(adjustedField, originalField);
adjustedField->typeLayout = adjustedFieldTypeLayout;
// We will now walk through the resource usage for
// the adjusted field, and try to figure out what
// to do with it all.
//
for(auto& resInfo : adjustedField->resourceInfos )
{
if( doesResourceRequireAdjustmentForArrayOfStructs(resInfo.kind) )
{
if(elementCount.isFinite())
{
// If the array size is finite, then the field's index/offset
// is just going to be strided by the array size since we
// are effectively doing AoS to SoA conversion.
//
resInfo.index *= elementCount.getFiniteValue();
}
else
{
// If we are making an unbounded array, then a `struct`
// field with resource type will turn into its own space,
// and it will start at register zero in that space.
//
resInfo.index = 0;
resInfo.space = spaceOffsetForField.getFiniteValue();
}
}
}
adjustedStructTypeLayout->fields.Add(adjustedField);
mapOriginalFieldToAdjusted.Add(originalField, adjustedField);
}
for( auto p : originalStructTypeLayout->mapVarToLayout )
{
Decl* key = p.Key;
RefPtr<VarLayout> originalVal = p.Value;
RefPtr<VarLayout> adjustedVal;
if( mapOriginalFieldToAdjusted.TryGetValue(originalVal, adjustedVal) )
{
adjustedStructTypeLayout->mapVarToLayout.Add(key, adjustedVal);
}
}
return adjustedStructTypeLayout;
}
else
{
// In the leaf case, we must have a field that used up some resource
// that requires adjustment. Because there is no sub-structure to work
// with, we can just return the type layout as-is, but we also want
// to make a note that this value should consume an additional register
// space *if* the element count is unbounded.
if( elementCount.isInfinite() )
{
ioAdditionalSpacesNeeded++;
}
return originalTypeLayout;
}
}
static TypeLayoutResult _createTypeLayout(
TypeLayoutContext const& context,
Type* type)
{
auto rules = context.rules;
if (auto parameterGroupType = as<ParameterGroupType>(type))
{
// If the user is just interested in uniform layout info,
// then this is easy: a `ConstantBuffer<T>` is really no
// different from a `Texture2D<U>` in terms of how it
// should be handled as a member of a container.
//
auto info = getParameterGroupLayoutInfo(parameterGroupType, rules);
// The more interesting case, though, is when the user
// is requesting us to actually create a `TypeLayout`,
// since in that case we need to:
//
// 1. Compute a layout for the data inside the constant
// buffer, including offsets, etc.
//
// 2. Compute information about any object types inside
// the constant buffer, which need to be surfaces out
// to the top level.
//
auto typeLayout = createParameterGroupTypeLayout(
context,
parameterGroupType);
return TypeLayoutResult(typeLayout, info);
}
else if (auto samplerStateType = as<SamplerStateType>(type))
{
return createSimpleTypeLayout(
rules->GetObjectLayout(ShaderParameterKind::SamplerState),
type,
rules);
}
else if (auto textureType = as<TextureType>(type))
{
// TODO: the logic here should really be defined by the rules,
// and not at this top level...
ShaderParameterKind kind;
switch( textureType->getAccess() )
{
default:
kind = ShaderParameterKind::MutableTexture;
break;
case SLANG_RESOURCE_ACCESS_READ:
kind = ShaderParameterKind::Texture;
break;
}
return createSimpleTypeLayout(
rules->GetObjectLayout(kind),
type,
rules);
}
else if (auto imageType = as<GLSLImageType>(type))
{
// TODO: the logic here should really be defined by the rules,
// and not at this top level...
ShaderParameterKind kind;
switch( imageType->getAccess() )
{
default:
kind = ShaderParameterKind::MutableImage;
break;
case SLANG_RESOURCE_ACCESS_READ:
kind = ShaderParameterKind::Image;
break;
}
return createSimpleTypeLayout(
rules->GetObjectLayout(kind),
type,
rules);
}
else if (auto textureSamplerType = as<TextureSamplerType>(type))
{
// TODO: the logic here should really be defined by the rules,
// and not at this top level...
ShaderParameterKind kind;
switch( textureSamplerType->getAccess() )
{
default:
kind = ShaderParameterKind::MutableTextureSampler;
break;
case SLANG_RESOURCE_ACCESS_READ:
kind = ShaderParameterKind::TextureSampler;
break;
}
return createSimpleTypeLayout(
rules->GetObjectLayout(kind),
type,
rules);
}
// TODO: need a better way to handle this stuff...
#define CASE(TYPE, KIND) \
else if(auto type_##TYPE = as<TYPE>(type)) do { \
auto info = rules->GetObjectLayout(ShaderParameterKind::KIND); \
auto typeLayout = createStructuredBufferTypeLayout( \
context, \
ShaderParameterKind::KIND, \
type_##TYPE, \
type_##TYPE->elementType.Ptr()); \
return TypeLayoutResult(typeLayout, info); \
} while(0)
CASE(HLSLStructuredBufferType, StructuredBuffer);
CASE(HLSLRWStructuredBufferType, MutableStructuredBuffer);
CASE(HLSLRasterizerOrderedStructuredBufferType, MutableStructuredBuffer);
CASE(HLSLAppendStructuredBufferType, MutableStructuredBuffer);
CASE(HLSLConsumeStructuredBufferType, MutableStructuredBuffer);
#undef CASE
// TODO: need a better way to handle this stuff...
#define CASE(TYPE, KIND) \
else if(as<TYPE>(type)) do { \
return createSimpleTypeLayout( \
rules->GetObjectLayout(ShaderParameterKind::KIND), \
type, rules); \
} while(0)
CASE(HLSLByteAddressBufferType, RawBuffer);
CASE(HLSLRWByteAddressBufferType, MutableRawBuffer);
CASE(HLSLRasterizerOrderedByteAddressBufferType, MutableRawBuffer);
CASE(GLSLInputAttachmentType, InputRenderTarget);
// This case is mostly to allow users to add new resource types...
CASE(UntypedBufferResourceType, RawBuffer);
#undef CASE
else if(auto basicType = as<BasicExpressionType>(type))
{
return createSimpleTypeLayout(
rules->GetScalarLayout(basicType->baseType),
type,
rules);
}
else if(auto vecType = as<VectorExpressionType>(type))
{
auto elementType = vecType->elementType;
size_t elementCount = (size_t) GetIntVal(vecType->elementCount);
auto element = _createTypeLayout(
context,
elementType);
auto info = rules->GetVectorLayout(element.info, elementCount);
RefPtr<VectorTypeLayout> typeLayout = new VectorTypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
typeLayout->uniformAlignment = info.alignment;
typeLayout->elementTypeLayout = element.layout;
typeLayout->uniformStride = element.info.getUniformLayout().size.getFiniteValue();
typeLayout->addResourceUsage(info.kind, info.size);
return TypeLayoutResult(typeLayout, info);
}
else if(auto matType = as<MatrixExpressionType>(type))
{
size_t rowCount = (size_t) GetIntVal(matType->getRowCount());
size_t colCount = (size_t) GetIntVal(matType->getColumnCount());
auto elementType = matType->getElementType();
auto elementResult = _createTypeLayout(
context,
elementType);
auto elementTypeLayout = elementResult.layout;
auto elementInfo = elementResult.info;
// The `GetMatrixLayout` implementation in the layout rules
// currently defaults to assuming row-major layout,
// so if we want column-major layout we achieve it here by
// transposing the major/minor axes counts.
//
size_t layoutMajorCount = rowCount;
size_t layoutMinorCount = colCount;
if (context.matrixLayoutMode == kMatrixLayoutMode_ColumnMajor)
{
size_t tmp = layoutMajorCount;
layoutMajorCount = layoutMinorCount;
layoutMinorCount = tmp;
}
auto info = rules->GetMatrixLayout(
elementInfo,
layoutMajorCount,
layoutMinorCount);
auto rowType = matType->getRowType();
RefPtr<VectorTypeLayout> rowTypeLayout = new VectorTypeLayout();
auto rowInfo = rules->GetVectorLayout(
elementInfo,
colCount);
size_t majorStride = info.elementStride;
size_t minorStride = elementInfo.getUniformLayout().size.getFiniteValue();
size_t rowStride = 0;
size_t colStride = 0;
if(context.matrixLayoutMode == kMatrixLayoutMode_ColumnMajor)
{
colStride = majorStride;
rowStride = minorStride;
}
else
{
rowStride = majorStride;
colStride = minorStride;
}
rowTypeLayout->type = type;
rowTypeLayout->rules = rules;
rowTypeLayout->uniformAlignment = elementInfo.getUniformLayout().alignment;
rowTypeLayout->uniformStride = colStride;
rowTypeLayout->elementTypeLayout = elementTypeLayout;
rowTypeLayout->addResourceUsage(rowInfo.kind, rowInfo.size);
RefPtr<MatrixTypeLayout> typeLayout = new MatrixTypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
typeLayout->uniformAlignment = info.alignment;
typeLayout->elementTypeLayout = rowTypeLayout;
typeLayout->uniformStride = rowStride;
typeLayout->mode = context.matrixLayoutMode;
typeLayout->addResourceUsage(info.kind, info.size);
return TypeLayoutResult(typeLayout, info);
}
else if (auto arrayType = as<ArrayExpressionType>(type))
{
auto elementResult = _createTypeLayout(
context,
arrayType->baseType.Ptr());
auto elementInfo = elementResult.info;
auto elementTypeLayout = elementResult.layout;
// To a first approximation, an array will usually be laid out
// by taking the element's type layout and laying out `elementCount`
// copies of it. There are of course many details that make
// this simplistic version of things not quite work.
//
// An important complication to deal with is the possibility of
// having "unbounded" arrays, which don't specify a size.'
// The layout rules for these vary heavily by resource kind and API.
//
auto elementCount = GetElementCount(arrayType->ArrayLength);
//
// We can compute the uniform storage layout of an array using
// the rules for the target API.
//
// TODO: ensure that this does something reasonable with the unbounded
// case, or else issue an error message that the target doesn't
// support unbounded types.
//
auto arrayUniformInfo = rules->GetArrayLayout(
elementInfo,
elementCount).getUniformLayout();
RefPtr<ArrayTypeLayout> typeLayout = new ArrayTypeLayout();
// Some parts of the array type layout object are easy to fill in:
typeLayout->type = type;
typeLayout->rules = rules;
typeLayout->originalElementTypeLayout = elementTypeLayout;
typeLayout->uniformAlignment = arrayUniformInfo.alignment;
typeLayout->uniformStride = arrayUniformInfo.elementStride;
typeLayout->addResourceUsage(LayoutResourceKind::Uniform, arrayUniformInfo.size);
//
// The tricky part in constructing an array type layout comes when
// the element type is (or nests) a structure with resource-type
// fields, because in that case we need to perform AoS-to-SoA
// conversion as part of computing the final type layout, and
// we also need to pre-compute an "adjusted" element type
// layout that accounts for the striding that happens with
// resource-type contents.
//
// This complication is only made worse when we have to deal with
// unbounded-size arrays over such element types, since those
// resource-type fields will each end up consuming a full space
// in the resulting layout.
//
// The `maybeAdjustLayoutForArrayElementType` computes an "adjusted"
// type layout for the element type which takes the array stride into
// account. If it returns the same type layout that was passed in,
// then that means no adjustement took place.
//
// The `additionalSpacesNeededForAdjustedElementType` variable counts
// the number of additional register spaces that were consumed,
// in the case of an unbounded array.
//
UInt additionalSpacesNeededForAdjustedElementType = 0;
RefPtr<TypeLayout> adjustedElementTypeLayout = maybeAdjustLayoutForArrayElementType(
elementTypeLayout,
elementCount,
additionalSpacesNeededForAdjustedElementType);
typeLayout->elementTypeLayout = adjustedElementTypeLayout;
// We will now iterate over the resources consumed by the element
// type to compute how they contribute to the resource usage
// of the overall array type.
//
for( auto elementResourceInfo : elementTypeLayout->resourceInfos )
{
// The uniform case was already handled above
if( elementResourceInfo.kind == LayoutResourceKind::Uniform )
continue;
LayoutSize arrayResourceCount = 0;
// In almost all cases, the resources consumed by an array
// will be its element count times the resources consumed
// by its element type.
//
// The first exception to this is arrays of resources when
// compiling to GLSL for Vulkan, where an entire array
// only consumes a single descriptor-table slot.
//
if (elementResourceInfo.kind == LayoutResourceKind::DescriptorTableSlot)
{
arrayResourceCount = elementResourceInfo.count;
}
//
// The next big exception is when we are forming an unbounded-size
// array and the element type got "adjusted," because that means
// the array type will need to allocate full spaces for any resource-type
// fields in the element type.
//
// Note: we carefully carve things out so that the case of a simple
// array of resources does *not* lead to the element type being adjusted,
// so that this logic doesn't trigger and we instead handle it with
// the default logic below.
//
else if(
elementCount.isInfinite()
&& adjustedElementTypeLayout != elementTypeLayout
&& doesResourceRequireAdjustmentForArrayOfStructs(elementResourceInfo.kind) )
{
// We want to ignore resource types consumed by the element type
// that need adjustement if the array size is infinite, since
// we will be allocating whole spaces for that part of the
// element's resource usage.
}
else
{
arrayResourceCount = elementResourceInfo.count * elementCount;
}
// Now that we've computed how the resource usage of the element type
// should contribute to the resource usage of the array, we can
// add in that resource usage.
//
typeLayout->addResourceUsage(
elementResourceInfo.kind,
arrayResourceCount);
}
// The loop above to compute the resource usage of the array from its
// element type ignored any resource-type fields in an unbounded-size
// array if they would have been allocated as full register spaces.
// Those same fields were counted in `additionalSpacesNeededForAdjustedElementType`,
// and need to be added into the total resource usage for the array
// if we skipped them as part of the loop (which happens when
// we detect that the element type layout had been "adjusted").
//
if( adjustedElementTypeLayout != elementTypeLayout )
{
typeLayout->addResourceUsage(LayoutResourceKind::RegisterSpace, additionalSpacesNeededForAdjustedElementType);
}
return TypeLayoutResult(typeLayout, arrayUniformInfo);
}
else if (auto declRefType = as<DeclRefType>(type))
{
auto declRef = declRefType->declRef;
if (auto structDeclRef = declRef.as<StructDecl>())
{
RefPtr<StructTypeLayout> typeLayout = new StructTypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
// The layout of a `struct` type is computed in the somewhat
// obvious fashion by keeping a running counter of the resource
// usage for each kind of resource, and then for a field that
// uses a given resource, assigning it the current offset and
// then bumping the offset by the field size. In the case of
// uniform data we also need to deal with alignment and other
// detailed layout rules.
UniformLayoutInfo info = rules->BeginStructLayout();
for (auto field : GetFields(structDeclRef))
{
// Static fields shouldn't take part in layout.
if(field.getDecl()->HasModifier<HLSLStaticModifier>())
continue;
// The fields of a `struct` type may include existential (interface)
// types (including as nested sub-fields), and any types present
// in those fields will need to be specialized based on the
// input arguments being passed to `_createTypeLayout`.
//
// We won't know how many type slots each field consumes until
// we process it, but we can figure out the starting index for
// the slots its will consume by looking at the layout we've
// computed so far.
//
Int baseExistentialSlotIndex = 0;
if(auto resInfo = typeLayout->FindResourceInfo(LayoutResourceKind::ExistentialTypeParam))
baseExistentialSlotIndex = Int(resInfo->count.getFiniteValue());
//
// When computing the layout for the field, we will give it access
// to all the incoming specialized type slots that haven't already
// been consumed/claimed by preceding fields.
//
auto fieldLayoutContext = context.withExistentialTypeSlotsOffsetBy(baseExistentialSlotIndex);
TypeLayoutResult fieldResult = _createTypeLayout(
fieldLayoutContext,
GetType(field).Ptr(),
field.getDecl());
RefPtr<TypeLayout> fieldTypeLayout = fieldResult.layout;
UniformLayoutInfo fieldInfo = fieldResult.info.getUniformLayout();
// Note: we don't add any zero-size fields
// when computing structure layout, just
// to avoid having a resource type impact
// the final layout.
//
// This means that the code to generate final
// declarations needs to *also* eliminate zero-size
// fields to be safe...
LayoutSize uniformOffset = info.size;
if(fieldInfo.size != 0)
{
uniformOffset = rules->AddStructField(&info, fieldInfo);
}
// We need to create variable layouts
// for each field of the structure.
RefPtr<VarLayout> fieldLayout = new VarLayout();
fieldLayout->varDecl = field;
fieldLayout->typeLayout = fieldTypeLayout;
typeLayout->fields.Add(fieldLayout);
typeLayout->mapVarToLayout.Add(field.getDecl(), fieldLayout);
// Set up uniform offset information, if there is any uniform data in the field
if( fieldTypeLayout->FindResourceInfo(LayoutResourceKind::Uniform) )
{
fieldLayout->AddResourceInfo(LayoutResourceKind::Uniform)->index = uniformOffset.getFiniteValue();
}
// Add offset information for any other resource kinds
for( auto fieldTypeResourceInfo : fieldTypeLayout->resourceInfos )
{
// Uniforms were dealt with above
if(fieldTypeResourceInfo.kind == LayoutResourceKind::Uniform)
continue;
// We should not have already processed this resource type
SLANG_RELEASE_ASSERT(!fieldLayout->FindResourceInfo(fieldTypeResourceInfo.kind));
// The field will need offset information for this kind
auto fieldResourceInfo = fieldLayout->AddResourceInfo(fieldTypeResourceInfo.kind);
// It is possible for a `struct` field to use an unbounded array
// type, and in the D3D case that would consume an unbounded number
// of registers. What is more, a single `struct` could have multiple
// such fields, or ordinary resource fields after an unbounded field.
//
// We handle this case by allocating a distinct register space for
// any field that consumes an unbounded amount of registers.
//
if( fieldTypeResourceInfo.count.isInfinite() )
{
// We need to add one register space to own the storage for this field.
//
auto structTypeSpaceResourceInfo = typeLayout->findOrAddResourceInfo(LayoutResourceKind::RegisterSpace);
auto spaceOffset = structTypeSpaceResourceInfo->count;
structTypeSpaceResourceInfo->count += 1;
// The field itself will record itself as having a zero offset into
// the chosen space.
//
fieldResourceInfo->space = spaceOffset.getFiniteValue();
fieldResourceInfo->index = 0;
}
else
{
// In the case where the field consumes a finite number of slots, we
// can simply set its offset/index to the number of such slots consumed
// so far, and then increment the number of slots consumed by the
// `struct` type itself.
//
auto structTypeResourceInfo = typeLayout->findOrAddResourceInfo(fieldTypeResourceInfo.kind);
fieldResourceInfo->index = structTypeResourceInfo->count.getFiniteValue();
structTypeResourceInfo->count += fieldTypeResourceInfo.count;
}
}
// Fields of a structure type may have existential/interface type,
// or nested existential/interface-type fields. When doing layout
// for a specialized program, these will show up as "pending" types
// that need to be laid out at the end of the surrounding block/container.
//
// Any pending types on fields of a structure become pending types
// on the structure itself.
//
for( auto pendingItem : fieldTypeLayout->pendingItems )
{
typeLayout->pendingItems.Add(pendingItem);
}
}
rules->EndStructLayout(&info);
typeLayout->uniformAlignment = info.alignment;
typeLayout->addResourceUsage(LayoutResourceKind::Uniform, info.size);
return TypeLayoutResult(typeLayout, info);
}
else if (auto globalGenParam = declRef.as<GlobalGenericParamDecl>())
{
SimpleLayoutInfo info;
info.alignment = 0;
info.size = 0;
info.kind = LayoutResourceKind::GenericResource;
auto genParamTypeLayout = new GenericParamTypeLayout();
// we should have already populated ProgramLayout::genericEntryPointParams list at this point,
// so we can find the index of this generic param decl in the list
genParamTypeLayout->type = type;
genParamTypeLayout->paramIndex = findGenericParam(context.programLayout->globalGenericParams, genParamTypeLayout->getGlobalGenericParamDecl());
genParamTypeLayout->rules = rules;
genParamTypeLayout->findOrAddResourceInfo(LayoutResourceKind::GenericResource)->count += 1;
return TypeLayoutResult(genParamTypeLayout, info);
}
else if( auto simpleGenericParam = declRef.as<GenericTypeParamDecl>() )
{
// A bare generic type parameter can come up during layout
// of a generic entry point (or an entry point nested in
// a generic type). For now we will just pretend like
// the fields of generic parameter type take no space,
// since there is no reasonable way to account for them
// in the resulting layout.
//
// TODO: It might be better to completely ignore generic
// entry points during initial layout, but doing so would
// mean that users couldn't get layout information on
// any parameters, even those that don't depend on
// generics.
//
return createSimpleTypeLayout(
SimpleLayoutInfo(),
type,
rules);
}
else if( auto interfaceDeclRef = declRef.as<InterfaceDecl>() )
{
// When laying out a type that includes interface-type fields,
// we cannot know how much space the concrete type that
// gets stored into the field consumes.
//
// If we were doing layout for a typical CPU target, then
// we could just say that each interface-type field consumes
// some fixed number of pointers (e.g., a data pointer plus a witness
// table pointer).
//
// We will borrow the intuition from that and invent a new
// resource kind for "existential slots" which conceptually
// represents the indirections needed to reference the
// data to be referenced by this field.
//
RefPtr<TypeLayout> typeLayout = new TypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
typeLayout->addResourceUsage(LayoutResourceKind::ExistentialTypeParam, 1);
typeLayout->addResourceUsage(LayoutResourceKind::ExistentialObjectParam, 1);
// If there are any concrete types available, the first one will be
// the value that should be plugged into the slot we just introduced.
//
if( context.existentialTypeArgCount )
{
RefPtr<Type> concreteType = context.existentialTypeArgs[0].type;
RefPtr<TypeLayout> concreteTypeLayout = createTypeLayout(context, concreteType);
// Layout for this specialized interface type then results
// in a type layout that tracks both the resource usage of the
// interface type itself (just the type + value slots introduced
// above), plus a "pending" type that represents the value
// conceptually pointed to by the interface-type field/variable at runtime.
//
TypeLayout::PendingItem pendingItem;
pendingItem.typeLayout = concreteTypeLayout;
typeLayout->pendingItems.Add(pendingItem);
}
return TypeLayoutResult(typeLayout, SimpleLayoutInfo());
}
}
else if (auto errorType = as<ErrorType>(type))
{
// An error type means that we encountered something we don't understand.
//
// We should probably inform the user with an error message here.
return createSimpleTypeLayout(
SimpleLayoutInfo(),
type,
rules);
}
else if( auto taggedUnionType = as<TaggedUnionType>(type) )
{
// A tagged union type needs to be laid out as the maximum
// size of any constituent type.
//
// In practice, only a tagged union of uniform data will
// work, but for now we will compute the maximum usage
// for each resource kind for generality.
//
// For the uniform data we will start with a size
// of zero and an alignment of one for our base case
// (this is what a tagged union of no cases would consume).
//
UniformLayoutInfo info(0, 1);
RefPtr<TaggedUnionTypeLayout> taggedUnionLayout = new TaggedUnionTypeLayout();
taggedUnionLayout->type = type;
taggedUnionLayout->rules = rules;
// Now we iterate over the case types and see if they
// change our computed maximum size/alignement.
//
for( auto caseType : taggedUnionType->caseTypes )
{
// Note: A tagged union type is not expected to have any existential/interface type
// slots; the case types that are provided must be fully specialized before the union is
// formed. Thus we don't need to mess around with existential type slots here the
// way we do for the `struct` case.
auto caseTypeResult = _createTypeLayout(context, caseType);
RefPtr<TypeLayout> caseTypeLayout = caseTypeResult.layout;
UniformLayoutInfo caseTypeInfo = caseTypeResult.info.getUniformLayout();
info.size = maximum(info.size, caseTypeInfo.size);
info.alignment = std::max(info.alignment, caseTypeInfo.alignment);
// We need to remember the layout of the case type
// on the final `TaggedUnionTypeLayout`.
//
taggedUnionLayout->caseTypeLayouts.Add(caseTypeLayout);
// We also need to consider contributions for other
// resource kinds beyond uniform data.
//
for( auto caseResInfo : caseTypeLayout->resourceInfos )
{
auto unionResInfo = taggedUnionLayout->findOrAddResourceInfo(caseResInfo.kind);
unionResInfo->count = maximum(unionResInfo->count, caseResInfo.count);
}
}
// After we've computed the size required to hold all the
// case types, we will allocate space for the tag field.
//
// TODO: This assumes the tag will always be allocated out
// of uniform storage, which means we can't support a tagged
// union as part of a varying input/output signature. That is
// probably a valid limitation, but it should get enforced
// somewhere along the way.
//
{
// The tag is always a `uint` for now.
//
auto tagInfo = context.rules->GetScalarLayout(BaseType::UInt);
info.size = RoundToAlignment(info.size, tagInfo.alignment);
taggedUnionLayout->tagOffset = info.size;
info.size += tagInfo.size;
info.alignment = std::max(info.alignment, tagInfo.alignment);
}
// As a final step, if we are computing a full `TypeLayout`
// we will make sure that its information on uniform layout
// matches what we've computed in the `UniformLayoutInfo` we return.
//
taggedUnionLayout->findOrAddResourceInfo(LayoutResourceKind::Uniform)->count = info.size;
taggedUnionLayout->uniformAlignment = info.alignment;
return TypeLayoutResult(taggedUnionLayout, info);
}
// catch-all case in case nothing matched
SLANG_ASSERT(!"unimplemented case in type layout");
return createSimpleTypeLayout(
SimpleLayoutInfo(),
type,
rules);
}
RefPtr<TypeLayout> getSimpleVaryingParameterTypeLayout(
TypeLayoutContext const& context,
Type* type,
EntryPointParameterDirectionMask directionMask)
{
auto rules = context.rules;
// TODO: This logic should ideally share as much
// as possible with the `_createTypeLayout` function,
// to avoid duplication, but we also have to deal
// with the many ways in which varying parameter
// layout differs from non-varying layout.
// We will compute resource consumption for the type
// as a varying input, output, or both/neither.
// To avoid duplication, we'll build an array that
// includes all the layout rules we need to apply.
//
int varyingRulesCount = 0;
LayoutRulesImpl* varyingRules[2];
if( directionMask & kEntryPointParameterDirection_Input )
{
varyingRules[varyingRulesCount++] = context.getRulesFamily()->getVaryingInputRules();
}
if( directionMask & kEntryPointParameterDirection_Output )
{
varyingRules[varyingRulesCount++] = context.getRulesFamily()->getVaryingOutputRules();
}
if(auto basicType = as<BasicExpressionType>(type))
{
auto baseType = basicType->baseType;
RefPtr<TypeLayout> typeLayout = new TypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
for( int rr = 0; rr < varyingRulesCount; ++rr )
{
auto info = varyingRules[rr]->GetScalarLayout(baseType);
typeLayout->addResourceUsage(info.kind, info.size);
}
return typeLayout;
}
else if(auto vecType = as<VectorExpressionType>(type))
{
auto elementType = vecType->elementType;
size_t elementCount = (size_t) GetIntVal(vecType->elementCount);
BaseType elementBaseType = BaseType::Void;
if( auto elementBasicType = as<BasicExpressionType>(elementType) )
{
elementBaseType = elementBasicType->baseType;
}
// Note that we do *not* add any resource usage to the type
// layout for the element type, because we currently cannot count
// varying parameter usage at a granularity finer than
// individual "locations."
//
RefPtr<TypeLayout> elementTypeLayout = new TypeLayout();
elementTypeLayout->type = elementType;
elementTypeLayout->rules = rules;
RefPtr<VectorTypeLayout> typeLayout = new VectorTypeLayout();
typeLayout->type = vecType;
typeLayout->rules = rules;
typeLayout->elementTypeLayout = elementTypeLayout;
for( int rr = 0; rr < varyingRulesCount; ++rr )
{
auto varyingRuleSet = varyingRules[rr];
auto elementInfo = varyingRuleSet->GetScalarLayout(elementBaseType);
auto info = varyingRuleSet->GetVectorLayout(elementInfo, elementCount);
typeLayout->addResourceUsage(info.kind, info.size);
}
return typeLayout;
}
else if(auto matType = as<MatrixExpressionType>(type))
{
size_t rowCount = (size_t) GetIntVal(matType->getRowCount());
size_t colCount = (size_t) GetIntVal(matType->getColumnCount());
auto elementType = matType->getElementType();
BaseType elementBaseType = BaseType::Void;
if( auto elementBasicType = as<BasicExpressionType>(elementType) )
{
elementBaseType = elementBasicType->baseType;
}
// Just as for `_createTypeLayout`, we need to handle row- and
// column-major matrices differently, to ensure we get
// the expected layout.
//
// A varying parameter with row-major layout is effectively
// just an array of row vectors, while a column-major one
// is just an array of column vectors.
//
size_t layoutMajorCount = rowCount;
size_t layoutMinorCount = colCount;
if (context.matrixLayoutMode == kMatrixLayoutMode_ColumnMajor)
{
size_t tmp = layoutMajorCount;
layoutMajorCount = layoutMinorCount;
layoutMinorCount = tmp;
}
RefPtr<TypeLayout> elementTypeLayout = new TypeLayout();
elementTypeLayout->type = elementType;
elementTypeLayout->rules = rules;
RefPtr<VectorTypeLayout> rowTypeLayout = new VectorTypeLayout();
rowTypeLayout->type = matType->getRowType();
rowTypeLayout->rules = rules;
rowTypeLayout->elementTypeLayout = elementTypeLayout;
RefPtr<MatrixTypeLayout> typeLayout = new MatrixTypeLayout();
typeLayout->type = type;
typeLayout->rules = rules;
typeLayout->elementTypeLayout = rowTypeLayout;
typeLayout->mode = context.matrixLayoutMode;
for( int rr = 0; rr < varyingRulesCount; ++rr )
{
auto varyingRuleSet = varyingRules[rr];
auto elementInfo = varyingRuleSet->GetScalarLayout(elementBaseType);
auto info = varyingRuleSet->GetMatrixLayout(elementInfo, layoutMajorCount, layoutMinorCount);
typeLayout->addResourceUsage(info.kind, info.size);
if(context.matrixLayoutMode == kMatrixLayoutMode_RowMajor)
{
// For row-major matrices only, we can compute an effective
// resource usage for the row type.
auto rowInfo = varyingRuleSet->GetVectorLayout(elementInfo, colCount);
rowTypeLayout->addResourceUsage(rowInfo.kind, rowInfo.size);
}
}
return typeLayout;
}
// catch-all case in case nothing matched
SLANG_ASSERT(!"unimplemented case for varying parameter layout");
return createSimpleTypeLayout(
SimpleLayoutInfo(),
type,
rules).layout;
}
RefPtr<TypeLayout> createTypeLayout(
TypeLayoutContext const& context,
Type* type)
{
return _createTypeLayout(context, type).layout;
}
RefPtr<TypeLayout> TypeLayout::unwrapArray()
{
TypeLayout* typeLayout = this;
while(auto arrayTypeLayout = as<ArrayTypeLayout>(typeLayout))
typeLayout = arrayTypeLayout->elementTypeLayout;
return typeLayout;
}
RefPtr<GlobalGenericParamDecl> GenericParamTypeLayout::getGlobalGenericParamDecl()
{
auto declRefType = as<DeclRefType>(type);
SLANG_ASSERT(declRefType);
auto rsDeclRef = declRefType->declRef.as<GlobalGenericParamDecl>();
return rsDeclRef.getDecl();
}
} // namespace Slang
|