summaryrefslogtreecommitdiff
path: root/tests/render/nointerpolation.hlsl.expected
diff options
context:
space:
mode:
authorJay Kwak <82421531+jkwak-work@users.noreply.github.com>2025-05-15 07:02:38 +0000
committerGitHub <noreply@github.com>2025-05-15 00:02:38 -0700
commit49de1e8f60c698e9d524befacc988fb06574b234 (patch)
treecc1006b24532b0f98a2f8af49010925e9d992f66 /tests/render/nointerpolation.hlsl.expected
parentdd275dd952afc1b0d1a156d786c28620a48863e1 (diff)
Support tensor addressing (#7060)
This commit implements two new types and related Load/Store functions in CoopMat. tensor_addrressing.TensorLayout tensor_addressing.TensorView CoopMat.Load(..., TensorLayout) CoopMat.Load(..., TensorLayout, TensorView) CoopMat.Store(..., TensorLayout) CoopMat.Store(..., TensorLayout, TensorView) CoopMat.Load(..., TensorLayout, TensorView)
Diffstat (limited to 'tests/render/nointerpolation.hlsl.expected')
0 files changed, 0 insertions, 0 deletions
='#n117'>117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
// slang-emit-hlsl.cpp
#include "slang-emit-hlsl.h"

#include "../core/slang-writer.h"
#include "slang-emit-source-writer.h"
#include "slang-ir-util.h"
#include "slang-mangled-lexer.h"

#include <assert.h>

namespace Slang
{

static const char* kHLSLBuiltInPrelude64BitCast = R"(
uint64_t _slang_asuint64(double x)
{
    uint32_t low;
    uint32_t high;
    asuint(x, low, high);
    return ((uint64_t)high << 32) | low;
}

double _slang_asdouble(uint64_t x)
{
    uint32_t low = x & 0xFFFFFFFF;
    uint32_t high = x >> 32;
    return asdouble(low, high);
}
)";

void HLSLSourceEmitter::_emitHLSLDecorationSingleString(
    const char* name,
    IRFunc* entryPoint,
    IRStringLit* val)
{
    SLANG_UNUSED(entryPoint);
    assert(val);

    m_writer->emit("[");
    m_writer->emit(name);
    m_writer->emit("(\"");
    m_writer->emit(val->getStringSlice());
    m_writer->emit("\")]\n");
}

void HLSLSourceEmitter::_emitHLSLDecorationSingleInt(
    const char* name,
    IRFunc* entryPoint,
    IRIntLit* val)
{
    SLANG_UNUSED(entryPoint);
    SLANG_ASSERT(val);

    auto intVal = getIntVal(val);

    m_writer->emit("[");
    m_writer->emit(name);
    m_writer->emit("(");
    m_writer->emit(intVal);
    m_writer->emit(")]\n");
}

void HLSLSourceEmitter::_emitHLSLRegisterSemantic(
    LayoutResourceKind kind,
    EmitVarChain* chain,
    IRInst* inst,
    char const* uniformSemanticSpelling)
{
    if (!chain)
        return;
    if (!chain->varLayout->usesResourceKind(kind))
        return;

    UInt index = getBindingOffset(chain, kind);
    UInt space = getBindingSpace(chain, kind);

    switch (kind)
    {
    case LayoutResourceKind::Uniform:
        {
            UInt offset = index;

            // The HLSL `c` register space is logically grouped in 16-byte registers,
            // while we try to traffic in byte offsets. That means we need to pick
            // a register number, based on the starting offset in 16-byte register
            // units, and then a "component" within that register, based on 4-byte
            // offsets from there. We cannot support more fine-grained offsets than that.

            m_writer->emit(" : ");
            m_writer->emit(uniformSemanticSpelling);
            m_writer->emit("(c");

            // Size of a logical `c` register in bytes
            auto registerSize = 16;

            // Size of each component of a logical `c` register, in bytes
            auto componentSize = 4;

            size_t startRegister = offset / registerSize;
            m_writer->emit(int(startRegister));

            size_t byteOffsetInRegister = offset % registerSize;

            // If this field doesn't start on an even register boundary,
            // then we need to emit additional information to pick the
            // right component to start from
            if (byteOffsetInRegister != 0)
            {
                // The value had better occupy a whole number of components.
                SLANG_RELEASE_ASSERT(byteOffsetInRegister % componentSize == 0);

                size_t startComponent = byteOffsetInRegister / componentSize;

                static const char* kComponentNames[] = {"x", "y", "z", "w"};
                m_writer->emit(".");
                m_writer->emit(kComponentNames[startComponent]);
            }
            m_writer->emit(")");
        }
        break;

    case LayoutResourceKind::InputAttachmentIndex:
        {
            m_writer->emit("[[vk::input_attachment_index(");
            m_writer->emit(index);
            m_writer->emit(")]]");
        }
        break;

    case LayoutResourceKind::RegisterSpace:
    case LayoutResourceKind::GenericResource:
    case LayoutResourceKind::ExistentialTypeParam:
    case LayoutResourceKind::ExistentialObjectParam:
        // ignore
        break;
    default:
        {
            if (m_codeGenContext->getTargetProgram()->getOptionSet().getBoolOption(
                    CompilerOptionName::NoHLSLBinding))
            {
                // If we are told not to emit hlsl binding, and the user has not provided explicit
                // binding, then skip emitting the `: register` semantics here.
                //
                if (!inst || !inst->findDecoration<IRHasExplicitHLSLBindingDecoration>())
                {
                    break;
                }
            }
            m_writer->emit(" : register(");
            switch (kind)
            {
            case LayoutResourceKind::ConstantBuffer:
                m_writer->emit("b");
                break;
            case LayoutResourceKind::ShaderResource:
                m_writer->emit("t");
                break;
            case LayoutResourceKind::UnorderedAccess:
                m_writer->emit("u");
                break;
            case LayoutResourceKind::SamplerState:
                m_writer->emit("s");
                break;
            default:
                SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled HLSL register type");
                break;
            }
            m_writer->emit(index);
            if (space)
            {
                m_writer->emit(", space");
                m_writer->emit(space);
            }
            m_writer->emit(")");
        }
    }
}

void HLSLSourceEmitter::_emitHLSLRegisterSemantics(
    EmitVarChain* chain,
    IRInst* inst,
    char const* uniformSemanticSpelling,
    EmitLayoutSemanticOption layoutSemanticOption)
{
    if (!chain)
        return;

    auto layout = chain->varLayout;

    switch (getSourceLanguage())
    {
    default:
        return;

    case SourceLanguage::HLSL:
        break;
    }

    for (auto rr : layout->getOffsetAttrs())
    {
        if (layoutSemanticOption == EmitLayoutSemanticOption::kPreType &&
            rr->getResourceKind() != LayoutResourceKind::InputAttachmentIndex)
            continue;
        _emitHLSLRegisterSemantic(rr->getResourceKind(), chain, inst, uniformSemanticSpelling);
    }
}

void HLSLSourceEmitter::_emitHLSLRegisterSemantics(
    IRVarLayout* varLayout,
    IRInst* inst,
    char const* uniformSemanticSpelling,
    EmitLayoutSemanticOption layoutSemanticOption)
{
    if (!varLayout)
        return;

    EmitVarChain chain(varLayout);
    _emitHLSLRegisterSemantics(&chain, inst, uniformSemanticSpelling, layoutSemanticOption);
}

void HLSLSourceEmitter::_emitHLSLParameterGroupFieldLayoutSemantics(EmitVarChain* chain)
{
    if (!chain)
        return;

    auto layout = chain->varLayout;
    for (auto rr : layout->getOffsetAttrs())
    {
        _emitHLSLRegisterSemantic(rr->getResourceKind(), chain, nullptr, "packoffset");
    }
}

void HLSLSourceEmitter::_emitHLSLParameterGroupFieldLayoutSemantics(
    IRVarLayout* fieldLayout,
    EmitVarChain* inChain)
{
    EmitVarChain chain(fieldLayout, inChain);
    _emitHLSLParameterGroupFieldLayoutSemantics(&chain);
}

void HLSLSourceEmitter::_emitHLSLParameterGroup(
    IRGlobalParam* varDecl,
    IRUniformParameterGroupType* type)
{
    LayoutResourceKind layoutResourceKind = LayoutResourceKind::ConstantBuffer;
    if (as<IRTextureBufferType>(type))
    {
        layoutResourceKind = LayoutResourceKind::ShaderResource;
        m_writer->emit("tbuffer ");
    }
    else
    {
        m_writer->emit("cbuffer ");
    }
    m_writer->emit(getName(varDecl));

    auto varLayout = getVarLayout(varDecl);
    SLANG_RELEASE_ASSERT(varLayout);

    EmitVarChain blockChain(varLayout);

    EmitVarChain containerChain = blockChain;
    EmitVarChain elementChain = blockChain;

    auto typeLayout = varLayout->getTypeLayout();
    if (auto parameterGroupTypeLayout = as<IRParameterGroupTypeLayout>(typeLayout))
    {
        containerChain =
            EmitVarChain(parameterGroupTypeLayout->getContainerVarLayout(), &blockChain);
        elementChain = EmitVarChain(parameterGroupTypeLayout->getElementVarLayout(), &blockChain);

        typeLayout = parameterGroupTypeLayout->getElementVarLayout()->getTypeLayout();
    }

    _emitHLSLRegisterSemantic(layoutResourceKind, &containerChain, varDecl, "register");

    auto elementType = type->getElementType();
    if (shouldForceUnpackConstantBufferElements(type) || hasExplicitConstantBufferOffset(type))
    {
        // If the user has provided any explicit `packoffset` modifiers,
        // or the user has explicitly requested for cbuffer fields to be unpacked,
        // we have to unwrap the struct and emit the fields directly.
        emitStructDeclarationsBlock(as<IRStructType>(elementType), true);
        m_writer->emit("\n");
        return;
    }


    m_writer->emit("\n{\n");
    m_writer->indent();


    emitType(elementType, getName(varDecl));
    m_writer->emit(";\n");

    m_writer->dedent();
    m_writer->emit("}\n");
}

void HLSLSourceEmitter::_emitHLSLTextureType(IRTextureTypeBase* texType)
{
    switch (texType->getAccess())
    {
    case SLANG_RESOURCE_ACCESS_READ:
        break;

    case SLANG_RESOURCE_ACCESS_READ_WRITE:
        m_writer->emit("RW");
        break;

    case SLANG_RESOURCE_ACCESS_WRITE:
        m_writer->emit("RW");
        break;

    case SLANG_RESOURCE_ACCESS_RASTER_ORDERED:
        m_writer->emit("RasterizerOrdered");
        break;

    case SLANG_RESOURCE_ACCESS_APPEND:
        m_writer->emit("Append");
        break;

    case SLANG_RESOURCE_ACCESS_CONSUME:
        m_writer->emit("Consume");
        break;

    case SLANG_RESOURCE_ACCESS_FEEDBACK:
        m_writer->emit("Feedback");
        break;

    default:
        SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled resource access mode");
        break;
    }

    switch (texType->GetBaseShape())
    {
    case SLANG_TEXTURE_1D:
        m_writer->emit("Texture1D");
        break;
    case SLANG_TEXTURE_2D:
        m_writer->emit("Texture2D");
        break;
    case SLANG_TEXTURE_3D:
        m_writer->emit("Texture3D");
        break;
    case SLANG_TEXTURE_CUBE:
        m_writer->emit("TextureCube");
        break;
    case SLANG_TEXTURE_BUFFER:
        m_writer->emit("Buffer");
        break;
    default:
        SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled resource shape");
        break;
    }

    if (texType->isMultisample())
    {
        m_writer->emit("MS");
    }
    if (texType->isArray())
    {
        m_writer->emit("Array");
    }
    m_writer->emit("<");
    emitType(texType->getElementType());
    auto sampleCount = as<IRIntLit>(texType->getSampleCount());
    if (sampleCount->getValue() != 0)
    {
        m_writer->emit(", ");
        m_writer->emit(sampleCount->getValue());
    }
    m_writer->emit(" >");
}

void HLSLSourceEmitter::_emitHLSLSubpassInputType(IRSubpassInputType* subpassType)
{
    m_writer->emit("SubpassInput");
    if (subpassType->isMultisample())
    {
        m_writer->emit("MS");
    }
    m_writer->emit("<");
    emitType(subpassType->getElementType());
    m_writer->emit(">");
}

void HLSLSourceEmitter::emitLayoutSemanticsImpl(
    IRInst* inst,
    char const* uniformSemanticSpelling,
    EmitLayoutSemanticOption layoutSemanticOption)
{
    auto layout = getVarLayout(inst);
    if (layout)
    {
        _emitHLSLRegisterSemantics(layout, inst, uniformSemanticSpelling, layoutSemanticOption);
    }
}

void HLSLSourceEmitter::emitParameterGroupImpl(
    IRGlobalParam* varDecl,
    IRUniformParameterGroupType* type)
{
    _emitHLSLParameterGroup(varDecl, type);
}

void HLSLSourceEmitter::emitEntryPointAttributesImpl(
    IRFunc* irFunc,
    IREntryPointDecoration* entryPointDecor)
{
    auto profile = m_effectiveProfile;
    auto stage = entryPointDecor->getProfile().getStage();

    if (profile.getFamily() == ProfileFamily::DX)
    {
        if (profile.getVersion() >= ProfileVersion::DX_6_1)
        {
            char const* stageName = getStageName(stage);
            if (stageName)
            {
                m_writer->emit("[shader(\"");
                m_writer->emit(stageName);
                m_writer->emit("\")]");
            }
        }
    }

    auto emitNumThreadsAttribute = [&]()
    {
        Int sizeAlongAxis[kThreadGroupAxisCount];
        getComputeThreadGroupSize(irFunc, sizeAlongAxis);

        m_writer->emit("[numthreads(");
        for (int ii = 0; ii < kThreadGroupAxisCount; ++ii)
        {
            if (ii != 0)
                m_writer->emit(", ");
            m_writer->emit(sizeAlongAxis[ii]);
        }
        m_writer->emit(")]\n");
    };

    auto emitWaveSizeAttribute = [&]()
    {
        Int waveSize;
        if (getComputeWaveSize(irFunc, &waveSize))
        {
            m_writer->emit("[WaveSize(");
            m_writer->emit(waveSize);
            m_writer->emit(")]\n");
        }
    };

    switch (stage)
    {
    case Stage::Compute:
        {
            emitWaveSizeAttribute();
            emitNumThreadsAttribute();
        }
        break;
    case Stage::Geometry:
        {
            if (auto decor = irFunc->findDecoration<IRMaxVertexCountDecoration>())
            {
                auto count = getIntVal(decor->getCount());
                m_writer->emit("[maxvertexcount(");
                m_writer->emit(Int(count));
                m_writer->emit(")]\n");
            }

            if (auto decor = irFunc->findDecoration<IRInstanceDecoration>())
            {
                auto count = getIntVal(decor->getCount());
                m_writer->emit("[instance(");
                m_writer->emit(Int(count));
                m_writer->emit(")]\n");
            }
            break;
        }
    case Stage::Domain:
        {
            /* [domain("isoline")] */
            if (auto decor = irFunc->findDecoration<IRDomainDecoration>())
            {
                _emitHLSLDecorationSingleString("domain", irFunc, decor->getDomain());
            }
            break;
        }
    case Stage::Hull:
        {
            // Lists these are only attributes for hull shader
            // https://docs.microsoft.com/en-us/windows/desktop/direct3d11/direct3d-11-advanced-stages-hull-shader-design

            /* [domain("isoline")] */
            if (auto decor = irFunc->findDecoration<IRDomainDecoration>())
            {
                _emitHLSLDecorationSingleString("domain", irFunc, decor->getDomain());
            }

            /* [domain("partitioning")] */
            if (auto decor = irFunc->findDecoration<IRPartitioningDecoration>())
            {
                _emitHLSLDecorationSingleString("partitioning", irFunc, decor->getPartitioning());
            }

            /* [outputtopology("line")] */
            if (auto decor = irFunc->findDecoration<IROutputTopologyDecoration>())
            {
                _emitHLSLDecorationSingleString("outputtopology", irFunc, decor->getTopology());
            }

            /* [outputcontrolpoints(4)] */
            if (auto decor = irFunc->findDecoration<IROutputControlPointsDecoration>())
            {
                _emitHLSLDecorationSingleInt(
                    "outputcontrolpoints",
                    irFunc,
                    decor->getControlPointCount());
            }

            /* [patchconstantfunc("HSConst")] */
            if (auto decor = irFunc->findDecoration<IRPatchConstantFuncDecoration>())
            {
                const String irName = getName(decor->getFunc());

                m_writer->emit("[patchconstantfunc(\"");
                m_writer->emit(irName);
                m_writer->emit("\")]\n");
            }

            break;
        }
    case Stage::Pixel:
        {
            if (irFunc->findDecoration<IREarlyDepthStencilDecoration>())
            {
                m_writer->emit("[earlydepthstencil]\n");
            }
            break;
        }
    case Stage::Mesh:
        {
            emitNumThreadsAttribute();
            if (auto decor = irFunc->findDecoration<IROutputTopologyDecoration>())
            {
                // TODO: Ellie validate here/elsewhere, what's allowed here is
                // different from the tesselator
                // The naming here is plural, so add an 's'
                _emitHLSLDecorationSingleString("outputtopology", irFunc, decor->getTopology());
            }
            break;
        }
    case Stage::Amplification:
        {
            emitNumThreadsAttribute();
            break;
        }
    // TODO: There are other stages that will need this kind of handling.
    default:
        break;
    }
}

bool HLSLSourceEmitter::tryEmitInstStmtImpl(IRInst* inst)
{
    auto diagnoseFloatAtommic = [&]()
    {
        getSink()->diagnose(
            inst,
            Diagnostics::unsupportedTargetIntrinsic,
            "floating point atomic operation");
    };
    switch (inst->getOp())
    {
    case kIROp_AtomicLoad:
        {
            emitInstResultDecl(inst);
            emitDereferenceOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(";\n");
            return true;
        }
    case kIROp_AtomicStore:
        {
            emitDereferenceOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(" = ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(";\n");
            return true;
        }
    case kIROp_AtomicExchange:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedExchange");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicCompareExchange:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedCompareExchange");
            if (inst->getDataType()->getOp() == kIROp_FloatType)
                m_writer->emit("FloatBitwise");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(2), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicAdd:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            if (inst->getDataType()->getOp() == kIROp_FloatType)
            {
                diagnoseFloatAtommic();
            }
            m_writer->emit("InterlockedAdd");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicSub:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            if (inst->getDataType()->getOp() == kIROp_FloatType)
            {
                diagnoseFloatAtommic();
            }
            m_writer->emit("InterlockedAdd");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", -(");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit("), ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicAnd:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedAnd");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicOr:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedOr");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicXor:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedXor");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicMin:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedMin");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicMax:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedMax");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", ");
            emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
            m_writer->emit(", ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicInc:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedAdd");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", 1, ");
            m_writer->emit(getName(inst));
            m_writer->emit(");\n");
            return true;
        }
    case kIROp_AtomicDec:
        {
            emitType(inst->getDataType(), getName(inst));
            m_writer->emit(";\n");
            m_writer->emit("InterlockedAdd");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(", -1, ");
            m_writer->emit(getName(inst));
            m_writer->emit(");");
            return true;
        }
    default:
        return false;
    }
}

