1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
|
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "common/LLVMWarningsPush.hpp"
#include "llvmWrapper/IR/DerivedTypes.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include "common/LLVMWarningsPop.hpp"
#include "common/LLVMUtils.h"
#include "LLVMWarningsPush.hpp"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Function.h"
#include "LLVMWarningsPop.hpp"
#include "Compiler/CISACodeGen/GenCodeGenModule.h"
#include "Compiler/CISACodeGen/PushAnalysis.hpp"
#include "Compiler/CISACodeGen/ShaderCodeGen.hpp"
#include "Compiler/CISACodeGen/CISACodeGen.h"
#include "Compiler/CISACodeGen/WIAnalysis.hpp"
#include "common/igc_regkeys.hpp"
#include "Compiler/IGCPassSupport.h"
#include "LLVM3DBuilder/MetadataBuilder.h"
#include "Compiler/MetaDataUtilsWrapper.h"
#include "common/debug/Debug.hpp"
#include <list>
#include "Probe/Assertion.h"
/***********************************************************************************
This File contains the logic to decide for each inputs and constant if the data
should be pushed or pull.
In case the data is pushed we remove the load instruction replace the value by
a function argument so that the liveness calculated is correct
************************************************************************************/
using namespace llvm;
using namespace IGC::IGCMD;
namespace IGC
{
#define PASS_FLAG "igc-push-value-info"
#define PASS_DESCRIPTION "hold push value information"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS true
//undef macros to avoid redefinition warnings
#undef PASS_FLAG
#undef PASS_DESCRIPTION
#undef PASS_ANALYSIS
#define PASS_FLAG "igc-push-analysis"
#define PASS_DESCRIPTION "promotes the values to be arguments"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS false
IGC_INITIALIZE_PASS_BEGIN(PushAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
IGC_INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
IGC_INITIALIZE_PASS_DEPENDENCY(PullConstantHeuristics)
IGC_INITIALIZE_PASS_END(PushAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
PushAnalysis::PushAnalysis()
: ModulePass(ID)
, m_PDT(nullptr)
, m_cbToLoad((uint)-1)
, m_maxStatelessOffset(0)
{
initializePushAnalysisPass(*PassRegistry::getPassRegistry());
}
const uint32_t PushAnalysis::MaxConstantBufferIndexSize = 256;
/// The maximum number of input attributes that will be pushed as part of the payload.
/// One attribute is 4 dwords, so e.g. 16 means we allocate max 64 GRFs for input payload.
const uint32_t PushAnalysis::MaxNumOfPushedInputs = 24;
/// The size occupied by the tessellation header in dwords
const uint32_t PushAnalysis::TessFactorsURBHeader = 8;
/// Maximum number of attributes pushed
const uint32_t PushAnalysis::m_pMaxNumOfVSPushedInputs = 24;
const uint32_t PushAnalysis::m_pMaxNumOfHSPushedInputs = 24;
const uint32_t PushAnalysis::m_pMaxNumOfDSPushedInputs = 24;
const uint32_t PushAnalysis::m_pMaxNumOfGSPushedInputs = 24;
template < typename T > std::string to_string(const T& n)
{
std::ostringstream stm;
stm << n;
return stm.str();
}
Value* PushAnalysis::addArgumentAndMetadata(llvm::Type* pType, std::string argName, IGC::WIAnalysis::WIDependancy dependency)
{
auto pArgInfo = m_pFuncUpgrade.AddArgument(argName, pType);
ModuleMetaData* modMD = nullptr;
modMD = getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData();
IGC::ArgDependencyInfoMD argDepInfoMD;
argDepInfoMD.argDependency = dependency;
modMD->pushInfo.pushAnalysisWIInfos.push_back(argDepInfoMD);
//Add it to arglist and increment Argument Index
m_argList.push_back(pArgInfo);
m_argIndex++;
m_funcTypeChanged = true;
return pArgInfo;
}
bool PushAnalysis::IsPushableBindlessLoad(
Instruction* inst,
int& grfOffset,
unsigned int& cbIdx,
unsigned int& offset)
{
LdRawIntrinsic* ldRaw = dyn_cast<LdRawIntrinsic>(inst);
if (!ldRaw ||
BINDLESS_CONSTANT_BUFFER != DecodeBufferType(
ldRaw->getResourceValue()->getType()->getPointerAddressSpace()))
{
return false;
}
std::function<bool(Value*)> isPushable;
isPushable = [this, &grfOffset, &cbIdx, &isPushable](Value* v)->bool
{
// Matches the following patterns:
// Pattern 1:
// %6 = add i32 %runtime_value_0, 4096
// %7 = inttoptr i32 %6 to i8 addrspace(1507328)*
// %8 = call <8 x float> @llvm.genx.GenISA.ldrawvector.indexed.v8f32.p1507328i8(i8 addrspace(1507328)* %7, i32 0, i32 4, i1 false)
// Pattern 2:
// %8 = call <8 x float> @llvm.genx.GenISA.ldrawvector.indexed.v8f32.p1507328i8(i8 addrspace(1507328)* %runtime_value_0, i32 0, i32 4, i1 false)
if (m_bindlessPushArgs.find(v) != m_bindlessPushArgs.end())
{
grfOffset = int_cast<int>(m_bindlessPushArgs.find(v)->second);
return true;
}
else if (IntToPtrInst* ptrToInt = dyn_cast<IntToPtrInst>(v))
{
return isPushable(ptrToInt->getOperand(0));
}
else if (Instruction* instr = dyn_cast<Instruction>(v))
{
if (instr->getOpcode() == Instruction::Add &&
isa<ConstantInt>(instr->getOperand(1)) &&
isPushable(instr->getOperand(0)))
{
ConstantInt* src1 = cast<ConstantInt>(instr->getOperand(1));
cbIdx += int_cast<unsigned int>(src1->getZExtValue()) >> m_context->platform.getBSOLocInExtDescriptor();
return true;
}
}
return false;
};
if (isPushable(ldRaw->getResourceValue()))
{
Value* offsetVal = ldRaw->getOffsetValue();
if (ConstantInt * offsetConstVal = dyn_cast<ConstantInt>(offsetVal))
{
offset = int_cast<unsigned int>(offsetConstVal->getZExtValue());
return true;
}
if (m_context->m_DriverInfo.SupportsDynamicUniformBuffers() &&
IGC_IS_FLAG_DISABLED(DisableSimplePushWithDynamicUniformBuffers))
{
unsigned int relativeOffsetInBytes = 0; // offset in bytes starting from dynamic buffer offset
if (GetConstantOffsetForDynamicUniformBuffer(offsetVal, relativeOffsetInBytes))
{
offset = relativeOffsetInBytes;
return true;
}
}
}
return false;
}
bool PushAnalysis::IsStatelessCBLoad(
llvm::Instruction* inst,
int& pushableAddressGrfOffset,
int& pushableOffsetGrfOffset,
unsigned int& pushableOffset)
{
if (!llvm::isa<llvm::LoadInst>(inst))
return false;
m_PDT = &getAnalysis<PostDominatorTreeWrapperPass>(*m_pFunction).getPostDomTree();
m_DT = &getAnalysis<DominatorTreeWrapperPass>(*m_pFunction).getDomTree();
m_entryBB = &m_pFunction->getEntryBlock();
// %15 = load <3 x float> addrspace(2)* %14, align 16
llvm::LoadInst* pLoad = llvm::cast<llvm::LoadInst>(inst);
uint address_space = pLoad->getPointerAddressSpace();
if (address_space != ADDRESS_SPACE_CONSTANT)
return false;
Value* pAddress = pLoad->getOperand(pLoad->getPointerOperandIndex());
// skip casts
if (isa<IntToPtrInst>(pAddress) || isa<PtrToIntInst>(pAddress) || isa<BitCastInst>(pAddress))
{
pAddress = cast<Instruction>(pAddress)->getOperand(0);
}
uint64_t offset = 0;
SmallVector<Value*, 4> potentialPushableAddresses;
std::function<void(Value*)> GetPotentialPushableAddresses;
GetPotentialPushableAddresses = [&potentialPushableAddresses, &offset, &GetPotentialPushableAddresses](
Value* pAddress)->void
{
BinaryOperator* pAdd = dyn_cast<BinaryOperator>(pAddress);
if (pAdd && pAdd->getOpcode() == llvm::Instruction::Add)
{
GetPotentialPushableAddresses(pAdd->getOperand(0));
GetPotentialPushableAddresses(pAdd->getOperand(1));
}
else if (isa<ZExtInst>(pAddress))
{
GetPotentialPushableAddresses(
cast<ZExtInst>(pAddress)->getOperand(0));
}
else if (isa<ConstantInt>(pAddress))
{
ConstantInt* pConst = cast<ConstantInt>(pAddress);
offset += pConst->getZExtValue();
}
else
{
potentialPushableAddresses.push_back(pAddress);
}
};
if (GenIntrinsicInst * genIntr = dyn_cast<GenIntrinsicInst>(pAddress))
{
/*
Examples of patterns matched on platforms without 64bit type support:
1. Pushable 64bit address + immediate offset case:
%29 = call { i32, i32 } @llvm.genx.GenISA.ptr.to.pair.p2v3f32(<3 x float> addrspace(2)* %runtime_value_6)
%30 = extractvalue { i32, i32 } %29, 1
%31 = extractvalue { i32, i32 } %29, 0
%32 = call <4 x float> addrspace(2)* @llvm.genx.GenISA.pair.to.ptr.p2v4f32(i32 %31, i32 %30)
or
%33 = call { i32, i32 } @llvm.genx.GenISA.ptr.to.pair.p2v4f32(<4 x float> addrspace(2)* %runtime_value_4)
%34 = extractvalue { i32, i32 } %33, 0
%35 = extractvalue { i32, i32 } %33, 1
%36 = call { i32, i32 } @llvm.genx.GenISA.add.pair(i32 %34, i32 %35, i32 368, i32 0)
%37 = extractvalue { i32, i32 } %36, 0
%38 = extractvalue { i32, i32 } %36, 1
%39 = call <2 x i32> addrspace(2)* @llvm.genx.GenISA.pair.to.ptr.p2v2i32(i32 %37, i32 %38)
2. Pushable 64bit address + pushable 32bit offset + immediate offset pattern:
%7 = call i32 @llvm.genx.GenISA.RuntimeValue.i32(i32 2)
%8 = call i64 @llvm.genx.GenISA.RuntimeValue.i64(i32 0)
%9 = bitcast i64 %8 to <2 x i32>
%10 = extractelement <2 x i32> %9, i32 0
%11 = extractelement <2 x i32> %9, i32 1
%12 = call { i32, i32 } @llvm.genx.GenISA.add.pair(i32 %10, i32 %11, i32 %1, i32 0)
%13 = extractvalue { i32, i32 } %12, 0
%14 = extractvalue { i32, i32 } %12, 1
%15 = call i8 addrspace(1441792)* addrspace(2)* @llvm.genx.GenISA.pair.to.ptr.p2p1441792i8(i32 %13, i32 %14)
*/
if (genIntr->getIntrinsicID() == GenISAIntrinsic::GenISA_pair_to_ptr)
{
ExtractValueInst* Lo = dyn_cast<ExtractValueInst>(genIntr->getOperand(0));
ExtractValueInst* Hi = dyn_cast<ExtractValueInst>(genIntr->getOperand(1));
if (Lo && Hi && Lo->getOperand(0) == Hi->getOperand(0))
{
if (GenIntrinsicInst * genIntr2 = dyn_cast<GenIntrinsicInst>(Lo->getOperand(0)))
{
if (genIntr2->getIntrinsicID() == GenISAIntrinsic::GenISA_ptr_to_pair)
{
offset = 0;
pAddress = genIntr2->getOperand(0);
}
if (genIntr2->getIntrinsicID() == GenISAIntrinsic::GenISA_add_pair)
{
Value* pAddress = nullptr;
ExtractValueInst* Lo2 = dyn_cast<ExtractValueInst>(genIntr2->getOperand(0));
ExtractValueInst* Hi2 = dyn_cast<ExtractValueInst>(genIntr2->getOperand(1));
if (Lo2 && Hi2 && Lo2->getOperand(0) == Hi2->getOperand(0))
{
if (GenIntrinsicInst* ptrToPair = dyn_cast<GenIntrinsicInst>(Lo2->getOperand(0)))
{
if (ptrToPair->getIntrinsicID() == GenISAIntrinsic::GenISA_ptr_to_pair)
{
// pattern no. 1
pAddress = ptrToPair->getOperand(0);
}
}
}
else
{
ExtractElementInst* Lo3 = dyn_cast<ExtractElementInst>(genIntr2->getOperand(0));
ExtractElementInst* Hi3 = dyn_cast<ExtractElementInst>(genIntr2->getOperand(1));
if (Lo3 && Hi3 && Lo3->getOperand(0) == Hi3->getOperand(0))
{
// pattern no. 2
pAddress = Lo3->getOperand(0);
}
}
if (pAddress &&
isa<ConstantInt>(genIntr2->getOperand(3)) &&
cast<ConstantInt>(genIntr2->getOperand(3))->getZExtValue() == 0)
{
offset = 0;
GetPotentialPushableAddresses(genIntr2->getOperand(2)); // offset
GetPotentialPushableAddresses(pAddress);
}
}
}
}
}
}
else
{
/*
Examples of patterns matched on platforms with 64bit type support:
1. Pushable 64bit address + immediate offset case:
%33 = ptrtoint <4 x float> addrspace(2)* %runtime_value_4 to i64
%34 = add i64 %33, 368
%chunkPtr = inttoptr i64 % 34 to <2 x i32> addrspace(2)*
2. Pushable 64bit address + pushable 32bit offset + immediate
offset case:
%0 = call i32 @llvm.genx.GenISA.RuntimeValue.i32(i32 3)
%1 = add i32 %0, 4
%2 = call i64 @llvm.genx.GenISA.RuntimeValue.i64(i32 1)
%3 = zext i32 %1 to i64
%4 = add i64 %2, %3
%5 = inttoptr i64 %4 to i8 addrspace(1507329)* addrspace(2)*
*/
offset = 0;
GetPotentialPushableAddresses(pAddress);
}
if (offset <= std::numeric_limits<uint>::max() && // pushableOffset is a 32bit value
(potentialPushableAddresses.size() == 1 ||
potentialPushableAddresses.size() == 2))
{
for (Value* potentialAddress : potentialPushableAddresses)
{
bool isPushable = IsPushableAddress(
inst,
potentialAddress,
pushableAddressGrfOffset,
pushableOffsetGrfOffset);
if (!isPushable)
{
return false;
}
}
IGC_ASSERT(pushableAddressGrfOffset >= 0);
pushableOffset = int_cast<uint>(offset);
return true;
}
return false;
}
bool PushAnalysis::IsPushableAddress(
llvm::Instruction* inst,
llvm::Value* pAddress,
int& pushableAddressGrfOffset,
int& pushableOffsetGrfOffset) const
{
// skip casts
while (
isa<IntToPtrInst>(pAddress) ||
isa<PtrToIntInst>(pAddress) ||
isa<BitCastInst>(pAddress))
{
pAddress = cast<Instruction>(pAddress)->getOperand(0);
}
llvm::GenIntrinsicInst* pRuntimeVal = llvm::dyn_cast<llvm::GenIntrinsicInst>(pAddress);
uint runtimeval0 = 0;
bool isRuntimeValFound = false;
if (pRuntimeVal == nullptr)
{
auto it = std::find(m_argList.begin(), m_argList.end(), pAddress);
if (it != m_argList.end())
{
int argIndex = (int) std::distance(m_argList.begin(), it);
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
for (auto index_it = pushInfo.constantReg.begin(); index_it != pushInfo.constantReg.end(); ++index_it)
{
if (index_it->second == argIndex)
{
runtimeval0 = index_it->first;
isRuntimeValFound = true;
}
}
}
if (!isRuntimeValFound)
return false;
}
else if(pRuntimeVal->getIntrinsicID() != llvm::GenISAIntrinsic::GenISA_RuntimeValue)
return false;
if (!isRuntimeValFound)
runtimeval0 = (uint)llvm::cast<llvm::ConstantInt>(pRuntimeVal->getOperand(0))->getZExtValue();
uint runtimevalSize = GetSizeInBits(pAddress->getType());
IGC_ASSERT(32 == runtimevalSize ||
64 == runtimevalSize);
const bool is64Bit = 64 == runtimevalSize;
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
// then check for static flag so that we can do push safely
for (auto it : pushInfo.pushableAddresses)
{
if (runtimeval0 * 4 != it.addressOffset)
{
continue;
}
if (IGC_IS_FLAG_ENABLED(DisableStaticCheck) ||
it.isStatic ||
IsSafeToPushNonStaticBufferLoad(inst))
{
// only a single 64bit pushable address and a single 32bit
// pushable offset is supported.
if (is64Bit && pushableAddressGrfOffset == -1)
{
pushableAddressGrfOffset = runtimeval0;
return true;
}
else if (!is64Bit && pushableOffsetGrfOffset == -1)
{
pushableOffsetGrfOffset = runtimeval0;
return true;
}
}
}
return false;
}
bool PushAnalysis::IsSafeToPushNonStaticBufferLoad(llvm::Instruction* inst) const
{
// Find the return BB or the return BB before discard lowering.
bool searchForRetBBBeforeDiscard = false;
BasicBlock* retBB = m_PDT->getRootNode()->getBlock();
if (!retBB)
{
#if LLVM_VERSION_MAJOR <= 10
auto& roots = m_PDT->getRoots();
IGC_ASSERT_MESSAGE(roots.size() == 1, "Unexpected multiple roots");
retBB = roots[0];
#else
auto roots = m_PDT->root_begin();
IGC_ASSERT_MESSAGE(m_PDT->root_size() == 1, "Unexpected multiple roots");
retBB = *roots;
#endif
}
for (auto& II : m_pFunction->getEntryBlock())
{
if (isa<GenIntrinsicInst>(&II, GenISAIntrinsic::GenISA_InitDiscardMask))
{
searchForRetBBBeforeDiscard = true;
break;
}
}
if (searchForRetBBBeforeDiscard)
{
for (auto it = pred_begin(retBB), ie = pred_end(retBB); it != ie; ++it)
{
BasicBlock* predBB = *it;
BranchInst* br = cast<BranchInst>(predBB->getTerminator());
if (br->isUnconditional())
{
retBB = predBB;
break;
}
}
}
if (m_DT->dominates(inst->getParent(), retBB))
{
return true;
}
return false;
}
//
// Calculate the offset in buffer relative to the dynamic uniform buffer offset.
//
// Below is an example of pattern we're looking for:
//
// %runtime_value_1 = call fast float @llvm.genx.GenISA.RuntimeValue(i32 1)
// %spv.bufferOffset.mdNode0.cr1 = bitcast float %runtime_value_1 to i32
// %1 = and i32 %spv.bufferOffset.mdNode1.cr1, -16
// %2 = add i32 %1, 24
// %fromGBP45 = inttoptr i32 %2 to float addrspace(65536)* // BTI = 0
// %ldrawidx46 = load float, float addrspace(65536)* %fromGBP45, align 4
//
// For the above example the the function will:
// - check if uniform buffer with bti=0 has its dynamic offset in
// runtime value 1
// - return relativeOffsetInBytes = 24
// This method will return true if the input UBO is a dynamic uniform buffer
// and the input offset value is a sum of buffer's dynamic offset and an
// immediate constant value.
//
bool PushAnalysis::GetConstantOffsetForDynamicUniformBuffer(
Value* offsetValue, // total buffer offset i.e. starting from 0
uint& relativeOffsetInBytes) // offset in bytes starting from dynamic offset in buffer
{
if (ConstantInt * constOffset = dyn_cast<ConstantInt>(offsetValue))
{
relativeOffsetInBytes = int_cast<uint>(constOffset->getZExtValue());
return true;
}
else if (Operator::getOpcode(offsetValue) == Instruction::Add)
{
const Instruction* addInst = cast<Instruction>(offsetValue);
uint offset0 = 0, offset1 = 0;
if (GetConstantOffsetForDynamicUniformBuffer(addInst->getOperand(0), offset0) &&
GetConstantOffsetForDynamicUniformBuffer(addInst->getOperand(1), offset1))
{
relativeOffsetInBytes = offset0 + offset1;
return true;
}
}
else if (Operator::getOpcode(offsetValue) == Instruction::Mul)
{
const Instruction* mulInst = cast<Instruction>(offsetValue);
uint a = 0, b = 0;
if (GetConstantOffsetForDynamicUniformBuffer(mulInst->getOperand(0), a) &&
GetConstantOffsetForDynamicUniformBuffer(mulInst->getOperand(1), b))
{
relativeOffsetInBytes = a * b;
return true;
}
}
else if (Operator::getOpcode(offsetValue) == Instruction::Shl)
{
const Instruction* shlInst = cast<Instruction>(offsetValue);
uint offset = 0, bitShift = 0;
if (GetConstantOffsetForDynamicUniformBuffer(shlInst->getOperand(0), offset) &&
GetConstantOffsetForDynamicUniformBuffer(shlInst->getOperand(1), bitShift))
{
relativeOffsetInBytes = offset << bitShift;
return true;
}
}
else if (Operator::getOpcode(offsetValue) == Instruction::And)
{
const Instruction* andInst = cast<Instruction>(offsetValue);
ConstantInt* src1 = dyn_cast<ConstantInt>(andInst->getOperand(1));
if (src1 &&
(int_cast<uint>(src1->getZExtValue()) == 0xFFFFFFE0 ||
int_cast<uint>(src1->getZExtValue()) == 0xFFFFFFF0))
{
uint offset = 0;
if (GetConstantOffsetForDynamicUniformBuffer(andInst->getOperand(0), offset) &&
(offset & int_cast<uint>(src1->getZExtValue())) == offset)
{
relativeOffsetInBytes = offset;
return true;
}
}
}
else if (Operator::getOpcode(offsetValue) == Instruction::Or)
{
Instruction* orInst = cast<Instruction>(offsetValue);
Instruction* src0 = dyn_cast<Instruction>(orInst->getOperand(0));
ConstantInt* src1 = dyn_cast<ConstantInt>(orInst->getOperand(1));
if (src1 && src0 &&
src0->getOpcode() == Instruction::And &&
isa<ConstantInt>(src0->getOperand(1)))
{
uint orOffset = int_cast<uint>(src1->getZExtValue());
uint andMask = int_cast<uint>(cast<ConstantInt>(src0->getOperand(1))->getZExtValue());
uint offset = 0;
if ((orOffset & andMask) == 0 &&
GetConstantOffsetForDynamicUniformBuffer(src0->getOperand(0), offset) &&
offset == 0)
{
relativeOffsetInBytes = orOffset;
return true;
}
}
}
else if (BitCastInst * bitCast = dyn_cast<BitCastInst>(offsetValue))
{
return GetConstantOffsetForDynamicUniformBuffer(bitCast->getOperand(0), relativeOffsetInBytes);
}
else if (IntToPtrInst * i2p = dyn_cast<IntToPtrInst>(offsetValue))
{
return GetConstantOffsetForDynamicUniformBuffer(i2p->getOperand(0), relativeOffsetInBytes);
}
else if (m_dynamicBufferOffsetArgs.find(offsetValue) != m_dynamicBufferOffsetArgs.end())
{
relativeOffsetInBytes = 0;
return true;
}
return false;
}
/// The constant-buffer id and element id must be compile-time immediate
/// in order to be added to thread-payload
bool PushAnalysis::IsPushableShaderConstant(
Instruction* inst,
SimplePushInfo& info)
{
Value* eltPtrVal = nullptr;
if (!isa<LoadInst>(inst) && !isa<LdRawIntrinsic>(inst))
return false;
Type* loadType = inst->getType();
Type* elemType = loadType->getScalarType();
// TODO: enable promotion of 8 bit, 16 bit and 64 bit values
if (!elemType->isFloatTy() &&
!elemType->isIntegerTy(32) &&
!(elemType->isPointerTy() && GetSizeInBits(elemType) == 32))
{
return false;
}
if (IsPushableBindlessLoad(
inst,
info.pushableOffsetGrfOffset,
info.cbIdx,
info.offset))
{
if ((info.offset % 4) == 0)
{
info.isBindless = true;
return true;
}
}
else if (IsLoadFromDirectCB(
inst,
info.cbIdx,
eltPtrVal))
{
if (info.cbIdx == getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData()->pushInfo.inlineConstantBufferSlot)
{
return false;
}
if (isa<ConstantPointerNull>(eltPtrVal))
{
info.offset = 0;
return true;
}
if (IntToPtrInst * i2p = dyn_cast<IntToPtrInst>(eltPtrVal))
{
Value* eltIdxVal = i2p->getOperand(0);
if (ConstantInt * eltIdx = dyn_cast<ConstantInt>(eltIdxVal))
{
info.offset = int_cast<uint>(eltIdx->getZExtValue());
if ((info.offset % 4) == 0)
{
return true;
}
}
}
if (m_context->m_DriverInfo.SupportsDynamicUniformBuffers() && IGC_IS_FLAG_DISABLED(DisableSimplePushWithDynamicUniformBuffers))
{
unsigned int relativeOffsetInBytes = 0; // offset in bytes starting from dynamic buffer offset
if (GetConstantOffsetForDynamicUniformBuffer(eltPtrVal, relativeOffsetInBytes))
{
info.offset = relativeOffsetInBytes;
if ((info.offset % 4) == 0)
{
return true;
}
}
}
return false;
}
else if (IsStatelessCBLoad(
inst,
info.pushableAddressGrfOffset,
info.pushableOffsetGrfOffset,
info.offset))
{
IGC_ASSERT(info.pushableAddressGrfOffset >= 0);
info.cbIdx = 0;
info.isStateless = true;
return true;
}
return false;
}
bool PushAnalysis::AreUniformInputsBasedOnDispatchMode()
{
return false;
}
bool PushAnalysis::DispatchGRFHardwareWAForHSAndGSDisabled()
{
// If the WA does not apply, we can push constants.
if (!m_context->platform.WaDispatchGRFHWIssueInGSAndHSUnit())
{
return true;
}
return true;
}
bool PushAnalysis::CanPushConstants()
{
if (IGC_GET_FLAG_VALUE(DisablePushConstant) & 0x1 ||
IGC_GET_FLAG_VALUE(DisablePushConstant) & (1 << static_cast<unsigned int>(m_context->type)))
{
return false;
}
if (!m_context->getModuleMetaData()->compOpt.PushConstantsEnable)
{
return false;
}
if (m_context->m_DriverInfo.WaDisablePushConstantsWithNoPushedAttributes() &&
m_context->platform.getWATable().Wa_16011983264 &&
m_context->type == ShaderType::HULL_SHADER)
{
Function* URBReadFunction = GenISAIntrinsic::getDeclaration(m_module, GenISAIntrinsic::GenISA_URBRead);
if (GetMaxNumberOfPushedInputs() == 0 ||
none_of(URBReadFunction->users(), [](const User* user) { return isa<GenIntrinsicInst>(user); }))
{
return false;
}
}
return false;
}
unsigned int PushAnalysis::GetMaxNumberOfPushedInputs()
{
if (IGC_GET_FLAG_VALUE(DisableAttributePush) & 0x1 ||
IGC_GET_FLAG_VALUE(DisableAttributePush) & static_cast<unsigned int>(m_context->type))
{
return 0;
}
return 0;
}
unsigned int PushAnalysis::GetSizeInBits(Type* type) const
{
unsigned int size = (unsigned int)type->getPrimitiveSizeInBits();
if (type->isPointerTy())
{
size = m_DL->getPointerSizeInBits(type->getPointerAddressSpace());
IGC_ASSERT(size == 32 || size == 64);
}
else if (type->isVectorTy() &&
type->getScalarType()->isPointerTy())
{
size = m_DL->getPointerSizeInBits(
type->getScalarType()->getPointerAddressSpace());
IGC_ASSERT(size == 32 || size == 64);
size = size * int_cast<uint>(cast<IGCLLVM::FixedVectorType>(type)->getNumElements());
}
return size;
}
void PushAnalysis::AllocatePushedConstant(
Instruction* load,
const SimplePushInfo& newChunk,
const unsigned int maxSizeAllowed)
{
if (!newChunk.isBindless &&
newChunk.cbIdx > m_context->m_DriverInfo.MaximumSimplePushBufferID())
{
return;
}
unsigned int size = GetSizeInBits(load->getType()) / 8;
IGC_ASSERT_MESSAGE(isa<LoadInst>(load) || isa<LdRawIntrinsic>(load),
"Expected a load instruction");
// greedy allocation for now
// first check if we are already pushing from the buffer
unsigned int piIndex;
bool regionFound = false;
for (piIndex = 0; piIndex < numSimplePush; piIndex++)
{
const SimplePushData& info = CollectAllSimplePushInfoArr[piIndex];
// Stateless load - GRF offsets need to match.
if (info.isStateless &&
newChunk.isStateless &&
info.pushableAddressGrfOffset == newChunk.pushableAddressGrfOffset &&
info.pushableOffsetGrfOffset == newChunk.pushableOffsetGrfOffset)
{
regionFound = true;
break;
}
// Bindless load - GRF offsets and bindless surface state offsets
// need to match.
if (info.isBindless &&
newChunk.isBindless &&
info.pushableOffsetGrfOffset == newChunk.pushableOffsetGrfOffset &&
info.cbIdx == newChunk.cbIdx)
{
regionFound = true;
break;
}
// Bound load - binding table indices need to match.
if (!info.isStateless &&
!newChunk.isStateless &&
!info.isBindless &&
!newChunk.isBindless &&
info.cbIdx == newChunk.cbIdx)
{
regionFound = true;
break;
}
}
if (regionFound)
{
SimplePushData& info = CollectAllSimplePushInfoArr[piIndex];
unsigned int newStartOffset = iSTD::RoundDown(
std::min(newChunk.offset, info.offset),
getMinPushConstantBufferAlignmentInBytes());
unsigned int newEndOffset = iSTD::Round(
std::max(newChunk.offset + size, info.offset + info.size),
getMinPushConstantBufferAlignmentInBytes());
unsigned int newSize = newEndOffset - newStartOffset;
if (newSize <= maxSizeAllowed)
{
info.offset = newStartOffset;
info.size = newSize;
info.Load.push_back(std::make_pair(load, newChunk.offset));
}
}
// we couldn't add it to an existing buffer try to add a new one if there is a slot available
else
{
unsigned int newStartOffset = iSTD::RoundDown(newChunk.offset, getMinPushConstantBufferAlignmentInBytes());
unsigned int newEndOffset = iSTD::Round(newChunk.offset + size, getMinPushConstantBufferAlignmentInBytes());
unsigned int newSize = newEndOffset - newStartOffset;
if (newSize <= maxSizeAllowed)
{
SimplePushData& info = CollectAllSimplePushInfoArr[numSimplePush];
info.pushableAddressGrfOffset = newChunk.pushableAddressGrfOffset;
info.pushableOffsetGrfOffset = newChunk.pushableOffsetGrfOffset;
info.cbIdx = newChunk.cbIdx;
info.isStateless = newChunk.isStateless;
info.isBindless = newChunk.isBindless;
info.offset = newStartOffset;
info.size = newSize;
info.Load.push_back(std::make_pair(load, newChunk.offset));
numSimplePush++;
}
}
return;
}
void PushAnalysis::PromoteLoadToSimplePush(Instruction* load, SimplePushInfo& info, unsigned int offset)
{
unsigned int num_elms = 1;
llvm::Type* pTypeToPush = load->getType();
if (pTypeToPush->isPointerTy())
{
pTypeToPush = IntegerType::get(
load->getContext(),
m_DL->getPointerSizeInBits(pTypeToPush->getPointerAddressSpace()));
}
llvm::Value* pReplacedInst = nullptr;
llvm::Type* pScalarTy = pTypeToPush;
if (pTypeToPush->isVectorTy())
{
num_elms = (unsigned)cast<IGCLLVM::FixedVectorType>(pTypeToPush)->getNumElements();
pTypeToPush = cast<VectorType>(pTypeToPush)->getElementType();
llvm::Type* pVecTy = IGCLLVM::FixedVectorType::get(pTypeToPush, num_elms);
pReplacedInst = llvm::UndefValue::get(pVecTy);
pScalarTy = cast<VectorType>(pVecTy)->getElementType();
}
SmallVector< SmallVector<ExtractElementInst*, 1>, 4> extracts(num_elms);
bool allExtract = VectorUsedByConstExtractOnly(load, extracts);
for (unsigned int i = 0; i < num_elms; ++i)
{
uint address = offset + i * (GetSizeInBits(pScalarTy) / 8);
auto it = info.simplePushLoads.find(address);
llvm::Value* value = nullptr;
if (it != info.simplePushLoads.end())
{
// Value is already getting pushed
IGC_ASSERT_MESSAGE((it->second <= m_argIndex), "Function arguments list and metadata are out of sync!");
value = m_argList[it->second];
}
else
{
value = addArgumentAndMetadata(pTypeToPush, VALUE_NAME("cb"), WIAnalysis::UNIFORM_GLOBAL);
info.simplePushLoads.insert(std::make_pair(address, m_argIndex));
}
if (pTypeToPush != value->getType())
{
IGC_ASSERT(pTypeToPush->isPointerTy() == value->getType()->isPointerTy());
value = pTypeToPush->isPointerTy() ?
CastInst::CreatePointerBitCastOrAddrSpaceCast(value, pTypeToPush, "", load) :
CastInst::CreateZExtOrBitCast(value, pTypeToPush, "", load);
}
if (load->getType()->isVectorTy())
{
if (!allExtract)
{
pReplacedInst = llvm::InsertElementInst::Create(
pReplacedInst, value, llvm::ConstantInt::get(llvm::IntegerType::get(load->getContext(), 32), i), "", load);
}
else
{
for (auto II : extracts[i])
{
II->replaceAllUsesWith(value);
}
}
}
else
{
if (load->getType()->isPointerTy())
{
value = IntToPtrInst::Create(
Instruction::IntToPtr,
value,
load->getType(),
load->getName(),
load);
}
pReplacedInst = value;
}
}
if (!allExtract)
{
load->replaceAllUsesWith(pReplacedInst);
}
}
void PushAnalysis::BlockPushConstants()
{
auto& inputs = m_context->getModuleMetaData()->pushInfo.inputs;
typedef const std::map<unsigned int, SInputDesc>::value_type& inputPairType;
unsigned int largestIndex = 0;
if (m_context->m_DriverInfo.EnableSimplePushRestriction())
{
auto largestPair = std::max_element(inputs.begin(), inputs.end(),
[](inputPairType a, inputPairType b) { return a.second.index < b.second.index; });
largestIndex = largestPair != inputs.end() ? largestPair->second.index : 0;
}
const unsigned int maxPushedGRFs = 96;
if (largestIndex >= maxPushedGRFs)
{
return;
}
// push up to 992 bytes of constants (31 32-byte units; this is
// the maximum value the read length in 3DSTATE_CONSTANT_ALL allows)
// The maximum number of GRFs used for all pushed data is 96.
const unsigned int cthreshold =
std::min(m_pullConstantHeuristics->getPushConstantThreshold(m_pFunction) * getMinPushConstantBufferAlignmentInBytes(),
(maxPushedGRFs - largestIndex) * getGRFSize());
unsigned int sizePushed = 0;
m_entryBB = &m_pFunction->getEntryBlock();
// Runtime values are changed to intrinsics. So we need to do it before.
for (auto bb = m_pFunction->begin(), be = m_pFunction->end(); bb != be; ++bb)
{
for (auto i = bb->begin(), ie = bb->end(); i != ie; ++i)
{
Instruction* const instr = &(*i);
SimplePushInfo info{};
bool isPushable = IsPushableShaderConstant(instr, info);
if(isPushable)
{
AllocatePushedConstant(
instr,
info,
cthreshold); // maxSizeAllowed
}
}
}
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
unsigned int simplePushBufferId = 0;
while ((pushInfo.simplePushBufferUsed < pushInfo.MaxNumberOfPushedBuffers) && CollectAllSimplePushInfoArr.size())
{
unsigned int iter = CollectAllSimplePushInfoArr.begin()->first;
SimplePushData info;
if (IGC_IS_FLAG_ENABLED(EnableSimplePushSizeBasedOpimization))
{
for (auto I = CollectAllSimplePushInfoArr.begin(), E = CollectAllSimplePushInfoArr.end(); I != E; I++)
{
if (I->second.size > info.size)
{
info = I->second;
iter = I->first;
}
}
}
else
{
info = CollectAllSimplePushInfoArr[simplePushBufferId];
iter = simplePushBufferId;
}
SimplePushInfo& newChunk = pushInfo.simplePushInfoArr[pushInfo.simplePushBufferUsed];
if (sizePushed + info.size <= cthreshold)
{
newChunk.cbIdx = info.cbIdx;
newChunk.isBindless = info.isBindless;
newChunk.isStateless = info.isStateless;
newChunk.offset = info.offset;
newChunk.size = info.size;
newChunk.pushableAddressGrfOffset = info.pushableAddressGrfOffset;
newChunk.pushableOffsetGrfOffset = info.pushableOffsetGrfOffset;
for (auto I = info.Load.begin(), E = info.Load.end(); I != E; I++)
PromoteLoadToSimplePush(I->first, newChunk, I->second);
pushInfo.simplePushBufferUsed++;
sizePushed += info.size;
}
CollectAllSimplePushInfoArr.erase(iter);
simplePushBufferId++;
}
}
PushConstantMode PushAnalysis::GetPushConstantMode()
{
PushConstantMode pushConstantMode = PushConstantMode::DEFAULT;
if(!CanPushConstants())
{
// Hardware can not do push constant mode or the registry has been set in a way to disable push altogether
pushConstantMode = PushConstantMode::NONE;
}
else
{
// Priority order of how the push constant mode is determined:
// 1.) Registry Keys
// 2.) Compiler Input
// 3.) Default Logic dependent on platform and attributes of the shader
// 1.) Check registry keys
if(pushConstantMode == PushConstantMode::DEFAULT)
{
if(IGC_IS_FLAG_ENABLED(forcePushConstantMode))
{
pushConstantMode = (PushConstantMode)IGC_GET_FLAG_VALUE(forcePushConstantMode);
}
}
// 2.) Check compiler input
if (pushConstantMode == PushConstantMode::DEFAULT)
{
pushConstantMode = m_context->m_pushConstantMode;
}
// 3.) Default Logic dependent on platform and attributes of the shader
if (pushConstantMode == PushConstantMode::DEFAULT)
{
if (m_context->m_DriverInfo.SupportsSimplePushOnly())
{
pushConstantMode = PushConstantMode::SIMPLE;
}
else if (m_context->platform.supportsHardwareResourceStreamer() || m_context->m_DriverInfo.SupportsGatherConstantOnly())
{
pushConstantMode = PushConstantMode::GATHER;
}
else if (m_context->m_DriverInfo.SupportsHWResourceStreameAndSimplePush())
{
pushConstantMode = PushConstantMode::SIMPLE;
}
else
{
// CPU copy
pushConstantMode = PushConstantMode::GATHER;
}
}
}
IGC_ASSERT_MESSAGE(pushConstantMode != PushConstantMode::DEFAULT, "GetPushConstantMode should resolve a non-DEFAULT mode!");
return pushConstantMode;
}
// process gather constants, update PushInfo.constants
void PushAnalysis::processGather(Instruction* inst, uint bufId, uint eltId)
{
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
eltId = eltId >> 2;
if (!m_context->m_DriverInfo.Uses3DSTATE_DX9_CONSTANT() &&
(eltId + inst->getType()->getPrimitiveSizeInBits() / 8) >= (MaxConstantBufferIndexSize * 4))
{
// Hardware supports pushing more than 256 constants
// in case 3DSTATE_DX9_CONSTANT mode is used
return;
}
else if (bufId > 15)
{
// resource streamer cannot push above buffer slot 15 and driver doesn't allow
// pushing inlined constant buffer
// should not be pushed and should always be pulled
return;
}
unsigned num_elms =
inst->getType()->isVectorTy() ? (unsigned)cast<IGCLLVM::FixedVectorType>(inst->getType())->getNumElements() : 1;
llvm::Type* pTypeToPush = inst->getType();
llvm::Value* replaceVector = nullptr;
unsigned int numberChannelReplaced = 0;
SmallVector< SmallVector<ExtractElementInst*, 1>, 4> extracts(num_elms);
bool allExtract = false;
if (inst->getType()->isVectorTy())
{
allExtract = LoadUsedByConstExtractOnly(cast<LoadInst>(inst), extracts);
pTypeToPush = cast<VectorType>(inst->getType())->getElementType();
}
for (unsigned int i = 0; i < num_elms; ++i)
{
if (allExtract && extracts[i].empty())
continue;
ConstantAddress address;
address.bufId = bufId;
address.eltId = eltId + i;
auto it = pushInfo.constants.find(address);
if (it != pushInfo.constants.end() ||
(pushInfo.constantReg.size() + pushInfo.constants.size() < m_pullConstantHeuristics->getPushConstantThreshold(m_pFunction) * 8))
{
llvm::Value* value = nullptr;
// The sum of all the 4 constant buffer read lengths must be <= size of 64 units.
// Each unit is of size 256-bit units. In some UMDs we program the
// ConstantRegisters and Constant Buffers in the ConstantBuffer0ReadLength. And this causes
// shaders to crash when the read length is > 64 units. To be safer we program the total number of
// GRF's used to 32 registers.
if (it == pushInfo.constants.end())
{
// We now put the Value as an argument to make sure its liveness starts
// at the beginning of the function and then we remove the instruction
// We now put the Value as an argument to make sure its liveness starts
// at the beginning of the function and then we remove the instruction
value = addArgumentAndMetadata(pTypeToPush,
VALUE_NAME(std::string("cb_") + to_string(bufId) + std::string("_") + to_string(eltId) + std::string("_elm") + to_string(i)),
WIAnalysis::UNIFORM_GLOBAL);
if (pTypeToPush != value->getType())
value = CastInst::CreateZExtOrBitCast(value, pTypeToPush, "", inst);
pushInfo.constants[address] = m_argIndex;
}
else
{
IGC_ASSERT_MESSAGE((it->second <= m_argIndex), "Function arguments list and metadata are out of sync!");
value = m_argList[it->second];
if (pTypeToPush != value->getType())
value = CastInst::CreateZExtOrBitCast(value, pTypeToPush, "", inst);
}
if (inst->getType()->isVectorTy())
{
if (!allExtract)
{
numberChannelReplaced++;
if (replaceVector == nullptr)
{
replaceVector = llvm::UndefValue::get(inst->getType());
}
replaceVector = llvm::InsertElementInst::Create(
replaceVector, value, llvm::ConstantInt::get(llvm::IntegerType::get(inst->getContext(), 32), i), "", inst);
}
else
{
for (auto II : extracts[i])
{
II->replaceAllUsesWith(value);
}
}
}
else
{
inst->replaceAllUsesWith(value);
}
}
if (replaceVector != nullptr && numberChannelReplaced == num_elms)
{
// for vector replace, we only replace the load if we were going to push
// all the channels
inst->replaceAllUsesWith(replaceVector);
}
}
}
void PushAnalysis::processInput(Instruction* inst, bool gsInstancingUsed)
{
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
e_interpolation mode = (e_interpolation)llvm::cast<llvm::ConstantInt>(inst->getOperand(1))->getZExtValue();
if (
(mode == EINTERPOLATION_VERTEX || mode == EINTERPOLATION_CONSTANT))
{
// inputs which get pushed are set as function arguments in order to have the correct liveness
if (llvm::ConstantInt * pIndex = llvm::dyn_cast<llvm::ConstantInt>(inst->getOperand(0)))
{
SInputDesc input;
input.index = static_cast<uint>(pIndex->getZExtValue());
input.interpolationMode = mode;
// if we know input is uniform, update WI analysis results.
const bool uniformInput =
(mode == EINTERPOLATION_CONSTANT) || gsInstancingUsed;
auto it = pushInfo.inputs.find(input.index);
if (it == pushInfo.inputs.end())
{
IGC_ASSERT(inst->getType()->isHalfTy() || inst->getType()->isFloatTy());
llvm::Type* floatTy = Type::getFloatTy(m_pFunction->getContext());
addArgumentAndMetadata(floatTy, VALUE_NAME(std::string("input_") + to_string(input.index)),
uniformInput ? WIAnalysis::UNIFORM_GLOBAL : WIAnalysis::RANDOM);
input.argIndex = m_argIndex;
pushInfo.inputs[input.index] = input;
}
else
{
IGC_ASSERT_MESSAGE((it->second.argIndex <= m_argIndex), "Function arguments list and metadata are out of sync!");
input.argIndex = it->second.argIndex;
}
llvm::Value* replacementValue = m_argList[input.argIndex];
if (inst->getType()->isHalfTy() && replacementValue->getType()->isFloatTy())
{
// Input is accessed using the half version of intrinsic, e.g.:
// call half @llvm.genx.GenISA.DCL.inputVec.f16 (i32 13, i32 2)
replacementValue = CastInst::CreateFPCast(replacementValue, inst->getType(), "", inst);
}
inst->replaceAllUsesWith(replacementValue);
}
}
}
void PushAnalysis::processInputVec(Instruction* inst, bool gsInstancingUsed)
{
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
// If the input index of llvm_shaderinputvec is a constant
if (llvm::ConstantInt * pIndex = llvm::dyn_cast<llvm::ConstantInt>(inst->getOperand(0)))
{
uint inputIndex = static_cast<uint>(pIndex->getZExtValue());
e_interpolation mode = (e_interpolation)llvm::cast<llvm::ConstantInt>(inst->getOperand(1))->getZExtValue();
// If the input index of llvm_shaderinputvec is a constant then we pull inputs if inputIndex <= MaxNumOfPushedInputs
if (pIndex && inputIndex <= MaxNumOfPushedInputs)
{
if (mode == EINTERPOLATION_CONSTANT || mode == EINTERPOLATION_VERTEX)
{
for (auto I = inst->user_begin(), E = inst->user_end(); I != E; ++I)
{
if (llvm::ExtractElementInst * extract = llvm::dyn_cast<llvm::ExtractElementInst>(*I))
{
SInputDesc input;
// if input is i1.xyzw, inputIndex = 1*4, extract->getIndexOperand() is the component
input.index = inputIndex * 4 +
int_cast<uint>(llvm::cast<ConstantInt>(extract->getIndexOperand())->getZExtValue());
input.interpolationMode = mode;
// if we know input is uniform, update WI analysis results.
const bool uniformInput =
(mode == EINTERPOLATION_CONSTANT) || gsInstancingUsed;
auto it = pushInfo.inputs.find(input.index);
if (it == pushInfo.inputs.end())
{
addArgumentAndMetadata(extract->getType(), VALUE_NAME(std::string("pushedinput_") + to_string(input.index)),
uniformInput ? WIAnalysis::UNIFORM_GLOBAL : WIAnalysis::RANDOM);
input.argIndex = m_argIndex;
pushInfo.inputs[input.index] = input;
}
else
{
IGC_ASSERT_MESSAGE((it->second.argIndex <= m_argIndex), "Function arguments list and metadata are out of sync!");
input.argIndex = it->second.argIndex;
}
extract->replaceAllUsesWith(m_argList[input.argIndex]);
}
}
}
}
else
{
// This should never happen for geometry shader since we leave GS specific
// intrinsic if we want pull model earlier in GS lowering.
IGC_ASSERT(m_context->type != ShaderType::GEOMETRY_SHADER);
}
}
}
void PushAnalysis::processURBRead(Instruction* inst, bool gsInstancingUsed,
bool vsHasConstantBufferIndexedWithInstanceId,
uint32_t vsUrbReadIndexForInstanceIdSGV)
{
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
if (llvm::ConstantInt * pVertexIndex = llvm::dyn_cast<llvm::ConstantInt>(inst->getOperand(0)))
{
uint vertexIndex = static_cast<uint>(pVertexIndex->getZExtValue());
uint numberOfElementsPerVertexThatAreGoingToBePushed = GetMaxNumberOfPushedInputs();
// If the input index of llvm_shaderinputvec is a constant
if (llvm::ConstantInt * pElementIndex = llvm::dyn_cast<llvm::ConstantInt>(inst->getOperand(1)))
{
int urbOffset = static_cast<int>(pElementIndex->getZExtValue());
int urbReadOffsetForPush = 0;
bool pushCondition = ((urbOffset >= urbReadOffsetForPush) && (urbOffset - urbReadOffsetForPush) < (int)numberOfElementsPerVertexThatAreGoingToBePushed);
// If the attribute index of URBRead is a constant then we pull
// inputs if elementIndex <= minElementsPerVertexThatCanBePushed
if (pElementIndex && pushCondition)
{
uint elementIndex = urbOffset - urbReadOffsetForPush;
uint currentElementIndex = (vertexIndex * numberOfElementsPerVertexThatAreGoingToBePushed * 4) + (elementIndex * 4);
for (auto I = inst->user_begin(), E = inst->user_end(); I != E; ++I)
{
llvm::ExtractElementInst* extract = llvm::dyn_cast<llvm::ExtractElementInst>(*I);
if (extract && llvm::isa<ConstantInt>(extract->getIndexOperand()))
{
SInputDesc input;
// if input is i1.xyzw, elementIndex = 1*4, extract->getIndexOperand() is the component
input.index =
currentElementIndex +
int_cast<uint>(cast<ConstantInt>(extract->getIndexOperand())->getZExtValue());
input.interpolationMode = AreUniformInputsBasedOnDispatchMode() ?
EINTERPOLATION_CONSTANT : EINTERPOLATION_VERTEX;
const bool uniformInput =
AreUniformInputsBasedOnDispatchMode() ||
(vsHasConstantBufferIndexedWithInstanceId &&
vsUrbReadIndexForInstanceIdSGV == input.index) ||
gsInstancingUsed;
auto it = pushInfo.inputs.find(input.index);
if (it == pushInfo.inputs.end())
{
addArgumentAndMetadata(extract->getType(), VALUE_NAME(std::string("urb_read_") + to_string(input.index)),
uniformInput ? WIAnalysis::UNIFORM_GLOBAL : WIAnalysis::RANDOM);
input.argIndex = m_argIndex;
pushInfo.inputs[input.index] = input;
}
else
{
IGC_ASSERT_MESSAGE((it->second.argIndex <= m_argIndex), "Function arguments list and metadata are out of sync!");
input.argIndex = it->second.argIndex;
}
extract->replaceAllUsesWith(m_argList[input.argIndex]);
}
}
}
}
}
}
// process runtime value, update PushInfo.constantReg
void PushAnalysis::processRuntimeValue(GenIntrinsicInst* intrinsic)
{
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
uint index = (uint)llvm::cast<llvm::ConstantInt>(intrinsic->getOperand(0))->getZExtValue();
auto it = pushInfo.constantReg.find(index);
Value* arg = nullptr;
Value* runtimeValue = intrinsic;
if (it == pushInfo.constantReg.end())
{
while (runtimeValue->hasOneUse() &&
(isa<BitCastInst>(runtimeValue->user_back()) ||
isa<IntToPtrInst>(runtimeValue->user_back())))
{
Value* castInst = runtimeValue->user_back();
if ((index % 2) != 0 &&
(64 == GetSizeInBits(castInst->getType())) &&
!castInst->getType()->isVectorTy())
{
// 64bit runtime values must be 8B aligned in GRFs.
break;
}
runtimeValue = castInst;
}
arg = addArgumentAndMetadata(
runtimeValue->getType(),
VALUE_NAME(std::string("runtime_value_") + to_string(index)),
WIAnalysis::UNIFORM_GLOBAL);
pushInfo.constantReg[index] = m_argIndex;
if (m_context->m_DriverInfo.SupportsDynamicUniformBuffers() &&
IGC_IS_FLAG_DISABLED(DisableSimplePushWithDynamicUniformBuffers) &&
pushInfo.dynamicBufferInfo.numOffsets > 0 &&
index >= pushInfo.dynamicBufferInfo.firstIndex &&
index < pushInfo.dynamicBufferInfo.firstIndex + pushInfo.dynamicBufferInfo.numOffsets)
{
m_dynamicBufferOffsetArgs.insert(arg);
}
for (unsigned int& runtimeValueIndex : pushInfo.bindlessPushInfo)
{
if (index == runtimeValueIndex)
{
m_bindlessPushArgs[arg] = index;
}
}
}
else
{
IGC_ASSERT_MESSAGE(it->second <= m_argIndex, "Function arguments list and metadata are out of sync!");
arg = m_argList[it->second];
while (arg->getType() != runtimeValue->getType() &&
runtimeValue->hasOneUse() &&
(isa<BitCastInst>(runtimeValue->user_back()) ||
isa<IntToPtrInst>(runtimeValue->user_back())))
{
runtimeValue = runtimeValue->user_back();
}
if (arg->getType() != runtimeValue->getType())
{
arg = CastInst::CreateBitOrPointerCast(
arg, runtimeValue->getType(), "", cast<Instruction>(runtimeValue));
}
}
runtimeValue->replaceAllUsesWith(arg);
}
//// Max number of control point inputs in 8 patch beyond which we always pull
/// and do not try to use a hybrid approach of pull and push
void PushAnalysis::ProcessFunction()
{
// if it's GS, get the properties object and find out if we use instancing
// since then payload is laid out differently.
const bool gsInstancingUsed =
false;
uint32_t vsUrbReadIndexForInstanceIdSGV = 0;
bool vsHasConstantBufferIndexedWithInstanceId = false;
m_funcTypeChanged = false; // Reset flag at the beginning of processing every function
PushConstantMode pushConstantMode = GetPushConstantMode();
for (auto BB = m_pFunction->begin(), E = m_pFunction->end(); BB != E; ++BB)
{
llvm::BasicBlock::InstListType& instructionList = BB->getInstList();
for (auto instIter = instructionList.begin(), endInstIter = instructionList.end(); instIter != endInstIter; ++instIter)
{
llvm::Instruction* inst = &(*instIter);
// skip dead instructions
if (inst->use_empty())
{
continue;
}
// code to push constant-buffer value into thread-payload
SimplePushInfo info{};
if (pushConstantMode == PushConstantMode::GATHER &&
IsPushableShaderConstant(inst, info) &&
!info.isBindless &&
!info.isStateless)
{
processGather(inst, info.cbIdx, info.offset);
}
else if (GetOpCode(inst) == llvm_input)
{
processInput(inst, gsInstancingUsed);
}
else if (GetOpCode(inst) == llvm_shaderinputvec)
{
processInputVec(inst, gsInstancingUsed);
}
else if (GenIntrinsicInst * intrinsic = dyn_cast<GenIntrinsicInst>(inst))
{
if (DispatchGRFHardwareWAForHSAndGSDisabled() &&
(intrinsic->getIntrinsicID() == GenISAIntrinsic::GenISA_URBRead) &&
(m_context->type != ShaderType::DOMAIN_SHADER))
{
processURBRead(inst, gsInstancingUsed,
vsHasConstantBufferIndexedWithInstanceId,
vsUrbReadIndexForInstanceIdSGV);
}
else if (intrinsic->getIntrinsicID() == GenISAIntrinsic::GenISA_RuntimeValue)
{
processRuntimeValue(intrinsic);
}
}
}
}
if (pushConstantMode == PushConstantMode::SIMPLE)
{
BlockPushConstants();
}
// WA: Gen11+ HW doesn't work correctly if doubles are on vertex shader input and the input has unused components,
// so ElementComponentEnableMask is not full => packing occurs
// Code below fills gaps in inputs, so the ElementComponentEnableMask if full even if we don't use all
// components in shader. This is needed, because in case of doubles there can be no URBRead if xy or zw
// components are not used.
// Right now only OGL is affected, so there is special disableVertexComponentPacking flag set by GLSL FE
// if there is double on input to vertex shader
if (!m_context->getModuleMetaData()->pushInfo.inputs.empty() &&
m_context->type == ShaderType::VERTEX_SHADER &&
m_context->getModuleMetaData()->compOpt.disableVertexComponentPacking)
{
PushInfo& pushInfo = m_context->getModuleMetaData()->pushInfo;
int maxIndex = pushInfo.inputs.rbegin()->first;
for (int i = 0; i < maxIndex; ++i)
{
if (pushInfo.inputs.find(i) == pushInfo.inputs.end())
{
SInputDesc input;
// if input is i1.xyzw, elementIndex = 1*4, extract->getIndexOperand() is the component
input.index = i;
input.interpolationMode = EINTERPOLATION_VERTEX;
const bool uniformInput =
AreUniformInputsBasedOnDispatchMode() ||
(vsHasConstantBufferIndexedWithInstanceId &&
vsUrbReadIndexForInstanceIdSGV == input.index) ||
gsInstancingUsed;
addArgumentAndMetadata(Type::getFloatTy(m_pFunction->getContext()), VALUE_NAME(std::string("urb_read_") + to_string(input.index)),
uniformInput ? WIAnalysis::UNIFORM_GLOBAL : WIAnalysis::RANDOM);
input.argIndex = m_argIndex;
pushInfo.inputs[input.index] = input;
}
}
}
if (m_funcTypeChanged)
{
m_isFuncTypeChanged[m_pFunction] = true;
}
else
{
m_isFuncTypeChanged[m_pFunction] = false;
}
m_pMdUtils->save(m_pFunction->getContext());
}
bool PushAnalysis::runOnModule(llvm::Module& M)
{
m_DL = &M.getDataLayout();
m_pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils();
m_pullConstantHeuristics = &getAnalysis<PullConstantHeuristics>();
m_context = getAnalysis<CodeGenContextWrapper>().getCodeGenContext();
MapList<Function*, Function*> funcsMapping;
bool retValue = false;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
{
Function* pFunc = &(*I);
// Only handle functions defined in this module
if (pFunc->isDeclaration() || !isEntryFunc(m_pMdUtils, pFunc))
continue;
m_pFuncUpgrade.SetFunctionToUpgrade(pFunc);
AnalyzeFunction(pFunc);
// Find out if function pFunc's type/signature changed
if (m_isFuncTypeChanged[pFunc])
{
retValue = true;
// Create the new function body and insert it into the module
Function* pNewFunc = m_pFuncUpgrade.RebuildFunction();
// Map old func to new func
funcsMapping[pFunc] = pNewFunc;
// This is a kernel function, so there should not be any call site
IGC_ASSERT(pFunc->use_empty());
}
m_pFuncUpgrade.Clean();
}
// Update IGC Metadata and shaders map
// Function declarations are changing, this needs to be reflected in the metadata.
MetadataBuilder mbuilder(&M);
for (auto i : funcsMapping)
{
IGCMD::IGCMetaDataHelper::moveFunction(
*m_pMdUtils, *m_context->getModuleMetaData(), i.first, i.second);
mbuilder.UpdateShadingRate(i.first, i.second);
auto& privateMemoryPerFG = m_context->getModuleMetaData()->PrivateMemoryPerFG;
privateMemoryPerFG[i.second] = privateMemoryPerFG[i.first];
privateMemoryPerFG.erase(i.first);
}
m_pMdUtils->save(M.getContext());
GenXFunctionGroupAnalysis* FGA = getAnalysisIfAvailable<GenXFunctionGroupAnalysis>();
// Go over all changed functions
for (MapList<Function*, Function*>::const_iterator I = funcsMapping.begin(), E = funcsMapping.end(); I != E; ++I)
{
Function* pFunc = I->first;
IGC_ASSERT_MESSAGE(pFunc->use_empty(), "Assume all user function are inlined at this point");
if (FGA && FGA->getModule()) {
FGA->replaceEntryFunc(pFunc, I->second);
}
// Now, after changing funciton signature,
// and validate there are no calls to the old function we can erase it.
pFunc->eraseFromParent();
}
DumpLLVMIR(m_context, "push_analysis");
return retValue;
}
char PushAnalysis::ID = 0;
}//namespace IGC
|