File: CodeGenContext.cpp

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

Copyright (C) 2018-2022 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include <sstream>
#include "common/LLVMWarningsPush.hpp"
#include <llvm/Support/ScaledNumber.h>
#include <llvm/Demangle/Demangle.h>
#include <llvm/IR/DebugInfo.h>
#include "common/LLVMWarningsPop.hpp"
#include "AdaptorCommon/RayTracing/RayTracingConstantsEnums.h"
#include "Compiler/CISACodeGen/ShaderCodeGen.hpp"
#include "Compiler/CISACodeGen/OpenCLKernelCodeGen.hpp"
#include "Compiler/CodeGenPublic.h"
#include "Probe/Assertion.h"

namespace IGC
{

    struct RetryState
    {
        bool allowLICM;
        bool allowCodeSinking;
        bool allowAddressArithmeticSinking;
        bool allowSimd32Slicing;
        bool allowPromotePrivateMemory;
        bool allowPreRAScheduler;
        bool allowVISAPreRAScheduler;
        bool allowLargeURBWrite;
        bool allowConstantCoalescing;
        bool allowLargeGRF;
        unsigned nextState;
    };

    static const RetryState RetryTable[] = {
        // licm  codSk AdrSk  Slice  PrivM  PreRA  VISAP  URBWr  Coals  GRF
        { true,  true, false, false, true,  true,  true,  true,  true,  false, 1 },
        { false, true, true,  true,  false, false, false, false, false, true, 500 }
    };

    static constexpr size_t RetryTableSize = sizeof(RetryTable) / sizeof(RetryState);

    RetryManager::RetryManager() : enabled(false), perKernel(false)
    {
        auto id = IGC_GET_FLAG_VALUE(RetryManagerFirstStateId);
        // We set firstStateId to be 0 even if RetryManagerFirstStateId is set
        // because it will have side effects on IsFirstTry. By doing so, we will
        // treat new retry state as NOT a first try which aligned with default compilation
        firstStateId = 0;
        stateId = id;
        IGC_ASSERT(stateId < RetryTableSize);
    }

    bool RetryManager::AdvanceState()
    {
        if (!enabled || IGC_IS_FLAG_ENABLED(DisableRecompilation))
        {
            return false;
        }
        IGC_ASSERT(stateId < RetryTableSize);
        stateId = RetryTable[stateId].nextState;
        return (stateId < RetryTableSize);
    }