bool HLSLSourceEmitter::tryEmitInstExprImpl(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
    switch (inst->getOp())
    {
    case kIROp_ControlBarrier:
        {
            m_writer->emit("GroupMemoryBatrierWithGroupSync();\n");
            return true;
        }
    case kIROp_MakeVector:
    case kIROp_MakeMatrix:
        {
            if (inst->getOperandCount() == 1)
            {
                EmitOpInfo outerPrec = inOuterPrec;
                bool needClose = false;

                auto prec = getInfo(EmitOp::Prefix);
                needClose = maybeEmitParens(outerPrec, prec);

                // Need to emit as cast for HLSL
                m_writer->emit("(");
                emitType(inst->getDataType());
                m_writer->emit(") ");
                emitOperand(inst->getOperand(0), rightSide(outerPrec, prec));

                maybeCloseParens(needClose);
                // Handled
                return true;
            }
            break;
        }
    case kIROp_BitCast:
        {
            // For simplicity, we will handle all bit-cast operations
            // by first casting the "from" type to an intermediate
            // integer type to hold the bits, and then convert *the*
            // type over to the desired "to" type.
            //
            // A fundamental invariant that must be guaranteed
            // by earlier steps is that a bit-cast instruction
            // is only generated when the "from" and "to" types
            // have the same size, and (in the case where they
            // are vectors) number of elements.
            //
            // In textual order, the conversion to the "to" type
            // comes first.
            //
            auto toType = extractBaseType(inst->getDataType());
            switch (toType)
            {
            default:
                diagnoseUnhandledInst(inst);
                break;

            case BaseType::Int8:
            case BaseType::Int16:
            case BaseType::Int:
            case BaseType::Int64:
            case BaseType::IntPtr:
            case BaseType::UInt8:
            case BaseType::UInt16:
            case BaseType::UInt:
            case BaseType::UInt64:
            case BaseType::UIntPtr:
            case BaseType::Bool:
            case BaseType::Int8x4Packed:
            case BaseType::UInt8x4Packed:
                // Because the intermediate type will always
                // be an integer type, we can convert to
                // another integer type of the same size
                // via a cast.
                m_writer->emit("(");
                emitType(inst->getDataType());
                m_writer->emit(")");
                break;
            case BaseType::Half:
                m_writer->emit("asfloat16");
                break;
            case BaseType::Float:
                // Note: at present HLSL only supports
                // reinterpreting integer bits as a `float`.
                //
                // There is no current function (it seems)
                // for bit-casting an `int16_t` to a `half`.
                m_writer->emit("asfloat");
                break;
            case BaseType::Double:
                ensurePrelude(kHLSLBuiltInPrelude64BitCast);
                m_writer->emit("_slang_asdouble");
                break;
            }
            m_writer->emit("(");
            int closeCount = 1;

            auto fromType = extractBaseType(inst->getOperand(0)->getDataType());
            switch (fromType)
            {
            default:
                diagnoseUnhandledInst(inst);
                break;

            case BaseType::Int64:
            case BaseType::UInt64:
            case BaseType::UInt:
            case BaseType::Int:
            case BaseType::Bool:
            case BaseType::Int8x4Packed:
            case BaseType::UInt8x4Packed:
                break;
            case BaseType::UInt16:
            case BaseType::Int16:
                break;
            case BaseType::Float:
                m_writer->emit("asuint(");
                closeCount++;
                break;

            case BaseType::Half:
                m_writer->emit("asuint16(");
                closeCount++;
                break;
            case BaseType::Double:
                ensurePrelude(kHLSLBuiltInPrelude64BitCast);
                m_writer->emit("_slang_asuint64(");
                closeCount++;
                break;
            }

            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));

            while (closeCount--)
                m_writer->emit(")");
            return true;
        }
    case kIROp_StringLit:
        {
            const auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Slang);

            StringBuilder buf;
            const UnownedStringSlice slice = as<IRStringLit>(inst)->getStringSlice();
            StringEscapeUtil::appendQuoted(handler, slice, buf);

            m_writer->emit(buf);

            return true;
        }
    case kIROp_LoadSamplerDescriptorFromHeap:
        {
            emitType(inst->getDataType());
            m_writer->emit("(");
            m_writer->emit("SamplerDescriptorHeap[");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit("])");
            return true;
        }
    case kIROp_LoadResourceDescriptorFromHeap:
        {
            emitType(inst->getDataType());
            m_writer->emit("(");
            m_writer->emit("ResourceDescriptorHeap[");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit("])");
            return true;
        }
    case kIROp_ByteAddressBufferLoad:
        {
            // HLSL byte-address buffers have two kinds of `Load` operations.
            //
            // First we have the `Load`, `Load2`, `Load3`, and `Load4` operations,
            // which are *not* generic/templated, and always return a scalar
            // or vector of `uint`. These are available on all profiles that
            // support byte-address buffers.
            //
            // Second we have the `Load<T>` generic, which itself comes in
            // two flavors. The basic version can only handle the case where `T`
            // is a scalar or vector, but can handle more types than the
            // non-generic operations. The more complex version can handle
            // aggregate tyeps as well, but we don't need to worry about
            // that because we will have legalized such operations out
            // already.
            //
            // Our task here is thus to pick between `Load`/`Load2`/`Load3`/`Load4`
            // or `Load<T>`, always preferring the functions that are more
            // universally available.
            //
            // We will thus inspect the type that is being loaded,
            // and determine if it is a scalar or vector, and then
            // if the elemnet type of that scalar/vector is `uint`.
            //
            auto elementType = inst->getDataType();
            IRIntegerValue elementCount = 1;
            if (auto vecType = as<IRVectorType>(elementType))
            {
                if (auto elementCountInst = as<IRIntLit>(vecType->getElementCount()))
                {
                    elementType = vecType->getElementType();
                    elementCount = elementCountInst->getValue();
                }
            }

            if (elementType->getOp() == kIROp_UIntType)
            {
                // If we are in the case that can use `Load`/`Load2`/`Load3`/`Load4`,
                // then we will always prefer to use it.
                //
                auto outerPrec = inOuterPrec;
                auto prec = getInfo(EmitOp::Postfix);
                bool needClose = maybeEmitParens(outerPrec, prec);

                emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
                m_writer->emit(".Load");
                if (elementCount != 1)
                {
                    m_writer->emit(elementCount);
                }
                m_writer->emit("(");
                emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
                m_writer->emit(")");

                maybeCloseParens(needClose);
                return true;
            }

            // Otherwise we fall back to the base case, which
            // is already handled by the base `CLikeSourceEmitter`
            return false;
        }
    case kIROp_ByteAddressBufferStore:
        {
            // Similar to the case for a load, we want to specialize
            // the generated code for the case where we store a `uint`
            // or a vector of `uint`.
            //
            auto elementType = inst->getDataType();
            IRIntegerValue elementCount = 1;
            if (auto vecType = as<IRVectorType>(elementType))
            {
                if (auto elementCountInst = as<IRIntLit>(vecType->getElementCount()))
                {
                    elementType = vecType->getElementType();
                    elementCount = elementCountInst->getValue();
                }
            }
            if (elementType->getOp() == kIROp_UIntType)
            {
                auto outerPrec = inOuterPrec;
                auto prec = getInfo(EmitOp::Postfix);
                bool needClose = maybeEmitParens(outerPrec, prec);

                emitOperand(inst->getOperand(0), leftSide(outerPrec, prec));
                m_writer->emit(".Store");
                if (elementCount != 1)
                {
                    m_writer->emit(elementCount);
                }
                m_writer->emit("(");
                emitOperand(inst->getOperand(1), getInfo(EmitOp::General));
                m_writer->emit(", ");
                emitOperand(
                    inst->getOperand(inst->getOperandCount() - 1),
                    getInfo(EmitOp::General));
                m_writer->emit(")");

                maybeCloseParens(needClose);
                return true;
            }

            // Otherwise we fall back to the base case, which
            // is already handled by the base `CLikeSourceEmitter`
            return false;
        }
        break;
    case kIROp_NonUniformResourceIndex:
        {
            // Need to emit as a Function call for HLSL
            m_writer->emit("NonUniformResourceIndex");
            m_writer->emit("(");
            emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
            m_writer->emit(")");

            // Handled
            return true;
        }
        break;
    default:
        break;
    }
    // Not handled
    return false;
}

