summaryrefslogtreecommitdiff
path: root/examples/model-viewer
diff options
context:
space:
mode:
authorkaizhangNV <149626564+kaizhangNV@users.noreply.github.com>2024-09-18 16:49:00 -0500
committerGitHub <noreply@github.com>2024-09-18 14:49:00 -0700
commit3240799c00488858afc7eeac9d1dc479609a1040 (patch)
treefb9b390a45eec1d27a717d0f1735dbff4059ac9b /examples/model-viewer
parent2d83875f4b376f047c4541a6f6c13d36e5aa228b (diff)
Lower the priority of looking up the rank of scope (#5065)
* Lower the priority of looking up the rank of scope In the previous change of #5060, we propose a way to resolve the ambiguous call when considering the scope of a function. But this rule should be considered as a low priority than "specialized candidate", aka. we should consider more "specialized candiate" first. * Count distance between reference site to declaration site Compare the candidate by calculating distance from reference site to declaration site via nearest common prefix in the scope tree. This will involve finding the common parent node of two child nodes and how sum the distance from the common parent to the two child nodes. * Change the priority higher than 'getOverloadRank' * Don't evaluate the scope rank algorithm on generic If the candidate is generic function, the function parameters won't be checked before 'CompareOverloadCandidates', so it will results in that the candidates this function could be invalid. We should not evaluate the distance algorithm in this case, instead we will evaluate later when the candidate is in flavor of Func or Expr since then all the type checks for the function will be done.
Diffstat (limited to 'examples/model-viewer')
0 files changed, 0 insertions, 0 deletions
8'>128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239
// slang-parameter-binding.cpp
#include "slang-parameter-binding.h"

#include "slang-lookup.h"
#include "slang-compiler.h"
#include "slang-type-layout.h"
#include "slang-ir-util.h"

#include "../compiler-core/slang-artifact-desc-util.h"

#include "slang-ir-string-hash.h"

#include "slang.h"

namespace Slang {

struct ParameterInfo;

// Information on ranges of registers already claimed/used
struct UsedRange
{
    // What parameter has claimed this range?
    VarLayout* parameter;

    // Begin/end of the range (half-open interval)
    UInt begin;
    UInt end;
};
bool operator<(UsedRange left, UsedRange right)
{
    if (left.begin != right.begin)
        return left.begin < right.begin;
    if (left.end != right.end)
        return left.end < right.end;
    return false;
}

static bool rangesOverlap(UsedRange const& x, UsedRange const& y)
{
    SLANG_ASSERT(x.begin <= x.end);
    SLANG_ASSERT(y.begin <= y.end);

    // If they don't overlap, then one must be earlier than the other,
    // and that one must therefore *end* before the other *begins*

    if (x.end <= y.begin) return false;
    if (y.end <= x.begin) return false;

    // Otherwise they must overlap
    return true;
}


struct UsedRanges
{
    // The `ranges` array maintains a sorted list of `UsedRange`
    // objects such that the `end` of a range is <= the `begin`
    // of any range that comes after it.
    //
    // The values covered by each `[begin,end)` range are marked
    // as used, and anything not in such an interval is implicitly
    // free.
    //
    // TODO: if it ever starts to matter for performance, we
    // could encode this information as a tree instead of an array.
    //
    List<UsedRange> ranges;

    // Add a range to the set, either by extending
    // existing range(s), or by adding a new one.
    //
    // If we find that the new range overlaps with
    // an existing range for a *different* parameter
    // then we return that parameter so that the
    // caller can issue an error.
    //
    VarLayout* Add(UsedRange range)
    {
        // The invariant on entry to this
        // function is that the `ranges` array
        // is sorted and no two entries in the
        // array intersect. We must preserve
        // that property as a postcondition.
        //
        // The other postcondition is that the
        // interval covered by the input `range`
        // must be marked as consumed.

        // We will try track any parameter associated
        // with an overlapping range that doesn't
        // match the parameter on `range`, so that
        // the compiler can issue useful diagnostics.
        //
        VarLayout* newParam = range.parameter;
        VarLayout* existingParam = nullptr;

        // A clever algorithm might use a binary
        // search to identify the first entry in `ranges`
        // that might overlap `range`, but we are going
        // to settle for being less clever for now, in
        // the hopes that we can at least be correct.
        //
        // Note: we are going to iterate over `ranges`
        // using indices, because we may actually modify
        // the array as we go.
        //
        Int rangeCount = ranges.getCount();
        for(Int rr = 0; rr < rangeCount; ++rr)
        {
            auto existingRange = ranges[rr];

            // The invariant on entry to each loop
            // iteration will be that `range` does
            // *not* intersect any preceding entry
            // in the array.
            //
            // Note that this invariant might be
            // true only because we modified
            // `range` along the way.
            //
            // If `range` does not intertsect `existingRange`
            // then our invariant will be trivially
            // true for the next iteration.
            //
            if(!rangesOverlap(existingRange, range))
            {
                continue;
            }

            // We now know that `range` and `existingRange`
            // intersect. The first thing to do
            // is to check if we have a parameter
            // associated with `existingRange`, so
            // that we can use it for emitting diagnostics
            // about the overlap:
            //
            if( existingRange.parameter
                && existingRange.parameter != newParam)
            {
                // There was an overlap with a range that
                // had a parameter specified, so we will
                // use that parameter in any subsequent
                // diagnostics.
                //
                existingParam = existingRange.parameter;
            }

            // Before we can move on in our iteration,
            // we need to re-establish our invariant by modifying
            // `range` so that it doesn't overlap with `existingRange`.
            // Of course we also want to end up with a correct
            // result for the overall operation, so we can't just
            // throw away intervals.
            //
            // We first note that if `range` starts before `existingRange`,
            // then the interval from `range.begin` to `existingRange.begin`
            // needs to be accounted for in the final result. Furthermore,
            // the interval `[range.begin, existingRange.begin)` could not
            // intersect with any range already in the `ranges` array,
            // because it comes strictly before `existingRange`, and our
            // invariant says there is no intersection with preceding ranges.
            //
            if(range.begin < existingRange.begin)
            {
                UsedRange prefix;
                prefix.begin = range.begin;
                prefix.end = existingRange.begin;
                prefix.parameter = range.parameter;
                ranges.add(prefix);
            }
            //
            // Now we know that the interval `[range.begin, existingRange.begin)`
            // is claimed, if it exists, and clearly the interval
            // `[existingRange.begin, existingRange.end)` is already claimed,
            // so the only interval left to consider would be
            // `[existingRange.end, range.end)`, if it is non-empty.
            // That range might intersect with others in the array, so
            // we will need to continue iterating to deal with that
            // possibility.
            //
            range.begin = existingRange.end;

            // If the range would be empty, then of course we have nothing
            // left to do.
            //
            if(range.begin >= range.end)
                break;

            // Otherwise, have can be sure that `range` now comes
            // strictly *after* `existingRange`, and thus our invariant
            // is preserved.
        }

        // If we manage to exit the loop, then we have resolved
        // an intersection with existing entries - possibly by
        // adding some new entries.
        //
        // If the `range` we are left with is still non-empty,
        // then we should go ahead and add it.
        //
        if(range.begin < range.end)
        {
            ranges.add(range);
        }

        // Any ranges that got added along the way might not
        // be in the proper sorted order, so we'll need to
        // sort the array to restore our global invariant.
        //
        ranges.sort();

        // We end by returning an overlapping parameter that
        // we found along the way, if any.
        //
        return existingParam;
    }

    VarLayout* Add(VarLayout* param, UInt begin, UInt end)
    {
        UsedRange range;
        range.parameter = param;
        range.begin = begin;
        range.end = end;
        return Add(range);
    }

    VarLayout* Add(VarLayout* param, UInt begin, LayoutSize end)
    {
        UsedRange range;
        range.parameter = param;
        range.begin = begin;
        range.end = end.isFinite() ? end.getFiniteValue() : UInt(-1);
        return Add(range);
    }

        /// Finds the range that contains the index
        /// Returns -1 if not found
    Index findRangeContaining(UInt index) const
    {
        const auto rangeCount = ranges.getCount();
        for (Index i = 0; i < rangeCount; ++i)
        {
            const auto& rr = ranges[i];
            if (index >= rr.begin && index < rr.end)
            {
                return index;
            }
        }
        return -1;
    }
        /// Finds the range index that contains the range passed in.
        /// Returns -1 if not found
    Index findRangeContaining(UInt index, UInt count) const
    {
        const auto start = index;
        const auto end = index + count;

        const auto rangeCount = ranges.getCount();
        for (Index i = 0; i < rangeCount; ++i)
        {
            const auto& rr = ranges[i];

            if (!(end <= rr.begin || start >= rr.end))
            {
                return i;
            }
        }
        return -1;
    }

    Index findRangeContaining(UInt index, LayoutSize size) const
    {
        if (size.isFinite())
        {
            const auto count = size.getFiniteValue();
            if (count > 0)
            {
                return (count == 1) ?
                    findRangeContaining(index) :
                    findRangeContaining(index, count);
            }
        }
        else
        {
            // The size is infinite...
            const auto rangeCount = ranges.getCount();
            for (Index i = 0; i < rangeCount; ++i)
            {
                // If the range end is part start index it's a hit
                if (ranges[i].end > index)
                {
                    return i;
                }
            }
        }
        return -1;
    }

    bool contains(UInt index) const { return findRangeContaining(index) >= 0; }

    // Try to find space for `count` entries
    UInt Allocate(VarLayout* param, UInt count)
    {
        UInt begin = 0;

        UInt rangeCount = ranges.getCount();
        for (UInt rr = 0; rr < rangeCount; ++rr)
        {
            // try to fit in before this range...

            UInt end = ranges[rr].begin;

            // If there is enough space...
            if (end >= begin + count)
            {
                // ... then claim it and be done
                Add(param, begin, begin + count);
                return begin;
            }

            // ... otherwise, we need to look at the
            // space between this range and the next
            begin = ranges[rr].end;
        }

        // We've run out of ranges to check, so we
        // can safely go after the last one!
        Add(param, begin, begin + count);
        return begin;
    }
};

struct ParameterBindingInfo
{
    size_t              space = 0;
    size_t              index = 0;
    LayoutSize          count = 0;
};

struct ParameterBindingAndKindInfo : ParameterBindingInfo
{
    LayoutResourceKind kind = LayoutResourceKind::None;
};

enum
{
    kLayoutResourceKindCount = SLANG_PARAMETER_CATEGORY_COUNT,
};

struct UsedRangeSet : RefObject
{
    // Information on what ranges of "registers" have already
    // been claimed, for each resource type
    UsedRanges usedResourceRanges[kLayoutResourceKindCount];
};

// Information on a single parameter
struct ParameterInfo : RefObject
{
    // Layout info for the variable that represents this parameter
    RefPtr<VarLayout> varLayout;

    ParameterBindingInfo    bindingInfo[kLayoutResourceKindCount];
};

struct EntryPointParameterBindingContext
{
    // What ranges of resources bindings are already claimed for this translation unit
    UsedRangeSet usedRangeSet;
};


// State that is shared during parameter binding,
// across all translation units
struct SharedParameterBindingContext
{
    SharedParameterBindingContext(
        LayoutRulesFamilyImpl*  defaultLayoutRules,
        ProgramLayout*          programLayout,
        TargetProgram*          inTargetProgram,
        DiagnosticSink*         sink)
        : defaultLayoutRules(defaultLayoutRules)
        , programLayout(programLayout)
        , targetRequest(inTargetProgram->getTargetReq())
        , targetProgram(inTargetProgram)
        , m_sink(sink)
    {
    }

    DiagnosticSink* m_sink = nullptr;

    // The program that we are laying out
    // Program* program = nullptr;

    // The target request that is triggering layout
    //
    // TODO: We should eventually strip this down to
    // just the subset of fields on the target that
    // can influence layout decisions.
    TargetRequest*  targetRequest = nullptr;

    TargetProgram* targetProgram = nullptr;

    LayoutRulesFamilyImpl* defaultLayoutRules;

    // All shader parameters we've discovered so far, and started to lay out...
    List<RefPtr<ParameterInfo>> parameters;

    // The program layout we are trying to construct
    RefPtr<ProgramLayout> programLayout;

    // What ranges of resources bindings are already claimed at the global scope?
    // We store one of these for each declared binding space/set.
    //
    Dictionary<UInt, RefPtr<UsedRangeSet>> globalSpaceUsedRangeSets;

    // Which register spaces have been claimed so far?
    UsedRanges usedSpaces;

    // The space to use for auto-generated bindings.
    UInt defaultSpace = 0;

    // Any NVAPI slot binding information that has been generated
    List<NVAPISlotModifier*> nvapiSlotModifiers;

    TargetRequest* getTargetRequest() { return targetRequest; }
    DiagnosticSink* getSink() { return m_sink; }
    Linkage* getLinkage() { return targetRequest->getLinkage(); }
    TargetProgram* getTargetProgram() { return targetProgram; }
};

static DiagnosticSink* getSink(SharedParameterBindingContext* shared)
{
    return shared->getSink();
}

// State that might be specific to a single translation unit
// or event to an entry point.
struct ParameterBindingContext
{
    // All the shared state needs to be available
    SharedParameterBindingContext* shared;

    // The type layout context to use when computing
    // the resource usage of shader parameters.
    TypeLayoutContext layoutContext;

    // What stage (if any) are we compiling for?
    Stage stage;

    // The entry point that is being processed right now.
    EntryPointLayout*   entryPointLayout = nullptr;

    TargetRequest* getTargetRequest() { return shared->getTargetRequest(); }
    TargetProgram* getTargetProgram() { return shared->getTargetProgram(); }
    LayoutRulesFamilyImpl* getRulesFamily() { return layoutContext.getRulesFamily(); }

    ASTBuilder* getASTBuilder() { return shared->getLinkage()->getASTBuilder(); }

    Linkage* getLinkage() { return shared->getLinkage(); }
};

static DiagnosticSink* getSink(ParameterBindingContext* context)
{
    return getSink(context->shared);
}


struct LayoutSemanticInfo
{
    LayoutResourceKind  kind; // the register kind
    UInt                space;
    UInt                index;

    // TODO: need to deal with component-granularity binding...
};

static bool isDigit(char c)
{
    return (c >= '0') && (c <= '9');
}

bool splitNameAndIndex(
    UnownedStringSlice const& text,
    UnownedStringSlice& outName,
    UnownedStringSlice& outDigits)
{
    char const* nameBegin = text.begin();
    char const* digitsEnd = text.end();

    char const* nameEnd = digitsEnd;
    // ExplicitIndex is when a semantic has an index at the end of its name
    // "SV_TARGET1" has an ExplicitIndex
    // "SV_TARGET" does not have an ExplicitIndex
    bool hasExplicitIndex = false;
    while( nameEnd != nameBegin && isDigit(*(nameEnd - 1)) )
    {
        hasExplicitIndex = true;
        nameEnd--;
    }
    char const* digitsBegin = nameEnd;

    outName = UnownedStringSlice(nameBegin, nameEnd);
    outDigits = UnownedStringSlice(digitsBegin, digitsEnd);
    return hasExplicitIndex;
}

LayoutResourceKind findRegisterClassFromName(UnownedStringSlice const& registerClassName)
{
    switch( registerClassName.getLength() )
    {
    case 1:
        switch (*registerClassName.begin())
        {
        case 'b': return LayoutResourceKind::ConstantBuffer;
        case 't': return LayoutResourceKind::ShaderResource;
        case 'u': return LayoutResourceKind::UnorderedAccess;
        case 's': return LayoutResourceKind::SamplerState;

        default:
            break;
        }
        break;

    case 5:
        if( registerClassName == toSlice("space") )
        {
            return LayoutResourceKind::SubElementRegisterSpace;
        }
        break;

    default:
        break;
    }
    return LayoutResourceKind::None;
}

LayoutSemanticInfo extractHLSLLayoutSemanticInfo(
    UnownedStringSlice  registerName,
    SourceLoc           registerLoc,
    UnownedStringSlice  spaceName,
    SourceLoc           spaceLoc,
    DiagnosticSink*     sink
    )
{
    LayoutSemanticInfo info;
    info.space = 0;
    info.index = 0;
    info.kind = LayoutResourceKind::None;

    if (registerName.getLength() == 0)
        return info;

    // The register name is expected to be in the form:
    //
    //      identifier-char+ digit+
    //
    // where the identifier characters name a "register class"
    // and the digits identify a register index within that class.
    //
    // We are going to split the string the user gave us
    // into these constituent parts:
    //
    UnownedStringSlice registerClassName;
    UnownedStringSlice registerIndexDigits;
    splitNameAndIndex(registerName, registerClassName, registerIndexDigits);

    LayoutResourceKind kind = findRegisterClassFromName(registerClassName);
    if(kind == LayoutResourceKind::None)
    {
        sink->diagnose(registerLoc, Diagnostics::unknownRegisterClass, registerClassName);
        return info;
    }

    // For a `register` semantic, the register index is not optional (unlike
    // how it works for varying input/output semantics).
    if( registerIndexDigits.getLength() == 0 )
    {
        sink->diagnose(registerLoc, Diagnostics::expectedARegisterIndex, registerClassName);
    }

    UInt index = 0;
    for(auto c : registerIndexDigits)
    {
        SLANG_ASSERT(isDigit(c));
        index = index * 10 + (c - '0');
    }

    UInt space = 0;
    if(spaceName.getLength() != 0)
    {
        UnownedStringSlice spaceSpelling;
        UnownedStringSlice spaceDigits;
        splitNameAndIndex(spaceName, spaceSpelling, spaceDigits);

        if( kind == LayoutResourceKind::SubElementRegisterSpace)
        {
            sink->diagnose(spaceLoc, Diagnostics::unexpectedSpecifierAfterSpace, spaceName);
        }
        else if( spaceSpelling != UnownedTerminatedStringSlice("space") )
        {
            sink->diagnose(spaceLoc, Diagnostics::expectedSpace, spaceSpelling);
        }
        else if( spaceDigits.getLength() == 0 )
        {
            sink->diagnose(spaceLoc, Diagnostics::expectedSpaceIndex);
        }
        else
        {
            for(auto c : spaceDigits)
            {
                SLANG_ASSERT(isDigit(c));
                space = space * 10 + (c - '0');
            }
        }
    }

    info.kind = kind;
    info.index = (int) index;
    info.space = space;
    return info;
}

static LayoutSemanticInfo _extractLayoutSemanticInfo(
    ParameterBindingContext*    context,
    HLSLLayoutSemantic*         semantic)
{
    Token const& registerToken = semantic->registerName;

    Token defaultSpaceToken;
    Token const* spaceToken = &defaultSpaceToken;
    if( auto registerSemantic = as<HLSLRegisterSemantic>(semantic) )
    {
        spaceToken = &registerSemantic->spaceName;
    }

    LayoutSemanticInfo info = extractHLSLLayoutSemanticInfo(
        registerToken.getContent(),
        registerToken.loc,
        spaceToken->getContent(),
        spaceToken->loc,
        getSink(context));

    return info;
}


//

// Given a GLSL `layout` modifier, we need to be able to check for
// a particular sub-argument and extract its value if present.
template<typename T>
static bool findLayoutArg(
    ModifiableSyntaxNode*    syntax,
    UInt*                           outVal)
{
    for( auto modifier : syntax->getModifiersOfType<T>() )
    {
        if( modifier )
        {
            *outVal = (UInt) strtoull(String(modifier->valToken.getContent()).getBuffer(), nullptr, 10);
            return true;
        }
    }
    return false;
}

template<typename T>
static bool findLayoutArg(
    DeclRef<Decl>   declRef,
    UInt*           outVal)
{
    return findLayoutArg<T>(declRef.getDecl(), outVal);
}

    /// Determine how to lay out a global variable that might be a shader parameter.
    ///
    /// Returns `nullptr` if the declaration does not represent a shader parameter.
RefPtr<TypeLayout> getTypeLayoutForGlobalShaderParameter(
    ParameterBindingContext*    context,
    VarDeclBase*                varDecl,
    Type*                       type)
{
    auto layoutContext = context->layoutContext;
    auto rules = layoutContext.getRulesFamily();

    if(varDecl->hasModifier<ShaderRecordAttribute>() && as<ConstantBufferType>(type))
    {
        return createTypeLayoutWith(
            layoutContext,
            rules->getShaderRecordConstantBufferRules(),
            type);
    }


    // We want to check for a constant-buffer type with a `push_constant` layout
    // qualifier before we move on to anything else.
    if( varDecl->hasModifier<PushConstantAttribute>() && as<ConstantBufferType>(type) )
    {
        return createTypeLayoutWith(
            layoutContext,
            rules->getPushConstantBufferRules(),
            type);
    }

    if (varDecl->hasModifier<SpecializationConstantAttribute>() ||
        varDecl->hasModifier<VkConstantIdAttribute>())
    {
        auto specializationConstantRule = rules->getSpecializationConstantRules();
        if (!specializationConstantRule)
        {
            // If the target doesn't support specialization constants, then we will
            // layout them as ordinary uniform data.
            specializationConstantRule = rules->getConstantBufferRules(context->getTargetRequest()->getOptionSet());
        }
        return createTypeLayoutWith(
            layoutContext,
            specializationConstantRule,
            type);
    }

    // TODO(tfoley): there may be other cases that we need to handle here

    // An "ordinary" global variable is implicitly a uniform
    // shader parameter.
    return createTypeLayoutWith(
        layoutContext,
        rules->getConstantBufferRules(context->getTargetRequest()->getOptionSet()),
        type);
}

//

struct EntryPointParameterState
{
    String*                             optSemanticName = nullptr;
    int*                                ioSemanticIndex = nullptr;
    EntryPointParameterDirectionMask    directionMask;
    int                                 semanticSlotCount;
    Stage                               stage = Stage::Unknown;
    bool                                isSampleRate = false;
    SourceLoc                           loc;
};


static RefPtr<TypeLayout> processEntryPointVaryingParameter(
    ParameterBindingContext*        context,
    Type*          type,
    EntryPointParameterState const& state,
    RefPtr<VarLayout>               varLayout);

static RefPtr<VarLayout> _createVarLayout(
    TypeLayout*             typeLayout,
    DeclRef<VarDeclBase>    varDeclRef)
{
    RefPtr<VarLayout> varLayout = new VarLayout();
    varLayout->typeLayout = typeLayout;
    varLayout->varDecl = varDeclRef;

    if(auto pendingDataTypeLayout = typeLayout->pendingDataTypeLayout)
    {
        RefPtr<VarLayout> pendingVarLayout = new VarLayout();
        pendingVarLayout->varDecl = varDeclRef;
        pendingVarLayout->typeLayout = pendingDataTypeLayout;
        varLayout->pendingVarLayout = pendingVarLayout;
    }

    return varLayout;
}

// Collect a single declaration into our set of parameters
static void collectGlobalScopeParameter(
    ParameterBindingContext*    context,
    ShaderParamInfo const&      shaderParamInfo,
    SubstitutionSet             globalGenericSubst)
{
    auto astBuilder = context->getASTBuilder();

    auto varDeclRef = shaderParamInfo.paramDeclRef;

    // We apply any substitutions for global generic parameters here.
    auto type = as<Type>(getType(astBuilder, varDeclRef)->substitute(astBuilder, globalGenericSubst));

    // We use a single operation to both check whether the
    // variable represents a shader parameter, and to compute
    // the layout for that parameter's type.
    auto typeLayout = getTypeLayoutForGlobalShaderParameter(
        context,
        varDeclRef.getDecl(),
        type);

    // If we did not find appropriate layout rules, then it
    // must mean that this global variable is *not* a shader
    // parameter.
    if(!typeLayout)
        return;

    // Now create a variable layout that we can use
    RefPtr<VarLayout> varLayout = _createVarLayout(typeLayout, varDeclRef);

    // The logic in `check.cpp` that created the `ShaderParamInfo`
    // will have identified any cases where there might be multiple
    // global variables that logically represent the same shader parameter.
    //
    // We will track the same basic information during layout using
    // the `ParameterInfo` type.
    //
    // TODO: `ParameterInfo` should probably become `LayoutParamInfo`.
    //
    ParameterInfo* parameterInfo = new ParameterInfo();
    context->shared->parameters.add(parameterInfo);

    // Add the created var layout to the parameter information structure,
    // so that we can update it as we proceed with parameter binding.
    //
    parameterInfo->varLayout = varLayout;
}

static UsedRangeSet* _getOrCreateUsedRangeSetForSpace(
    ParameterBindingContext*    context,
    UInt                        space)
{
    auto& globalSpaceUsedRangeSets = context->shared->globalSpaceUsedRangeSets;

    auto& value = globalSpaceUsedRangeSets.getOrAddValue(space, RefPtr<UsedRangeSet>());
    if (!value)
    {
        value = new UsedRangeSet();
    }
    return value;
}

static UsedRangeSet* _getUsedRangeSetForSpace(
    ParameterBindingContext* context,
    UInt                        space)
{
    auto& globalSpaceUsedRangeSets = context->shared->globalSpaceUsedRangeSets;

    if (auto usedRangeSetPtr = globalSpaceUsedRangeSets.tryGetValue(space))
    {
        return *usedRangeSetPtr;
    }
    return nullptr;
}

// Record that a particular register space (or set, in the GLSL case)
// has been used in at least one binding, and so it should not
// be used by auto-generated bindings that need to claim entire
// spaces.
static VarLayout* markSpaceUsed(
    ParameterBindingContext*    context,
    VarLayout*                  varLayout,
    UInt                        space)
{
    return context->shared->usedSpaces.Add(varLayout, space, space+1);
}

static UInt allocateUnusedSpaces(
    ParameterBindingContext*    context,
    UInt                        count)
{
    return context->shared->usedSpaces.Allocate(nullptr, count);
}

static bool shouldDisableDiagnostic(
    Decl*                   decl,
    DiagnosticInfo const&   diagnosticInfo)
{
    for( auto dd = decl; dd; dd = dd->parentDecl )
    {
        for( auto modifier : dd->modifiers )
        {
            auto allowAttr = as<AllowAttribute>(modifier);
            if(!allowAttr)
                continue;

            if(allowAttr->diagnostic == &diagnosticInfo)
                return true;
        }
    }
    return false;
}

static void addExplicitParameterBinding(
    ParameterBindingContext*    context,
    RefPtr<ParameterInfo>       parameterInfo,
    VarDeclBase*                varDecl,
    LayoutSemanticInfo const&   semanticInfo,
    LayoutSize                  count)
{
    auto kind = semanticInfo.kind;

    auto& bindingInfo = parameterInfo->bindingInfo[(int)kind];
    if( bindingInfo.count != 0 )
    {
        // We already have a binding here, so we want to
        // confirm that it matches the new one that is
        // incoming...
        if( bindingInfo.count != count
            || bindingInfo.index != semanticInfo.index
            || bindingInfo.space != semanticInfo.space )
        {
            getSink(context)->diagnose(varDecl, Diagnostics::conflictingExplicitBindingsForParameter, getReflectionName(varDecl));
        }

        // TODO(tfoley): `register` semantics can technically be
        // profile-specific (not sure if anybody uses that)...
    }
    else
    {
        bindingInfo.count = count;
        bindingInfo.index = semanticInfo.index;
        bindingInfo.space = semanticInfo.space;

        VarLayout* overlappedVarLayout = nullptr;
        if( kind == LayoutResourceKind::RegisterSpace || kind == LayoutResourceKind::SubElementRegisterSpace )
        {
            // Parameter is being bound to an entire space, so we
            // need to mark the given space as used and report
            // an error if another parameter was already allocated
            // there.
            //
            overlappedVarLayout = markSpaceUsed(context, parameterInfo->varLayout, semanticInfo.index);
        }
        else
        {
            auto usedRangeSet = _getOrCreateUsedRangeSetForSpace(context, semanticInfo.space);

            // Record that the particular binding space was
            // used by an explicit binding, so that we don't
            // claim it for auto-generated bindings that
            // need to grab a full space
            markSpaceUsed(context, parameterInfo->varLayout, semanticInfo.space);

            overlappedVarLayout = usedRangeSet->usedResourceRanges[(int)semanticInfo.kind].Add(
                parameterInfo->varLayout,
                semanticInfo.index,
                semanticInfo.index + count);
        }

        if (overlappedVarLayout)
        {
            //legal if atomicUint
            if(parameterInfo->varLayout->getVariable()->getType()->astNodeType == ASTNodeType::GLSLAtomicUintType
                && overlappedVarLayout->getVariable()->getType()->astNodeType == ASTNodeType::GLSLAtomicUintType)
            {
                return;
            }
            auto paramA = parameterInfo->varLayout->getVariable();
            auto paramB = overlappedVarLayout->getVariable();

            auto& diagnosticInfo = Diagnostics::parameterBindingsOverlap;

            // If *both* of the shader parameters declarations agree
            // that overlapping bindings should be allowed, then we
            // will not emit a diagnostic. Otherwise, we will warn
            // the user because such overlapping bindings are likely
            // to indicate a programming error.
            //
            if(shouldDisableDiagnostic(paramA, diagnosticInfo)
                && shouldDisableDiagnostic(paramB, diagnosticInfo))
            {
            }
            else
            {
                bool written = getSink(context)->diagnose(paramA, diagnosticInfo,
                    getReflectionName(paramA),
                    getReflectionName(paramB));
                if (written)
                    getSink(context)->diagnose(paramB, Diagnostics::seeDeclarationOf, getReflectionName(paramB));
            }
        }
    }
}

static void addExplicitParameterBindings_HLSL(
    ParameterBindingContext*    context,
    RefPtr<ParameterInfo>       parameterInfo,
    RefPtr<VarLayout>           varLayout)
{
    // We only want to apply D3D `register` modifiers when compiling for
    // D3D and Metal targets.
    //
    // TODO: Nominally, the `register` keyword allows for a shader
    // profile to be specified, so that a given binding only
    // applies for a specific profile:
    //
    //      https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
    //
    // We might want to consider supporting that syntax in the
    // long run, in order to handle bindings for multiple targets
    // in a more consistent fashion (whereas using `register` for D3D
    // and `[[vk::binding(...)]]` for Vulkan creates a lot of
    // visual noise).
    //
    // For now we do the filtering on target in a very direct fashion:
    //
    if(!isD3DTarget(context->getTargetRequest()) && !isMetalTarget(context->getTargetRequest()))
        return;

    auto typeLayout = varLayout->typeLayout;
    auto varDecl = varLayout->varDecl;

    // If the declaration has explicit binding modifiers, then
    // here is where we want to extract and apply them...
    if (auto inputAttachmentIndexLayoutAttribute = varDecl.getDecl()->findModifier<GLSLInputAttachmentIndexLayoutAttribute>())
    {
        LayoutSemanticInfo semanticInfo;
        semanticInfo.index = (UInt)inputAttachmentIndexLayoutAttribute->location;
        semanticInfo.space = 0;
        semanticInfo.kind = LayoutResourceKind::InputAttachmentIndex;

        if (auto varDeclBase = varDecl.as<VarDeclBase>())
            addExplicitParameterBinding(context, parameterInfo, varDeclBase.getDecl(), semanticInfo, 1);
    }

    // Look for HLSL `register` or `packoffset` semantics.
    for (auto semantic : varDecl.getDecl()->getModifiersOfType<HLSLLayoutSemantic>())
    {
        // Need to extract the information encoded in the semantic
        LayoutSemanticInfo semanticInfo = _extractLayoutSemanticInfo(context, semantic);
        auto kind = semanticInfo.kind;
        if (kind == LayoutResourceKind::None)
            continue;

        // TODO: need to special-case when this is a `c` register binding...

        // Find the appropriate resource-binding information
        // inside the type, to see if we even use any resources
        // of the given kind.

        auto typeRes = typeLayout->FindResourceInfo(kind);
        LayoutSize count = 0;
        if (typeRes)
        {
            count = typeRes->count;
        }
        else
        {
            // TODO: warning here!
        }

        if (auto varDeclBase = varDecl.as<VarDeclBase>())
            addExplicitParameterBinding(context, parameterInfo, varDeclBase.getDecl(), semanticInfo, count);
    }
}

static void _maybeDiagnoseMissingVulkanLayoutModifier(
    ParameterBindingContext*    context,
    DeclRef<VarDeclBase> const& varDecl)
{
    // If the user didn't specify a `binding` (and optional `set`) for Vulkan,
    // but they *did* specify a `register` for D3D, then that is probably an
    // oversight on their part.
    if( auto registerModifier = varDecl.getDecl()->findModifier<HLSLRegisterSemantic>() )
    {
        getSink(context)->diagnose(registerModifier, Diagnostics::registerModifierButNoVulkanLayout, varDecl.getName());
    }
}

static void addExplicitParameterBindings_GLSL(
    ParameterBindingContext*    context,
    RefPtr<ParameterInfo>       parameterInfo,
    RefPtr<VarLayout>           varLayout)
{
    // We only want to apply GLSL-style layout modifers
    // when compiling for a Khronos-related target. 
    //
    // TODO: This should have some finer granularity
    // so that we are able to distinguish between
    // Vulkan and OpenGL as targets.
    //
    if(!isKhronosTarget(context->getTargetRequest()))
        return;

    auto typeLayout = varLayout->typeLayout;
    auto varDecl = varLayout->varDecl;

    // The catch in GLSL is that the expected resource type
    // is implied by the parameter declaration itself, and
    // the `layout` modifier is only allowed to adjust
    // the index/offset/etc.
    //

    enum 
    {
        kResInfo = 0,
        kSubpassResInfo,
        kMaxResCount,
    };

    TypeLayout::ResourceInfo* foundResInfo = nullptr;
    struct ResAndSemanticInfo
    {
        TypeLayout::ResourceInfo* resInfo = nullptr;
        LayoutSemanticInfo semanticInfo;
        ResAndSemanticInfo()
        {
            semanticInfo.index = 0;
            semanticInfo.space = 0;
        }
    };
    ResAndSemanticInfo info[kMaxResCount] = {};
    
    if (auto foundInputAttachmentIndex = typeLayout->FindResourceInfo(LayoutResourceKind::InputAttachmentIndex))
    {
        foundResInfo = foundInputAttachmentIndex;
        // Try to find `input_attachment_index`
        if (auto glslAttachmentIndexAttr = varDecl.getDecl()->findModifier<GLSLInputAttachmentIndexLayoutAttribute>())
        {
            info[kSubpassResInfo].resInfo = foundResInfo;
            // Subpass fills semantic info of a descriptor and subpass
            info[kSubpassResInfo].semanticInfo.index = (UInt)glslAttachmentIndexAttr->location;
            info[kSubpassResInfo].semanticInfo.space = 0;
        }
    }

    if(auto foundDescriptorTableSlot = typeLayout->FindResourceInfo(LayoutResourceKind::DescriptorTableSlot))
    {
        foundResInfo = foundDescriptorTableSlot;
        // Try to find `binding` and `set`
        if (auto glslBindingAttr = varDecl.getDecl()->findModifier<GLSLBindingAttribute>())
        {
            info[kResInfo].resInfo = foundResInfo;
            info[kResInfo].semanticInfo.index = glslBindingAttr->binding;
            info[kResInfo].semanticInfo.space = glslBindingAttr->set;
        }
    }
    else if(auto foundSubElementRegisterSpace = typeLayout->FindResourceInfo(LayoutResourceKind::SubElementRegisterSpace))
    {
        foundResInfo = foundSubElementRegisterSpace;
        // Try to find `set`
        if (auto attr = varDecl.getDecl()->findModifier<GLSLBindingAttribute>())
        {
            info[kResInfo].resInfo = foundResInfo;
            if (attr->binding != 0)
            {
                getSink(context)->diagnose(attr, Diagnostics::wholeSpaceParameterRequiresZeroBinding, varDecl.getName(), attr->binding);
            }
            info[kResInfo].semanticInfo.index = attr->set;
            info[kResInfo].semanticInfo.space = 0;
        }
    }
    else if(auto foundSpecializationConstant = typeLayout->FindResourceInfo(LayoutResourceKind::SpecializationConstant))
    {
        info[kResInfo].resInfo = foundSpecializationConstant;

        if (auto layoutAttr = varDecl.getDecl()->findModifier<VkConstantIdAttribute>())
            info[kResInfo].semanticInfo.index = layoutAttr->location;
        else
            return;
    }


    auto varDeclBase = as<VarDeclBase>(varDecl);
    bool hasABinding = false;
    for (int i = 0; i < kMaxResCount; i++)
    {
        auto* resInfoItem = info[i].resInfo;
        auto& semanticInfo = info[i].semanticInfo;
        if (!resInfoItem)
            continue;

        auto kind = resInfoItem->kind;
        auto count = resInfoItem->count;
        semanticInfo.kind = kind;
        hasABinding = true;
        if(!varDeclBase)
            break;

        addExplicitParameterBinding(context, parameterInfo, varDeclBase.getDecl(), semanticInfo, count);
    }
    if(hasABinding)
        return;

    auto hlslToVulkanLayoutOptions = context->getTargetProgram()->getHLSLToVulkanLayoutOptions();
    bool warnedMissingVulkanLayoutModifier = false;
    // If we are not told how to infer bindings with a compile option, we warn
    if (hlslToVulkanLayoutOptions == nullptr || !hlslToVulkanLayoutOptions->canInferBindings())
    {
        warnedMissingVulkanLayoutModifier = true;
        _maybeDiagnoseMissingVulkanLayoutModifier(context, varDecl.as<VarDeclBase>());
    }

    // We need an HLSL register semantic to to infer from
    auto hlslRegSemantic = varDecl.getDecl()->findModifier<HLSLRegisterSemantic>();
    if (!hlslRegSemantic)
    {
        // We'll use inference from the HLSL like layout that will happen elsewhere
        return;
    }

    
    const auto hlslInfo = _extractLayoutSemanticInfo(context, hlslRegSemantic);
    if (hlslInfo.kind == LayoutResourceKind::None)
    {
        // Doesn't have an HLSL resource consumption, so we are done
        return;
    }

    // We can't infer TextureSampler from HLSL (it's not an HLSL concept)
    // So use default layout
    auto varType = getType(context->getASTBuilder(), varDecl.as<VarDeclBase>());
    if (auto textureType = as<TextureType>(varType))
    {
        if (textureType->isCombined())
            return;
    }
    
    // Can we map to a Vulkan kind in principal?
    const HLSLToVulkanLayoutOptions::Kind vulkanKind = HLSLToVulkanLayoutOptions::getKind(hlslInfo.kind);
    if (vulkanKind == HLSLToVulkanLayoutOptions::Kind::Invalid)
    {
        // If we can't use inference, for the kind we'll use other mechanisms so we are done
        return;
    }

    // If inference is not enabled for this kind, we can issue a warning
    if (hlslToVulkanLayoutOptions && !hlslToVulkanLayoutOptions->canInfer(vulkanKind, hlslInfo.space))
    {
        if(!warnedMissingVulkanLayoutModifier)
        {
            _maybeDiagnoseMissingVulkanLayoutModifier(context, varDecl.as<VarDeclBase>());
            warnedMissingVulkanLayoutModifier = true;
        }
    }

    // We use the HLSL binding directly (even though this notionally for GLSL/Vulkan)
    // We'll do the shifting at later later point in _maybeApplyHLSLToVulkanShifts
    info[kResInfo].resInfo = typeLayout->findOrAddResourceInfo(hlslInfo.kind);

    if (warnedMissingVulkanLayoutModifier)
    {
        // If we warn due to invalid bindings and user did not set how to interpret 'hlsl style bindings', we should map 
        // `register` 1:1 with equivlent vulkan bindings.
        if(!hlslToVulkanLayoutOptions
            || hlslToVulkanLayoutOptions->getKindShiftEnabledFlags() == HLSLToVulkanLayoutOptions::KindFlag::None)
        {
            info[kResInfo].resInfo->kind = LayoutResourceKind::DescriptorTableSlot;
            info[kResInfo].resInfo->count = 1;
        }
        else
        {
            return;
        }
    }

    info[kResInfo].semanticInfo.kind = info[kResInfo].resInfo->kind;
    info[kResInfo].semanticInfo.index = UInt(hlslInfo.index);
    info[kResInfo].semanticInfo.space = UInt(hlslInfo.space);
    const LayoutSize count = info[kResInfo].resInfo->count;

    addExplicitParameterBinding(context, parameterInfo, as<VarDeclBase>(varDecl.getDecl()), info[kResInfo].semanticInfo, count);
}

// Given a single parameter, collect whatever information we have on
// how it has been explicitly bound, which may come from multiple declarations
void _generateParameterBindings(
    ParameterBindingContext*    context,
    RefPtr<ParameterInfo>       parameterInfo)
{
    // There must have been a declaration for the parameter.
    SLANG_RELEASE_ASSERT(parameterInfo->varLayout);

    // We will look for explicit binding information on the declaration.
    auto varLayout = parameterInfo->varLayout;

    // Handle HLSL `register` and `packoffset` modifiers
    addExplicitParameterBindings_HLSL(context, parameterInfo, varLayout);


    // Handle GLSL `layout` modifiers and `[vk::...]` attributes.
    //
    // TODO: We should deprecate the support for `layout` and then rename
    // these `_HLSL` and `_GLSL` functions to be more explicit and clear
    // about the fact that they are specific to the *target* and not to
    // the *source language* (as they were at one point).
    //
    addExplicitParameterBindings_GLSL(context, parameterInfo, varLayout);
}

// Generate the binding information for a shader parameter.
static void completeBindingsForParameterImpl(
    ParameterBindingContext*    context,
    RefPtr<VarLayout>           firstVarLayout,
    ParameterBindingInfo        bindingInfos[kLayoutResourceKindCount])
{
    // For any resource kind used by the parameter
    // we need to update its layout information
    // to include a binding for that resource kind.
    //
    auto firstTypeLayout = firstVarLayout->typeLayout;

    // We need to deal with allocation of full register spaces first,
    // since that is the most complicated bit of logic.
    //
    // We will compute how many full register spaces the parameter
    // needs to allocate, across all the kinds of resources it
    // consumes, so that we can allocate a contiguous range of
    // spaces.
    //
    UInt spacesToAllocateCount = 0;
    for(auto typeRes : firstTypeLayout->resourceInfos)
    {
        auto kind = typeRes.kind;

        // We want to ignore resource kinds for which the user
        // has specified an explicit binding, since those won't
        // go into our contiguously allocated range.
        //
        auto& bindingInfo = bindingInfos[(int)kind];
        if( bindingInfo.count != 0 )
        {
            continue;
        }

        // Now we inspect the kind of resource to figure out
        // its space requirements:
        //
        switch( kind )
        {
        default:
            // An unbounded-size array will need its own space.
            //
            if( typeRes.count.isInfinite() )
            {
                spacesToAllocateCount++;
            }
            break;

        case LayoutResourceKind::SubElementRegisterSpace:
            // If the parameter consumes any full spaces (e.g., it
            // is a `struct` type with one or more unbounded arrays
            // for fields), then we will include those spaces in
            // our allocaiton.
            //
            // We assume/require here that we never end up needing
            // an unbounded number of spaces.
            // TODO: we should enforce that somewhere with an error.
            //
            spacesToAllocateCount += typeRes.count.getFiniteValue();
            break;

        case LayoutResourceKind::Uniform:
            // We want to ignore uniform data for this calculation,
            // since any uniform data in top-level shader parameters
            // needs to go into a global constant buffer.
            //
            break;

        case LayoutResourceKind::GenericResource:
            // This is more of a marker case, and shouldn't ever
            // need a space allocated to it.
            break;
        }
    }

    // If we compute that the parameter needs some number of full
    // spaces allocated to it, then we will go ahead and allocate
    // contiguous spaces here.
    //
    UInt firstAllocatedSpace = 0;
    if(spacesToAllocateCount)
    {
        firstAllocatedSpace = allocateUnusedSpaces(context, spacesToAllocateCount);
    }

    // We'll then dole the allocated spaces (if any) out to the resource
    // categories that need them.
    //
    UInt currentAllocatedSpace = firstAllocatedSpace;

    for(auto typeRes : firstTypeLayout->resourceInfos)
    {
        // Did we already apply some explicit binding information
        // for this resource kind?
        auto kind = typeRes.kind;
        auto& bindingInfo = bindingInfos[(int)kind];
        if( bindingInfo.count != 0 )
        {
            // If things have already been bound, our work is done.
            //
            // TODO: it would be good to handle the case where a
            // binding specified a space, but not an offset/index
            // for some kind of resource.
            //
            continue;
        }

        auto count = typeRes.count;

        // Certain resource kinds require special handling.
        //
        // Note: This `switch` statement should have a `case` for
        // all of the special cases above that affect the computation of
        // `spacesToAllocateCount`.
        //
        switch( kind )
        {
        case LayoutResourceKind::SubElementRegisterSpace:
            {
                // The parameter's type needs to consume some number of whole
                // register spaces, and we have already allocated a contiguous
                // range of spaces above.
                //
                // As always, we can't handle the case of a parameter that needs
                // an infinite number of spaces.
                //
                SLANG_ASSERT(count.isFinite());
                bindingInfo.count = count;

                // We will use the spaces we've allocated, and bump
                // the variable tracking the "current" space by
                // the number of spaces consumed.
                //
                bindingInfo.index = currentAllocatedSpace;
                currentAllocatedSpace += count.getFiniteValue();

                // TODO: what should we store as the "space" for
                // an allocation of register spaces? Either zero
                // or `space` makes sense, but it isn't clear
                // which is a better choice.
                bindingInfo.space = 0;

                continue;
            }

        case LayoutResourceKind::GenericResource:
            {
                // `GenericResource` is somewhat confusingly named,
                // but simply indicates that the type of this parameter
                // in some way depends on a generic parameter that has
                // not been bound to a concrete value, so that asking
                // specific questions about its resource usage isn't
                // really possible.
                //
                bindingInfo.space = 0;
                bindingInfo.count = 1;
                bindingInfo.index = 0;
                continue;
            }

        case LayoutResourceKind::Uniform:
            // TODO: we don't currently handle global-scope uniform parameters.
            break;
        }

        // At this point, we know the parameter consumes some resource
        // (e.g., D3D `t` registers or Vulkan `binding`s), and the user
        // didn't specify an explicit binding, so we will have to
        // assign one for them.
        //
        // If we are consuming an infinite amount of the given resource
        // (e.g., an unbounded array of `Texure2D` requires an infinite
        // number of `t` regisers in D3D), then we will go ahead
        // and assign a full space:
        //
        if( count.isInfinite() )
        {
            bindingInfo.count = count;
            bindingInfo.index = 0;
            bindingInfo.space = currentAllocatedSpace;
            currentAllocatedSpace++;
        }
        else
        {
            // If we have a finite amount of resources, then
            // we will go ahead and allocate from the "default"
            // space.

            UInt space = context->shared->defaultSpace;
            RefPtr<UsedRangeSet> usedRangeSet = _getOrCreateUsedRangeSetForSpace(context, space);

            bindingInfo.count = count;
            bindingInfo.index = usedRangeSet->usedResourceRanges[(int)kind].Allocate(firstVarLayout, count.getFiniteValue());
            bindingInfo.space = space;
        }
    }
}

static void applyBindingInfoToParameter(
    RefPtr<VarLayout>       varLayout,
    ParameterBindingInfo    bindingInfos[kLayoutResourceKindCount])
{
    for(auto k = 0; k < kLayoutResourceKindCount; ++k)
    {
        auto kind = LayoutResourceKind(k);
        auto& bindingInfo = bindingInfos[k];

        // skip resources we aren't consuming
        if(bindingInfo.count == 0)
            continue;

        // Add a record to the variable layout
        auto varRes = varLayout->AddResourceInfo(kind);
        varRes->space = (int) bindingInfo.space;
        varRes->index = (int) bindingInfo.index;
    }
}

// Generate the binding information for a shader parameter.
static void completeBindingsForParameter(
    ParameterBindingContext*    context,
    RefPtr<ParameterInfo>       parameterInfo)
{
    auto varLayout = parameterInfo->varLayout;
    SLANG_RELEASE_ASSERT(varLayout);

    completeBindingsForParameterImpl(
        context,
        varLayout,
        parameterInfo->bindingInfo);

    // At this point we should have explicit binding locations chosen for
    // all the relevant resource kinds, so we can apply these to the
    // declarations:

    applyBindingInfoToParameter(varLayout, parameterInfo->bindingInfo);
}

static void completeBindingsForParameter(
    ParameterBindingContext*    context,
    RefPtr<VarLayout>           varLayout)
{
    ParameterBindingInfo bindingInfos[kLayoutResourceKindCount];
    completeBindingsForParameterImpl(
        context,
        varLayout,
        bindingInfos);
    applyBindingInfoToParameter(varLayout, bindingInfos);
}

    /// Allocate binding location for any "pending" data in a shader parameter.
    ///
    /// When a parameter contains interface-type fields (recursively), we might
    /// not have included them in the base layout for the parameter, and instead
    /// need to allocate space for them after all other shader parameters have
    /// been laid out.
    ///
    /// This function should be called on the `pendingVarLayout` field of an
    /// existing `VarLayout` to ensure that its pending data has been properly
    /// assigned storage. It handles the case where the `pendingVarLayout`
    /// field is null.
    ///
static void _allocateBindingsForPendingData(
    ParameterBindingContext*    context,
    RefPtr<VarLayout>           pendingVarLayout)
{
    if(!pendingVarLayout) return;

    completeBindingsForParameter(context, pendingVarLayout);
}

struct SimpleSemanticInfo
{
    String  name;
    int     index;
};

SimpleSemanticInfo decomposeSimpleSemantic(
    HLSLSimpleSemantic* semantic)
{
    auto composedName = semantic->name.getContent();

    // look for a trailing sequence of decimal digits
    // at the end of the composed name
    UInt length = composedName.getLength();
    UInt indexLoc = length;
    while( indexLoc > 0 )
    {
        auto c = composedName[indexLoc-1];
        if( c >= '0' && c <= '9' )
        {
            indexLoc--;
            continue;
        }
        else
        {
            break;
        }
    }

    SimpleSemanticInfo info;

    // 
    if( indexLoc == length )
    {
        // No index suffix
        info.name = composedName;
        info.index = 0;
    }
    else
    {
        // The name is everything before the digits
        String stringComposedName(composedName);

        info.name = stringComposedName.subString(0, indexLoc);
        info.index = strtol(stringComposedName.begin() + indexLoc, nullptr, 10);
    }
    return info;
}

static RefPtr<TypeLayout> processSimpleEntryPointParameter(
    ParameterBindingContext*        context,
    Type*          type,
    EntryPointParameterState const& inState,
    RefPtr<VarLayout>               varLayout,
    int                             semanticSlotCount = 1)
{
    EntryPointParameterState state = inState;
    state.semanticSlotCount = semanticSlotCount;

    auto optSemanticName    =  state.optSemanticName;
    auto semanticIndex      = *state.ioSemanticIndex;

    String semanticName = optSemanticName ? *optSemanticName : "";
    String sn = semanticName.toLower();

    RefPtr<TypeLayout> typeLayout;

    // First we check for a system-value semantic, operating
    // under the assumption that *any* semantic with an `SV_`
    // or `NV_` prefix is a system value.
    //
    if (sn.startsWith("sv_")
        || sn.startsWith("nv_"))
    {
        // Fragment shader color/render target outputs need to be handled
        // specially, because they are declared with an `SV`-prefixed
        // "system value" semantic, but in practice they are ordinary
        // user-defined outputs.
        //
        // TODO: We should consider allowing fragment-shader outputs
        // with arbitrary semantics, and simply treat them as if
        // they were declared with `SV_Target`.
        //
        if( (state.directionMask & kEntryPointParameterDirection_Output)
            && (state.stage == Stage::Fragment)
            && (sn == "sv_target") )
        {
            // Note: For D3D shader models 5.0 and below, each `SV_Target<N>`
            // output conflicts with UAV register `u<N>`.
            //
            if( isD3DTarget(context->getTargetRequest()) )
            {
                auto version = context->getTargetProgram()->getOptionSet().getProfileVersion();
                if( version <= ProfileVersion::DX_5_0 )
                {
                    // We will address the conflict here by claiming the corresponding
                    // `u` register.
                    //
                    // Note: because entry point parameters get processed *before*
                    // registers get assigned to global-scope parameters, this
                    // allocation will prevent register `u<N>` from being auto-assigned
                    // to any global parameter.
                    //
                    // TODO: construct a `ParameterInfo` we can use here so that
                    // overlapped layout errors get reported nicely.
                    //
                    auto usedResourceSet = _getOrCreateUsedRangeSetForSpace(context, 0);
                    usedResourceSet->usedResourceRanges[int(LayoutResourceKind::UnorderedAccess)].Add(nullptr, semanticIndex, semanticIndex + semanticSlotCount);
                }
            }

            // A fragment shader output is effectively a user-defined output,
            // even if it was declared with `SV_Target`.
            //
            typeLayout = getSimpleVaryingParameterTypeLayout(
                context->layoutContext,
                type,
                kEntryPointParameterDirection_Output);
        }
        else if (isSPIRV(context->getTargetRequest()->getTarget())
             && (
                    (state.directionMask & kEntryPointParameterDirection_Input && state.stage == Stage::Fragment)
                    || (state.directionMask & kEntryPointParameterDirection_Output && state.stage == Stage::Vertex)
                )
            && sn == "sv_instanceid"
            )
        {
            // This fragment-shader-input/vertex-shader-output is effectively not a system semantic for SPIR-V,
            typeLayout = getSimpleVaryingParameterTypeLayout(
                context->layoutContext,
                type,
                state.directionMask);
        }
        else
        {
            // For a system-value parameter (that didn't match the
            // `SV_Target` special case above) we create a default
            // layout that consumes no input/output varying slots.
            //
            // The rationale here is that system parameters are distinct
            // form user-defined parameters for layout purposes, and
            // in particular should not be assigned `location`s on
            // GLSL-based targets.
            //
            typeLayout = getSimpleVaryingParameterTypeLayout(
                context->layoutContext,
                type,
                0);

            // We need to compute whether an entry point consumes
            // any sample-rate inputs, and along with explicitly
            // `sample`-qualified parameters, we also need to
            // detect use of `SV_SampleIndex` as an input.
            //
            if (state.directionMask & kEntryPointParameterDirection_Input)
            {
                if (sn == "sv_sampleindex")
                {
                    state.isSampleRate = true;
                }
            }
        }

        // For any case of a system-value semantic (including `SV_Target`)
        // we record the system-value semantic so it can be queried
        // via reflection.
        //
        // TODO: We might want to consider skipping this step for
        // `SV_Target` outputs and treating them consistently as
        // just user-defined outputs.
        //
        if (varLayout)
        {
            varLayout->systemValueSemantic = semanticName;
            varLayout->systemValueSemanticIndex = semanticIndex;
        }

        // TODO: We might want to consider tracking some kind of usage
        // information for system inputs/outputs. In particular, it
        // would be good to check for and diagnose overlapping system
        // value declarations.

        // TODO: We should eventually be checking that system values
        // are appropriate to the stage that they appear on, and also
        // map the system value semantic string over to an `enum`
        // type of known/supported system value semantics.
    }
    else
    {
        // In this case we have a user-defined semantic, which means
        // an ordinary input and/or output varying parameter.
        //
        typeLayout = getSimpleVaryingParameterTypeLayout(
                context->layoutContext,
                type,
                state.directionMask);
    }

    if (state.isSampleRate
        && (state.directionMask & kEntryPointParameterDirection_Input)
        && (context->stage == Stage::Fragment))
    {
        if (auto entryPointLayout = context->entryPointLayout)
        {
            entryPointLayout->flags |= EntryPointLayout::Flag::usesAnySampleRateInput;
        }
    }

    *state.ioSemanticIndex += state.semanticSlotCount;
    typeLayout->type = type;

    return typeLayout;
}

    /// Compute layout information for an entry-point parameter `decl`.
    ///
    /// This function should be used for a top-level entry point varying
    /// parameter or a field of a structure used for varying parameters,
    /// but *not* for any recursive case that operates on a type without
    /// an associated declaration (e.g., recursing on `X` when dealing
    /// with a parameer of type `X[]`).
    ///
    /// This function is responsible for processing any atributes or
    /// other modifiers on the declaration that should impact out layout
    /// is computed.
    ///
static RefPtr<TypeLayout> processEntryPointVaryingParameterDecl(
    ParameterBindingContext*        context,
    Decl*                           decl,
    Type*                    type,
    EntryPointParameterState const& inState,
    RefPtr<VarLayout>               varLayout)
{
    // One of our responsibilities when recursing through varying
    // parameters is to compute the semantic name/index for each
    // parameter.
    //
    // Semantics can either be declared per field/parameter:
    //
    //      struct Output
    //      {
    //          float4 a : A;
    //          float4 b : B;
    //      }
    //
    // or they can be applied to an entire aggregate type:
    //
    //      void entryPoint(out Output o : OUTPUT) { ... }
    //
    // When these both of the above cases apply to a
    // leaf parameter/field, then the policy is that the
    // "outer-most" semantic wins. Thus in the case above,
    // `o.a` gets semantic `OUTPUT0` and `o.b` gets semantic
    // `OUTPUT1`.

    // By default the state we use for processing the
    // parameter/field `decl` will be the state that was
    // inherited from the outer context (if any).
    //
    EntryPointParameterState state = inState;

    // If there is already a semantic name coming from the
    // outer context, we will use it, but if there is no
    // outer semantic *and* the current field/parameter `decl`
    // has an explicit semantic, we will use that.
    //
    // Note: we allocate the storage for the variables that
    // will track the semantic state outside the conditional,
    // so that they are in scope for the recusrivse call
    // coming up.
    //
    SimpleSemanticInfo semanticInfo;
    int semanticIndex = 0;
    if( !state.optSemanticName )
    {
        if( auto semantic = decl->findModifier<HLSLSimpleSemantic>() )
        {
            semanticInfo = decomposeSimpleSemantic(semantic);
            semanticIndex = semanticInfo.index;

            state.optSemanticName = &semanticInfo.name;
            state.ioSemanticIndex = &semanticIndex;
        }
    }

    // One of our tasks is to track whether a fragment shader
    // has any sample-rate varying inputs. To that end, we
    // will pass down a marker if this parameter was declared
    // with the `sample` modifier, so that we can detect
    // sample-rate inputs at the leaves.
    //
    if (decl)
    {
        if (decl->findModifier<HLSLSampleModifier>())
        {
            state.isSampleRate = true;
        }
    }

    // With the state to use for assigning semantics computed,
    // we now do processing that depends on the type of
    // the parameter, which may involve recursing into its
    // fields.
    //
    // The result of this step is the type layout to use for
    // our field/parameter `decl` in this context.
    //
    auto typeLayout = processEntryPointVaryingParameter(context, type, state, varLayout);

    // For Khronos targets (OpenGL and Vulkan), we need to process
    // the `[[vk::location(...)]]` and `[[vk::index(...)]]` attributes,
    // if present.
    //
    // TODO: In principle we should *also* be using the data from
    // `SV_Target<N>` semantics as an equivalent to `location = <N>`
    // when targetting Vulkan. Right now we are kind of skating by
    // on the fact that people almost always declare `SV_Target`s
    // in numerical order, so that our automatic assignment of
    // `location`s in declaration order coincidentally matches
    // the `SV_Target` order.
    //
    if( isKhronosTarget(context->getTargetRequest()) )
    {
        if( auto locationAttr = decl->findModifier<GLSLLocationAttribute>() )
        {
            int location = locationAttr->value;

            int index = 0;
            if( auto indexAttr = decl->findModifier<GLSLIndexAttribute>() )
            {
                index = indexAttr->value;
            }

            // TODO: We should eventually include validation that a non-zero
            // `vk::index` is only valid for fragment shader color outputs.

            // Once we've extracted the data from the attribute(s), we
            // need to apply it to the `varLayout` for the parameter/field `decl`.
            //
            LayoutResourceKind kinds[] = { LayoutResourceKind::VaryingInput, LayoutResourceKind::VaryingOutput };
            for( auto kind : kinds )
            {
                auto typeResInfo = typeLayout->FindResourceInfo(kind);
                if(!typeResInfo)
                    continue;

                auto varResInfo = varLayout->findOrAddResourceInfo(kind);
                varResInfo->index = location;

                // Note: OpenGL and Vulkan represent dual-source color blending
                // differently from multiple render targets (MRT) at the source
                // level.
                //
                // When using MRT, GLSL (and thus SPIR-V) looks like this:
                //
                //      layout(location = 0) vec4 a;
                //      layout(location = 1) vec4 b;
                //
                // When using dual-source blending the GLSL/SPIR-V looks like:
                //
                //      layout(location = 0)            vec4 a;
                //      layout(location = 0, index = 1) vec4 b;
                //
                // Thus for a parameter of kind `VaryingOutput` when targetting
                // GLSL/SPIR-V, we need a way to encode the value that was pased
                // for `index` on the secondary color output.
                //
                // We are already using the `index` field in the `VarLayout::ResourceInfo`
                // to store what GLSL/SPIR-V calls the "location," so we will
                // hijack the `space` field (which is usually unused for varying
                // parameters) to store the GLSL/SPIR-V "index" value.
                //
                varResInfo->space = index;
            }
        }
        else if( auto indexAttr = decl->findModifier<GLSLIndexAttribute>() )
        {
            getSink(context)->diagnose(indexAttr, Diagnostics::vkIndexWithoutVkLocation, decl->getName());
        }
    }

    return typeLayout;
}

static RefPtr<TypeLayout> processEntryPointVaryingParameter(
    ParameterBindingContext*        context,
    Type*                    type,
    EntryPointParameterState const& state,
    RefPtr<VarLayout>               varLayout)
{
    // Make sure to associate a stage with every
    // varying parameter (including sub-fields of
    // `struct`-type parameters), since downstream
    // code generation will need to look at the
    // stage (possibly on individual leaf fields) to
    // decide when to emit things like the `flat`
    // interpolation modifier.
    //
    if( varLayout )
    {
        varLayout->stage = state.stage;
    }

    // The default handling of varying parameters should not apply
    // to geometry shader output streams; they have their own special rules.
    if( auto gsStreamType = as<HLSLStreamOutputType>(type) )
    {
        //

        auto elementType = gsStreamType->getElementType();

        int semanticIndex = 0;

        EntryPointParameterState elementState;
        elementState.directionMask = kEntryPointParameterDirection_Output;
        elementState.ioSemanticIndex = &semanticIndex;
        elementState.isSampleRate = false;
        elementState.optSemanticName = nullptr;
        elementState.semanticSlotCount = 0;
        elementState.stage = state.stage;
        elementState.loc = state.loc;

        auto elementTypeLayout = processEntryPointVaryingParameter(context, elementType, elementState, nullptr);

        RefPtr<StreamOutputTypeLayout> typeLayout = new StreamOutputTypeLayout();
        typeLayout->type = type;
        typeLayout->rules = elementTypeLayout->rules;
        typeLayout->elementTypeLayout = elementTypeLayout;

        for(auto resInfo : elementTypeLayout->resourceInfos)
            typeLayout->addResourceUsage(resInfo);

        return typeLayout;
    }

    // Raytracing shaders have a slightly different interpretation of their
    // "varying" input/output parameters, since they don't have the same
    // idea of previous/next stage as the rasterization shader types.
    //
    if( state.directionMask & kEntryPointParameterDirection_Output )
    {
        // Note: we are silently treating `out` parameters as if they
        // were `in out` for this test, under the assumption that
        // an `out` parameter represents a write-only payload.

        switch(state.stage)
        {
        default:
            // Not a raytracing shader.
            break;

        case Stage::Intersection:
        case Stage::RayGeneration:
            // Don't expect this case to have any `in out` parameters.
            getSink(context)->diagnose(state.loc, Diagnostics::dontExpectOutParametersForStage, getStageName(state.stage));
            break;

        case Stage::AnyHit:
        case Stage::ClosestHit:
        case Stage::Miss:
            // `in out` or `out` parameter is payload
            return createTypeLayoutWith(
                context->layoutContext,
                context->getRulesFamily()->getRayPayloadParameterRules(),
                type
            );

        case Stage::Callable:
            // `in out` or `out` parameter is payload
            return createTypeLayoutWith(
                context->layoutContext,
                context->getRulesFamily()->getCallablePayloadParameterRules(),
                type
            );

        }
    }
    else
    {
        switch(state.stage)
        {
        default:
            // Not a raytracing shader.
            break;

        case Stage::Intersection:
        case Stage::RayGeneration:
        case Stage::Miss:
        case Stage::Callable:
            // Don't expect this case to have any `in` parameters.
            //
            // TODO: For a miss or callable shader we could interpret
            // an `in` parameter as indicating a payload that the
            // programmer doesn't intend to write to.
            //
            getSink(context)->diagnose(state.loc, Diagnostics::dontExpectInParametersForStage, getStageName(state.stage));
            break;

        case Stage::AnyHit:
        case Stage::ClosestHit:
            // `in` parameter is hit attributes
            return createTypeLayoutWith(
                context->layoutContext,
                context->getRulesFamily()->getHitAttributesParameterRules(),
                type
            );
        }
    }

    // If there is an available semantic name and index,
    // then we should apply it to this parameter unconditionally
    // (that is, not just if it is a leaf parameter).
    auto optSemanticName    =  state.optSemanticName;
    if (optSemanticName && varLayout)
    {
        // Always store semantics in upper-case for
        // reflection information, since they are
        // supposed to be case-insensitive and
        // upper-case is the dominant convention.
        String semanticName = *optSemanticName;
        String sn = semanticName.toUpper();

        auto semanticIndex      = *state.ioSemanticIndex;

        varLayout->semanticName = sn;
        varLayout->semanticIndex = semanticIndex;
        varLayout->flags |= VarLayoutFlag::HasSemantic;
    }

    // Scalar and vector types are treated as outputs directly
    if(auto basicType = as<BasicExpressionType>(type))
    {
        return processSimpleEntryPointParameter(context, basicType, state, varLayout);
    }
    else if(auto vectorType = as<VectorExpressionType>(type))
    {
        return processSimpleEntryPointParameter(context, vectorType, state, varLayout);
    }
    // A matrix is processed as if it was an array of rows
    else if( auto matrixType = as<MatrixExpressionType>(type) )
    {
        auto rowCount = getIntVal(matrixType->getRowCount());
        return processSimpleEntryPointParameter(context, matrixType, state, varLayout, (int) rowCount);
    }
    else if( auto arrayType = as<ArrayExpressionType>(type) )
    {
        // Note: Bad Things will happen if we have an array input
        // without a semantic already being enforced.
        
        auto elementCount = (UInt) getIntVal(arrayType->getElementCount());
        if (arrayType->isUnsized())
            elementCount = 0;

        // We use the first element to derive the layout for the element type
        auto elementTypeLayout = processEntryPointVaryingParameter(context, arrayType->getElementType(), state, varLayout);

        // We still walk over subsequent elements to make sure they consume resources
        // as needed
        for( UInt ii = 1; ii < elementCount; ++ii )
        {
            processEntryPointVaryingParameter(context, arrayType->getElementType(), state, nullptr);
        }

        RefPtr<ArrayTypeLayout> arrayTypeLayout = new ArrayTypeLayout();
        arrayTypeLayout->elementTypeLayout = elementTypeLayout;
        arrayTypeLayout->type = arrayType;

        for (auto rr : elementTypeLayout->resourceInfos)
        {
            arrayTypeLayout->findOrAddResourceInfo(rr.kind)->count = rr.count * elementCount;
        }

        return arrayTypeLayout;
    }
    else if( auto meshOutputType = as<MeshOutputType>(type) )
    {
        // TODO: Ellie, revisit
        // Note: Bad Things will happen if we have an array input
        // without a semantic already being enforced.

        // We use the first element to derive the layout for the element type
        auto elementTypeLayout = processEntryPointVaryingParameter(context, meshOutputType->getElementType(), state, varLayout);

        RefPtr<ArrayTypeLayout> arrayTypeLayout = new ArrayTypeLayout();
        arrayTypeLayout->elementTypeLayout = elementTypeLayout;
        arrayTypeLayout->type = arrayType;

        // TODO: Ellie, this is probably not the right place to handle this
        // On GLSL the indices type is built in and as such doesn't consume
        // resources.
        if(!isKhronosTarget(context->getTargetRequest()) || !as<IndicesType>(type))
        {
            for (auto rr : elementTypeLayout->resourceInfos)
            {
                // TODO: Ellie, explain why only one slot is consumed here
                arrayTypeLayout->findOrAddResourceInfo(rr.kind)->count = rr.count;
            }
        }

        return arrayTypeLayout;
    }
    else if (auto patchType = as<HLSLPatchType>(type))
    {
        // Similar to the MeshOutput case, a `InputPatch` or `OutputPatch` type is just like an array.
        //
        auto elementTypeLayout = processEntryPointVaryingParameter(context, patchType->getElementType(), state, varLayout);

        RefPtr<ArrayTypeLayout> arrayTypeLayout = new ArrayTypeLayout();
        arrayTypeLayout->elementTypeLayout = elementTypeLayout;
        arrayTypeLayout->type = arrayType;

        for (auto rr : elementTypeLayout->resourceInfos)
        {
            arrayTypeLayout->findOrAddResourceInfo(rr.kind)->count = rr.count;
        }

        return arrayTypeLayout;
    }
    // Ignore a bunch of types that don't make sense here...
    else if (const auto subpassType = as<SubpassInputType>(type)) { return nullptr;  }
    else if (const auto textureType = as<TextureType>(type)) { return nullptr;  }
    else if(const auto samplerStateType = as<SamplerStateType>(type)) { return nullptr;  }
    else if(const auto constantBufferType = as<ConstantBufferType>(type)) { return nullptr;  }
    else if (auto ptrType = as<PtrType>(type))
    {
        SLANG_ASSERT(ptrType->astNodeType == ASTNodeType::PtrType);

        // Work out the layout for the value/target type
        auto valueTypeLayout = processEntryPointVaryingParameter(context, ptrType->getValueType(), state, varLayout);

        RefPtr<PointerTypeLayout> ptrTypeLayout = new PointerTypeLayout();
        ptrTypeLayout->valueTypeLayout = valueTypeLayout;

        return ptrTypeLayout;
    }
    // Catch declaration-reference types late in the sequence, since
    // otherwise they will include all of the above cases...
    else if( auto declRefType = as<DeclRefType>(type) )
    {
        auto declRef = declRefType->getDeclRef();

        if (auto structDeclRef = declRef.as<StructDecl>())
        {
            RefPtr<StructTypeLayout> structLayout = new StructTypeLayout();
            structLayout->type = type;

            // We will recursively walk the fields of a `struct` type
            // to compute layouts for those fields.
            //
            // Along the way, we may find fields with explicit layout
            // annotations, along with fields that have no explicit
            // layout. We will consider it an error to have a mix of
            // the two.
            //
            // TODO: We could support a mix of implicit and explicit
            // layout by performing layout on fields in two passes,
            // much like is done for the global scope. This would
            // complicate layout significantly for little practical
            // benefit, so it is very much a "nice to have" rather
            // than a "must have" feature.
            //
            Decl* firstExplicit = nullptr;
            Decl* firstImplicit = nullptr;
            for( auto field : getFields(context->getASTBuilder(), structDeclRef, MemberFilterStyle::Instance) )
            {
                RefPtr<VarLayout> fieldVarLayout = new VarLayout();
                fieldVarLayout->varDecl = field;

                structLayout->fields.add(fieldVarLayout);
                structLayout->mapVarToLayout.add(field.getDecl(), fieldVarLayout);

                auto fieldTypeLayout = processEntryPointVaryingParameterDecl(
                    context,
                    field.getDecl(),
                    getType(context->getASTBuilder(), field),
                    state,
                    fieldVarLayout);

                if (!fieldTypeLayout)
                {
                    getSink(context)->diagnose(field, Diagnostics::notValidVaryingParameter, field);
                    continue;
                }
                fieldVarLayout->typeLayout = fieldTypeLayout;

                // The field needs to have offset information stored
                // in `fieldVarLayout` for every kind of resource
                // consumed by `fieldTypeLayout`.
                //
                for(auto fieldTypeResInfo : fieldTypeLayout->resourceInfos)
                {
                    SLANG_RELEASE_ASSERT(fieldTypeResInfo.count != 0);
                    auto kind = fieldTypeResInfo.kind;

                    auto structTypeResInfo = structLayout->findOrAddResourceInfo(kind);

                    auto fieldResInfo = fieldVarLayout->FindResourceInfo(kind);
                    if( !fieldResInfo )
                    {
                        if(!firstImplicit) firstImplicit = field.getDecl();

                        // In the implicit-layout case, we assign the field
                        // the next available offset after the fields that
                        // have preceded it.
                        //
                        fieldResInfo = fieldVarLayout->findOrAddResourceInfo(kind);
                        fieldResInfo->index = structTypeResInfo->count.getFiniteValue();
                        structTypeResInfo->count += fieldTypeResInfo.count;
                    }
                    else
                    {
                        if(!firstExplicit) firstExplicit = field.getDecl();

                        // In the explicit case, the field already has offset
                        // information, and we just need to update the computed
                        // size of the `struct` type to account for the field.
                        //
                        auto fieldEndOffset = fieldResInfo->index + fieldTypeResInfo.count;
                        structTypeResInfo->count = maximum(structTypeResInfo->count, fieldEndOffset);
                    }

                }
            }
            if( firstImplicit && firstExplicit )
            {
                getSink(context)->diagnose(firstImplicit, Diagnostics::mixingImplicitAndExplicitBindingForVaryingParams, firstImplicit->getName(), firstExplicit->getName());
            }

            return structLayout;
        }
        else if (auto globalGenericParamDecl = declRef.as<GlobalGenericParamDecl>())
        {
            auto& layoutContext = context->layoutContext;

            if( auto concreteType = findGlobalGenericSpecializationArg(
                layoutContext,
                globalGenericParamDecl.getDecl()) )
            {
                // If we know what concrete type has been used to specialize
                // the global generic type parameter, then we should use
                // the concrete type instead.
                //
                // Note: it should be illegal for the user to use a generic
                // type parameter in a varying parameter list without giving
                // it an explicit user-defined semantic. Otherwise, it would be possible
                // that the concrete type that gets plugged in is a user-defined
                // `struct` that uses some `SV_` semantics in its definition,
                // so that any static information about what system values
                // the entry point uses would be incorrect.
                //
                return processEntryPointVaryingParameter(context, concreteType, state, varLayout);
            }
            else
            {
                // If we don't know a concrete type, then we aren't generating final
                // code, so the reflection information should show the generic
                // type parameter.
                //
                // We don't make any attempt to assign varying parameter resources
                // to the generic type, since we can't know how many "slots"
                // of varying input/output it would consume.
                //
                return createTypeLayoutForGlobalGenericTypeParam(layoutContext, type, globalGenericParamDecl.getDecl());
            }
        }
        else if (auto associatedTypeParam = declRef.as<AssocTypeDecl>())
        {
            RefPtr<TypeLayout> assocTypeLayout = new TypeLayout();
            assocTypeLayout->type = type;
            return assocTypeLayout;
        }
        else
        {
            SLANG_UNEXPECTED("unhandled type kind");
        }
    }
    
    // If we ran into an error in checking the user's code, then skip this parameter
    else if( const auto errorType = as<ErrorType>(type) )
    {
        return nullptr;
    }

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

    /// Compute the type layout for a parameter declared directly on an entry point.
static RefPtr<TypeLayout> computeEntryPointParameterTypeLayout(
    ParameterBindingContext*        context,
    DeclRef<VarDeclBase>            paramDeclRef,
    RefPtr<VarLayout>               paramVarLayout,
    EntryPointParameterState&       state)
{
    auto paramType = getType(context->getASTBuilder(), paramDeclRef);
    SLANG_ASSERT(paramType);

    if( paramDeclRef.getDecl()->hasModifier<HLSLUniformModifier>() )
    {
        // An entry-point parameter that is explicitly marked `uniform` represents
        // a uniform shader parameter passed via the implicitly-defined
        // constant buffer (e.g., the `$Params` constant buffer seen in fxc/dxc output).
        //
        return createTypeLayoutWith(
            context->layoutContext,
            context->getRulesFamily()->getConstantBufferRules(context->getTargetRequest()->getOptionSet()),
            paramType);
    }
    else
    {
        // The default case is a varying shader parameter, which could be used for
        // input, output, or both.
        //
        // The varying case needs to not only compute a layout, but also assocaite
        // "semantic" strings/indices with the varying parameters by recursively
        // walking their structure.

        state.directionMask = 0;

        // If it appears to be an input, process it as such.
        if( paramDeclRef.getDecl()->hasModifier<InModifier>()
            || paramDeclRef.getDecl()->hasModifier<InOutModifier>()
            || !paramDeclRef.getDecl()->hasModifier<OutModifier>() )
        {
            state.directionMask |= kEntryPointParameterDirection_Input;
        }

        // If it appears to be an output, process it as such.
        if(paramDeclRef.getDecl()->hasModifier<OutModifier>()
            || paramDeclRef.getDecl()->hasModifier<InOutModifier>())
        {
            state.directionMask |= kEntryPointParameterDirection_Output;
        }

        // For the purposes of type layout, mesh shader outputs are always
        // treated as output only, despite missing an 'out' modifier
        if(as<MeshOutputType>(paramDeclRef.getDecl()->getType()))
        {
            state.directionMask = kEntryPointParameterDirection_Output;
        }

        return processEntryPointVaryingParameterDecl(
            context,
            paramDeclRef.getDecl(),
            paramType,
            state,
            paramVarLayout);
    }
}

// There are multiple places where we need to compute the layout
// for a "scope" such as the global scope or an entry point.
// The `ScopeLayoutBuilder` encapsulates the logic around:
//
// * Doing layout for the ordinary/uniform fields, which involves
//   using the `struct` layout rules for constant buffers on
//   the target.
//
// * Creating a final type/var layout that reflects whether the
//   scope needs a constant buffer to be allocated to it.
//
struct ScopeLayoutBuilder
{
    ParameterBindingContext*    m_context = nullptr;
    TypeLayoutContext           m_layoutContext;
    RefPtr<StructTypeLayout>    m_structLayout;
    UniformLayoutInfo           m_structLayoutInfo;

    // We need to compute a layout for any "pending" data inside
    // of the parameters being added to the scope, to facilitate
    // later allocating space for all the pending parameters after
    // the primary shader parameters.
    //
    StructTypeLayoutBuilder     m_pendingDataTypeLayoutBuilder;

    void beginLayout(
        ParameterBindingContext*    context,
        TypeLayoutContext           layoutContext)
    {
        m_context = context;
        m_layoutContext = layoutContext;

        auto rules = layoutContext.rules;
        m_structLayout = new StructTypeLayout();
        m_structLayout->rules = rules;

        m_structLayoutInfo = rules->BeginStructLayout();
    }


    void beginLayout(
        ParameterBindingContext* context)
    {
        beginLayout(context, context->layoutContext);
    }

    void _addParameter(
        RefPtr<VarLayout>   varLayout)
    {
        // Does the parameter have any uniform data?
        auto layoutInfo = varLayout->typeLayout->FindResourceInfo(LayoutResourceKind::Uniform);
        LayoutSize uniformSize = layoutInfo ? layoutInfo->count : 0;
        if( uniformSize != 0 )
        {
            // Make sure uniform fields get laid out properly...

            UniformLayoutInfo fieldInfo(
                uniformSize,
                varLayout->typeLayout->uniformAlignment);

            auto rules = m_layoutContext.rules;
            LayoutSize uniformOffset = rules->AddStructField(
                &m_structLayoutInfo,
                fieldInfo);

            varLayout->findOrAddResourceInfo(LayoutResourceKind::Uniform)->index = uniformOffset.getFiniteValue();
        }

        m_structLayout->fields.add(varLayout);

        m_structLayout->mapVarToLayout.add(varLayout->varDecl.getDecl(), varLayout);
    }

    void addParameter(
        RefPtr<VarLayout> varLayout)
    {
        _addParameter(varLayout);

        // Any "pending" items on a field type become "pending" items
        // on the overall `struct` type layout.
        //
        // TODO: This logic ends up duplicated between here and the main
        // `struct` layout logic in `type-layout.cpp`. If this gets any
        // more complicated we should see if there is a way to share it.
        //
        if( auto fieldPendingDataTypeLayout = varLayout->typeLayout->pendingDataTypeLayout )
        {
            auto rules = m_layoutContext.rules;
            m_pendingDataTypeLayoutBuilder.beginLayoutIfNeeded(nullptr, rules);
            auto varDeclBase = varLayout->varDecl.as<VarDeclBase>();
            if (!varDeclBase)
                return;
            auto fieldPendingDataVarLayout = m_pendingDataTypeLayoutBuilder.addField(varDeclBase, fieldPendingDataTypeLayout);

            m_structLayout->pendingDataTypeLayout = m_pendingDataTypeLayoutBuilder.getTypeLayout();

            varLayout->pendingVarLayout = fieldPendingDataVarLayout;
        }
    }

    void addParameter(
        ParameterInfo* parameterInfo)
    {
        auto varLayout = parameterInfo->varLayout;
        SLANG_RELEASE_ASSERT(varLayout);

        _addParameter(varLayout);

        // Global parameters will have their non-orindary/uniform
        // pending data handled by the main parameter binding
        // logic, but we still need to construct a layout
        // that includes any pending data.
        //
        if(auto fieldPendingVarLayout = varLayout->pendingVarLayout)
        {
            auto fieldPendingTypeLayout = fieldPendingVarLayout->typeLayout;

            auto rules = m_layoutContext.rules;
            m_pendingDataTypeLayoutBuilder.beginLayoutIfNeeded(nullptr, rules);
            m_structLayout->pendingDataTypeLayout = m_pendingDataTypeLayoutBuilder.getTypeLayout();

            auto fieldUniformLayoutInfo = fieldPendingTypeLayout->FindResourceInfo(LayoutResourceKind::Uniform);
            LayoutSize fieldUniformSize = fieldUniformLayoutInfo ? fieldUniformLayoutInfo->count : 0;
            if( fieldUniformSize != 0 )
            {
                // Make sure uniform fields get laid out properly...

                UniformLayoutInfo fieldInfo(
                    fieldUniformSize,
                    fieldPendingTypeLayout->uniformAlignment);

                LayoutSize uniformOffset = rules->AddStructField(
                    m_pendingDataTypeLayoutBuilder.getStructLayoutInfo(),
                    fieldInfo);

                fieldPendingVarLayout->findOrAddResourceInfo(LayoutResourceKind::Uniform)->index = uniformOffset.getFiniteValue();
            }

            m_pendingDataTypeLayoutBuilder.getTypeLayout()->fields.add(fieldPendingVarLayout);
        }

    }

    RefPtr<VarLayout> endLayout(VarLayout* inVarLayout = nullptr)
    {
        // Finish computing the layout for the ordindary data (if any).
        //
        auto rules = m_layoutContext.rules;
        rules->EndStructLayout(&m_structLayoutInfo);
        m_pendingDataTypeLayoutBuilder.endLayout();

        // Copy the final layout information computed for ordinary data
        // over to the struct type layout for the scope.
        //
        m_structLayout->addResourceUsage(LayoutResourceKind::Uniform, m_structLayoutInfo.size);
        m_structLayout->uniformAlignment = m_structLayout->uniformAlignment;

        RefPtr<TypeLayout> scopeTypeLayout = m_structLayout;

        // If a constant buffer is needed (because there is a non-zero
        // amount of uniform data), then we need to wrap up the layout
        // to reflect the constant buffer that will be generated.
        //
        scopeTypeLayout = createConstantBufferTypeLayoutIfNeeded(
            m_layoutContext,
            scopeTypeLayout);

        // We now have a bunch of layout information, which we should
        // record into a suitable object that represents the scope
        RefPtr<VarLayout> scopeVarLayout = inVarLayout;
        if (!scopeVarLayout)
        {
            scopeVarLayout = new VarLayout();
        }

        scopeVarLayout->typeLayout = scopeTypeLayout;

        if( auto pendingTypeLayout = scopeTypeLayout->pendingDataTypeLayout )
        {
            RefPtr<VarLayout> pendingVarLayout = new VarLayout();
            pendingVarLayout->typeLayout = pendingTypeLayout;
            scopeVarLayout->pendingVarLayout = pendingVarLayout;
        }

        return scopeVarLayout;
    }
};

// Scope layout builder specialized to the case of "simple"
// scopes (more or less everything but the global scope)
//
struct SimpleScopeLayoutBuilder : ScopeLayoutBuilder
{
    typedef ScopeLayoutBuilder Super;

        // Add a "simple" parameter that cannot have any user-defined
        // register or binding modifiers, so that its layout computation
        // can be simplified greatly.
        //
    void addSimpleParameter(
        RefPtr<VarLayout> varLayout)
    {
        // The main `addParameter` logic will deal with any ordinary/uniform data,
        // and with the "pending" part of the layout.
        //
        addParameter(varLayout);

        // That leaves us to deal with the resource usage that isn't
        // handled by `addParameter`, which we will defer until
        // `endLayout()` is called.
    }

    RefPtr<VarLayout> endLayout()
    {
        // In order to support a mix of parameters with explicit
        // and implicit layout, we will process the parameters in
        // two phases.
        //
        // In the first phase we will collect information about
        // resource ranges already claimed by parameters in the
        // scope.
        //
        UsedRanges usedRangeSet[kLayoutResourceKindCount];
        for( auto paramVarLayout : m_structLayout->fields )
        {
            auto paramTypeLayout = paramVarLayout->getTypeLayout();
            for (auto paramTypeResInfo : paramTypeLayout->resourceInfos)
            {
                auto kind = paramTypeResInfo.kind;
                if (kind == LayoutResourceKind::Uniform) continue;

                // We will look for an explicit/existing binding in
                // the parameter var layout, which would represent
                // an explicit binding, and skip the parameter if
                // we don't find one.
                //
                auto paramResInfo = paramVarLayout->FindResourceInfo(kind);
                if(!paramResInfo)
                    continue;

                // If we found an explicit binding, then we need
                // to add it to our set for tracking.
                //
                auto startOffset = paramResInfo->index;
                auto endOffset = startOffset + paramTypeResInfo.count;
                usedRangeSet[int(kind)].Add(paramVarLayout, startOffset, endOffset);
            }
        }
        //
        // Next we iterate over the parameters again, and assign
        // unused ranges to all of those that didn't have ranges
        // explicitly bound.
        //
        for( auto paramVarLayout : m_structLayout->fields )
        {
            auto paramTypeLayout = paramVarLayout->getTypeLayout();
            for (auto paramTypeResInfo : paramTypeLayout->resourceInfos)
            {
                auto kind = paramTypeResInfo.kind;
                if (kind == LayoutResourceKind::Uniform) continue;

                // We only care about parameters that are not already
                // explicitly bound, so we will skip those that already
                // have offset information for `kind`.
                //
                auto paramResInfo = paramVarLayout->FindResourceInfo(kind);
                if(paramResInfo)
                    continue;
                paramResInfo = paramVarLayout->findOrAddResourceInfo(kind);

                paramResInfo->index = usedRangeSet[int(kind)].Allocate(paramVarLayout, paramTypeResInfo.count.getFiniteValue());
            }
        }
        //
        // Finally, we need to compute the overall resource usage of
        // the scope/aggregate, so that it includes the ranges consumed
        // by all of the parameters/fields.
        //
        for( auto paramVarLayout : m_structLayout->fields )
        {
            auto paramTypeLayout = paramVarLayout->getTypeLayout();
            for (auto paramTypeResInfo : paramTypeLayout->resourceInfos)
            {
                auto kind = paramTypeResInfo.kind;
                if (kind == LayoutResourceKind::Uniform) continue;

                auto paramResInfo = paramVarLayout->FindResourceInfo(kind);
                SLANG_ASSERT(paramResInfo);
                if(!paramResInfo) continue;

                auto startOffset = paramResInfo->index;
                auto endOffset = startOffset + paramTypeResInfo.count;

                auto scopeResInfo = m_structLayout->findOrAddResourceInfo(paramTypeResInfo.kind);
                scopeResInfo->count = maximum(scopeResInfo->count, endOffset);
            }
        }

        // Once we are done providing explicit offsets for all the parameters,
        // we can defer to the base `ScopeLayoutBuilder` logic to decide
        // whether to allocate a default constant buffer or anything like that.
        //
        return Super::endLayout();
    }
};

    /// Helper routine to allocate a constant buffer binding if one is needed.
    ///
    /// This function primarily exists to encapsulate the logic for allocating
    /// the resources required for a constant buffer in the appropriate
    /// target-specific fashion.
    ///
static ParameterBindingAndKindInfo _allocateConstantBufferBinding(
    ParameterBindingContext*    context)
{
    UInt space = context->shared->defaultSpace;
    auto usedRangeSet = _getOrCreateUsedRangeSetForSpace(context, space);

    auto layoutInfo = context->getRulesFamily()
                          ->getConstantBufferRules(context->getTargetRequest()->getOptionSet())
                          ->GetObjectLayout(ShaderParameterKind::ConstantBuffer, context->layoutContext.objectLayoutOptions)
                          .getSimple();

    ParameterBindingAndKindInfo info;
    info.kind = layoutInfo.kind;
    info.count = layoutInfo.size;
    info.index = usedRangeSet->usedResourceRanges[(int)layoutInfo.kind].Allocate(nullptr, layoutInfo.size.getFiniteValue());
    info.space = space;
    return info;
}

static ParameterBindingAndKindInfo _assignConstantBufferBinding(
    ParameterBindingContext* context,
    VarLayout* varLayout,
    UInt space, 
    UInt index)
{
    auto usedRangeSet = _getOrCreateUsedRangeSetForSpace(context, space);

    auto layoutInfo = context->getRulesFamily()
        ->getConstantBufferRules(context->getTargetRequest()->getOptionSet())
        ->GetObjectLayout(ShaderParameterKind::ConstantBuffer, context->layoutContext.objectLayoutOptions)
        .getSimple();

    const Index count = Index(layoutInfo.size.getFiniteValue());

    auto existingParam = usedRangeSet->usedResourceRanges[(int)layoutInfo.kind].Add(varLayout, index, index + count);
    SLANG_UNUSED(existingParam);
    SLANG_ASSERT(existingParam == nullptr);

    ParameterBindingAndKindInfo info;
    info.kind = layoutInfo.kind;
    info.count = count;
    info.index = index;
    info.space = space;
    return info;
}

    /// Remove resource usage from `typeLayout` that should only be stored per-entry-point.
    ///
    /// This is used when constructing the overall layout for an entry point, to make sure
    /// that certain kinds of resource usage from the entry point don't "leak" into
    /// the resource usage of the overall program.
    ///
static void removePerEntryPointParameterKinds(
    TypeLayout* typeLayout)
{
    typeLayout->removeResourceUsage(LayoutResourceKind::VaryingInput);
    typeLayout->removeResourceUsage(LayoutResourceKind::VaryingOutput);
    typeLayout->removeResourceUsage(LayoutResourceKind::ShaderRecord);
    typeLayout->removeResourceUsage(LayoutResourceKind::HitAttributes);
    typeLayout->removeResourceUsage(LayoutResourceKind::ExistentialObjectParam);
    typeLayout->removeResourceUsage(LayoutResourceKind::ExistentialTypeParam);
}

static void removePerEntryPointParameterKinds(
    VarLayout* varLayout)
{
    removePerEntryPointParameterKinds(varLayout->typeLayout);

    varLayout->removeResourceUsage(LayoutResourceKind::VaryingInput);
    varLayout->removeResourceUsage(LayoutResourceKind::VaryingOutput);
    varLayout->removeResourceUsage(LayoutResourceKind::ShaderRecord);
    varLayout->removeResourceUsage(LayoutResourceKind::HitAttributes);
    varLayout->removeResourceUsage(LayoutResourceKind::ExistentialObjectParam);
    varLayout->removeResourceUsage(LayoutResourceKind::ExistentialTypeParam);
}

    /// Iterate over the parameters of an entry point to compute its requirements.
    ///
static RefPtr<EntryPointLayout> collectEntryPointParameters(
    ParameterBindingContext*                    context,
    EntryPoint*                                 entryPoint,
    String                                      entryPointNameOverride,
    EntryPoint::EntryPointSpecializationInfo*   specializationInfo)
{
    auto astBuilder = context->getASTBuilder();

    // We will take responsibility for creating and filling in
    // the `EntryPointLayout` object here.
    //
    RefPtr<EntryPointLayout> entryPointLayout = new EntryPointLayout();
    entryPointLayout->profile = entryPoint->getProfile();
    entryPointLayout->name = entryPoint->getName();
    entryPointLayout->nameOverride = entryPointNameOverride;

    // The entry point layout must be added to the output
    // program layout so that it can be accessed by reflection.
    //
    context->shared->programLayout->entryPoints.add(entryPointLayout);

    DeclRef<FuncDecl> entryPointFuncDeclRef = entryPoint->getFuncDeclRef();

    // HACK: We might have an `EntryPoint` that has been deserialized, in
    // which case we don't currently have access to its AST-level information,
    // and as a result we cannot collect parameter information from it.
    //
    if( !entryPointFuncDeclRef )
    {
        // TODO: figure out what fields we absolutely need to fill in.

        RefPtr<StructTypeLayout> paramsTypeLayout = new StructTypeLayout();

        RefPtr<VarLayout> paramsLayout = new VarLayout();
        paramsLayout->typeLayout = paramsTypeLayout;

        entryPointLayout->parametersLayout = paramsLayout;

        return entryPointLayout;
    }

    // If specialization was applied to the entry point, then the side-band
    // information that was generated will have a more specialized reference
    // to the entry point with generic parameters filled in. We should
    // use that version if it is available.
    //
    if(specializationInfo)
        entryPointFuncDeclRef = specializationInfo->specializedFuncDeclRef;

    auto entryPointType = DeclRefType::create(astBuilder, entryPointFuncDeclRef);

    entryPointLayout->entryPoint = entryPointFuncDeclRef;
    entryPointLayout->program = context->getTargetProgram()->getProgram();

    // For the duration of our parameter collection work we will
    // establish this entry point as the current one in the context.
    //
    context->entryPointLayout = entryPointLayout;

    // We are going to iterate over the entry-point parameters,
    // and while we do so we will go ahead and perform layout/binding
    // assignment for two cases:
    //
    // First, the varying parameters of the entry point will have
    // their semantics and locations assigned, so we set up state
    // for tracking that layout.
    //
    int defaultSemanticIndex = 0;
    EntryPointParameterState state;
    state.ioSemanticIndex = &defaultSemanticIndex;
    state.optSemanticName = nullptr;
    state.semanticSlotCount = 0;
    state.stage = entryPoint->getStage();

    // Second, we will compute offsets for any "ordinary" data
    // in the parameter list (e.g., a `uniform float4x4 mvp` parameter),
    // which is what the `ScopeLayoutBuilder` is designed to help with.
    //
    TypeLayoutContext layoutContext = context->layoutContext;

    if(isKhronosTarget(context->getTargetRequest()))
    {
        // For Vulkan/SPIR-V targets, there are various cases for
        // how parameters that would otherwise just be a `ConstantBuffer<...>`
        // get passed, that the compiler and application need to agree
        // on.
        //
        // As a matter of policy, the Slang compiler will interpret
        // direct entry-point `uniform` parameters as being passed
        // using whatever is the most natural and efficient mechanism
        // based on the shader stage.
        //
        // In the case of rasterization and compute shaders, this means
        // passing entry-point `uniform` parmaeters via a "push constant"
        // buffer.
        //
        // In the case of ray-tracing shaders, this means passing entry-point
        // `uniform` parameters via the "shader record."
        //
        switch( entryPoint->getStage() )
        {
        default:
            layoutContext = layoutContext.with(layoutContext.getRulesFamily()->getPushConstantBufferRules());
            break;

        case Stage::AnyHit:
        case Stage::Callable:
        case Stage::ClosestHit:
        case Stage::Intersection:
        case Stage::Miss:
        case Stage::RayGeneration:
            layoutContext = layoutContext.with(layoutContext.getRulesFamily()->getShaderRecordConstantBufferRules());
            break;
        }
    }

    SimpleScopeLayoutBuilder scopeBuilder;
    scopeBuilder.beginLayout(context, layoutContext);
    auto paramsStructLayout = scopeBuilder.m_structLayout;
    paramsStructLayout->type = entryPointType;

    for( auto& shaderParamInfo : entryPoint->getShaderParams() )
    {
        auto paramDeclRef = shaderParamInfo.paramDeclRef;

        // Any generic specialization applied to the entry-point function
        // must also be applied to its parameters.
        paramDeclRef = context->getASTBuilder()->getMemberDeclRef(entryPointFuncDeclRef, paramDeclRef.getDecl());

        // When computing layout for an entry-point parameter,
        // we want to make sure that the layout context has access
        // to the existential type arguments (if any) that were
        // provided for the entry-point existential type parameters (if any).
        //
        if(specializationInfo)
        {
            auto& existentialSpecializationArgs = specializationInfo->existentialSpecializationArgs;
            auto genericSpecializationParamCount = entryPoint->getGenericSpecializationParamCount();

            context->layoutContext = context->layoutContext
                .withSpecializationArgs(
                    existentialSpecializationArgs.getBuffer(),
                    existentialSpecializationArgs.getCount())
                .withSpecializationArgsOffsetBy(
                    shaderParamInfo.firstSpecializationParamIndex - genericSpecializationParamCount);
        }

        // Any error messages we emit during the process should
        // refer to the location of this parameter.
        //
        state.loc = paramDeclRef.getLoc();

        // We are going to construct the variable layout for this
        // parameter *before* computing the type layout, because
        // the type layout computation is also determining the effective
        // semantic of the parameter, which needs to be stored
        // back onto the `VarLayout`.
        //
        RefPtr<VarLayout> paramVarLayout = new VarLayout();
        paramVarLayout->varDecl = paramDeclRef;
        paramVarLayout->stage = state.stage;

        auto paramTypeLayout = computeEntryPointParameterTypeLayout(
            context,
            paramDeclRef,
            paramVarLayout,
            state);
        paramVarLayout->typeLayout = paramTypeLayout;

        // We expect to always be able to compute a layout for
        // entry-point parameters, but to be defensive we will
        // skip parameters that couldn't have a layout computed
        // when assertions are disabled.
        //
        SLANG_ASSERT(paramTypeLayout);
        if(!paramTypeLayout)
            continue;

        // Now that we've computed the layout to use for the parameter,
        // we need to add its resource usage to that of the entry
        // point as a whole.
        //
        scopeBuilder.addSimpleParameter(paramVarLayout);
    }
    entryPointLayout->parametersLayout = scopeBuilder.endLayout();

    // For an entry point with a non-`void` return type, we need to process the
    // return type as a varying output parameter.
    //
    // TODO: Ideally we should make the layout process more robust to empty/void
    // types and apply this logic unconditionally.
    //
    auto resultType = getResultType(astBuilder, entryPointFuncDeclRef);
    SLANG_ASSERT(resultType);

    if( !resultType->equals(astBuilder->getVoidType()) )
    {
        state.loc = entryPointFuncDeclRef.getLoc();
        state.directionMask = kEntryPointParameterDirection_Output;

        RefPtr<VarLayout> resultLayout = new VarLayout();
        resultLayout->stage = state.stage;

        auto resultTypeLayout = processEntryPointVaryingParameterDecl(
            context,
            entryPointFuncDeclRef.getDecl(),
            resultType,
            state,
            resultLayout);

        if( resultTypeLayout )
        {
            resultLayout->typeLayout = resultTypeLayout;

            for (auto rr : resultTypeLayout->resourceInfos)
            {
                auto entryPointRes = paramsStructLayout->findOrAddResourceInfo(rr.kind);
                resultLayout->findOrAddResourceInfo(rr.kind)->index = entryPointRes->count.getFiniteValue();
                entryPointRes->count += rr.count;
            }
        }

        entryPointLayout->resultLayout = resultLayout;
    }

    // We don't want certain kinds of resource usage within an entry
    // point to "leak" into the overall resource usage of the entry
    // point and thus lead to offsetting of successive entry points.
    //
    // For example if we have a vertex and a fragment entry point
    // in the some program, and each has one varying input, then
    // the both the vertex and fragment varying outputs should have
    // a location/index of zero. It would be bad if the fragment
    // input (or whichever entry point comes second in the global
    // ordering) started at location one, because then it wouldn't
    // line up correctly with any vertex stage outputs.
    //
    // We handle this with a bit of a kludge, by removing the
    // particular `LayoutResourceKind`s that are susceptible to
    // this problem from the overall resource usage of the entry
    // point.
    //
    removePerEntryPointParameterKinds(paramsStructLayout);
    removePerEntryPointParameterKinds(entryPointLayout->parametersLayout);

    return entryPointLayout;
}

    /// Visitor used by `collectGlobalGenericArguments`
struct CollectGlobalGenericArgumentsVisitor : ComponentTypeVisitor
{
    CollectGlobalGenericArgumentsVisitor(
        ParameterBindingContext*    context)
        : m_context(context)
    {}

    ParameterBindingContext* m_context;

    void visitRenamedEntryPoint(
        RenamedEntryPointComponentType* entryPoint,
        EntryPoint::EntryPointSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        entryPoint->getBase()->acceptVisitor(this, specializationInfo);
    }

    void visitEntryPoint(EntryPoint* entryPoint, EntryPoint::EntryPointSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        SLANG_UNUSED(entryPoint);
        SLANG_UNUSED(specializationInfo);
    }

    void visitTypeConformance(TypeConformance* conformance) SLANG_OVERRIDE
    {
        SLANG_UNUSED(conformance);
    }

    void visitModule(Module* module, Module::ModuleSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        SLANG_UNUSED(module);

        if(!specializationInfo)
            return;

        for(auto& globalGenericArg : specializationInfo->genericArgs)
        {
            if(auto globalGenericTypeParamDecl = as<GlobalGenericParamDecl>(globalGenericArg.paramDecl))
            {
                m_context->shared->programLayout->globalGenericArgs.add(globalGenericTypeParamDecl, globalGenericArg.argVal);
            }
        }
    }

    void visitComposite(CompositeComponentType* composite, CompositeComponentType::CompositeSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        visitChildren(composite, specializationInfo);
    }

    void visitSpecialized(SpecializedComponentType* specialized) SLANG_OVERRIDE
    {
        specialized->getBaseComponentType()->acceptVisitor(this, specialized->getSpecializationInfo());
    }
};

    /// Collect an ordered list of all the specialization arguments given for global generic specialization parameters in `program`.
    ///
    /// This information is used to accelerate the process of mapping a global generic type
    /// to its definition during type layout.
    ///
static void collectGlobalGenericArguments(
    ParameterBindingContext*    context,
    ComponentType*              program)
{
    CollectGlobalGenericArgumentsVisitor visitor(context);
    program->acceptVisitor(&visitor, nullptr);
}

    /// Collect information about the (unspecialized) specialization parameters of `program` into `context`.
    ///
    /// This function computes the reflection/layout for for the specialization parameters, so
    /// that they can be exposed to the API user.
    ///
static void collectSpecializationParams(
    ParameterBindingContext*    context,
    ComponentType*              program)
{
    auto specializationParamCount = program->getSpecializationParamCount();
    for(Index ii = 0; ii < specializationParamCount; ++ii)
    {
        auto specializationParam = program->getSpecializationParam(ii);
        switch(specializationParam.flavor)
        {
        case SpecializationParam::Flavor::GenericType:
        case SpecializationParam::Flavor::GenericValue:
            {
                RefPtr<GenericSpecializationParamLayout> paramLayout = new GenericSpecializationParamLayout();
                paramLayout->decl = as<Decl>(specializationParam.object);
                context->shared->programLayout->specializationParams.add(paramLayout);
            }
            break;

        case SpecializationParam::Flavor::ExistentialType:
        case SpecializationParam::Flavor::ExistentialValue:
            {
                RefPtr<ExistentialSpecializationParamLayout> paramLayout = new ExistentialSpecializationParamLayout();
                paramLayout->type = as<Type>(specializationParam.object);
                context->shared->programLayout->specializationParams.add(paramLayout);
            }
            break;

        default:
            SLANG_UNEXPECTED("unhandled specialization parameter flavor");
            break;
        }
    }
}

    /// Visitor used by `collectParameters()`
struct CollectParametersVisitor : ComponentTypeVisitor
{
    CollectParametersVisitor(
        ParameterBindingContext*    context)
        : m_context(context)
    {}

    ParameterBindingContext* m_context;
    String m_currentEntryPointNameOverride;

    void visitComposite(CompositeComponentType* composite, CompositeComponentType::CompositeSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        // The parameters of a composite component type can
        // be determined by just visiting its children in order.
        //
        visitChildren(composite, specializationInfo);
    }

    void visitSpecialized(SpecializedComponentType* specialized) SLANG_OVERRIDE
    {
        // The parameters of a specialized component type
        // are just those of its base component type, with
        // appropriate specialization information passed
        // along.
        //
        visitChildren(specialized);
    }


    void visitEntryPoint(EntryPoint* entryPoint, EntryPoint::EntryPointSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        // An entry point is a leaf case.
        //
        // In our current model an entry point does not introduce
        // any global shader parameters, but in practice it effectively
        // acts a lot like a single global shader parameter named after
        // the entry point and with a `struct` type that combines
        // all the `uniform` entry point parameters.
        //
        // Later passes will need to make sure that the entry point
        // gets enumerated in the right order relative to any global
        // shader parameters.
        //

        ParameterBindingContext contextData = *m_context;
        auto context = &contextData;
        context->stage = entryPoint->getStage();
        collectEntryPointParameters(
            context, entryPoint, m_currentEntryPointNameOverride, specializationInfo);
    }

    void visitRenamedEntryPoint(
        RenamedEntryPointComponentType* renamedEntryPoint,
        EntryPoint::EntryPointSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        auto lastNameOverride = m_currentEntryPointNameOverride;
        m_currentEntryPointNameOverride = renamedEntryPoint->getEntryPointNameOverride(0);
        renamedEntryPoint->getBase()->acceptVisitor(this, specializationInfo);
        m_currentEntryPointNameOverride = lastNameOverride;
    }

    void visitModule(Module* module, Module::ModuleSpecializationInfo* specializationInfo) SLANG_OVERRIDE
    {
        // A single module represents a leaf case for layout.
        //
        // We will enumerate the (global) shader parameters declared
        // in the module and add each to our canonical ordering.
        //
        auto paramCount = module->getShaderParamCount();

       ExpandedSpecializationArg* specializationArgs = specializationInfo
           ? specializationInfo->existentialArgs.getBuffer()
           : nullptr;

        for(Index pp = 0; pp < paramCount; ++pp)
        {
            auto shaderParamInfo = module->getShaderParam(pp);
            if(specializationArgs)
            {
                m_context->layoutContext = m_context->layoutContext.withSpecializationArgs(
                    specializationArgs,
                    shaderParamInfo.specializationParamCount);
                specializationArgs += shaderParamInfo.specializationParamCount;
            }

            collectGlobalScopeParameter(m_context, shaderParamInfo, SubstitutionSet());
        }

        if( auto moduleDecl = module->getModuleDecl() )
        {
            if( auto nvapiSlotModifier = moduleDecl->findModifier<NVAPISlotModifier>() )
            {
                m_context->shared->nvapiSlotModifiers.add(nvapiSlotModifier);
            }
        }
    }

    void visitTypeConformance(TypeConformance* conformance) SLANG_OVERRIDE
    {
        SLANG_UNUSED(conformance);
    }
};

    /// Recursively collect the global shader parameters and entry points in `program`.
    ///
    /// This function is used to establish the global ordering of parameters and
    /// entry points used for layout.
    ///
static void collectParameters(
    ParameterBindingContext*            inContext,
    ComponentType*                      program)
{
    // All of the parameters in translation units directly
    // referenced in the compile request are part of one
    // logical namespace/"linkage" so that two parameters
    // with the same name should represent the same
    // parameter, and get the same binding(s)

    ParameterBindingContext contextData = *inContext;
    auto context = &contextData;
    context->stage = Stage::Unknown;

    CollectParametersVisitor visitor(context);
    program->acceptVisitor(&visitor, nullptr);
}

    /// Emit a diagnostic about a uniform/ordinary parameter at global scope.
void diagnoseGlobalUniform(
    SharedParameterBindingContext*  sharedContext,
    VarDeclBase*                    varDecl)
{
    // This subroutine gets invoked if a shader parameter containing
    // "ordinary" data (sometimes just called "uniform" data) is present
    // at the global scope.
    //
    // Slang can support such parameters by aggregating them into
    // an implicit constant buffer, but it is also common for programmers
    // to accidentally declare a global-scope shader parameter when they
    // meant to declare a global variable instead:
    //
    //      int gCounter = 0; // this is a shader parameter, not a global
    //
    // In order to avoid mistakes, we'd like to warn the user when
    // they write code like the above, and hint to them that they
    // should make their intention more explicit with a keyword:
    //
    //      static int gCounter = 0; // this is now a (static) global
    //
    //      uniform int gCounter; // this is now explicitly a shader parameter
    //
    // We skip the diagnostic whenever the variable was explicitly `uniform`,
    // under the assumption that the programmer who added that modifier
    // knew what they were opting into.
    //
    if(varDecl->hasModifier<HLSLUniformModifier>())
        return;

    getSink(sharedContext)->diagnose(varDecl, Diagnostics::globalUniformNotExpected, varDecl->getName());
}


static int _calcTotalNumUsedRegistersForLayoutResourceKind(ParameterBindingContext* bindingContext, LayoutResourceKind kind)
{
    int numUsed = 0;
    for (auto& [_, rangeSet] : bindingContext->shared->globalSpaceUsedRangeSets)
    {
        const auto& usedRanges = rangeSet->usedResourceRanges[kind];
        for (const auto& usedRange : usedRanges.ranges)
        {
            numUsed += int(usedRange.end - usedRange.begin);
        }
    }
    return numUsed;
}

static bool _isCPUTarget(CodeGenTarget target)
{
    const auto desc = ArtifactDescUtil::makeDescForCompileTarget(asExternal(target));
    return ArtifactDescUtil::isCpuLikeTarget(desc);
}

static bool _isPTXTarget(CodeGenTarget target)
{
    switch (target)
    {
        case CodeGenTarget::CUDASource:
        case CodeGenTarget::PTX:
        {
            return true;
        }
        default: return false;
    }
}

    /// Keep track of the running global counter for entry points and global parameters visited.
    ///
    /// Because of explicit `register` and `[[vk::binding(...)]]` support, parameter binding
    /// needs to proceed in multiple passes, and each pass must both visit the things that
    /// need layout (parameters and entry points) in the same order in each pass, and must