    bool RetryManager::AllowLICM() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowLICM;
    }

    bool RetryManager::AllowAddressArithmeticSinking() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowAddressArithmeticSinking;
    }

    bool RetryManager::AllowPromotePrivateMemory() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowPromotePrivateMemory;
    }

    bool RetryManager::AllowPreRAScheduler() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowPreRAScheduler;
    }

    bool RetryManager::AllowVISAPreRAScheduler() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowVISAPreRAScheduler;
    }

    bool RetryManager::AllowCodeSinking() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowCodeSinking;
    }

    bool RetryManager::AllowSimd32Slicing() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowSimd32Slicing;
    }

    bool RetryManager::AllowLargeURBWrite() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowLargeURBWrite;
    }

    bool RetryManager::AllowConstantCoalescing() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowConstantCoalescing;
    }

    bool RetryManager::AllowLargeGRF() const
    {
        IGC_ASSERT(stateId < RetryTableSize);
        return RetryTable[stateId].allowLargeGRF;
    }

    void RetryManager::SetFirstStateId(int id)
    {
        firstStateId = id;
    }

    bool RetryManager::IsFirstTry() const
    {
        return (stateId == firstStateId);
    }

    bool RetryManager::IsLastTry() const
    {
        return (!enabled ||
            IGC_IS_FLAG_ENABLED(DisableRecompilation) ||
            lastSpillSize < IGC_GET_FLAG_VALUE(AllowedSpillRegCount) ||
            (stateId < RetryTableSize && RetryTable[stateId].nextState >= RetryTableSize));
    }

    unsigned RetryManager::GetRetryId() const
    {
        return stateId;
    }

    void RetryManager::Enable()
    {
        enabled = true;
    }

    void RetryManager::Disable()
    {
        if (!perKernel)
        {
            enabled = false;
        }
    }

    void RetryManager::SetSpillSize(unsigned int spillSize)
    {
        lastSpillSize = spillSize;
    }

    unsigned int RetryManager::GetLastSpillSize() const
    {
        return lastSpillSize;
    }

    void RetryManager::ClearSpillParams()
    {
        lastSpillSize = 0;
        numInstructions = 0;
    }

    // save entry for given SIMD mode, to avoid recompile for next retry.
    void RetryManager::SaveSIMDEntry(SIMDMode simdMode, CShader* shader)
    {
        auto entry = GetCacheEntry(simdMode);
        IGC_ASSERT(entry);
        if (entry)
        {
            entry->shader = shader;
        }
    }

    CShader* RetryManager::GetSIMDEntry(SIMDMode simdMode)
    {
        auto entry = GetCacheEntry(simdMode);
        IGC_ASSERT(entry);
        return entry ? entry->shader : nullptr;
    }

    RetryManager::~RetryManager()
    {
        for (auto& it : cache)
        {
            if (it.shader)
            {
                delete it.shader;
            }
        }
    }

    bool RetryManager::AnyKernelSpills() const
    {
        return std::any_of(std::begin(cache), std::end(cache), [](const CacheEntry& entry) {
            return entry.shader && entry.shader->m_spillCost > 0.0;
        });
    }

    bool RetryManager::PickupKernels(CodeGenContext* cgCtx)
    {
        {
            IGC_ASSERT_MESSAGE(0, "TODO for other shader types");
            return true;
        }
    }

    CShader* RetryManager::PickCSEntryForcedFromDriver(SIMDMode& simdMode, unsigned char forcedSIMDModeFromDriver)
    {
        SIMDMode simdModeCandidate = lanesToSIMDMode(forcedSIMDModeFromDriver);
        auto entry = GetCacheEntry(simdModeCandidate);
        if (!entry)
        {
            return nullptr;
        }

        if ((entry->shader && entry->shader->m_spillSize == 0) || IsLastTry())
        {
            simdMode = entry->simdMode;
            return entry->shader;
        }
        return nullptr;
    }

    CShader* RetryManager::PickCSEntryByRegKey(SIMDMode& simdMode, ComputeShaderContext* cgCtx)
    {
        if (IGC_IS_FLAG_ENABLED(ForceCSSIMD32))
        {
            simdMode = SIMDMode::SIMD32;
            return GetSIMDEntry(simdMode);
        }
        else
        {
            if (IGC_IS_FLAG_ENABLED(ForceCSSIMD16) && GetSIMDEntry(SIMDMode::SIMD16))
            {
                simdMode = SIMDMode::SIMD16;
                return GetSIMDEntry(simdMode);
            }
            else
            {
                if (IGC_IS_FLAG_ENABLED(ForceCSLeastSIMD)
                    || (IGC_IS_FLAG_ENABLED(ForceCSLeastSIMD4RQ) && cgCtx->hasSyncRTCalls()))
                {
                    return PickCSEntryFinally(simdMode);
                }
            }
        }
        return nullptr;
    }

    CShader* RetryManager::PickCSEntryEarly(SIMDMode& simdMode, ComputeShaderContext* cgCtx)
    {
        struct SIMDInfo {
            SIMDMode simdMode;
            CShader* shader;
            float occupancy;
            bool noSpill;
        };

        auto getSIMDInfo = [this, cgCtx](const SIMDMode& simdMode)
        {
            CShader* shader = GetSIMDEntry(simdMode);
            return SIMDInfo{
                simdMode,
                shader,
                cgCtx->GetThreadOccupancy(simdMode),
                shader && shader->m_spillCost <= cgCtx->GetSpillThreshold()
            };
        };

        auto simd8info = getSIMDInfo(SIMDMode::SIMD8);
        auto simd16info = getSIMDInfo(SIMDMode::SIMD16);
        auto simd32info = getSIMDInfo(SIMDMode::SIMD32);

        // If SIMD32/16/8 are all allowed, then choose one which has highest thread occupancy

        if (IGC_IS_FLAG_ENABLED(EnableHighestSIMDForNoSpill))
        {
            if (simd32info.noSpill)
            {
                simdMode = simd32info.simdMode;
                return simd32info.shader;
            }

            if (simd16info.noSpill)
            {
                simdMode = simd16info.simdMode;
                return simd16info.shader;
            }
        }
        else
        {
            float maxOccupancy = std::max(std::max(simd8info.occupancy, simd16info.occupancy), simd32info.occupancy);

            if (simd32info.noSpill)
            {
                if (simd32info.occupancy == maxOccupancy || cgCtx->m_ForceOneSIMD)
                {
                    simdMode = simd32info.simdMode;
                    return simd32info.shader;
                }

                IGC_ASSERT_MESSAGE(!simd8info.shader || simd8info.noSpill, "If SIMD32 doesn't spill, SIMD8 shouldn't, if it exists");
                IGC_ASSERT_MESSAGE(!simd16info.shader || simd16info.noSpill, "If SIMD32 doesn't spill, SIMD16 shouldn't, if it exists");
            }

            if (simd16info.noSpill)
            {
                if (simd16info.occupancy == maxOccupancy || cgCtx->m_ForceOneSIMD)
                {
                    simdMode = simd16info.simdMode;
                    return simd16info.shader;
                }
                IGC_ASSERT_MESSAGE(!simd8info.shader || simd8info.noSpill, "If SIMD16 doesn't spill, SIMD8 shouldn't, if it exists");
            }
        }

        bool needToRetry = false;
        if (cgCtx->m_slmSize)
        {
            if (simd16info.occupancy > simd8info.occupancy || simd32info.occupancy > simd16info.occupancy)
            {
                needToRetry = true;
            }
        }

        SIMDMode maxSimdMode = cgCtx->GetMaxSIMDMode();
        if (maxSimdMode == SIMDMode::SIMD8 || !needToRetry)
        {
            if (simd8info.shader && simd8info.shader->m_spillSize == 0)
            {
                simdMode = simd8info.simdMode;
                return simd8info.shader;
            }
        }
        return nullptr;
    }

    CShader* RetryManager::PickCSEntryFinally(SIMDMode& simdMode)
    {
        for (const auto& it : cache)
        {
            if (it.shader)
            {
                simdMode = it.simdMode;
                return it.shader;
            }
        }
        return nullptr;
    }



    RetryManager::CacheEntry* RetryManager::GetCacheEntry(SIMDMode simdMode)
    {
        auto result = std::find_if(std::begin(cache), std::end(cache), [&simdMode](const CacheEntry& entry) {
            return entry.simdMode == simdMode;
        });
        return result != std::end(cache) ? result : nullptr;
    }

    LLVMContextWrapper::LLVMContextWrapper(bool createResourceDimTypes)
    {
        if (createResourceDimTypes)
        {
            CreateResourceDimensionTypes(*this);
        }
    }

    void LLVMContextWrapper::AddRef()
    {
        refCount++;
    }

    void LLVMContextWrapper::Release()
    {
        refCount--;
        if (refCount == 0)
        {
            delete this;
        }
    }

    /** get shader's thread group size */
    unsigned ComputeShaderContext::GetThreadGroupSize()
    {
        llvm::GlobalVariable* pGlobal = getModule()->getGlobalVariable("ThreadGroupSize_X");
        m_threadGroupSize_X = int_cast<unsigned>(llvm::cast<llvm::ConstantInt>(pGlobal->getInitializer())->getZExtValue());

        pGlobal = getModule()->getGlobalVariable("ThreadGroupSize_Y");
        m_threadGroupSize_Y = int_cast<unsigned>(llvm::cast<llvm::ConstantInt>(pGlobal->getInitializer())->getZExtValue());

        pGlobal = getModule()->getGlobalVariable("ThreadGroupSize_Z");
        m_threadGroupSize_Z = int_cast<unsigned>(llvm::cast<llvm::ConstantInt>(pGlobal->getInitializer())->getZExtValue());

        return m_threadGroupSize_X * m_threadGroupSize_Y * m_threadGroupSize_Z;
    }

    unsigned ComputeShaderContext::GetSlmSizePerSubslice()
    {
        return platform.getSlmSizePerSsOrDss();
    }

    unsigned ComputeShaderContext::GetSlmSize() const
    {
        return m_slmSize;
    }

    float ComputeShaderContext::GetThreadOccupancy(SIMDMode simdMode)
    {
        return GetThreadOccupancyPerSubslice(simdMode, GetThreadGroupSize(), GetHwThreadsPerWG(platform), m_slmSize, GetSlmSizePerSubslice());
    }

    /** get smallest SIMD mode allowed based on thread group size */
    SIMDMode ComputeShaderContext::GetLeastSIMDModeAllowed()
    {
        SIMDMode mode = getLeastSIMDAllowed(
            GetThreadGroupSize(),
            GetHwThreadsPerWG(platform));
        return mode;
    }

    /** get largest SIMD mode for performance based on thread group size */
    SIMDMode ComputeShaderContext::GetMaxSIMDMode()
    {
        unsigned threadGroupSize = GetThreadGroupSize();
        SIMDMode mode;
        if (threadGroupSize <= 8)
        {
            mode = SIMDMode::SIMD8;
        }
        else if (threadGroupSize <= 16)
        {
            mode = SIMDMode::SIMD16;
        }
        else
        {
            mode = SIMDMode::SIMD32;
        }
        return mode;
    }

    float ComputeShaderContext::GetSpillThreshold() const
    {
        float spillThresholdSLM = platform.adjustedSpillThreshold() / 100.0f;
        //enable CSSpillThresholdSLM with desired value to override the default value.
        if(IGC_IS_FLAG_ENABLED(CSSpillThresholdSLM))
            spillThresholdSLM = float(IGC_GET_FLAG_VALUE(CSSpillThresholdSLM)) / 100.0f;
        float spillThresholdNoSLM =
            float(IGC_GET_FLAG_VALUE(CSSpillThresholdNoSLM)) / 100.0f;
        return m_slmSize ? spillThresholdSLM : spillThresholdNoSLM;
    }

    bool ComputeShaderContext::CheckSLMLimit(SIMDMode simdMode)
    {
        // check if SLM fits in DSS
        if (IGC_IS_FLAG_ENABLED(CheckCSSLMLimit) &&
            getModuleMetaData()->csInfo.waveSize == 0 &&
            platform.isProductChildOf(IGFX_DG2) &&
            m_DriverInfo.SupportCSSLMLimit() &&
            m_slmSize > 0)
        {
            unsigned int slmPerDSS = 0; // in kB
            switch (simdMode)
            {
                // # Unfused EU = 16
                // # HW threads/EU = 8
                // SIMD16: 16*8*16 = 2048 pixelsPerDSS
                // SIMD32: 16*8*32 = 4096 pixelsPerDSS
                //
                // To calculate SLM/DSS in kB
                // ThreadGroupSize (TGSize) is # pixels in Thread Group
                // (m_slmSize * pixelsPerDSS / TGSize) / 1024
            case SIMDMode::SIMD8:
                slmPerDSS = m_slmSize / GetThreadGroupSize();
                break;
            case SIMDMode::SIMD16:
                slmPerDSS = m_slmSize * 2 / GetThreadGroupSize();
                break;
            case SIMDMode::SIMD32:
                slmPerDSS = m_slmSize * 4 / GetThreadGroupSize();
                break;
            default:
                break;
            }

            unsigned int slmPerDSS_limit = 128;

            if (slmPerDSS > slmPerDSS_limit) {
                SetSIMDInfo(SIMD_SKIP_PERF, simdMode, ShaderDispatchMode::NOT_APPLICABLE);
                return false;
            }

        }

        return true;
    }

    bool OpenCLProgramContext::isSPIRV() const
    {
        return isSpirV;
    }

    void OpenCLProgramContext::setAsSPIRV()
    {
        isSpirV = true;
    }

    bool OpenCLProgramContext::needsDivergentBarrierHandling() const {
        return IGC_IS_FLAG_ENABLED(EnableDivergentBarrierWA) ||
               m_InternalOptions.EnableDivergentBarrierHandling;
    }

    float OpenCLProgramContext::getProfilingTimerResolution()
    {
        return m_ProfilingTimerResolution;
    }

    uint32_t OpenCLProgramContext::getNumThreadsPerEU() const
    {
        if (m_Options.IntelRequiredEUThreadCount)
        {
            return m_Options.requiredEUThreadCount;
        }
        if (m_InternalOptions.IntelNumThreadPerEU || m_InternalOptions.Intel256GRFPerThread)
        {
            return m_InternalOptions.numThreadsPerEU;
        }

        return 0;
    }

    uint32_t OpenCLProgramContext::getNumGRFPerThread(bool returnDefault)
    {
        if (platform.supportsStaticRegSharing())
        {
            if (m_InternalOptions.Intel128GRFPerThread)
            {
                return 128;
            }
            else if (m_InternalOptions.Intel256GRFPerThread)
            {
                return 256;
            }
        }
        return CodeGenContext::getNumGRFPerThread(returnDefault);
    }

    bool OpenCLProgramContext::forceGlobalMemoryAllocation() const
    {
        return m_InternalOptions.ForceGlobalMemoryAllocation ||
               (m_hasGlobalInPrivateAddressSpace && IGC_IS_FLAG_ENABLED(EnableZEBinary));
    }

    bool OpenCLProgramContext::allocatePrivateAsGlobalBuffer() const
    {
        return forceGlobalMemoryAllocation() ||
            (m_instrTypes.hasDynamicGenericLoadStore &&
                platform.canForcePrivateToGlobal());
    }

    bool OpenCLProgramContext::noLocalToGenericOptionEnabled() const
    {
        return m_InternalOptions.NoLocalToGeneric;
    }

    bool OpenCLProgramContext::enableTakeGlobalAddress() const
    {
        return m_Options.EnableTakeGlobalAddress || getModuleMetaData()->capabilities.globalVariableDecorationsINTEL;
    }

    int16_t OpenCLProgramContext::getVectorCoalescingControl() const
    {
        // cmdline option > registry key
        int val = m_InternalOptions.VectorCoalescingControl;
        if (val < 0)
        {
            // no cmdline option
            val = IGC_GET_FLAG_VALUE(VATemp);
        }
        return val;
    }

    uint32_t OpenCLProgramContext::getPrivateMemoryMinimalSizePerThread() const
    {
        return m_InternalOptions.IntelPrivateMemoryMinimalSizePerThread;
    }

    uint32_t OpenCLProgramContext::getIntelScratchSpacePrivateMemoryMinimalSizePerThread() const
    {
        return m_InternalOptions.IntelScratchSpacePrivateMemoryMinimalSizePerThread;
    }

    void OpenCLProgramContext::failOnSpills()
    {
        if (!m_InternalOptions.FailOnSpill)
        {
            return;
        }
        // If there is fail-on-spill option provided
        // and __attribute__((annotate("igc-do-not-spill"))) is present for a kernel,
        // we fail compilation
        auto& programList = m_programOutput.m_ShaderProgramList;
        for (auto& kernel : programList)
        {
            for (auto mode : { SIMDMode::SIMD8, SIMDMode::SIMD16, SIMDMode::SIMD32 })
            {
                COpenCLKernel* shader = static_cast<COpenCLKernel*>(kernel->GetShader(mode));

                if (!COpenCLKernel::IsValidShader(shader))
                {
                    continue;
                }

                auto& funcMD = modMD->FuncMD[shader->entry];
                auto& annotatnions = funcMD.UserAnnotations;
                auto output = shader->ProgramOutput();

                if (output->m_scratchSpaceUsedBySpills > 0 &&
                    std::find(annotatnions.begin(), annotatnions.end(), "igc-do-not-spill") != annotatnions.end())
                {
                    std::string msg =
                        "Spills detected in kernel: "
                        + shader->m_kernelInfo.m_kernelName;
                    EmitError(msg.c_str(), nullptr);
                }
            }
        }
    }

    void OpenCLProgramContext::InternalOptions::parseOptions(const char* IntOptStr)
    {
        // Assume flags is in the form: <f0>[=<v0>] <f1>[=<v1>] ...
        // flag name and its value are either seperated by one or many ' ' or a single '='.
        // A flag seperator between two flags is always one or many ' '.
        const char* NAMESEP = " =";  // separator b/w name and its value

        llvm::StringRef opts(IntOptStr);
        size_t Pos = 0;
        while (Pos != llvm::StringRef::npos)
        {
            // Get a flag name
            Pos = opts.find_first_not_of(' ', Pos);
            if (Pos == llvm::StringRef::npos)
                continue;

            size_t ePos = opts.find_first_of(NAMESEP, Pos);
            llvm::StringRef flagName = opts.substr(Pos, ePos - Pos);

            // Build options:  -cl-intel-xxxx, -ze-intel-xxxx, -ze-opt-xxxx
            //                 -cl-xxxx, -ze-xxxx
            // Both cl version and ze version means the same thing.
            // Here, strip off common prefix.
            size_t prefix_len;
            if (flagName.startswith("-cl-intel") || flagName.startswith("-ze-intel"))
            {
                prefix_len = 9;
            }
            else if (flagName.startswith("-ze-opt"))
            {
                prefix_len = 7;
            }
            else if (flagName.startswith("-cl") || flagName.startswith("-ze"))
            {
                prefix_len = 3;
            }
            else
            {
                // not a valid flag, skip
                Pos = opts.find_first_of(' ', Pos);
                continue;
            }

            llvm::StringRef suffix = flagName.drop_front(prefix_len);
            if (suffix.equals("-replace-global-offsets-by-zero"))
            {
                replaceGlobalOffsetsByZero = true;
            }
            else if (suffix.equals("-kernel-debug-enable"))
            {
                KernelDebugEnable = true;
            }
            else if (suffix.equals("-include-sip-csr"))
            {
                IncludeSIPCSR = true;
            }
            else if (suffix.equals("-include-sip-kernel-debug"))
            {
                IncludeSIPKernelDebug = true;
            }
            else if (suffix.equals("-include-sip-kernel-local-debug"))
            {
                IncludeSIPKernelDebugWithLocalMemory = true;
            }
            else if (suffix.equals("-use-32bit-ptr-arith"))
            {
                Use32BitPtrArith = true;
            }

            // -cl-intel-greater-than-4GB-buffer-required, -ze-opt-greater-than-4GB-buffer-required
            else if (suffix.equals("-greater-than-4GB-buffer-required"))
            {
                IntelGreaterThan4GBBufferRequired = true;
            }

            // -cl-intel-has-buffer-offset-arg, -ze-opt-has-buffer-offset-arg
            else if (suffix.equals("-has-buffer-offset-arg"))
            {
                IntelHasBufferOffsetArg = true;
            }

            // -cl-intel-buffer-offset-arg-required, -ze-opt-buffer-offset-arg-required
            else if (suffix.equals("-buffer-offset-arg-required"))
            {
                IntelBufferOffsetArgOptional = false;
            }

            // -cl-intel-has-positive-pointer-offset, -ze-opt-has-positive-pointer-offset
            else if (suffix.equals("-has-positive-pointer-offset"))
            {
                IntelHasPositivePointerOffset = true;
            }

            // -cl-intel-has-subDW-aligned-ptr-arg, -ze-opt-has-subDW-aligned-ptr-arg
            else if (suffix.equals("-has-subDW-aligned-ptr-arg"))
            {
                IntelHasSubDWAlignedPtrArg = true;
            }

            // -cl-intel-disable-a64WA
            else if (suffix.equals("-disable-a64WA"))
            {
                IntelDisableA64WA = true;
            }

            // -cl-intel-force-enable-a64WA
            else if (suffix.equals("-force-enable-a64WA"))
            {
                IntelForceEnableA64WA = true;
            }

            // GTPin flags used by L0 driver runtime
            // -cl-intel-gtpin-rera
            else if (suffix.equals("-gtpin-rera"))
            {
                GTPinReRA = true;
            }
            else if (suffix.equals("-gtpin-grf-info"))
            {
                GTPinGRFInfo = true;
            }
            else if (suffix.equals("-gtpin-scratch-area-size"))
            {
                GTPinScratchAreaSize = true;
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);
                if (valStr.getAsInteger(10, GTPinScratchAreaSizeValue))
                {
                    IGC_ASSERT(0);
                }
                Pos = valEnd;
                continue;
            }
            else if (suffix.equals("-gtpin-indir-ref"))
            {
                GTPinIndirRef = true;
            }

            // -cl-intel-no-prera-scheduling
            else if (suffix.equals("-no-prera-scheduling"))
            {
                IntelEnablePreRAScheduling = false;
            }
            // -cl-intel-no-local-to-generic
            else if (suffix.equals("-no-local-to-generic"))
            {
                NoLocalToGeneric = true;
            }
            // -cl-intel-force-global-mem-allocation
            else if (suffix.equals("-force-global-mem-allocation"))
            {
                ForceGlobalMemoryAllocation = true;
            }

            //
            // Options to set the number of GRF and threads
            // (All start with -cl-intel or -ze-opt)
            else if (suffix.equals("-128-GRF-per-thread"))
            {
                Intel128GRFPerThread = true;
                numThreadsPerEU = 8;
            }
            else if (suffix.equals("-256-GRF-per-thread") ||
                suffix.equals("-large-register-file"))
            {
                Intel256GRFPerThread = true;
                numThreadsPerEU = 4;
            }
            else if (suffix.equals("-num-thread-per-eu"))
            {
                IntelNumThreadPerEU = true;

                // Take an integer value after this option:
                //   <flag> <number>
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);
                if (valStr.getAsInteger(10, numThreadsPerEU))
                {
                    IGC_ASSERT(0);
                }
                Pos = valEnd;
                continue;
            }
            else if (suffix.equals("-large-grf-kernel"))
            {
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);

                LargeGRFKernels.push_back(valStr.str());
                Pos = valEnd;
                continue;
            }
            else if (suffix.equals("-regular-grf-kernel"))
            {
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);

                RegularGRFKernels.push_back(valStr.str());
                Pos = valEnd;
                continue;
            }
            // -cl-intel-force-emu-int32divrem
            else if (suffix.equals("-force-emu-int32divrem"))
            {
                IntelForceInt32DivRemEmu = true;
            }
            // -cl-intel-force-emu-sp-int32divrem
            else if (suffix.equals("-force-emu-sp-int32divrem"))
            {
                IntelForceInt32DivRemEmuSP = true;
            }
            // -cl-intel-force-disable-4GB-buffer
            else if (suffix.equals("-force-disable-4GB-buffer"))
            {
                IntelForceDisable4GBBuffer = true;
            }
            // -cl-intel-use-bindless-buffers
            else if (suffix.equals("-use-bindless-buffers"))
            {
                PromoteStatelessToBindless = true;
            }
            // -cl-intel-use-bindless-images
            else if (suffix.equals("-use-bindless-images"))
            {
                PreferBindlessImages = true;
            }
            // -cl-intel-use-bindless-mode
            else if (suffix.equals("-use-bindless-mode"))
            {
                // This is a new option that combines bindless generation for buffers
                // and images. Keep the old internal options to have compatibility
                // for existing tests. Those (old) options could be removed in future.
                UseBindlessMode = true;
                PreferBindlessImages = true;
                PromoteStatelessToBindless = true;
            }
            // -cl-intel-use-bindless-printf
            else if (suffix.equals("-use-bindless-printf"))
            {
                UseBindlessPrintf = true;
            }
            // -cl-intel-use-bindless-legacy-mode
            else if (suffix.equals("-use-bindless-legacy-mode"))
            {
                UseBindlessLegacyMode = true;
            }
            // -cl-intel-use-bindless-advanced-mode
            else if (suffix.equals("-use-bindless-advanced-mode"))
            {
                UseBindlessLegacyMode = false;
            }
            // -cl-intel-vector-coalesing
            else if (suffix.equals("-vector-coalescing"))
            {
                // -cl-intel-vector-coalescing=<0-5>.
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);

                int16_t val = 0;
                if (valStr.getAsInteger(10, val))
                {
                    IGC_ASSERT_MESSAGE(false, "-cl-intel-vector-coalescing: invalid value, ignored!");
                }
                else if (val >= 0 && val <= 5)
                {
                    VectorCoalescingControl = val;
                }
                Pos = valEnd;
                continue;
            }
            // -cl-allow-zebin
            else if (suffix.equals("-allow-zebin"))
            {
                if (!IGC_IS_FLAG_SET(EnableZEBinary))
                {
                    IGC_SET_FLAG_VALUE(EnableZEBinary, true);
                }
            }
            // -cl-disable-zebin
            else if (suffix.equals("-disable-zebin"))
            {
                if (!IGC_IS_FLAG_SET(EnableZEBinary))
                {
                    IGC_SET_FLAG_VALUE(EnableZEBinary, false);
                }
            }
            // -cl-intel-exclude-ir-from-zebin
            else if (suffix.equals("-exclude-ir-from-zebin"))
            {
                ExcludeIRFromZEBinary = true;
            }
            else if (suffix.equals("-emit-zebin-visa-sections"))
            {
                EmitZeBinVISASections = true;
            }
            // -cl-intel-no-spill
            else if (suffix.equals("-no-spill"))
            {
                // This is an option to avoid spill/fill instructions in scheduler kernel.
                // OpenCL Runtime triggers scheduler kernel offline compilation while driver building,
                // since scratch space is not supported in this specific case, we cannot end up with
                // spilling kernel. If this option is set, then IGC will recompile the kernel with
                // some some optimizations disabled to avoid spill/fill instructions.
                NoSpill = true;
            }
            // -cl-intel-disable-noMaskWA, -ze-intel-disable-noMaskWA
            else if (suffix.equals("-disable-noMaskWA"))
            {
                DisableNoMaskWA = true;
            }
            // -cl-intel-ignoreBFRounding, -ze-intel-ignoreBFRounding
            else if (suffix.equals("-ignoreBFRounding"))
            {
                IgnoreBFRounding = true;
            }
            // -cl-compile-one-at-time
            else if (suffix.equals("-compile-one-at-time"))
            {
                CompileOneKernelAtTime = true;
            }
            // -cl-skip-reloc-add
            else if (suffix.equals("-skip-reloc-add"))
            {
                AllowRelocAdd = false;
            }
            // -cl-intel-disableEUFusion
            // -ze-intel-disableEUFusion
            else if (suffix.equals("-disableEUFusion"))
            {
                DisableEUFusion = true;
            }
            // -cl-intel-functonControl [<n>]
            // -ze-intel-functionControl [<n>]
            else if (suffix.equals("-functionControl"))
            {
                int val = 0;
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);
                if (valStr.getAsInteger(10, val))
                {
                    IGC_ASSERT(0);
                }
                if (val >= 0)
                {
                    FunctionControl = val;
                }
                Pos = valEnd;
            }
            else if (suffix.equals("-fail-on-spill"))
            {
                FailOnSpill = true;
            }
            // -[cl|ze]-load-cache-default[=| ]<positive int>
            // -[cl|ze]-store-cache-default[=| ]<positive int>
            else if (suffix.equals("-load-cache-default") || suffix.equals("-store-cache-default"))
            {
                bool isLoad = suffix.equals("-load-cache-default");
                int val = 0;
                size_t valStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valEnd = opts.find_first_of(' ', valStart);
                llvm::StringRef valStr = opts.substr(valStart, valEnd - valStart);
                if (valStr.getAsInteger(10, val))
                {
                    IGC_ASSERT(0);
                }
                if (val >= 0)
                {
                    if (isLoad)
                        LoadCacheDefault = val;
                    else
                        StoreCacheDefault = val;
                }
                Pos = valEnd;
            }
            // -cl-poison-unsupported-fp64-kernels
            // -ze-poison-unsupported-fp64-kernels
            else if (suffix.equals("-poison-unsupported-fp64-kernels"))
            {
                // This option forces IGC to poison kernels using fp64
                // operations on platforms without HW support for fp64.
                EnableUnsupportedFP64Poisoning = true;
            }
            // *-private-memory-minimal-size-per-thread <SIZE>
            // SIZE >= 0
            else if (suffix.equals("-private-memory-minimal-size-per-thread"))
            {
                size_t valueStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valueEnd = opts.find_first_of(' ', valueStart);
                llvm::StringRef valueString = opts.substr(valueStart, valueEnd - valueStart);

                IntelPrivateMemoryMinimalSizePerThread = 0;
                if (valueString.getAsInteger(10, IntelPrivateMemoryMinimalSizePerThread))
                {
                    IGC_ASSERT(0);
                }
                Pos = valueEnd;
                continue;
            }
            // *-scratch-space-private-memory-minimal-size-per-thread <SIZE>
            // SIZE >= 0
            else if (suffix.equals("-scratch-space-private-memory-minimal-size-per-thread"))
            {
                size_t valueStart = opts.find_first_not_of(' ', ePos + 1);
                size_t valueEnd = opts.find_first_of(' ', valueStart);
                llvm::StringRef valueString = opts.substr(valueStart, valueEnd - valueStart);

                IntelScratchSpacePrivateMemoryMinimalSizePerThread = 0;
                if (valueString.getAsInteger(10, IntelScratchSpacePrivateMemoryMinimalSizePerThread))
                {
                    IGC_ASSERT(0);
                }
                Pos = valueEnd;
                continue;
            }
            else if (suffix.equals("-enable-divergent-barrier-handling"))
            {
                EnableDivergentBarrierHandling = true;
            }
            // -cl-intel-high-accuracy-nolut-math
            else if (suffix.equals("-high-accuracy-nolut-math"))
            {
                UseHighAccuracyMathFuncs = true;
            }

            // advance to the next flag
            Pos = opts.find_first_of(' ', Pos);
        }
        if (IntelForceDisable4GBBuffer)
        {
            IntelGreaterThan4GBBufferRequired = false;
        }
    }

    void CodeGenContext::initLLVMContextWrapper(bool createResourceDimTypes)
    {
        llvmCtxWrapper = new LLVMContextWrapper(createResourceDimTypes);
        llvmCtxWrapper->AddRef();
    }

    llvm::LLVMContext* CodeGenContext::getLLVMContext() const {
        return llvmCtxWrapper;
    }

    IGC::IGCMD::MetaDataUtils* CodeGenContext::getMetaDataUtils() const
    {
        IGC_ASSERT_MESSAGE(nullptr != m_pMdUtils, "Metadata Utils is not initialized");
        return m_pMdUtils;
    }

    IGCLLVM::Module* CodeGenContext::getModule() const { return module; }

    static void initCompOptionFromRegkey(CodeGenContext* ctx)
    {
        SetCurrentDebugHash(ctx->hash);

        CompOptions& opt = ctx->getModuleMetaData()->compOpt;

        opt.pixelShaderDoNotAbortOnSpill =
            IGC_IS_FLAG_ENABLED(PixelShaderDoNotAbortOnSpill);
        opt.forcePixelShaderSIMDMode =
            IGC_GET_FLAG_VALUE(ForcePixelShaderSIMDMode);
    }

    void CodeGenContext::setModule(llvm::Module* m)
    {
        module = (IGCLLVM::Module*)m;
        m_pMdUtils = new IGC::IGCMD::MetaDataUtils(m);
        modMD = new IGC::ModuleMetaData();
        initCompOptionFromRegkey(this);
    }

    // Several clients explicitly delete module without resetting module to null.
    // This causes the issue later when the dtor is invoked (trying to delete a
    // dangling pointer again). This function is used to replace any explicit
    // delete in order to prevent deleting dangling pointers happening.
    void CodeGenContext::deleteModule()
    {
        delete m_pMdUtils;
        delete modMD;
        delete module;
        m_pMdUtils = nullptr;
        modMD = nullptr;
        module = nullptr;
        delete annotater;
        annotater = nullptr;
    }

    IGC::ModuleMetaData* CodeGenContext::getModuleMetaData() const
    {
        IGC_ASSERT_MESSAGE(nullptr != modMD, "Module Metadata is not initialized");
        return modMD;
    }

    unsigned int CodeGenContext::getRegisterPointerSizeInBits(unsigned int AS) const
    {
        unsigned int pointerSizeInRegister = 32;
        switch (AS)
        {
        case ADDRESS_SPACE_GLOBAL:
        case ADDRESS_SPACE_CONSTANT:
        case ADDRESS_SPACE_GENERIC:
        case ADDRESS_SPACE_GLOBAL_OR_PRIVATE:
            pointerSizeInRegister =
                getModule()->getDataLayout().getPointerSizeInBits(AS);
            break;
        case ADDRESS_SPACE_LOCAL:
        case ADDRESS_SPACE_THREAD_ARG:
            pointerSizeInRegister = 32;
            break;
        case ADDRESS_SPACE_PRIVATE:
            if (getModuleMetaData()->compOpt.UseScratchSpacePrivateMemory)
            {
                pointerSizeInRegister = 32;
            }
            else
            {
                pointerSizeInRegister = ((type == ShaderType::OPENCL_SHADER) ?
                    getModule()->getDataLayout().getPointerSizeInBits(AS) : 64);
            }
            break;
        default:
            {
                pointerSizeInRegister = 32;
            }
            break;
        }
        return pointerSizeInRegister;
    }

    bool CodeGenContext::enableFunctionCall() const
    {
        return (m_enableSubroutine || m_enableFunctionPointer);
    }

    /// Check for user functions in the module and enable the m_enableSubroutine flag if exists
    void CodeGenContext::CheckEnableSubroutine(llvm::Module& M)
    {
        bool EnableSubroutine = false;
        bool EnableStackFuncs = false;
        for (auto& F : M)
        {
            if (F.isDeclaration() ||
                F.use_empty() ||
                isEntryFunc(getMetaDataUtils(), &F))
            {
                continue;
            }

            if (F.hasFnAttribute("KMPLOCK") ||
                F.hasFnAttribute(llvm::Attribute::NoInline) ||
                !F.hasFnAttribute(llvm::Attribute::AlwaysInline))
            {
                EnableSubroutine = true;
                if (F.hasFnAttribute("visaStackCall") && !F.user_empty())
                {
                    EnableStackFuncs = true;
                }
            }
        }
        m_enableSubroutine = EnableSubroutine;
        m_hasStackCalls = EnableStackFuncs;
    }

    void CodeGenContext::InitVarMetaData() {}

    CodeGenContext::~CodeGenContext()
    {
        clear();
    }


    void CodeGenContext::clear()
    {
        m_enableSubroutine = false;
        m_enableFunctionPointer = false;

        delete modMD;
        delete m_pMdUtils;
        modMD = nullptr;
        m_pMdUtils = nullptr;

        delete module;
        llvmCtxWrapper->Release();
        module = nullptr;
        llvmCtxWrapper = nullptr;
    }

    void CodeGenContext::clearMD()
    {
        delete modMD;
        delete m_pMdUtils;
        modMD = nullptr;
        m_pMdUtils = nullptr;
    }

    static const llvm::Function *getRelatedFunction(const llvm::Value *value)
    {
        if (value == nullptr)
            return nullptr;

        if (const llvm::Function *F = llvm::dyn_cast<llvm::Function>(value)) {
            return F;
        }
        if (const llvm::Argument *A = llvm::dyn_cast<llvm::Argument>(value)) {
            return A->getParent();
        }
        if (const llvm::BasicBlock *BB = llvm::dyn_cast<llvm::BasicBlock>(value)) {
            return BB->getParent();
        }
        if (const llvm::Instruction *I = llvm::dyn_cast<llvm::Instruction>(value)) {
            return I->getParent()->getParent();
        }

        return nullptr;
    }

    static bool isEntryPoint(const CodeGenContext *ctx, const llvm::Function *F)
    {
        if (F == nullptr) {
            return false;
        }

        auto& FuncMD = ctx->getModuleMetaData()->FuncMD;
        auto FuncInfo = FuncMD.find(const_cast<llvm::Function *>(F));
        if (FuncInfo == FuncMD.end()) {
            return false;
        }

        const FunctionMetaData* MD = &FuncInfo->second;
        return MD->functionType == KernelFunction;
    }

    static void findCallingKernels
        (const CodeGenContext *ctx, const llvm::Function *F, llvm::SmallPtrSetImpl<const llvm::Function *> &kernels)
    {
        if (F == nullptr || kernels.count(F))
            return;

        for (const llvm::User *U : F->users()) {
            auto *CI = llvm::dyn_cast<llvm::CallInst>(U);
            if (CI == nullptr)
                continue;

            if (CI->getCalledFunction() != F)
                continue;

            const llvm::Function *caller = getRelatedFunction(CI);
            if (isEntryPoint(ctx, caller)) {
                kernels.insert(caller);
                continue;
            }
            // Caller is not a kernel, try to check which kerneles might
            // be calling it:
            findCallingKernels(ctx, caller, kernels);
        }
    }

    static bool handleOpenMPDemangling(const std::string &name, std::string *strippedName) {
        // OpenMP mangled names have following structure:
        //
        // __omp_offloading_DD_FFFF_PP_lBB
        //
        // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
        // mangled name of the function that encloses the target region and BB is the
        // line number of the target region.
        if (name.rfind("__omp_offloading_", 0) != 0) {
            return false;
        }
        size_t offset = sizeof "__omp_offloading_";
        offset = name.find('_', offset + 1); // Find end of DD.
        if (offset == std::string::npos)
            return false;
        offset = name.find('_', offset + 1); // Find end of FFFF.
        if (offset == std::string::npos)
            return false;

        const size_t start = offset + 1;
        const size_t end = name.rfind('_'); // Find beginning of lBB.
        if (end == std::string::npos)
            return false;

        *strippedName = name.substr(start, end - start);
        return true;
    }

    bool CodeGenContext::HasFuncExpensiveLoop(llvm::Function* pFunc)
    {
        if (m_FuncHasExpensiveLoops.find(pFunc) !=
            m_FuncHasExpensiveLoops.end())
        {
            return m_FuncHasExpensiveLoops[pFunc];
        }
        return false;
    }


    static std::string demangleFuncName(const std::string &rawName) {
        // OpenMP adds additional prefix and suffix to the mangling scheme,
        // remove it if present.
        std::string name;
        if (!handleOpenMPDemangling(rawName, &name)) {
            // If OpenMP demangling didn't succeed just proceed with received
            // symbol name
            name = rawName;
        }
#if LLVM_VERSION_MAJOR >= 10
        return llvm::demangle(name);
#else
        char *demangled = nullptr;

        demangled = llvm::itaniumDemangle(name.c_str(), nullptr, nullptr, nullptr);
        if (demangled == nullptr) {
            demangled = llvm::microsoftDemangle(name.c_str(), nullptr, nullptr, nullptr);
        }

        if (demangled == nullptr) {
            return name;
        }

        std::string result = demangled;
        std::free(demangled);
        return result;
#endif
    }

    void CodeGenContext::EmitError(std::ostream &OS, const char* errorstr, const llvm::Value* context) const
    {
        OS << "\nerror: ";
        OS << errorstr;
        // Try to get debug location to print out the relevant info.
        if (const llvm::Instruction *I = llvm::dyn_cast_or_null<llvm::Instruction>(context)) {
            if (const llvm::DILocation *DL = I->getDebugLoc()) {
                OS << "\nin file: " << DL->getFilename().str() << ":" << DL->getLine() << "\n";
            }
        }
        // Try to find function related to given context
        // to print more informative error message.
        if (const llvm::Function *F = getRelatedFunction(context)) {
            // If the function is a kernel just print the kernel name.
            if (isEntryPoint(this, F)) {
                OS << "\nin kernel: '" << demangleFuncName(std::string(F->getName())) << "'";
            // If the function is not a kernel try to print all kernels that
            // might be using this function.
            } else {
                llvm::SmallPtrSet<const llvm::Function *, 16> kernels;
                findCallingKernels(this, F, kernels);

                const size_t kernelsCount = kernels.size();
                OS << "\nin function: '" << demangleFuncName(std::string(F->getName())) << "' ";
                if (kernelsCount == 0) {
                    OS << "called indirectly by at least one of the kernels.\n";
                } else if (kernelsCount == 1) {
                    const llvm::Function *kernel = *kernels.begin();
                    OS << "called by kernel: '" << demangleFuncName(std::string(kernel->getName())) << "'\n";
                } else {
                    OS << "called by kernels:\n";
                    for (const llvm::Function *kernel : kernels) {
                        OS << "  - '" << demangleFuncName(std::string(kernel->getName())) << "'\n";
                    }
                }
            }
        }
        OS << "\nerror: backend compiler failed build.\n";
    }

    void CodeGenContext::EmitError(const char* errorstr, const llvm::Value *context)
    {
        EmitError(this->oclErrorMessage, errorstr, context);
    }

    void CodeGenContext::EmitWarning(const char* warningstr)
    {
        this->oclWarningMessage << "\nwarning: ";
        this->oclWarningMessage << warningstr;
        this->oclWarningMessage << "\n";
    }

    CompOptions& CodeGenContext::getCompilerOption()
    {
        return getModuleMetaData()->compOpt;
    }

    void CodeGenContext::resetOnRetry()
    {
        m_tempCount = 0;
    }

    uint32_t CodeGenContext::getNumThreadsPerEU() const
    {
        return 0;
    }

    /// parameter "returnDefault" controls what to return when
    /// there is no user-forced setting
    uint32_t CodeGenContext::getNumGRFPerThread(bool returnDefault)
    {
        constexpr uint32_t DEFAULT_TOTAL_GRF_NUM = 128;

        if (m_NumGRFPerThread)
            return m_NumGRFPerThread;

        if (IGC_GET_FLAG_VALUE(TotalGRFNum) != 0)
        {
            m_NumGRFPerThread = IGC_GET_FLAG_VALUE(TotalGRFNum);
            return m_NumGRFPerThread;
        }
        if (getModuleMetaData()->csInfo.forceTotalGRFNum != 0)
        {
            {
                m_NumGRFPerThread = getModuleMetaData()->csInfo.forceTotalGRFNum;
                return m_NumGRFPerThread;
            }
        }
        if (hasSyncRTCalls() && IGC_GET_FLAG_VALUE(TotalGRFNum4RQ) != 0)
        {
            m_NumGRFPerThread = IGC_GET_FLAG_VALUE(TotalGRFNum4RQ);
            return m_NumGRFPerThread;
        }
        if (this->type == ShaderType::COMPUTE_SHADER && IGC_GET_FLAG_VALUE(TotalGRFNum4CS) != 0)
        {
            m_NumGRFPerThread = IGC_GET_FLAG_VALUE(TotalGRFNum4CS);
            return m_NumGRFPerThread;
        }
        return (returnDefault ? DEFAULT_TOTAL_GRF_NUM : 0);
    }

    bool CodeGenContext::forceGlobalMemoryAllocation() const
    {
        return false;
    }

    bool CodeGenContext::allocatePrivateAsGlobalBuffer() const
    {
        return false;
    }

    bool CodeGenContext::noLocalToGenericOptionEnabled() const
    {
        return false;
    }

    bool CodeGenContext::enableTakeGlobalAddress() const
    {
        return false;
    }

    int16_t CodeGenContext::getVectorCoalescingControl() const
    {
        return 0;
    }

    uint32_t CodeGenContext::getPrivateMemoryMinimalSizePerThread() const
    {
        return 0;
    }

    uint32_t CodeGenContext::getIntelScratchSpacePrivateMemoryMinimalSizePerThread() const
    {
        return 0;
    }

    bool CodeGenContext::isPOSH() const
    {
        return this->getModule()->getModuleFlag(
            "IGC::PositionOnlyVertexShader") != nullptr;
    }

    void CodeGenContext::setFlagsPerCtx()
    {
        if (m_DriverInfo.DessaAliasLevel() != -1) {
            if ((int)IGC_GET_FLAG_VALUE(EnableDeSSAAlias) > m_DriverInfo.DessaAliasLevel())
            {
                IGC_SET_FLAG_VALUE(EnableDeSSAAlias, m_DriverInfo.DessaAliasLevel());
            }
        }
    }

    void CodeGenContext::createFunctionIDs()
    {
        // Assign a unique ID for each entry function.
        if (IGC_IS_FLAG_ENABLED(DumpUseShorterName) &&
            m_functionIDs.empty() &&  module != nullptr && m_pMdUtils != nullptr)
        {
            int id = 0;
            for (auto i = m_pMdUtils->begin_FunctionsInfo(), e = m_pMdUtils->end_FunctionsInfo(); i != e; ++i)
            {
                Function* pFunc = i->first;
                // Skip non-entry functions.
                if (!isEntryFunc(m_pMdUtils, pFunc))
                {
                    continue;
                }

                // Use kernel name so that it is created once and will work for both the first and retry.
                StringRef kernelName = pFunc->getName();
                if (!kernelName.empty()) {
                    // entry without name will not be in the map (getFunctionID() will
                    // return 0. Thus, ID here starts from 1.
                    m_functionIDs[kernelName.str()] = ++id;
                }
            }
            m_enableDumpUseShorterName = true;
        }
    }

    int CodeGenContext::getFunctionID(Function* F)
    {
        StringRef kernelName = F->getName();
        auto MI = m_functionIDs.find(kernelName.str());
        if (MI == m_functionIDs.end()) {
            return 0;
        }
        return MI->second;
    }

    unsigned MeshShaderContext::GetThreadGroupSize()
    {
        unsigned int threadGroupSize = ((type == ShaderType::MESH_SHADER) ?
            getModuleMetaData()->msInfo.WorkGroupSize : getModuleMetaData()->taskInfo.WorkGroupSize);

        return threadGroupSize;
    }

    unsigned MeshShaderContext::GetHwThreadPerWorkgroup()
    {
        unsigned hwThreadPerWorkgroup = platform.getMaxNumberHWThreadForEachWG();

        if (platform.supportPooledEU())
        {
            hwThreadPerWorkgroup = platform.getMaxNumberThreadPerWorkgroupPooledMax();
        }
        return hwThreadPerWorkgroup;
    }

    unsigned int MeshShaderContext::GetSlmSize() const
    {
        unsigned int slmSize = ((type == ShaderType::MESH_SHADER) ?
            getModuleMetaData()->msInfo.WorkGroupMemorySizeInBytes :
            getModuleMetaData()->taskInfo.WorkGroupMemorySizeInBytes);
        return slmSize;
    }

    // Use compute shader thresholds.
    float MeshShaderContext::GetSpillThreshold() const
    {
        float spillThresholdSLM =
            float(IGC_GET_FLAG_VALUE(CSSpillThresholdSLM)) / 100.0f;
        float spillThresholdNoSLM =
            float(IGC_GET_FLAG_VALUE(CSSpillThresholdNoSLM)) / 100.0f;
        return GetSlmSize() > 0 ? spillThresholdSLM : spillThresholdNoSLM;
    }

    // Calculates thread occupancy for given simd size.
    float MeshShaderContext::GetThreadOccupancy(SIMDMode simdMode)
    {
        return GetThreadOccupancyPerSubslice(
            simdMode,
            GetThreadGroupSize(),
            GetHwThreadsPerWG(platform),
            GetSlmSize(),
            platform.getSlmSizePerSsOrDss());
    }

    SIMDMode MeshShaderContext::GetLeastSIMDModeAllowed()
    {
        unsigned threadGroupSize = GetThreadGroupSize();
        unsigned hwThreadPerWorkgroup = GetHwThreadPerWorkgroup();

        if ((threadGroupSize <= hwThreadPerWorkgroup * 8) &&
            threadGroupSize <= 512)
        {
            return platform.getMinDispatchMode();
        }
        else
        {
            if (threadGroupSize <= hwThreadPerWorkgroup * 16)
            {
                return SIMDMode::SIMD16;
            }
            else
            {
                return SIMDMode::SIMD32;
            }
        }
    }

    SIMDMode MeshShaderContext::GetMaxSIMDMode()
    {
        unsigned threadGroupSize = GetThreadGroupSize();

        if (threadGroupSize <= 8)
        {
            return platform.getMinDispatchMode();
        }
        else if (threadGroupSize <= 16)
        {
            return SIMDMode::SIMD16;
        }
        else
        {
            return SIMDMode::SIMD32;
        }
    }

    SIMDMode MeshShaderContext::GetBestSIMDMode()
    {
        const SIMDMode minMode = GetLeastSIMDModeAllowed();
        const SIMDMode maxMode = GetMaxSIMDMode();

        SIMDMode bestMode = SIMDMode::SIMD16;

        if (bestMode < minMode)
        {
            bestMode = minMode;
        }

        if (bestMode > maxMode)
        {
            bestMode = maxMode;
        }

        return bestMode;
    }

    void RayDispatchShaderContext::setShaderHash(llvm::Function* F) const
    {
        auto* MD = getModuleMetaData();
        auto I = MD->FuncMD.find(F);
        if (I == MD->FuncMD.end())
            return;

        auto& rtInfo = I->second.rtInfo;
        StringRef Name = F->getName();

        uint64_t Hashes[] = {
            BitcodeHash,
            iSTD::HashFromBuffer(Name.data(), Name.size())
        };

        rtInfo.ShaderHash = iSTD::Hash((DWORD*)Hashes, std::size(Hashes) * 2);
    }

    Optional<RTStackFormat::HIT_GROUP_TYPE> RayDispatchShaderContext::getHitGroupType(
        const std::string &Name) const
    {
        auto I = HitGroupRefs.find(Name);
        if (I == HitGroupRefs.end())
            return None;

        auto &Refs = I->second;
        IGC_ASSERT(!Refs.empty());

        auto HitTy = Refs[0]->Type;

        IGC_ASSERT(llvm::all_of(Refs, [&](auto &HG) { return HG->Type == HitTy; }));

        return HitTy;
    }

    llvm::Optional<SIMDMode> RayDispatchShaderContext::knownSIMDSize() const
    {
        uint32_t ForcedSIMDSize = IGC_GET_FLAG_VALUE(ForceRayTracingSIMDWidth);

        switch (ForcedSIMDSize)
        {
        case 0: // default
            return platform.getPreferredRayTracingSIMDSize();
        case 8:
            return SIMDMode::SIMD8;
        case 16:
            return SIMDMode::SIMD16;
        default:
            IGC_ASSERT_MESSAGE(0, "not an option!");
            return llvm::None;
        }
    }

    bool RayDispatchShaderContext::canEfficientTile() const
    {
        auto canDo = [](uint32_t XDim) {
            return iSTD::IsPowerOfTwo(XDim) && XDim > 1;
        };

        uint32_t XDim1D = opts().TileXDim1D;
        uint32_t XDim2D = opts().TileXDim2D;

        return canDo(XDim1D) && canDo(XDim2D);
    }

    Optional<std::string> RayDispatchShaderContext::getIntersectionAnyHit(
        const std::string& IntersectionName) const
    {
        auto I = HitGroupRefs.find(IntersectionName);
        IGC_ASSERT(I != HitGroupRefs.end());

        auto& Refs = I->second;
        IGC_ASSERT(!Refs.empty());

        auto AnyHit = Refs[0]->AnyHit;

        IGC_ASSERT(llvm::all_of(Refs, [&](auto &HG) { return HG->AnyHit == AnyHit; }));

        return AnyHit;
    }

    const std::vector<HitGroupInfo*>*
    RayDispatchShaderContext::hitgroupRefs(const std::string& Name) const
    {
        auto I = HitGroupRefs.find(Name);
        if (I == HitGroupRefs.end())
            return nullptr;

        auto& Refs = I->second;
        return &Refs;
    }

    const std::vector<HitGroupInfo>&
    RayDispatchShaderContext::hitgroups() const
    {
        return HitGroups;
    }

    void RayDispatchShaderContext::takeHitGroupTable(std::vector<HitGroupInfo>&& Table)
    {
        HitGroupRefs.clear();
        HitGroups = std::move(Table);

        for (auto& HG : HitGroups)
        {
            if (HG.AnyHit)
                HitGroupRefs[*HG.AnyHit].push_back(&HG);
            if (HG.Intersection)
                HitGroupRefs[*HG.Intersection].push_back(&HG);
            if (HG.ClosestHit)
                HitGroupRefs[*HG.ClosestHit].push_back(&HG);
        }
    }

    bool RayDispatchShaderContext::requiresIndirectContinuationHandling() const
    {
        if (IGC_IS_FLAG_ENABLED(EnableInlinedContinuations) &&
            canWholeProgramCompile())
        {
            return false;
        }

        uint32_t Threshold = IGC_GET_FLAG_VALUE(ContinuationInlineThreshold);
        return forcedIndirectContinuations() ||
               !canWholeProgramCompile()     ||
               modMD->rtInfo.NumContinuations > Threshold;
    }

    bool RayDispatchShaderContext::forcedIndirectContinuations() const
    {
        return IGC_IS_FLAG_ENABLED(EnableIndirectContinuations) || forceIndirectContinuations;
    }

    bool RayDispatchShaderContext::canWholeProgramCompile() const
    {
        if (IGC_GET_FLAG_VALUE(ForceWholeProgramCompile))
            return true;

        return canWholeShaderCompile() && canWholeFunctionCompile();
    }

    bool RayDispatchShaderContext::canWholeShaderCompile() const
    {
        if (forceIndirectContinuations)
            return false;

        return config == CompileConfig::IMMUTABLE_RTPSO && !hasPrecompiledObjects;
    }

    bool RayDispatchShaderContext::canWholeFunctionCompile() const
    {
        // This will have more logic once dynamic shader linking is in place.
        return true;
    }

    bool RayDispatchShaderContext::tryPayloadSinking() const
    {
        return pipelineConfig.maxTraceRecursionDepth == 1 &&
               IGC_IS_FLAG_DISABLED(DisablePayloadSinking);
    }

    bool RayDispatchShaderContext::isRTPSO() const
    {
        switch (config)
        {
        case CompileConfig::MUTABLE_RTPSO:
        case CompileConfig::IMMUTABLE_RTPSO:
            return true;
        case CompileConfig::CSO:
            return false;
        }

        return false;
    }

    bool RayDispatchShaderContext::isDispatchAlongY() const
    {
        const bool AlongY =
            m_DriverInfo.supportsRaytracingDispatchComputeWalkerAlongYFirst();
        return opts().DispatchAlongY && AlongY;
    }

    bool RayDispatchShaderContext::doSpillWidening() const
    {
        if (IGC_IS_FLAG_DISABLED(EnableSpillWidening))
            return false;

        // It's easier to just only do this with stateful SWStack so it's easier
        // to find the spills later on.
        auto Offset = getModuleMetaData()->rtInfo.SWStackSurfaceStateOffset;
        return Offset.has_value();
    }

    uint64_t RayDispatchShaderContext::getShaderHash(const CShader* Prog) const
    {
        auto* MD = getModuleMetaData();
        auto I = MD->FuncMD.find(Prog->entry);
        if (I != MD->FuncMD.end())
            return I->second.rtInfo.ShaderHash;
        else
            return 0;
    }

    uint32_t RayDispatchShaderContext::getMissShaderCount() const
    {
        return m_MissShaderCount;
    }

    bool RayDispatchShaderContext::doSyncDispatchRays() const
    {
        if (!opts().UseSyncDispatchRays ||
            pipelineConfig.maxTraceRecursionDepth != 1)
        {
            return false;
        }

        // temporary phase 1 checks
        if (!canWholeProgramCompile() ||
            hitgroups().size() > 1 ||
            getMissShaderCount() > 1)
        {
            return false;
        }

        return true;
    }

}