void HLSLSourceEmitter::emitVectorTypeNameImpl(IRType* elementType, IRIntegerValue elementCount)
{
    // In some cases we *need* to use the built-in syntax sugar for vector types,
    // so we will try to emit those whenever possible.
    //
    if (elementCount >= 1 && elementCount <= 4)
    {
        switch (elementType->getOp())
        {
        case kIROp_FloatType:
        case kIROp_IntType:
        case kIROp_UIntType:
            // TODO: There are more types that need to be covered here
            emitType(elementType);
            m_writer->emit(elementCount);
            return;

        default:
            break;
        }
    }

    // As a fallback, we will use the `vector<...>` type constructor,
    // although we should not expect to run into types that don't
    // have a sugared form.
    //
    m_writer->emit("vector<");
    emitType(elementType);
    m_writer->emit(",");
    m_writer->emit(elementCount);
    m_writer->emit(">");
}

void HLSLSourceEmitter::emitLoopControlDecorationImpl(IRLoopControlDecoration* decl)
{
    switch (decl->getMode())
    {
    case kIRLoopControl_Unroll:
        m_writer->emit("[unroll]\n");
        break;
    case kIRLoopControl_Loop:
        m_writer->emit("[loop]\n");
        break;
    default:
        break;
    }
}

static bool _canEmitExport(const Profile& profile)
{
    const auto family = profile.getFamily();
    const auto version = profile.getVersion();
    // Is ita late enough version of shader model to output with 'export'
    return (family == ProfileFamily::DX && version >= ProfileVersion::DX_6_1);
}

/* virtual */ void HLSLSourceEmitter::emitFuncDecorationsImpl(IRFunc* func)
{
    // Specially handle export, as we don't want to emit it multiple times
    if (getTargetProgram()->getOptionSet().getBoolOption(
            CompilerOptionName::GenerateWholeProgram) &&
        _canEmitExport(m_effectiveProfile))
    {
        for (auto decoration : func->getDecorations())
        {
            const auto op = decoration->getOp();
            if (op == kIROp_PublicDecoration || op == kIROp_HLSLExportDecoration)
            {
                m_writer->emit("export\n");
                break;
            }
        }
    }

    // Use the default for others
    Super::emitFuncDecorationsImpl(func);
}

void HLSLSourceEmitter::emitIfDecorationsImpl(IRIfElse* ifInst)
{
    if (ifInst->findDecorationImpl(kIROp_BranchDecoration))
    {
        m_writer->emit("[branch]\n");
    }
    else if (ifInst->findDecorationImpl(kIROp_FlattenDecoration))
    {
        m_writer->emit("[flatten]\n");
    }
}

void HLSLSourceEmitter::emitSwitchDecorationsImpl(IRSwitch* switchInst)
{
    if (switchInst->findDecorationImpl(kIROp_BranchDecoration))
    {
        m_writer->emit("[branch]\n");
    }
}

void HLSLSourceEmitter::emitFuncDecorationImpl(IRDecoration* decoration)
{
    switch (decoration->getOp())
    {
    case kIROp_NoInlineDecoration:
        m_writer->emit("[noinline]\n");
        break;

    default:
        break;
    }
}


void HLSLSourceEmitter::emitSimpleValueImpl(IRInst* inst)
{
    switch (inst->getOp())
    {
    case kIROp_FloatLit:
        {
            IRConstant* constantInst = static_cast<IRConstant*>(inst);
            IRConstant::FloatKind kind = constantInst->getFloatKind();
            switch (kind)
            {
            case IRConstant::FloatKind::Nan:
                {
                    m_writer->emit("(0.0 / 0.0)");
                    return;
                }
            case IRConstant::FloatKind::PositiveInfinity:
                {
                    m_writer->emit("(1.0 / 0.0)");
                    return;
                }
            case IRConstant::FloatKind::NegativeInfinity:
                {
                    m_writer->emit("(-1.0 / 0.0)");
                    return;
                }
            default:
                break;
            }
            break;
        }

    default:
        break;
    }

    Super::emitSimpleValueImpl(inst);
}

void HLSLSourceEmitter::emitSimpleTypeAndDeclaratorImpl(IRType* type, DeclaratorInfo* declarator)
{
    if (declarator)
    {
        // HLSL only allow matrix layout modifier when declaring a variable or struct field.
        if (auto matType = as<IRMatrixType>(type))
        {
            auto matrixLayout = getIntVal(matType->getLayout());
            if (getTargetProgram()->getOptionSet().getMatrixLayoutMode() !=
                (MatrixLayoutMode)matrixLayout)
            {
                switch (matrixLayout)
                {
                case SLANG_MATRIX_LAYOUT_COLUMN_MAJOR:
                    m_writer->emit("column_major ");
                    break;
                case SLANG_MATRIX_LAYOUT_ROW_MAJOR:
                    m_writer->emit("row_major ");
                    break;
                default:
                    break;
                }
            }
        }
    }
    Super::emitSimpleTypeAndDeclaratorImpl(type, declarator);
}

void HLSLSourceEmitter::emitSimpleTypeImpl(IRType* type)
{
    switch (type->getOp())
    {
    case kIROp_VoidType:
    case kIROp_BoolType:
    case kIROp_Int8Type:
    case kIROp_IntType:
    case kIROp_Int64Type:
    case kIROp_UInt8Type:
    case kIROp_UIntType:
    case kIROp_UInt64Type:
    case kIROp_FloatType:
    case kIROp_DoubleType:
    case kIROp_Int16Type:
    case kIROp_UInt16Type:
    case kIROp_HalfType:
    case kIROp_Int8x4PackedType:
    case kIROp_UInt8x4PackedType:
        {
            m_writer->emit(getDefaultBuiltinTypeName(type->getOp()));
            return;
        }
#if SLANG_PTR_IS_64
    case kIROp_IntPtrType:
        m_writer->emit("int64_t");
        return;
    case kIROp_UIntPtrType:
        m_writer->emit("uint64_t");
        return;
#else
    case kIROp_IntPtrType:
        m_writer->emit("int");
        return;
    case kIROp_UIntPtrType:
        m_writer->emit("uint");
        return;
#endif
    case kIROp_StructType:
        m_writer->emit(getName(type));
        return;

    case kIROp_VectorType:
        {
            auto vecType = (IRVectorType*)type;
            emitVectorTypeNameImpl(
                vecType->getElementType(),
                getIntVal(vecType->getElementCount()));
            return;
        }
    case kIROp_MatrixType:
        {
            auto matType = (IRMatrixType*)type;
            bool canUseSugar = true;
            switch (matType->getElementType()->getOp())
            {
            case kIROp_IntType:
            case kIROp_UIntType:
            case kIROp_FloatType:
                canUseSugar = true;
                break;
            default:
                canUseSugar = false;
                break;
            }
            if (!as<IRIntLit>(matType->getRowCount()) || !as<IRIntLit>(matType->getColumnCount()))
                canUseSugar = false;
            if (canUseSugar)
            {
                emitType(matType->getElementType());
                m_writer->emitInt64(getIntVal(matType->getRowCount()));
                m_writer->emit("x");
                m_writer->emitInt64(getIntVal(matType->getColumnCount()));
            }
            else
            {
                m_writer->emit("matrix<");
                emitType(matType->getElementType());
                m_writer->emit(",");
                emitVal(matType->getRowCount(), getInfo(EmitOp::General));
                m_writer->emit(",");
                emitVal(matType->getColumnCount(), getInfo(EmitOp::General));
                m_writer->emit("> ");
            }
            return;
        }
    case kIROp_SamplerStateType:
    case kIROp_SamplerComparisonStateType:
        {
            auto samplerStateType = cast<IRSamplerStateTypeBase>(type);

            switch (samplerStateType->getOp())
            {
            case kIROp_SamplerStateType:
                m_writer->emit("SamplerState");
                break;
            case kIROp_SamplerComparisonStateType:
                m_writer->emit("SamplerComparisonState");
                break;
            default:
                SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled sampler state flavor");
                break;
            }
            return;
        }
    case kIROp_NativeStringType:
    case kIROp_StringType:
        {
            m_writer->emit("int");
            return;
        }
    case kIROp_RayQueryType:
        {
            m_writer->emit("RayQuery<");
            emitSimpleValue(type->getOperand(0));
            m_writer->emit(" >");
            return;
        }
    case kIROp_HitObjectType:
        {
            m_writer->emit("NvHitObject");
            return;
        }
    case kIROp_TextureFootprintType:
        {
            m_writer->emit("uint4");
            return;
        }
    case kIROp_AtomicType:
        {
            emitSimpleTypeImpl(cast<IRAtomicType>(type)->getElementType());
            return;
        }
    case kIROp_ConstRefType:
        {
            emitSimpleTypeImpl(as<IRConstRefType>(type)->getValueType());
            return;
        }
    default:
        break;
    }

    // TODO: Ideally the following should be data-driven,
    // based on meta-data attached to the definitions of
    // each of these IR opcodes.
    if (auto texType = as<IRTextureType>(type))
    {
        _emitHLSLTextureType(texType);
        return;
    }
    else if (auto imageType = as<IRGLSLImageType>(type))
    {
        _emitHLSLTextureType(imageType);
        return;
    }
    else if (auto subpassType = as<IRSubpassInputType>(type))
    {
        _emitHLSLSubpassInputType(subpassType);
        return;
    }
    else if (auto cbufferType = as<IRConstantBufferType>(type))
    {
        m_writer->emit("ConstantBuffer<");
        emitType(cbufferType->getElementType());
        m_writer->emit(" >");
        return;
    }
    else if (auto structuredBufferType = as<IRHLSLStructuredBufferTypeBase>(type))
    {
        switch (structuredBufferType->getOp())
        {
        case kIROp_HLSLStructuredBufferType:
            m_writer->emit("StructuredBuffer");
            break;
        case kIROp_HLSLRWStructuredBufferType:
            m_writer->emit("RWStructuredBuffer");
            break;
        case kIROp_HLSLRasterizerOrderedStructuredBufferType:
            m_writer->emit("RasterizerOrderedStructuredBuffer");
            break;
        case kIROp_HLSLAppendStructuredBufferType:
            m_writer->emit("AppendStructuredBuffer");
            break;
        case kIROp_HLSLConsumeStructuredBufferType:
            m_writer->emit("ConsumeStructuredBuffer");
            break;

        default:
            SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled structured buffer type");
            break;
        }

        m_writer->emit("<");
        emitType(structuredBufferType->getElementType());
        m_writer->emit(" >");

        return;
    }
    else if (const auto untypedBufferType = as<IRUntypedBufferResourceType>(type))
    {
        switch (type->getOp())
        {
        case kIROp_HLSLByteAddressBufferType:
            m_writer->emit("ByteAddressBuffer");
            break;
        case kIROp_HLSLRWByteAddressBufferType:
            m_writer->emit("RWByteAddressBuffer");
            break;
        case kIROp_HLSLRasterizerOrderedByteAddressBufferType:
            m_writer->emit("RasterizerOrderedByteAddressBuffer");
            break;
        case kIROp_RaytracingAccelerationStructureType:
            m_writer->emit("RaytracingAccelerationStructure");
            break;
        default:
            SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled buffer type");
            break;
        }

        return;
    }
    else if (auto specializedType = as<IRSpecialize>(type))
    {
        // If a `specialize` instruction made it this far, then
        // it represents an intrinsic generic type.
        //
        emitSimpleType((IRType*)getSpecializedValue(specializedType));
        m_writer->emit("<");
        UInt argCount = specializedType->getArgCount();
        for (UInt ii = 0; ii < argCount; ++ii)
        {
            if (ii != 0)
                m_writer->emit(", ");
            emitVal(specializedType->getArg(ii), getInfo(EmitOp::General));
        }
        m_writer->emit(" >");
        return;
    }

    // HACK: As a fallback for HLSL targets, assume that the name of the
    // instruction being used is the same as the name of the HLSL type.
    {
        auto opInfo = getIROpInfo(type->getOp());
        m_writer->emit(opInfo.name);
        UInt operandCount = type->getOperandCount();
        if (operandCount)
        {
            m_writer->emit("<");
            for (UInt ii = 0; ii < operandCount; ++ii)
            {
                if (ii != 0)
                    m_writer->emit(", ");
                emitVal(type->getOperand(ii), getInfo(EmitOp::General));
            }
            m_writer->emit(" >");
        }
    }
}

void HLSLSourceEmitter::emitRateQualifiersAndAddressSpaceImpl(
    IRRate* rate,
    [[maybe_unused]] AddressSpace addressSpace)
{
    if (as<IRGroupSharedRate>(rate))
    {
        m_writer->emit("groupshared ");
    }
}

void HLSLSourceEmitter::emitSemanticsImpl(IRInst* inst, bool allowOffsets)
{
    if (auto semanticDecoration = inst->findDecoration<IRSemanticDecoration>())
    {
        m_writer->emit(" : ");
        m_writer->emit(semanticDecoration->getSemanticName());
        return;
    }
    else if (auto packOffsetDecoration = inst->findDecoration<IRPackOffsetDecoration>())
    {
        if (allowOffsets)
        {
            m_writer->emit(" : packoffset(c");
            m_writer->emit(packOffsetDecoration->getRegisterOffset()->getValue());
            if (packOffsetDecoration->getComponentOffset())
            {
                switch (packOffsetDecoration->getComponentOffset()->getValue())
                {
                case 0:
                    break;
                case 1:
                    m_writer->emit(".y");
                    break;
                case 2:
                    m_writer->emit(".z");
                    break;
                case 3:
                    m_writer->emit(".w");
                    break;
                }
            }
            m_writer->emit(")");
            return;
        }
    }

    if (auto readAccessSemantic = inst->findDecoration<IRStageReadAccessDecoration>())
        _emitStageAccessSemantic(readAccessSemantic, "read");
    if (auto writeAccessSemantic = inst->findDecoration<IRStageWriteAccessDecoration>())
        _emitStageAccessSemantic(writeAccessSemantic, "write");

    if (auto layoutDecoration = inst->findDecoration<IRLayoutDecoration>())
    {
        auto layout = layoutDecoration->getLayout();
        if (auto varLayout = as<IRVarLayout>(layout))
        {
            emitSemanticsUsingVarLayout(varLayout);
        }
        else if (auto entryPointLayout = as<IREntryPointLayout>(layout))
        {
            if (auto resultLayout = entryPointLayout->getResultLayout())
            {
                emitSemanticsUsingVarLayout(resultLayout);
            }
        }
    }
}

void HLSLSourceEmitter::_emitStageAccessSemantic(
    IRStageAccessDecoration* decoration,
    const char* name)
{
    Int stageCount = decoration->getStageCount();
    if (stageCount == 0)
        return;

    m_writer->emit(" : ");
    m_writer->emit(name);
    m_writer->emit("(");
    for (Int i = 0; i < stageCount; ++i)
    {
        if (i != 0)
            m_writer->emit(", ");
        m_writer->emit(decoration->getStageName(i));
    }
    m_writer->emit(")");
}

void HLSLSourceEmitter::emitPostKeywordTypeAttributesImpl(IRInst* inst)
{
    if (const auto payloadDecoration = inst->findDecoration<IRPayloadDecoration>())
    {
        m_writer->emit("[payload] ");
    }
}

void HLSLSourceEmitter::_emitPrefixTypeAttr(IRAttr* attr)
{
    switch (attr->getOp())
    {
    default:
        Super::_emitPrefixTypeAttr(attr);
        break;

    case kIROp_UNormAttr:
        m_writer->emit("unorm ");
        break;
    case kIROp_SNormAttr:
        m_writer->emit("snorm ");
        break;
    }
}

void HLSLSourceEmitter::emitSimpleFuncParamImpl(IRParam* param)
{
    // A mesh shader input payload has it's own weird stuff going on, handled
    // in emitMeshShaderModifiers, skip this bit which will introduce an
    // invalid "groupshared" keyword.
    if (!param->findDecoration<IRHLSLMeshPayloadDecoration>())
        emitRateQualifiersAndAddressSpace(param);

    if (auto decor = param->findDecoration<IRGeometryInputPrimitiveTypeDecoration>())
    {
        switch (decor->getOp())
        {
        case kIROp_TriangleInputPrimitiveTypeDecoration:
            m_writer->emit("triangle ");
            break;
        case kIROp_PointInputPrimitiveTypeDecoration:
            m_writer->emit("point ");
            break;
        case kIROp_LineInputPrimitiveTypeDecoration:
            m_writer->emit("line ");
            break;
        case kIROp_LineAdjInputPrimitiveTypeDecoration:
            m_writer->emit("lineadj ");
            break;
        case kIROp_TriangleAdjInputPrimitiveTypeDecoration:
            m_writer->emit("triangleadj ");
            break;
        default:
            SLANG_ASSERT(!"Unknown primitive type");
            break;
        }
    }

    Super::emitSimpleFuncParamImpl(param);
}

static UnownedStringSlice _getInterpolationModifierText(IRInterpolationMode mode)
{
    switch (mode)
    {
    case IRInterpolationMode::PerVertex:
    case IRInterpolationMode::NoInterpolation:
        return UnownedStringSlice::fromLiteral("nointerpolation");
    case IRInterpolationMode::NoPerspective:
        return UnownedStringSlice::fromLiteral("noperspective");
    case IRInterpolationMode::Linear:
        return UnownedStringSlice::fromLiteral("linear");
    case IRInterpolationMode::Sample:
        return UnownedStringSlice::fromLiteral("sample");
    case IRInterpolationMode::Centroid:
        return UnownedStringSlice::fromLiteral("centroid");
    default:
        return UnownedStringSlice();
    }
}

void HLSLSourceEmitter::emitInterpolationModifiersImpl(
    IRInst* varInst,
    IRType* valueType,
    IRVarLayout* layout)
{
    SLANG_UNUSED(layout);
    SLANG_UNUSED(valueType);

    for (auto dd : varInst->getDecorations())
    {
        if (dd->getOp() != kIROp_InterpolationModeDecoration)
            continue;

        auto decoration = (IRInterpolationModeDecoration*)dd;

        UnownedStringSlice modeText = _getInterpolationModifierText(decoration->getMode());
        if (modeText.getLength() > 0)
        {
            m_writer->emit(modeText);
            m_writer->emitChar(' ');
        }
    }
}

void HLSLSourceEmitter::emitPackOffsetModifier(
    IRInst* varInst,
    IRType* valueType,
    IRPackOffsetDecoration* layout)
{
    SLANG_UNUSED(varInst);
    SLANG_UNUSED(valueType);
    SLANG_UNUSED(layout);
    // We emit packoffset as a semantic in `emitSemantic`, so nothing to do here.
}

void HLSLSourceEmitter::emitMeshShaderModifiersImpl(IRInst* varInst)
{
    if (auto modifier = varInst->findDecoration<IRMeshOutputDecoration>())
    {
        // DXC requires that mesh payload parameters have "out" specified
        const char* s = as<IRVerticesDecoration>(modifier)     ? "out vertices "
                        : as<IRIndicesDecoration>(modifier)    ? "out indices "
                        : as<IRPrimitivesDecoration>(modifier) ? "out primitives "
                                                               : nullptr;
        SLANG_ASSERT(s && "Unhandled type of mesh output decoration");
        m_writer->emit(s);
    }
    if (varInst->findDecoration<IRHLSLMeshPayloadDecoration>())
    {
        // DXC requires that mesh payload parameters have "in" specified
        m_writer->emit("in payload ");
    }
}

void HLSLSourceEmitter::emitVarDecorationsImpl(IRInst* varDecl)
{
    for (auto decoration : varDecl->getDecorations())
    {
        if (auto collection = as<IRMemoryQualifierSetDecoration>(decoration))
        {
            auto flags = collection->getMemoryQualifierBit();
            if (flags & MemoryQualifierSetModifier::Flags::kCoherent)
                m_writer->emit("globallycoherent\n");
            continue;
        }
    }
}

void HLSLSourceEmitter::handleRequiredCapabilitiesImpl(IRInst* inst)
{
    if (inst->findDecoration<IRRequiresNVAPIDecoration>())
    {
        m_extensionTracker->m_requiresNVAPI = true;
    }
}

void HLSLSourceEmitter::emitFrontMatterImpl(TargetRequest*)
{
    if (m_extensionTracker->m_requiresNVAPI)
    {
        // If the generated code includes implicit NVAPI use,
        // then we need to ensure that NVAPI support is included
        // via the prelude.
        //
        m_writer->emit("#define SLANG_HLSL_ENABLE_NVAPI 1\n");

        // TODO(JS): For now when using NVAPI for generated code we do not want to
        // use HLSL2021 features, that are typically used for Shader Execution Reordering
        // so we turn on the 'macro' based interface by default
        m_writer->emit(toSlice("#define NV_HITOBJECT_USE_MACRO_API 1\n"));

        // In addition, if the user has informed the Slang compiler of
        // the register/space that it wants to use for NVAPI, then we
        // need to pass along that information to prelude in the
        // generated code, so that it can be picked up by the NVAPI
        // header at the point where it gets included.
        //
        // Note: If the user doesn't inform the Slang compiler where
        // it wants the NVAPI parameter to be bound, then a downstream
        // compiler error is going to occur. We could try to produce
        // our own error message here, but our error is unlikely to
        // be significantly better, and also it is *technically*
        // possible for the user to use Slang to generate HLSL,
        // and then go on to compile it manually via fxc/dxc, where
        // they could pass in these `#define`s using command-line
        // or API options.
        //
        if (auto decor = m_irModule->getModuleInst()->findDecoration<IRNVAPISlotDecoration>())
        {
            m_writer->emit("#define NV_SHADER_EXTN_SLOT ");
            m_writer->emit(decor->getRegisterName());
            m_writer->emit("\n");

            // Note: We only emit a preprocessor directive if the space
            // is not `space0`, because we want to ensure that the output
            // code can compile with fxc when possible (and fxc has no
            // understanding of `space`s).
            //
            auto spaceName = decor->getSpaceName();
            if (spaceName != "space0")
            {
                m_writer->emit("#define NV_SHADER_EXTN_REGISTER_SPACE ");
                m_writer->emit(spaceName);
                m_writer->emit("\n");
            }
        }
    }

    // Emit any layout declarations

    switch (getTargetProgram()->getOptionSet().getMatrixLayoutMode())
    {
    case kMatrixLayoutMode_RowMajor:
    default:
        m_writer->emit("#pragma pack_matrix(row_major)\n");
        break;
    case kMatrixLayoutMode_ColumnMajor:
        m_writer->emit("#pragma pack_matrix(column_major)\n");
        break;
    }
}

void HLSLSourceEmitter::emitGlobalInstImpl(IRInst* inst)
{
    if (const auto nvapiDecor = inst->findDecoration<IRNVAPIMagicDecoration>())
    {
        // When emitting one of the "magic" NVAPI declarations,
        // we will wrap it in a preprocessor conditional that
        // skips it if the NVAPI header is already being included
        // via the prelude. In that case, the definitions from
        // the prelude-included NVAPI will be used instead of
        // those that were processed by the Slang front-end.
        //
        // TODO: In theory we could drop the downstream preprocessor
        // conditional here, and either emit or not emit the
        // instruction based on whether the code needs NVAPI (which
        // is when `SLANG_HLSL_ENABLE_NVAPI` would be set).
        // Such a change would require that we replace the current
        // approach of tracking extension use during emit with an
        // approach that detects requirements as a pure pre-pass.
        //
        // Note: We skip `IRStructKey` instructions here because
        // the fields of the `NvShaderExtnStruct` are also decorated,
        // but field keys don't produce anything in the output, so
        // we'd have conditionals that are wrapping empty lines.
        //
        if (!as<IRStructKey>(inst))
        {