File: SpillManagerGMRF.cpp

package info (click to toggle)
intel-graphics-compiler2 2.24.13-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 113,504 kB
  • sloc: cpp: 812,849; lisp: 288,219; ansic: 102,423; python: 4,010; yacc: 2,588; lex: 1,666; pascal: 318; sh: 162; makefile: 38
file content (6227 lines) | stat: -rw-r--r-- 237,620 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
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2022 Intel Corporation

SPDX-License-Identifier: MIT

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

#include "SpillManagerGMRF.h"
#include "BuildIR.h"
#include "DebugInfo.h"
#include "FlowGraph.h"
#include "G4_IR.hpp"
#include "GraphColor.h"
#include "PointsToAnalysis.h"

#include <cmath>
#include <unordered_set>

using namespace vISA;

// Configurations

#define ADDRESS_SENSITIVE_SPILLS_IMPLEMENTED
#define SCRATCH_SPACE_ADDRESS_UNIT 5

// #define DISABLE_SPILL_MEMORY_COMPRESSION
// #define VERIFY_SPILL_ASSIGNMENTS

// Constant declarations

static const unsigned DWORD_BYTE_SIZE = 4;
static const unsigned OWORD_BYTE_SIZE = 16;
static const unsigned HWORD_BYTE_SIZE = 32;
static const unsigned PAYLOAD_INPUT_REG_OFFSET = 0;
static const unsigned PAYLOAD_INPUT_SUBREG_OFFSET = 0;
static const unsigned OWORD_PAYLOAD_SPOFFSET_REG_OFFSET = 0;
static const unsigned OWORD_PAYLOAD_SPOFFSET_SUBREG_OFFSET = 2;
static const unsigned DWORD_PAYLOAD_SPOFFSET_REG_OFFSET = 1;
static const unsigned DWORD_PAYLOAD_SPOFFSET_SUBREG_OFFSET = 0;
static const unsigned OWORD_PAYLOAD_WRITE_REG_OFFSET = 1;
static const unsigned OWORD_PAYLOAD_WRITE_SUBREG_OFFSET = 0;
// dword scatter is always in SIMD8 mode
static const unsigned DWORD_PAYLOAD_WRITE_REG_OFFSET = 2;
static const unsigned DWORD_PAYLOAD_WRITE_SUBREG_OFFSET = 0;
static const unsigned OWORD_PAYLOAD_HEADER_MIN_HEIGHT = 1;
static const unsigned DWORD_PAYLOAD_HEADER_MIN_HEIGHT = 2;
static const unsigned OWORD_PAYLOAD_HEADER_MAX_HEIGHT = 1;
static const unsigned DWORD_PAYLOAD_HEADER_MAX_HEIGHT = 3;
static const unsigned DEF_HORIZ_STRIDE = 1;
static const unsigned REG_ORIGIN = 0;
static const unsigned SUBREG_ORIGIN = 0;

static const unsigned SEND_GT_READ_TYPE_BIT_OFFSET = 13;
static const unsigned SEND_GT_WRITE_TYPE_BIT_OFFSET = 13;
static const unsigned SEND_GT_DESC_DATA_SIZE_BIT_OFFSET = 8;
static const unsigned SEND_GT_OW_READ_TYPE = 0;
static const unsigned SEND_GT_OW_WRITE_TYPE = 8;
static const unsigned SEND_GT_SC_READ_TYPE = 6;
static const unsigned SEND_GT_SC_WRITE_TYPE = 11;
static const unsigned SEND_GT_DP_RD_EX_DESC_IMM = 5;
static const unsigned SEND_GT_DP_SC_RD_EX_DESC_IMM =
    4; // scatter reads go to sampler cache
static const unsigned SEND_GT_DP_WR_EX_DESC_IMM = 5;

static const unsigned SEND_IVB_MSG_TYPE_BIT_OFFSET = 14;
static const unsigned SEND_IVB_OW_READ_TYPE = 0;
static const unsigned SEND_IVB_OW_WRITE_TYPE = 8;
static const unsigned SEND_IVB_SC_READ_TYPE = 3;
static const unsigned SEND_IVB_SC_WRITE_TYPE = 11;
static const unsigned SEND_IVB_DP_RD_EX_DESC_IMM = 10; // data cache
static const unsigned SEND_IVB_DP_WR_EX_DESC_IMM = 10; // data cache

// Scratch msg
static const unsigned SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT = 1;
static const unsigned SCRATCH_MSG_DESC_CATEORY = 18;
static const unsigned SCRATCH_MSG_DESC_OPERATION_MODE = 17;
static const unsigned SCRATCH_MSG_DESC_CHANNEL_MODE = 16;
static const unsigned SCRATCH_MSG_INVALIDATE_AFTER_READ = 15;
static const unsigned SCRATCH_MSG_DESC_BLOCK_SIZE = 12;

#define LIMIT_SEND_EXEC_SIZE(EXEC_SIZE) (((EXEC_SIZE) > 16) ? 16 : (EXEC_SIZE))
#define SPILL_PAYLOAD_HEIGHT_LIMIT 4

void splice(G4_BB *bb, INST_LIST_ITER iter, INST_LIST &instList,
            unsigned int CISAOff) {
  // Update CISA offset of all instructions in instList before splicing
  // operation.
  // FIXME: shouldn't we just take the vISA offset of iter? Under what condition
  // do we want to override it?
  for (auto inst : instList) {
    inst->setVISAId(CISAOff);
  }

  bb->splice(iter, instList);
}

// spill/fill temps are always GRF-aligned, and are also even/odd aligned
// following the original declare's alignment
static void setNewDclAlignment(GlobalRA &gra, G4_Declare *newDcl,
                               bool evenAlign) {
  newDcl->setSubRegAlign(gra.builder.getGRFAlign());
  if (evenAlign) {
    newDcl->setEvenAlign();
  }

  gra.setSubRegAlign(newDcl, gra.builder.getGRFAlign());
  gra.setEvenAligned(newDcl, evenAlign);
}

SpillManagerGRF::SpillManagerGRF(
    GlobalRA &g, unsigned spillAreaOffset, const LivenessAnalysis *lvInfo,
    const Interference *intf, const LR_LIST *spilledLRs, bool failSafeSpill,
    unsigned spillRegSize, unsigned indrSpillRegSize,
    bool enableSpillSpaceCompression, bool useScratchMsg)
  : gra(g), builder_(g.kernel.fg.builder), varIdCount_(lvInfo->getNumSelectedVar()),
    latestImplicitVarIdCount_(0),
    lvInfo_(lvInfo), lrInfo_(&g.incRA.getLRs()), spilledLRs_(spilledLRs),
    nextSpillOffset_(spillAreaOffset),
    doSpillSpaceCompression(enableSpillSpaceCompression),
    failSafeSpill_(failSafeSpill), spillIntf_(intf),
    useScratchMsg_(useScratchMsg), refs(g.kernel),
    context(g, &g.incRA.getLRs()) {

  spillAreaOffset_ = spillAreaOffset;
  builder_->instList.clear();
  spillRegStart_ = g.kernel.getNumRegTotal();
  indrSpillRegStart_ = spillRegStart_;
  spillRegOffset_ = spillRegStart_;
  if (failSafeSpill) {
    bool isStackCall = builder_->usesStack();
    unsigned int stackCallRegSize =
        isStackCall ? g.kernel.stackCall.numReservedABIGRF() : 0;
    indrSpillRegStart_ -= (stackCallRegSize + indrSpillRegSize);
    spillRegStart_ = indrSpillRegStart_ - spillRegSize;
  }
  curInst = nullptr;
  globalScratchOffset =
      gra.kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);
  spilledLSLRs_ = nullptr;
  if (builder_->hasScratchSurface()) {
    builder_->initScratchSurfaceOffset();
    auto entryBB = builder_->kernel.fg.getEntryBB();
    auto iter = std::find_if(entryBB->begin(), entryBB->end(),
                             [](G4_INST *inst) { return !inst->isLabel(); });
    splice(entryBB, iter, builder_->instList, UNMAPPABLE_VISA_INDEX);
  }

  if (failSafeSpill_) {
    if (gra.kernel.getOption(vISA_NewFailSafeRA)) {
      unsigned int spaceForPhyGRFSpill =
          BoundedRA::getNumPhyVarSlots(gra.kernel);
      int off = (int)spillAreaOffset;
      getSpillOffset(off);
      unsigned int aligned_off = ROUND(off, builder_->numEltPerGRF<Type_UB>());
      context.setSpillOff(aligned_off);
      vISA_ASSERT(spillAreaOffset_ == nextSpillOffset_, "expecting equality");
      spillAreaOffset_ =
          ROUND(spillAreaOffset_, builder_->numEltPerGRF<Type_UB>());
      spillAreaOffset_ += spaceForPhyGRFSpill;
      vISA_ASSERT(globalScratchOffset + spillAreaOffset_ >=
                      (ROUND(off, builder_->numEltPerGRF<Type_UB>()) +
                       spaceForPhyGRFSpill),
                  "unexpected overlap");
      nextSpillOffset_ = spillAreaOffset_;
      if (gra.getNumReservedGRFs() > 0)
        context.setReservedStart(spillRegStart_);
    }
  }
}

SpillManagerGRF::SpillManagerGRF(GlobalRA &g, unsigned spillAreaOffset,
                                 const LivenessAnalysis *lvInfo,
                                 LSLR_LIST *spilledLSLRs,
                                 bool enableSpillSpaceCompression,
                                 bool useScratchMsg)
  : gra(g), builder_(g.kernel.fg.builder), varIdCount_(lvInfo->getNumSelectedVar()),
    latestImplicitVarIdCount_(0), lvInfo_(lvInfo), lrInfo_(nullptr),
    spilledLSLRs_(spilledLSLRs), nextSpillOffset_(spillAreaOffset),
    doSpillSpaceCompression(enableSpillSpaceCompression),
    failSafeSpill_(false), useScratchMsg_(useScratchMsg), refs(g.kernel),
    context(g) {
  spillAreaOffset_ = spillAreaOffset;
  builder_->instList.clear();
  curInst = nullptr;
  globalScratchOffset =
      gra.kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);

  if (builder_->hasScratchSurface()) {
    builder_->initScratchSurfaceOffset();
    auto entryBB = builder_->kernel.fg.getEntryBB();
    auto iter = std::find_if(entryBB->begin(), entryBB->end(),
                             [](G4_INST *inst) { return !inst->isLabel(); });
    splice(entryBB, iter, builder_->instList, UNMAPPABLE_VISA_INDEX);
  }
}

bool SpillManagerGRF::headerNeeded() const {
  if (useScratchMsg_ && builder_->getPlatform() >= GENX_SKL)
    return false;

  if (builder_->kernel.fg.getHasStackCalls() ||
      builder_->kernel.fg.getIsStackCallFunc())
    return false;

  if (gra.useLscForSpillFill)
    return false;

  return true;
}

// Get the base regvar for the source or destination region.
template <class REGION_TYPE>
G4_RegVar *SpillManagerGRF::getRegVar(REGION_TYPE *region) const {
  G4_RegVar *spilledRegVar = (G4_RegVar *)region->getBase();
  return spilledRegVar;
}

// Obtain the register file type of the regvar.
G4_RegFileKind SpillManagerGRF::getRFType(G4_RegVar *regvar) const {
  return regvar->getDeclare()->getRegFile();
}

// Obtain the register file type of the region.
template <class REGION_TYPE>
G4_RegFileKind SpillManagerGRF::getRFType(REGION_TYPE *region) const {
  if (region->getBase()->isRegVar())
    return getRFType(region->getBase()->asRegVar());
  else if (region->getBase()->isGreg())
    return G4_GRF;
  else
    return G4_ADDRESS;
}

// Get the byte offset of the origin of the source or destination region.
// The row offset component is calculated based on the the parameters of
// the corresponding declare directive, while the column offset is calculated
// based on the region parameters.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getRegionOriginOffset(REGION_TYPE *region) const {
  unsigned rowOffset = builder_->numEltPerGRF<Type_UB>() * region->getRegOff();
  unsigned columnOffset = region->getSubRegOff() * region->getElemSize();
  return rowOffset + columnOffset;
}

// Get a GRF aligned mask
unsigned SpillManagerGRF::grfMask() const {
  unsigned mask = 0;
  mask = (mask - 1);
  vISA_ASSERT(std::log2(builder_->numEltPerGRF<Type_UB>()) ==
                  (float)((int)(std::log2(builder_->numEltPerGRF<Type_UB>()))),
              "expected integral value");
  unsigned int bits =
      (unsigned int)std::log2(builder_->numEltPerGRF<Type_UB>());
  mask = mask << bits;
  return mask;
}

// Get an hex word mask with the lower 5 bits zeroed.
unsigned SpillManagerGRF::hwordMask() const {
  unsigned mask = 0;
  mask = (mask - 1);
  mask = mask << 5;
  return mask;
}

// Get an octal word mask with the lower 4 bits zeroed.
unsigned SpillManagerGRF::owordMask() const {
  unsigned mask = 0;
  mask = (mask - 1);
  mask = mask << 4;
  return mask;
}

// Test of the offset is oword aligned.
bool SpillManagerGRF::owordAligned(unsigned offset) const {
  return (offset & owordMask()) == offset;
}

// Get the ceil of the ratio.
unsigned SpillManagerGRF::cdiv(unsigned dvd, unsigned dvr) {
  return (dvd / dvr) + ((dvd % dvr) ? 1 : 0);
}

// Get the live range corresponding to id.
bool SpillManagerGRF::shouldSpillRegister(G4_RegVar *regVar) const {
  if (getRFType(regVar) == G4_ADDRESS) {
    return false;
  }
  G4_RegVar *actualRegVar =
      (regVar->getDeclare()->getAliasDeclare())
          ? regVar->getDeclare()->getAliasDeclare()->getRegVar()
          : regVar;
  if (actualRegVar->getId() == UNDEFINED_VAL)
    return false;
  else if (regVar->isRegVarTransient() || regVar->isRegVarTmp())
    return false;
#ifndef ADDRESS_SENSITIVE_SPILLS_IMPLEMENTED
  else if (lvInfo_->isAddressSensitive(regVar->getId()))
    return false;
#endif
  else if (builder_->kernel.fg.isPseudoVCADcl(actualRegVar->getDeclare()) ||
           builder_->kernel.fg.isPseudoVCEDcl(actualRegVar->getDeclare()))
    return false;
  else
    return (*lrInfo_)[actualRegVar->getId()]->getPhyReg() == nullptr;
}

// Get the regvar with the id.
G4_RegVar *SpillManagerGRF::getRegVar(unsigned id) const {
  return (lvInfo_->vars)[id];
}

// Get the byte size of the live range.
unsigned SpillManagerGRF::getByteSize(G4_RegVar *regVar) const {
  unsigned normalizedRowSize = (regVar->getDeclare()->getNumRows() > 1)
                                   ? builder_->numEltPerGRF<Type_UB>()
                                   : regVar->getDeclare()->getNumElems() *
                                         regVar->getDeclare()->getElemSize();
  return normalizedRowSize * regVar->getDeclare()->getNumRows();
}

// Return all overlapping variables with dcl. Vector is not sorted
// so order of variables can change across runs.
void SpillManagerGRF::getOverlappingIntervals(
    G4_Declare *dcl, std::vector<G4_Declare *> &intervals) const {
  auto dclMask = gra.getAugmentationMask(dcl);

  // non-default variables have complete interference marked
  if (dclMask == AugmentationMasks::NonDefault)
    return;

  std::unordered_set<G4_Declare *> overlappingDcls;
  auto &allDclIntervals = gra.getAllIntervals(dcl);

  for (auto &dclInterval : allDclIntervals) {
    for (auto *otherDcl : spillingIntervals) {
      if (otherDcl == dcl)
        continue;

      if (dclMask != gra.getAugmentationMask(otherDcl))
        continue;

      auto &otherDclAllIntervals = gra.getAllIntervals(otherDcl);
      for (auto &otherDclInterval : otherDclAllIntervals) {
        if (dclInterval.intervalsOverlap(otherDclInterval)) {
          overlappingDcls.insert(otherDcl);
          break;
        }
      }
    }
  }

  intervals.insert(intervals.end(), overlappingDcls.begin(),
                   overlappingDcls.end());
}

// Calculate the spill memory displacement for the regvar.
unsigned SpillManagerGRF::calculateSpillDisp(G4_RegVar *regVar) const {
  vASSERT(regVar->getDisp() == UINT_MAX);

  // Locate the blocked locations calculated from the interfering
  // spilled live ranges and put them into a list in ascending order.

  using LocList = std::list<G4_RegVar *>;
  LocList locList;
  [[maybe_unused]] unsigned lrId = (regVar->getId() >= varIdCount_)
                      ? regVar->getBaseRegVar()->getId()
                      : regVar->getId();
  vASSERT(lrId < varIdCount_);

  const std::vector<unsigned int> &intfs =
      spillIntf_->getSparseIntfForVar(lrId);
  for (auto edge : intfs) {
    auto lrEdge = getRegVar(edge);
    if (lrEdge->isRegVarTransient())
      continue;
    if (lrEdge->getDisp() == UINT_MAX)
      continue;
    locList.push_back(lrEdge);
  }

  std::vector<G4_Declare *> overlappingDcls;
  getOverlappingIntervals((*lrInfo_)[lrId]->getDcl()->getRootDeclare(),
                          overlappingDcls);
  for (auto overlap : overlappingDcls) {
    auto lrEdge = overlap->getRegVar();
    if (lrEdge->getDisp() == UINT_MAX)
      continue;
    locList.push_back(lrEdge);
  }

  locList.sort([](G4_RegVar *v1, G4_RegVar *v2) {
    return v1->getDisp() < v2->getDisp();
  });
  locList.unique();

  // Find a spill slot for lRange within the locList.
  // we always start searching from nextSpillOffset_ to facilitate
  // intra-iteration reuse. cross iteration reuse is not done in interest of
  // compile time.
  unsigned regVarLocDisp =
      ROUND(nextSpillOffset_, builder_->numEltPerGRF<Type_UB>());
  unsigned regVarSize = getByteSize(regVar);

  for (G4_RegVar *curLoc : locList) {
    unsigned curLocDisp = curLoc->getDisp();
    if (regVarLocDisp < curLocDisp && regVarLocDisp + regVarSize <= curLocDisp)
      break;
    unsigned curLocEnd = curLocDisp + getByteSize(curLoc);
    {
      if (curLocEnd % builder_->numEltPerGRF<Type_UB>() != 0)
        curLocEnd = ROUND(curLocEnd, builder_->numEltPerGRF<Type_UB>());
    }

    regVarLocDisp = (regVarLocDisp > curLocEnd) ? regVarLocDisp : curLocEnd;
  }

  return regVarLocDisp;
}

unsigned SpillManagerGRF::calculateSpillDispForLS(G4_RegVar *regVar) const {
  vASSERT(regVar->getDisp() == UINT_MAX);

  // Locate the blocked locations calculated from the interfering
  // spilled live ranges and put them into a list in ascending order.

  std::vector<G4_RegVar *> locList;
  [[maybe_unused]] unsigned lrId = (regVar->getId() >= varIdCount_)
                      ? regVar->getBaseRegVar()->getId()
                      : regVar->getId();
  vASSERT(lrId < varIdCount_);

  for (auto* lr : (*spilledLSLRs_)) {
    G4_Declare* dcl = regVar->getDeclare();
    while (dcl->getAliasDeclare()) {
      dcl = dcl->getAliasDeclare();
    }
    LSLiveRange* curLr = gra.getLSLR(dcl);
    unsigned int curSid, curEid, sid, eid;
    curLr->getFirstRef(curSid);
    curLr->getLastRef(curEid);
    lr->getFirstRef(sid);
    lr->getLastRef(eid);
    if (curSid <= eid && sid <= curEid) {
      G4_RegVar* intfRegVar = lr->getTopDcl()->getRegVar();
      if (intfRegVar->isRegVarTransient())
        continue;

      unsigned iDisp = intfRegVar->getDisp();
      if (iDisp == UINT_MAX)
        continue;
      locList.push_back(intfRegVar);
    }
  }

  std::sort(locList.begin(), locList.end(), [](G4_RegVar *v1, G4_RegVar *v2) {
    return v1->getDisp() < v2->getDisp();
  });

  // Find a spill slot for lRange within the locList.
  // we always start searching from nextSpillOffset_ to facilitate
  // intra-iteration reuse. cross iteration reuse is not done in interest of
  // compile time.
  unsigned regVarLocDisp =
      ROUND(nextSpillOffset_, builder_->numEltPerGRF<Type_UB>());
  unsigned regVarSize = getByteSize(regVar);

  for (auto* curLoc : locList) {
    unsigned curLocDisp = curLoc->getDisp();
    if (regVarLocDisp < curLocDisp && regVarLocDisp + regVarSize <= curLocDisp)
      break;
    unsigned curLocEnd = curLocDisp + getByteSize(curLoc);
    {
      if (curLocEnd % builder_->numEltPerGRF<Type_UB>() != 0)
        curLocEnd = ROUND(curLocEnd, builder_->numEltPerGRF<Type_UB>());
    }

    regVarLocDisp = (regVarLocDisp > curLocEnd) ? regVarLocDisp : curLocEnd;
  }

  return regVarLocDisp;
}

// Get the spill/fill displacement of the segment containing the region.
// A segment is the smallest dword or oword aligned portion of memory
// containing the destination or source operand that can be read or saved.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getSegmentDisp(REGION_TYPE *region,
                                         G4_ExecSize execSize) {
  vASSERT(region->getElemSize() && execSize);
  if (isUnalignedRegion(region, execSize))
    return getEncAlignedSegmentDisp(region, execSize);
  else
    return getRegionDisp(region);
}

// Get the spill/fill displacement of the regvar.
unsigned SpillManagerGRF::getDisp(G4_RegVar *regVar) {
  // Already calculated spill memory disp

  if (regVar->getDisp() != UINT_MAX) {
    return regVar->getDisp();
  } else if (regVar->isAliased()) {
    // If it is an aliased regvar then calculate the disp for the
    // actual regvar and then calculate the disp of the aliased regvar
    // based on it.
    G4_Declare *regVarDcl = regVar->getDeclare();
    return getDisp(regVarDcl->getAliasDeclare()->getRegVar()) +
           regVarDcl->getAliasOffset();
  } else if (gra.splitResults.find(regVar->getDeclare()->getRootDeclare()) !=
             gra.splitResults.end()) {
    // this variable is result of variable splitting optimization.
    // original variable is guaranteed to have spilled. if split
    // variable also spills then reuse original variable's spill
    // location.
    auto it = gra.splitResults.find(regVar->getDeclare()->getRootDeclare());
    auto disp = getDisp((*it).second.origDcl->getRegVar());
    regVar->setDisp(disp);
  } else if (regVar->isRegVarTransient() &&
             getDisp(regVar->getBaseRegVar()) != UINT_MAX) {
    // If its base regvar has been assigned a disp, then the spill memory
    // has already been allocated for it, simply calculate the disp based
    // on the enclosing segment disp.
    vASSERT(regVar->getBaseRegVar() != regVar);
    unsigned itsDisp;

    if (regVar->isRegVarSpill()) {
      G4_RegVarTransient *tRegVar = static_cast<G4_RegVarTransient *>(regVar);
      auto dstRR = tRegVar->getRepRegion()->asDstRegRegion();
      vASSERT(getSegmentByteSize(dstRR, tRegVar->getExecSize()) <=
              getByteSize(tRegVar));
      itsDisp = getSegmentDisp(dstRR, tRegVar->getExecSize());
    } else if (regVar->isRegVarFill()) {
      G4_RegVarTransient *tRegVar = static_cast<G4_RegVarTransient *>(regVar);
      auto srcRR = tRegVar->getRepRegion()->asSrcRegRegion();
      vASSERT(getSegmentByteSize(srcRR, tRegVar->getExecSize()) <=
              getByteSize(tRegVar));
      itsDisp = getSegmentDisp(srcRR, tRegVar->getExecSize());
    } else {
      vISA_ASSERT(false, "Incorrect spill/fill ranges.");
      itsDisp = 0;
    }

    regVar->setDisp(itsDisp);
  } else {
    // Allocate the spill and evaluate its disp
    if (doSpillSpaceCompression) {
      vASSERT(regVar->isRegVarTransient() == false);
      if (spilledLSLRs_ != nullptr) {
        regVar->setDisp(calculateSpillDispForLS(regVar));
      } else {
        regVar->setDisp(calculateSpillDisp(regVar));
      }
    } else {
      vASSERT(regVar->isRegVarTransient() == false);
      if (regVar->getId() >= varIdCount_) {
        if (regVar->getBaseRegVar()->getDisp() != UINT_MAX) {
          regVar->setDisp(regVar->getBaseRegVar()->getDisp());
          return regVar->getDisp();
        }
      }

      if ((spillAreaOffset_) % builder_->numEltPerGRF<Type_UB>() != 0) {
        (spillAreaOffset_) =
            ROUND(spillAreaOffset_, builder_->numEltPerGRF<Type_UB>());
      }

      regVar->setDisp(spillAreaOffset_);
      spillAreaOffset_ += getByteSize(regVar);
    }
  }

  // ToDo: log this in some dump to help debug
  // regVar->getDeclare()->dump();
  // std::cerr << "spill offset = " << regVar->getDisp() << "\n";

  return regVar->getDisp();
}

// Get the spill/fill displacement of the region.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getRegionDisp(REGION_TYPE *region) {
  return getDisp(getRegVar(region)) + getRegionOriginOffset(region);
}

// Get the type of send message to use to spill/fill the region.
// The type can be either on oword read/write or a scatter read/write.
// If the segment corresponding to the region is dword sized then a
// dword read/write is used else an oword read/write is used.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getMsgType(REGION_TYPE *region,
                                     G4_ExecSize execSize) {
  unsigned regionDisp = getRegionDisp(region);
  unsigned regionByteSize = getRegionByteSize(region, execSize);
  if (owordAligned(regionDisp) && owordAligned(regionByteSize))
    return owordMask();
  else
    return getEncAlignedSegmentMsgType(region, execSize);
}

// Determine if the region is unaligned w.r.t spill/fill memory read/writes.
// If the exact region cannot be read/written from spill/fill memory using
// one send instruction, then it is unaligned.
template <class REGION_TYPE>
bool SpillManagerGRF::isUnalignedRegion(REGION_TYPE *region,
                                        G4_ExecSize execSize) {
  unsigned regionDisp = getRegionDisp(region);
  unsigned regionByteSize = getRegionByteSize(region, execSize);

  bool needs32ByteAlign = useScratchMsg_;
  needs32ByteAlign |= gra.useLscForSpillFill;

  auto bytePerGRF = builder_->numEltPerGRF<Type_UB>();
  if (needs32ByteAlign) {
    if (regionDisp % bytePerGRF == 0 && regionByteSize % bytePerGRF == 0) {
      return regionByteSize / bytePerGRF != 1 &&
             regionByteSize / bytePerGRF != 2 &&
             regionByteSize / bytePerGRF != 4;
    } else
      return true;
  } else {
    if (owordAligned(regionDisp) && owordAligned(regionByteSize)) {
      //  Current intrinsic spill/fill cannot handle partial region spill.
      //  If it's the partial region of a large size variable, such as V91 in
      //  following instructions, the preload is needed. mov (16) V91(6,0)<1>:ub
      //  %retval_ub(0,0)<1;1,0>:ub {H1, Align1} mov (16) V91(6,16)<1>:ub
      //  %retval_ub(0,16)<1;1,0>:ub {H1, Align1}
      G4_RegVar *var = getRegVar(region);
      if ((var->getDeclare()->getByteSize() > bytePerGRF) &&
          (regionByteSize < bytePerGRF || regionDisp % bytePerGRF)) {
        return true;
      }
      return regionByteSize / OWORD_BYTE_SIZE != 1 &&
             regionByteSize / OWORD_BYTE_SIZE != 2 &&
             regionByteSize / OWORD_BYTE_SIZE != 4;
    } else
      return true;
  }
}

// Calculate the smallest aligned segment encompassing the region.
template <class REGION_TYPE>
void SpillManagerGRF::calculateEncAlignedSegment(REGION_TYPE *region,
                                                 G4_ExecSize execSize,
                                                 unsigned &start, unsigned &end,
                                                 unsigned &type) {
  unsigned regionDisp = getRegionDisp(region);
  unsigned regionByteSize = getRegionByteSize(region, execSize);

  if (needGRFAlignedOffset()) {
    unsigned hwordLB = regionDisp & grfMask();
    unsigned hwordRB = hwordLB + builder_->numEltPerGRF<Type_UB>();
    unsigned blockSize = builder_->numEltPerGRF<Type_UB>();

    while (regionDisp + regionByteSize > hwordRB) {
      hwordRB += blockSize;
    }

    vASSERT((hwordRB - hwordLB) / builder_->numEltPerGRF<Type_UB>() <= 4);
    start = hwordLB;
    end = hwordRB;
    type = grfMask();
  } else {
    unsigned owordLB = regionDisp & owordMask();
    unsigned owordRB = owordLB + OWORD_BYTE_SIZE;
    unsigned blockSize = OWORD_BYTE_SIZE;

    while (regionDisp + regionByteSize > owordRB) {
      owordRB += blockSize;
      blockSize *= 2;
    }

    vASSERT((owordRB - owordLB) / builder_->numEltPerGRF<Type_UB>() <= 4);
    start = owordLB;
    end = owordRB;
    type = owordMask();
  }
}

// Get the byte size of the aligned segment for the region.

template <class REGION_TYPE>
unsigned SpillManagerGRF::getEncAlignedSegmentByteSize(REGION_TYPE *region,
                                                       G4_ExecSize execSize) {
  unsigned start, end, type;
  calculateEncAlignedSegment(region, execSize, start, end, type);
  return end - start;
}

// Get the start offset of the aligned segment for the region.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getEncAlignedSegmentDisp(REGION_TYPE *region,
                                                   G4_ExecSize execSize) {
  unsigned start, end, type;
  calculateEncAlignedSegment(region, execSize, start, end, type);
  return start;
}

// Get the type of message to be used to read/write the enclosing aligned
// segment for the region.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getEncAlignedSegmentMsgType(REGION_TYPE *region,
                                                      G4_ExecSize execSize) {
  unsigned start, end, type;
  calculateEncAlignedSegment(region, execSize, start, end, type);
  return type;
}

// Get the byte size of the segment for the region.
template <class REGION_TYPE>
unsigned SpillManagerGRF::getSegmentByteSize(REGION_TYPE *region,
                                             G4_ExecSize execSize) {
  vASSERT(region->getElemSize() && execSize);
  if (isUnalignedRegion(region, execSize))
    return getEncAlignedSegmentByteSize(region, execSize);
  else
    return getRegionByteSize(region, execSize);
}

// Get the byte size of the destination region.
unsigned SpillManagerGRF::getRegionByteSize(G4_DstRegRegion *region,
                                            G4_ExecSize execSize) const {
  unsigned size =
      region->getHorzStride() * region->getElemSize() * (execSize - 1) +
      region->getElemSize();

  return size;
}

// Get the byte size of the source region.

unsigned SpillManagerGRF::getRegionByteSize(G4_SrcRegRegion *region,
                                            G4_ExecSize execSize) const {
  vASSERT(execSize % region->getRegion()->width == 0);
  unsigned nRows = execSize / region->getRegion()->width;
  unsigned size = 0;

  for (unsigned int i = 0; i < nRows - 1; i++) {
    size += region->getRegion()->vertStride * region->getElemSize();
  }

  size += region->getRegion()->horzStride * region->getElemSize() *
              (region->getRegion()->width - 1) +
          region->getElemSize();
  return size;
}

// Check if the instruction is a SIMD 16 or 32 instruction that is logically
// equivalent to two instructions the second of which uses register operands
// at the following row with the same sub-register index.
bool SpillManagerGRF::isComprInst(G4_INST *inst) const {
  return inst->isComprInst();
}

// Check if the source in a compressed instruction operand occupies a second
// register.
bool SpillManagerGRF::isMultiRegComprSource(G4_SrcRegRegion *src,
                                            G4_INST *inst) const {
  if (!inst->isComprInst()) {
    return false;
  } else if (src->isScalar()) {
    return false;
  } else if (inst->getExecSize() <= 8) {
    return false;
  } else if (!src->asSrcRegRegion()->crossGRF(*builder_)) {
    return false;
  } else if (inst->getExecSize() == 16 && inst->getDst() &&
             inst->getDst()->getTypeSize() == 4 &&
             inst->getDst()->getHorzStride() == 1) {
    if (src->getTypeSize() == 2 && src->isNativePackedRegion()) {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
}

// Send message information query
unsigned SpillManagerGRF::getSendMaxResponseLength() const {
  return 8;
}


// Send message information query
#define SEND_GT_MAX_MESSAGE_LENGTH 15
unsigned SpillManagerGRF::getSendMaxMessageLength() const {
  return SEND_GT_MAX_MESSAGE_LENGTH;
}

// Send message information query
unsigned SpillManagerGRF::getSendDescDataSizeBitOffset() {
  return SEND_GT_DESC_DATA_SIZE_BIT_OFFSET;
}

// Send message information query
unsigned SpillManagerGRF::getSendReadTypeBitOffset() const {
  return SEND_IVB_MSG_TYPE_BIT_OFFSET;
}

// Send message information query
unsigned SpillManagerGRF::getSendWriteTypeBitOffset() {
  return SEND_IVB_MSG_TYPE_BIT_OFFSET;
}

// Send message information query
unsigned SpillManagerGRF::getSendScReadType() const {
  return SEND_IVB_SC_READ_TYPE;
}

// Send message information query
unsigned SpillManagerGRF::getSendScWriteType() const {
  return SEND_IVB_SC_WRITE_TYPE;
}

// Send message information query
unsigned SpillManagerGRF::getSendOwordReadType() const {
  return SEND_IVB_OW_READ_TYPE;
}

// Send message information query
unsigned SpillManagerGRF::getSendOwordWriteType() {
  return SEND_IVB_OW_WRITE_TYPE;
}

unsigned SpillManagerGRF::getSendExDesc(bool isWrite, bool isScatter) const {
  return isWrite ? SEND_IVB_DP_WR_EX_DESC_IMM : SEND_IVB_DP_RD_EX_DESC_IMM;
}

bool SpillManagerGRF::useSplitSend() const { return builder_->useSends(); }

// Get a unique spill range index.
unsigned SpillManagerGRF::getSpillIndex() {
  return spillRangeCount_++;
}

// Get a unique fill range index.
unsigned SpillManagerGRF::getFillIndex() {
  return fillRangeCount_++;
}

// Get a unique tmp index.
unsigned SpillManagerGRF::getTmpIndex() {
  return tmpRangeCount_++;
}

// Get a unique msg spill index.
unsigned SpillManagerGRF::getMsgSpillIndex() {
  return msgSpillRangeCount_++;
}

// Get a unique msg fill index.
unsigned SpillManagerGRF::getMsgFillIndex() {
  return msgFillRangeCount_++;
}

// Get a unique addr spill/fill index.
unsigned SpillManagerGRF::getAddrSpillFillIndex() {
  return addrSpillFillRangeCount_++;
}

// Create a declare directive for a new live range (spill/fill/msg)
// introduced as part of the spill code generation.
G4_Declare *SpillManagerGRF::createRangeDeclare(
    const char *name, G4_RegFileKind regFile, unsigned short nElems,
    unsigned short nRows, G4_Type type, DeclareType kind, G4_RegVar *base,
    G4_Operand *repRegion, G4_ExecSize execSize) {
  G4_Declare *rangeDeclare = builder_->createDeclare(
      name, regFile, nElems, nRows, type, kind, base, repRegion, execSize);
  // TODO: Remove call to setId() as ids are to be computed/set by LivenessAnalysis
  if (!gra.incRA.isEnabled())
    rangeDeclare->getRegVar()->setId(varIdCount_ + latestImplicitVarIdCount_++);
  gra.setBBId(rangeDeclare, bbId_);
  return rangeDeclare;
}

// Create a GRF regvar and its declare directive to represent the spill/fill
// live range.
// The size of the regvar is calculated from the size of the spill/fill
// region. If the spill/fill region fits into one row, then width of the
// regvar is exactly as needed for the spill/fill segment, else it is
// made to occupy exactly two full rows. In either case the regvar is made
// to have 16 word alignment requirement. This is to satisfy the requirements
// of the send instruction used to save/load the value from memory. For
// region's in simd16 instruction contexts we multiply the height by 2
// except for source region's with scalar replication.
template <class REGION_TYPE>
G4_Declare *SpillManagerGRF::createTransientGRFRangeDeclare(
    REGION_TYPE *region, bool isFill, unsigned index, G4_ExecSize execSize,
    G4_INST *inst) {
  const char *nameStr = isFill ? "FL_%s_%d" : "SP_%s_%d";
  const char *name = gra.builder.getNameString(
      64, nameStr, getRegVar(region)->getName(), index);
  G4_Type type = region->getType();
  unsigned segmentByteSize = getSegmentByteSize(region, execSize);
  DeclareType regVarKind =
      (region->isDstRegRegion()) ? DeclareType::Spill : DeclareType::Fill;
  unsigned short width, height;

  if (segmentByteSize > builder_->numEltPerGRF<Type_UB>() ||
      region->crossGRF(*builder_)) {
    vASSERT(builder_->numEltPerGRF<Type_UB>() % region->getElemSize() == 0);
    width = builder_->numEltPerGRF<Type_UB>() / region->getElemSize();
    height = 2;
  } else {
    vASSERT(segmentByteSize % region->getElemSize() == 0);
    width = segmentByteSize / region->getElemSize();
    height = 1;
  }

  if (needGRFAlignedOffset()) {
    // the message will read/write a minimum of one GRF
    if (height == 1 && width < (builder_->getGRFSize() / region->getElemSize()))
      width = builder_->getGRFSize() / region->getElemSize();
  }

  G4_Declare *transientRangeDeclare =
      createRangeDeclare(name, G4_GRF, width, height, type, regVarKind,
                         region->getBase()->asRegVar(), region, execSize);

  if (failSafeSpill_) {
    if (!gra.kernel.getOption(vISA_NewFailSafeRA)) {
      transientRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(spillRegOffset_), 0);
      spillRegOffset_ += height;
    } else {
      transientRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(height)), 0);
    }
  }

  // FIXME: We should take the original declare's alignment too, but I'm worried
  // we may get perf regression if FE is over-aligning or the alignment is not
  // necessary for this inst. So Either is used for now and we can change it
  // later if there are bugs
  setNewDclAlignment(gra, transientRangeDeclare, false);
  return transientRangeDeclare;
}

static unsigned short getSpillRowSizeForSendDst(G4_INST *inst) {
  vASSERT(inst);
  unsigned short nRows = 0;
  const IR_Builder &builder = inst->getBuilder();
  auto dst = inst->getDst();

  if (inst->isSend()) {
    G4_SendDesc *msgDesc = inst->getMsgDesc();
    nRows = msgDesc->getDstLenRegs();
    if (dst->getTopDcl()->getByteSize() <= inst->getBuilder().getGRFSize()) {
      // we may have a send that that writes to a <1 GRF variable, but due to
      // A64 message requirements the send has a response length > 1. We return
      // row size as one instead as we've only allocated one GRF for the spilled
      // variable in scratch space
      nRows = 1;
    }
  } else {
    vASSERT(dst->getLinearizedStart() % builder.numEltPerGRF<Type_UB>() == 0);
    unsigned int rangeSize = (dst->getLinearizedEnd() - dst->getLinearizedStart() + 1);
    unsigned int grfSize = builder.numEltPerGRF<Type_UB>();
    nRows = (rangeSize / grfSize) + ((rangeSize % grfSize) == 0 ? 0 : 1);
  }
  return nRows;
}

// Create a regvar and its declare directive to represent the spill live
// range that appears as a send instruction post destination GRF.
// The type of the regvar is set as dword and its width 8. The type of
// the post destination does not matter, so we just use type dword, and
// a width of 8 so that a row corresponds to a physical register.
G4_Declare *SpillManagerGRF::createPostDstSpillRangeDeclare(G4_INST *sendOut) {
  auto dst = sendOut->getDst();
  G4_RegVar *spilledRegVar = getRegVar(dst);
  const char *name =
      gra.builder.getNameString(64, "SP_GRF_%s_%d", spilledRegVar->getName(),
                                getSpillIndex());
  unsigned short nRows = getSpillRowSizeForSendDst(sendOut);

  G4_DstRegRegion *normalizedPostDst =
      builder_->createDst(spilledRegVar, dst->getRegOff(), SUBREG_ORIGIN,
                          DEF_HORIZ_STRIDE, Type_UD);

  // We use the width as the user specified, the height however is
  // calculated based on the message descriptor to limit register
  // pressure induced by the spill range.

  G4_Declare *transientRangeDeclare = createRangeDeclare(
      name, G4_GRF, builder_->numEltPerGRF<Type_UD>(), nRows, Type_UD,
      DeclareType::Spill, spilledRegVar, normalizedPostDst,
      G4_ExecSize(builder_->numEltPerGRF<Type_UD>()));

  if (failSafeSpill_) {
    if (!builder_->getOption(vISA_NewFailSafeRA)) {
      if (useSplitSend()) {
        transientRangeDeclare->getRegVar()->setPhyReg(
            builder_->phyregpool.getGreg(spillRegStart_), 0);
        spillRegOffset_ += nRows;
      } else {
        transientRangeDeclare->getRegVar()->setPhyReg(
            builder_->phyregpool.getGreg(spillRegStart_ + 1), 0);
        spillRegOffset_ += nRows + 1;
      }
    } else {
      vISA_ASSERT(useSplitSend(), "split send disabled");
      transientRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(nRows)), 0);
    }
  }

  return transientRangeDeclare;
}

// Create a regvar and its declare directive to represent the spill live range.
G4_Declare *
SpillManagerGRF::createSpillRangeDeclare(G4_DstRegRegion *spilledRegion,
                                         G4_ExecSize execSize, G4_INST *inst) {
  return createTransientGRFRangeDeclare(spilledRegion, false /*isFill*/,
                                        getSpillIndex(), execSize, inst);
}

// Create a regvar and its declare directive to represent the GRF fill live
// range.
G4_Declare *SpillManagerGRF::createGRFFillRangeDeclare(
    G4_SrcRegRegion *fillRegion, G4_ExecSize execSize, G4_INST *inst) {
  vASSERT(getRFType(fillRegion) == G4_GRF);
  G4_Declare *fillRangeDecl = createTransientGRFRangeDeclare(
      fillRegion, true /*isFill*/, getFillIndex(), execSize, inst);
  return fillRangeDecl;
}

static unsigned short getSpillRowSizeForSendSrc(G4_INST *inst,
                                                G4_SrcRegRegion *filledRegion) {
  vASSERT(inst);
  const IR_Builder &builder = inst->getBuilder();
  unsigned short nRows = 0;

  if (inst->isSend()) {
    G4_SendDesc *msgDesc = inst->getMsgDesc();
    if (inst->isSplitSend() &&
        (inst->getSrc(1)->asSrcRegRegion() == filledRegion)) {
      nRows = msgDesc->getSrc1LenRegs();
    } else {
      nRows = msgDesc->getSrc0LenRegs();
    }
  } else {
    unsigned int rangeSize = filledRegion->getLinearizedEnd() -
                             filledRegion->getLinearizedStart() + 1;
    unsigned int grfSize = builder.numEltPerGRF<Type_UB>();
    nRows = (rangeSize / grfSize) + ((rangeSize % grfSize) == 0 ? 0 : 1);
  }

  return nRows;
}

// Create a regvar and its declare directive to represent the GRF fill live
// range.
G4_Declare *
SpillManagerGRF::createSendFillRangeDeclare(G4_SrcRegRegion *filledRegion,
                                            G4_INST *sendInst) {
  G4_RegVar *filledRegVar = getRegVar(filledRegion);
  const char *name = gra.builder.getNameString(
      64, "FL_Send_%s_%d", filledRegVar->getName(), getFillIndex());
  unsigned short nRows = getSpillRowSizeForSendSrc(sendInst, filledRegion);

  G4_SrcRegRegion *normalizedSendSrc = builder_->createSrcRegRegion(
      filledRegion->getModifier(), Direct, filledRegVar,
      filledRegion->getRegOff(), filledRegion->getSubRegOff(),
      filledRegion->getRegion(), filledRegion->getType());
  unsigned short width =
      builder_->numEltPerGRF<Type_UB>() / filledRegion->getElemSize();
  vASSERT(builder_->numEltPerGRF<Type_UB>() % filledRegion->getElemSize() == 0);

  // We use the width as the user specified, the height however is
  // calculated based on the message descriptor to limit register
  // pressure induced by the spill range.

  G4_Declare *transientRangeDeclare = createRangeDeclare(
      name, G4_GRF, width, nRows, filledRegion->getType(), DeclareType::Fill,
      filledRegVar, normalizedSendSrc, G4_ExecSize(width));

  setNewDclAlignment(gra, transientRangeDeclare,
                     filledRegVar->getDeclare()->isEvenAlign());

  if (failSafeSpill_) {
    if (!builder_->getOption(vISA_NewFailSafeRA)) {
      if (sendInst->isEOT() && builder_->hasEOTGRFBinding()) {
        // make sure eot src is in last 16 GRF
        uint32_t eotStart = gra.kernel.getNumRegTotal() - 16;
        if (spillRegOffset_ < eotStart) {
          spillRegOffset_ = eotStart;
        }
      }
      transientRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(spillRegOffset_), 0);
      spillRegOffset_ += nRows;
    } else {
      bool isEOT = sendInst->isEOT() && builder_->hasEOTGRFBinding();
      unsigned int startGRF =
          isEOT ? gra.kernel.getNumRegTotal() - 16 : BoundedRA::NOT_FOUND;
      transientRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(nRows, startGRF)), 0);
    }
  }

  return transientRangeDeclare;
}

// Create a regvar and its declare directive to represent the temporary live
// range.
G4_Declare *
SpillManagerGRF::createTemporaryRangeDeclare(G4_DstRegRegion *spilledRegion,
                                             G4_ExecSize execSize,
                                             bool forceSegmentAlignment) {
  const char *name = gra.builder.getNameString(
      64, "TM_GRF_%s_%d", getRegVar(spilledRegion)->getName(), getTmpIndex());
  unsigned byteSize = (forceSegmentAlignment)
                          ? getSegmentByteSize(spilledRegion, execSize)
                          : getRegionByteSize(spilledRegion, execSize);

  // ensure tmp reg is large enough to hold all data when sub-reg offset is
  // non-zero
  byteSize += spilledRegion->getSubRegOff() * spilledRegion->getElemSize();

  vASSERT(byteSize <= 4u * builder_->numEltPerGRF<Type_UB>());
  vASSERT(byteSize % spilledRegion->getElemSize() == 0);

  G4_Type type = spilledRegion->getType();
  DeclareType regVarKind = DeclareType::Tmp;

  unsigned short width, height;
  if (byteSize > (2 * builder_->numEltPerGRF<Type_UB>())) {
    height = 4;
    width = builder_->numEltPerGRF<Type_UB>() / spilledRegion->getElemSize();
  } else if (byteSize > builder_->numEltPerGRF<Type_UB>()) {
    height = 2;
    width = builder_->numEltPerGRF<Type_UB>() / spilledRegion->getElemSize();
  } else {
    height = 1;
    width = byteSize / spilledRegion->getElemSize();
  }

  G4_RegVar *spilledRegVar = getRegVar(spilledRegion);

  G4_Declare *temporaryRangeDeclare =
      createRangeDeclare(name, G4_GRF, width, height, type, regVarKind,
                         spilledRegVar, NULL, G4_ExecSize(0));

  if (failSafeSpill_) {
    if (!builder_->getOption(vISA_NewFailSafeRA)) {
      temporaryRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(spillRegOffset_), 0);
      spillRegOffset_ += height;
    } else {
      temporaryRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(height)), 0);
    }
  }

  setNewDclAlignment(gra, temporaryRangeDeclare, false);
  return temporaryRangeDeclare;
}

// Create a destination region that could be used in place of the spill regvar.
// If the region is unaligned then the origin of the destination region
// is the displacement of the orginal region from its segment, else the
// origin is 0.
G4_DstRegRegion *SpillManagerGRF::createSpillRangeDstRegion(
    G4_RegVar *spillRangeRegVar, G4_DstRegRegion *spilledRegion,
    G4_ExecSize execSize, unsigned regOff) {
  if (isUnalignedRegion(spilledRegion, execSize)) {
    unsigned segmentDisp = getEncAlignedSegmentDisp(spilledRegion, execSize);
    unsigned regionDisp = getRegionDisp(spilledRegion);
    vASSERT(regionDisp >= segmentDisp);
    unsigned short subRegOff =
        (regionDisp - segmentDisp) / spilledRegion->getElemSize();
    vASSERT((regionDisp - segmentDisp) % spilledRegion->getElemSize() == 0);
    vASSERT(subRegOff * spilledRegion->getElemSize() +
                getRegionByteSize(spilledRegion, execSize) <=
            2u * builder_->numEltPerGRF<Type_UB>());

    if (useScratchMsg_) {
      G4_Declare *parent_dcl =
          spilledRegion->getBase()->asRegVar()->getDeclare();
      unsigned off = 0;
      while (parent_dcl->getAliasDeclare() != NULL) {
        // off is in bytes
        off += parent_dcl->getAliasOffset();
        parent_dcl = parent_dcl->getAliasDeclare();
      }
      off = off % builder_->numEltPerGRF<Type_UB>();
      // sub-regoff is in units of element size
      subRegOff =
          spilledRegion->getSubRegOff() + off / spilledRegion->getElemSize();
    }

    return builder_->createDst(spillRangeRegVar, (unsigned short)regOff,
                               subRegOff, spilledRegion->getHorzStride(),
                               spilledRegion->getType());
  }

  else {
    return builder_->createDst(spillRangeRegVar, (short)regOff, SUBREG_ORIGIN,
                               spilledRegion->getHorzStride(),
                               spilledRegion->getType());
  }
}

// Create a source region that could be used to copy out the temporary range
// (that was created to replace the portion of the spilled live range appearing
// in an instruction destination) into the segment aligned spill range for the
// spilled live range that can be written out to spill memory.
G4_SrcRegRegion *SpillManagerGRF::createTemporaryRangeSrcRegion(
    G4_RegVar *tmpRangeRegVar, G4_DstRegRegion *spilledRegion,
    G4_ExecSize execSize, unsigned regOff) {
  uint16_t horzStride = spilledRegion->getHorzStride();
  // A scalar region is returned when execsize is 1.
  const RegionDesc *rDesc =
      builder_->createRegionDesc(execSize, horzStride, 1, 0);

  return builder_->createSrc(tmpRangeRegVar, (short)regOff,
                             spilledRegion->getSubRegOff(), rDesc,
                             spilledRegion->getType());
}

// Create a source region that could be used in place of the fill regvar.
// If the region is unaligned then the origin of the destination region
// is the displacement of the orginal region from its segment, else the
// origin is 0.
G4_SrcRegRegion *
SpillManagerGRF::createFillRangeSrcRegion(G4_RegVar *fillRangeRegVar,
                                          G4_SrcRegRegion *filledRegion,
                                          G4_ExecSize execSize) {
  // we need to preserve accRegSel if it's set
  if (isUnalignedRegion(filledRegion, execSize)) {
    unsigned segmentDisp = getEncAlignedSegmentDisp(filledRegion, execSize);
    unsigned regionDisp = getRegionDisp(filledRegion);
    vASSERT(regionDisp >= segmentDisp);
    unsigned short subRegOff =
        (regionDisp - segmentDisp) / filledRegion->getElemSize();
    vASSERT((regionDisp - segmentDisp) % filledRegion->getElemSize() == 0);

    return builder_->createSrcRegRegion(
        filledRegion->getModifier(), Direct, fillRangeRegVar, REG_ORIGIN,
        subRegOff, filledRegion->getRegion(), filledRegion->getType(),
        filledRegion->getAccRegSel());
  } else {
    // fill intrinsic's sub-reg offset is always 0 since it is GRF aligned.
    // but original filled range's offset may not be 0, so actual filled
    // src needs to use sub-reg offset from original region.
    return builder_->createSrcRegRegion(
        filledRegion->getModifier(), Direct, fillRangeRegVar, REG_ORIGIN,
        filledRegion->getSubRegOff(), filledRegion->getRegion(),
        filledRegion->getType(), filledRegion->getAccRegSel());
  }
}

// Create a source region for the spill regvar that can be used as an operand
// for a mov instruction used to copy the value to an send payload for
// an oword block write message. The spillRangeRegVar segment is guaranteed
// to start at an dword boundary and of a dword aligned size by construction.
// The whole spillRangeRegVar segment needs to be copied out to the send
// payload. The source region generated is <4;4,1>:ud so that a row occupies
// a packed oword. The exec size used in the copy instruction needs to be a
// multiple of 4 depending on the size of the spill regvar - 4 or 8 for the
// the spill regvar appearing as the destination in a regulat 2 cycle
// instructions and 16 when appearing in simd16 instructions.
G4_SrcRegRegion *SpillManagerGRF::createBlockSpillRangeSrcRegion(
    G4_RegVar *spillRangeRegVar, unsigned regOff, unsigned subregOff) {
  vASSERT(getByteSize(spillRangeRegVar) % DWORD_BYTE_SIZE == 0);
  const RegionDesc *rDesc =
      builder_->rgnpool.createRegion(DWORD_BYTE_SIZE, DWORD_BYTE_SIZE, 1);
  return builder_->createSrc(spillRangeRegVar, (short)regOff, (short)subregOff,
                             rDesc, Type_UD);
}

std::optional<G4_Declare *>
SpillManagerGRF::getPreDefinedMRangeDeclare() const {
  if (useSplitSend() && useScratchMsg_)
    return builder_->getBuiltinR0();
  if (gra.useLscForSpillFill)
    // TODO: I think we can remove this, as if useLscForSpillFill is true
    // useScratchMsg_ should also be true.
    return nullptr;
  if (builder_->usesStack())
    return gra.kernel.fg.scratchRegDcl;
  return std::nullopt;
}

// Create a GRF regvar and a declare directive for it, to represent an
// implicit MFR live range that will be used as the send message payload
// header and write payload for spilling a regvar to memory.
G4_Declare *SpillManagerGRF::createMRangeDeclare(G4_RegVar *regVar) {

  auto maybeDcl = getPreDefinedMRangeDeclare();
  if (maybeDcl)
    return *maybeDcl;

  // For legacy platforms where we can neither use LSC nor the scratch message
  // for spill/fill.
  G4_RegVar *repRegVar =
      (regVar->isRegVarTransient()) ? regVar->getBaseRegVar() : regVar;
  const char *name = gra.builder.getNameString(
      64, "SP_MSG_%s_%d", repRegVar->getName(), getMsgSpillIndex());

  unsigned short height = 1;
  if (!useSplitSend()) {
    unsigned regVarByteSize = getByteSize(regVar);
    unsigned writePayloadHeight =
        cdiv(regVarByteSize, builder_->numEltPerGRF<Type_UB>());

    if (writePayloadHeight > SPILL_PAYLOAD_HEIGHT_LIMIT) {
      writePayloadHeight = SPILL_PAYLOAD_HEIGHT_LIMIT;
    }
    unsigned payloadHeaderHeight = (regVarByteSize != DWORD_BYTE_SIZE)
                                       ? OWORD_PAYLOAD_HEADER_MAX_HEIGHT
                                       : DWORD_PAYLOAD_HEADER_MAX_HEIGHT;
    height = payloadHeaderHeight + writePayloadHeight;
    // We should not find ourselves using dword scattered write
    if (useScratchMsg_) {
      vASSERT(payloadHeaderHeight != DWORD_PAYLOAD_HEADER_MAX_HEIGHT);
    }
  }
  unsigned short width = builder_->numEltPerGRF<Type_UD>();

  G4_Declare *msgRangeDeclare = createRangeDeclare(
      name, G4_GRF, width, height, Type_UD, DeclareType::Tmp,
      regVar->getNonTransientBaseRegVar(), NULL, G4_ExecSize(0));

  if (failSafeSpill_) {
    if (!builder_->getOption(vISA_NewFailSafeRA)) {
      msgRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(spillRegStart_), 0);
    } else {
      msgRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(height)), 0);
    }
  }

  return msgRangeDeclare;
}

// Create a GRF regvar and a declare directive for it, to represent an
// implicit live range that will be used as the send message payload
// header and write payload for spilling a regvar region to memory.
G4_Declare *SpillManagerGRF::createMRangeDeclare(G4_DstRegRegion *region,
                                                 G4_ExecSize execSize) {
  auto maybeDcl = getPreDefinedMRangeDeclare();
  if (maybeDcl)
    return *maybeDcl;

  // For legacy platforms where we can neither use LSC nor the scratch message
  // for spill/fill.
  const char *name = gra.builder.getNameString(
      64, "SP_MSG_%s_%d", getRegVar(region)->getName(), getMsgSpillIndex());
  unsigned short height = 1;
  if (!useSplitSend()) {
    unsigned regionByteSize = getSegmentByteSize(region, execSize);
    unsigned writePayloadHeight =
        cdiv(regionByteSize, builder_->numEltPerGRF<Type_UB>());
    unsigned msgType = getMsgType(region, execSize);
    unsigned payloadHeaderHeight =
        (msgType == owordMask() || msgType == hwordMask())
            ? OWORD_PAYLOAD_HEADER_MAX_HEIGHT
            : DWORD_PAYLOAD_HEADER_MAX_HEIGHT;
    // We should not find ourselves using dword scattered write
    if (useScratchMsg_) {
      vASSERT(payloadHeaderHeight != DWORD_PAYLOAD_HEADER_MAX_HEIGHT);
    }
    height = payloadHeaderHeight + writePayloadHeight;
  }
  unsigned short width = builder_->numEltPerGRF<Type_UD>();
  G4_Declare *msgRangeDeclare =
      createRangeDeclare(name, G4_GRF, width, height, Type_UD, DeclareType::Tmp,
                         region->getBase()->asRegVar(), NULL, G4_ExecSize(0));

  if (failSafeSpill_) {
    if (!builder_->getOption(vISA_NewFailSafeRA)) {
      msgRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(spillRegOffset_), 0);
      spillRegOffset_ += height;
    } else {
      msgRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(height)), 0);
    }
  }

  return msgRangeDeclare;
}

// Create a GRF regvar and a declare directive for it, that will be used as
// the send message payload header and write payload for filling a regvar
// from memory.

G4_Declare *SpillManagerGRF::createMRangeDeclare(G4_SrcRegRegion *region,
                                                 G4_ExecSize execSize) {
  auto maybeDcl = getPreDefinedMRangeDeclare();
  if (maybeDcl)
    return *maybeDcl;

  // For legacy platforms where we can neither use LSC nor the scratch message
  // for spill/fill.
  const char *name = gra.builder.getNameString(
      64, "FL_MSG_%s_%d", getRegVar(region)->getName(), getMsgFillIndex());
  getSegmentByteSize(region, execSize);
  unsigned payloadHeaderHeight = (getMsgType(region, execSize) == owordMask())
                                     ? OWORD_PAYLOAD_HEADER_MIN_HEIGHT
                                     : DWORD_PAYLOAD_HEADER_MIN_HEIGHT;

  // We should not find ourselves using dword scattered write
  if (useScratchMsg_) {
    vASSERT(payloadHeaderHeight != DWORD_PAYLOAD_HEADER_MAX_HEIGHT);
    // When using scratch msg descriptor we don't need to use a
    // separate GRF for payload. Source operand of send can directly
    // use r0.0.
    return builder_->getBuiltinR0();
  }

  unsigned height = payloadHeaderHeight;
  unsigned width = builder_->numEltPerGRF<Type_UD>();
  G4_Declare *msgRangeDeclare = createRangeDeclare(
      name, G4_GRF, (unsigned short)width, (unsigned short)height, Type_UD,
      DeclareType::Tmp, region->getBase()->asRegVar(), NULL, G4_ExecSize(0));

  if (failSafeSpill_) {
    if (!builder_->getOption(vISA_NewFailSafeRA)) {
      msgRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(spillRegOffset_), 0);
      spillRegOffset_ += height;
    } else {
      msgRangeDeclare->getRegVar()->setPhyReg(
          builder_->phyregpool.getGreg(context.getFreeGRF(height)), 0);
    }
  }

  return msgRangeDeclare;
}

// Create a destination region for the GRF regvar for the write payload
// portion of the oword block send message (used for spill). The exec size
// can be either 4 or 8 for a regular 2 cycle instruction detination spills or
// 16 for simd16 instruction destination spills.
G4_DstRegRegion *SpillManagerGRF::createMPayloadBlockWriteDstRegion(
    G4_RegVar *grfRange, unsigned regOff, unsigned subregOff) {
  regOff += OWORD_PAYLOAD_WRITE_REG_OFFSET;
  subregOff += OWORD_PAYLOAD_WRITE_SUBREG_OFFSET;
  return builder_->createDst(grfRange, (short)regOff, (short)subregOff,
                             DEF_HORIZ_STRIDE, Type_UD);
}

// Create a destination region for the GRF regvar for the input header
// payload portion of the send message to the data port. The exec size
// needs to be 8 for the mov instruction that uses this as a destination.
G4_DstRegRegion *
SpillManagerGRF::createMHeaderInputDstRegion(G4_RegVar *grfRange,
                                             unsigned subregOff) {
  return builder_->createDst(grfRange, PAYLOAD_INPUT_REG_OFFSET,
                             (short)subregOff, DEF_HORIZ_STRIDE, Type_UD);
}

// Create a destination region for the GRF regvar for the payload offset
// portion of the oword block send message. The exec size needs to be 1
// for the mov instruction that uses this as a destination.
G4_DstRegRegion *
SpillManagerGRF::createMHeaderBlockOffsetDstRegion(G4_RegVar *grfRange) {
  return builder_->createDst(grfRange, OWORD_PAYLOAD_SPOFFSET_REG_OFFSET,
                             OWORD_PAYLOAD_SPOFFSET_SUBREG_OFFSET,
                             DEF_HORIZ_STRIDE, Type_UD);
}

// Create a source region for the input payload (r0.0). The exec size
// needs to be 8 for the mov instruction that uses this as a source.
G4_SrcRegRegion *SpillManagerGRF::createInputPayloadSrcRegion() {
  G4_RegVar *inputPayloadDirectReg = builder_->getBuiltinR0()->getRegVar();
  const RegionDesc *rDesc = builder_->rgnpool.createRegion(
      builder_->numEltPerGRF<Type_UD>(), builder_->numEltPerGRF<Type_UD>(),
      DEF_HORIZ_STRIDE);
  return builder_->createSrc(inputPayloadDirectReg, PAYLOAD_INPUT_REG_OFFSET,
                             PAYLOAD_INPUT_SUBREG_OFFSET, rDesc, Type_UD);
}

// Create and initialize the message header for the send instruction for
// save/load of value to/from memory.
// The header includes the input payload and the offset (for spill disp).
template <class REGION_TYPE>
G4_Declare *SpillManagerGRF::createAndInitMHeader(REGION_TYPE *region,
                                                  G4_ExecSize execSize) {
  G4_Declare *mRangeDcl = createMRangeDeclare(region, execSize);
  return initMHeader(mRangeDcl, region, execSize);
}

// Initialize the message header for the send instruction for save/load
// of value to/from memory.
// The header includes the input payload and the offset (for spill disp).
template <class REGION_TYPE>
G4_Declare *SpillManagerGRF::initMHeader(G4_Declare *mRangeDcl,
                                         REGION_TYPE *region,
                                         G4_ExecSize execSize) {
  // Initialize the message header with the input payload.
  if ((useScratchMsg_ && mRangeDcl == builder_->getBuiltinR0()) ||
      !headerNeeded()) {
    // mRangeDcl is NULL for fills
    return mRangeDcl;
  }

  G4_DstRegRegion *mHeaderInputDstRegion =
      createMHeaderInputDstRegion(mRangeDcl->getRegVar());
  G4_SrcRegRegion *inputPayload = createInputPayloadSrcRegion();
  createMovInst(G4_ExecSize(builder_->numEltPerGRF<Type_UD>()),
                mHeaderInputDstRegion, inputPayload);

  if (useScratchMsg_) {
    // Initialize msg header when region is a spill
    // When using scratch msg description, we only need to copy
    // r0.0 in to msg header. Memory offset will be
    // specified in the msg descriptor.
  } else {
    // Initialize the message header with the spill disp for block
    // read/write.
    G4_DstRegRegion *mHeaderOffsetDstRegion =
        createMHeaderBlockOffsetDstRegion(mRangeDcl->getRegVar());
    int offset = getSegmentDisp(region, execSize);
    getSpillOffset(offset);
    unsigned segmentDisp = offset / OWORD_BYTE_SIZE;
    G4_Imm *segmentDispImm = builder_->createImm(segmentDisp, Type_UD);

    if (!region->isSrcRegRegion() && !region->isDstRegRegion()) {
      vISA_ASSERT(false, ERROR_GRAPHCOLOR);
    }

    if (builder_->getIsKernel() == false) {
      createAddFPInst(g4::SIMD1, mHeaderOffsetDstRegion, segmentDispImm);
    } else {
      createMovInst(g4::SIMD1, mHeaderOffsetDstRegion, segmentDispImm);
    }
  }

  // Initialize the message header with the spill disp for scatter
  // read/write.
  return mRangeDcl;
}

// Create and initialize the message header for the send instruction.
// The header includes the input payload (for spill disp).
G4_Declare *SpillManagerGRF::createAndInitMHeader(G4_RegVar *regVar) {
  G4_Declare *mRangeDcl = createMRangeDeclare(regVar);
  return initMHeader(mRangeDcl);
}

// Initialize the message header for the send instruction.
// The header includes the input payload (for spill disp).
G4_Declare *SpillManagerGRF::initMHeader(G4_Declare *mRangeDcl) {
  // Initialize the message header with the input payload.
  if ((useScratchMsg_ && mRangeDcl == builder_->getBuiltinR0()) ||
      !headerNeeded()) {
    // mRangeDcl is NULL for fills
    return mRangeDcl;
  }

  G4_DstRegRegion *mHeaderInputDstRegion =
      createMHeaderInputDstRegion(mRangeDcl->getRegVar());
  G4_SrcRegRegion *inputPayload = createInputPayloadSrcRegion();
  createMovInst(G4_ExecSize(builder_->numEltPerGRF<Type_UD>()),
                mHeaderInputDstRegion, inputPayload);

  return mRangeDcl;
}

// Initialize the the write payload part of the message for spilled regvars.
// Either of the following restrictions for spillRangeDcl are assumed:
//        - the regvar element type is dword and its 2 <= width <= 8 and
//        height - regOff == 1
//        - the regvar element type is dword and its width = 8 and
//        2 <= height - regOff <= 8
//      - the regvar element type is dword and its width and height are 1
void SpillManagerGRF::initMWritePayload(G4_Declare *spillRangeDcl,
                                        G4_Declare *mRangeDcl, unsigned regOff,
                                        unsigned height) {
  if (useSplitSend()) {
    // no need for payload moves if using sends
    return;
  }

  // We use an block write when the spilled regvars's segment is greater
  // than a dword. Generate a mov to copy the oword aligned segment into
  // the write payload part of the message.
  {
    unsigned nRows = height;

    for (unsigned i = 0; i < nRows; i++) {
      G4_SrcRegRegion *spillRangeSrcRegion = createBlockSpillRangeSrcRegion(
          spillRangeDcl->getRegVar(), i + regOff);
      G4_DstRegRegion *mPayloadWriteDstRegion =
          createMPayloadBlockWriteDstRegion(mRangeDcl->getRegVar(), i);
      G4_ExecSize movExecSize =
          G4_ExecSize((nRows > 1) ? builder_->numEltPerGRF<Type_UD>()
                                  : spillRangeDcl->getNumElems());
      createMovInst(movExecSize, mPayloadWriteDstRegion, spillRangeSrcRegion);
    }
  }
}

// Initialize the the write payload part of the message for spilled regions.
void SpillManagerGRF::initMWritePayload(G4_Declare *spillRangeDcl,
                                        G4_Declare *mRangeDcl,
                                        G4_DstRegRegion *spilledRangeRegion,
                                        G4_ExecSize execSize, unsigned regOff) {
  // We use an block write when the spilled region's segment is greater
  // than a dword. Generate a mov to copy the oword aligned segment into
  // the write payload part of the message.
  if (useSplitSend()) {
    // no need for payload moves
    return;
  } else {
    G4_SrcRegRegion *spillRangeSrcRegion =
        createBlockSpillRangeSrcRegion(spillRangeDcl->getRegVar(), regOff);
    G4_DstRegRegion *mPayloadWriteDstRegion =
        createMPayloadBlockWriteDstRegion(mRangeDcl->getRegVar());
    unsigned segmentByteSize = getSegmentByteSize(spilledRangeRegion, execSize);
    G4_ExecSize movExecSize{segmentByteSize / DWORD_BYTE_SIZE};

    // Write entire GRF when using scratch msg descriptor
    if (useScratchMsg_) {
      if (movExecSize <= 8)
        movExecSize = g4::SIMD8;
      else if (movExecSize < g4::SIMD16)
        movExecSize = g4::SIMD16;
    }

    vASSERT(segmentByteSize % DWORD_BYTE_SIZE == 0);
    vASSERT(movExecSize <= g4::SIMD16);
    createMovInst(movExecSize, mPayloadWriteDstRegion, spillRangeSrcRegion);
  }
}

// Return the block size encoding for oword block reads.
unsigned SpillManagerGRF::blockSendBlockSizeCode(unsigned size) {
  auto code = GlobalRA::sendBlockSizeCode(size);
  return code << getSendDescDataSizeBitOffset();
}

// Return the block size encoding for dword scatter reads.
unsigned SpillManagerGRF::scatterSendBlockSizeCode(unsigned size) const {
  unsigned code;

  switch (size) {
  case 1:
    // We will use an exec size of 1 to perform 1 dword read/write.
  case 8:
    code = 0x02;
    break;
  case 16:
    code = 0x03;
    break;
  default:
    vISA_ASSERT_UNREACHABLE("invalid size");
    code = 0;
  }

  return code << getSendDescDataSizeBitOffset();
}

static uint32_t getScratchBlocksizeEncoding(int numGRF,
                                            const IR_Builder &builder) {

  int size = (numGRF * builder.getGRFSize()) / 32; // in HWwords
  unsigned blocksize_encoding = 0;
  if (size == 1) {
    blocksize_encoding = 0x0;
  } else if (size == 2) {
    blocksize_encoding = 0x1;
  } else if (size == 4) {
    blocksize_encoding = 0x2;
  } else if (size == 8) {
    vASSERT(builder.getPlatform() >= GENX_SKL);
    blocksize_encoding = 0x3;
  } else
    vASSERT(false);
  return blocksize_encoding;
}

std::tuple<uint32_t, G4_ExecSize>
SpillManagerGRF::createSpillSendMsgDescOWord(const IR_Builder &builder,
                                             unsigned int height) {
  unsigned segmentByteSize = height * builder.numEltPerGRF<Type_UB>();
  unsigned writePayloadCount =
      cdiv(segmentByteSize, builder.numEltPerGRF<Type_UB>());
  unsigned statelessSurfaceIndex = 0xFF;
  unsigned int message = statelessSurfaceIndex;

  unsigned headerPresent = 0x80000;
  message |= headerPresent;
  unsigned messageType = getSendOwordWriteType();
  message |= messageType << getSendWriteTypeBitOffset();
  unsigned payloadHeaderCount = OWORD_PAYLOAD_HEADER_MAX_HEIGHT;
  // split send not used since msg type is oword
  unsigned messageLength = writePayloadCount + payloadHeaderCount;
  message |= messageLength << getSendMsgLengthBitOffset();
  unsigned segmentOwordSize = cdiv(segmentByteSize, OWORD_BYTE_SIZE);
  message |= blockSendBlockSizeCode(segmentOwordSize);
  auto execSize =
      G4_ExecSize(LIMIT_SEND_EXEC_SIZE(segmentOwordSize * DWORD_BYTE_SIZE));

  return std::make_tuple(message, execSize);
}

// Create the message descriptor for a spill send instruction for spilled
// post destinations of send instructions.
G4_Imm *SpillManagerGRF::createSpillSendMsgDesc(unsigned regOff,
                                                unsigned height,
                                                G4_ExecSize &execSize,
                                                G4_RegVar *base) {
  unsigned message = 0;

  if (useScratchMsg_) {
    unsigned headerPresent = 0x80000;
    message = headerPresent;
    unsigned msgLength = useSplitSend()
                             ? SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT
                             : SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT + height;
    message |= (msgLength << getSendMsgLengthBitOffset());
    message |= (1 << SCRATCH_MSG_DESC_CATEORY);
    message |= (1 << SCRATCH_MSG_DESC_CHANNEL_MODE);
    message |= (1 << SCRATCH_MSG_DESC_OPERATION_MODE);
    unsigned blocksize_encoding =
        getScratchBlocksizeEncoding(height, *builder_);
    message |= (blocksize_encoding << SCRATCH_MSG_DESC_BLOCK_SIZE);
    int offset = getDisp(base);
    getSpillOffset(offset);
    // message expects offsets to be in HWord
    message |= (offset + regOff * builder_->getGRFSize()) >>
               SCRATCH_SPACE_ADDRESS_UNIT;
    execSize = g4::SIMD16;
  } else {
    auto [message, retSize] = createSpillSendMsgDescOWord(*builder_, height);
    execSize = retSize;
  }
  return builder_->createImm(message, Type_UD);
}

// Create the message descriptor for a spill send instruction for spilled
// destination regions.
std::tuple<G4_Imm *, G4_ExecSize>
SpillManagerGRF::createSpillSendMsgDesc(G4_DstRegRegion *spilledRangeRegion,
                                        G4_ExecSize execSize) {
  unsigned message = 0;

  if (useScratchMsg_) {
    /*
    bits    description
    18:0    function control
    19    Header present
    24:20    Response length
    28:25    Message length
    31:29    MBZ

    18:0
    11:0    Offset (12b hword offset)
    13:12    Block size (00 - 1 register, 01 - 2 regs, 10 - reserved, 11 - 4
    regs) 14    MBZ 15    Invalidate after read (0 - no invalidate, 1 -
    invalidate) 16    Channel mode (0 - oword, 1 - dword) 17    Operation type
    (0 - read, 1 - write) 18    Category (1 - scratch block read/write)
    */
    unsigned segmentByteSize = getSegmentByteSize(spilledRangeRegion, execSize);
    unsigned writePayloadCount =
        cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
    unsigned headerPresent = 0x80000;
    message |= headerPresent;

    unsigned payloadHeaderCount = SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT;
    // message length = 1 if we are using sends, 1 + payload otherwise
    unsigned messageLength = useSplitSend()
                                 ? payloadHeaderCount
                                 : writePayloadCount + payloadHeaderCount;
    message |= (messageLength << getSendMsgLengthBitOffset());
    message |= (1 << SCRATCH_MSG_DESC_CATEORY);        // category
    message |= (1 << SCRATCH_MSG_DESC_CHANNEL_MODE);   // channel mode
    message |= (1 << SCRATCH_MSG_DESC_OPERATION_MODE); // write operation
    unsigned numGRFs = cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());

    unsigned blocksize_encoding =
        getScratchBlocksizeEncoding(numGRFs, *builder_);

    message |= (blocksize_encoding << SCRATCH_MSG_DESC_BLOCK_SIZE);
    int offset = getRegionDisp(spilledRangeRegion);
    getSpillOffset(offset);
    message |= offset >> SCRATCH_SPACE_ADDRESS_UNIT;
    if (numGRFs > 1) {
      execSize = g4::SIMD16;
    } else {
      if (execSize > g4::SIMD8) {
        execSize = g4::SIMD16;
      } else {
        execSize = g4::SIMD8;
      }
    }
  } else {
    unsigned segmentByteSize = getSegmentByteSize(spilledRangeRegion, execSize);
    unsigned writePayloadCount =
        cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
    unsigned statelessSurfaceIndex = 0xFF;
    message = statelessSurfaceIndex;

    unsigned headerPresent = 0x80000;
    message |= headerPresent;
    unsigned messageType = getSendOwordWriteType();
    message |= messageType << getSendWriteTypeBitOffset();
    unsigned payloadHeaderCount = OWORD_PAYLOAD_HEADER_MAX_HEIGHT;
    unsigned messageLength = useSplitSend()
                                 ? payloadHeaderCount
                                 : writePayloadCount + payloadHeaderCount;
    message |= messageLength << getSendMsgLengthBitOffset();
    unsigned segmentOwordSize = cdiv(segmentByteSize, OWORD_BYTE_SIZE);
    message |= blockSendBlockSizeCode(segmentOwordSize);
    execSize =
        G4_ExecSize(LIMIT_SEND_EXEC_SIZE(segmentOwordSize * DWORD_BYTE_SIZE));
  }
  return std::make_tuple(builder_->createImm(message, Type_UD), execSize);
}

// Create an add instruction to add the FP needed for generating spill/fill
// code. We always set the NoMask flag and use a null conditional modifier.
G4_INST *SpillManagerGRF::createAddFPInst(G4_ExecSize execSize,
                                          G4_DstRegRegion *dst,
                                          G4_Operand *src) {
  const RegionDesc *rDesc = builder_->getRegionScalar();
  G4_Operand *fp = builder_->createSrc(
      builder_->kernel.fg.framePtrDcl->getRegVar(), 0, 0, rDesc, Type_UD);
  auto newInst = builder_->createBinOp(G4_add, execSize, dst, fp, src,
                                       InstOpt_WriteEnable, true);
  newInst->inheritDIFrom(curInst);

  return newInst;
}

// Create a mov instruction needed for generating spill/fill code.
// We always set the NoMask flag and use a null conditional modifier.
G4_INST *SpillManagerGRF::createMovInst(G4_ExecSize execSize,
                                        G4_DstRegRegion *dst, G4_Operand *src,
                                        G4_Predicate *predicate,
                                        unsigned int options) {
  auto newInst = builder_->createMov(execSize, dst, src, options, true);

  if (predicate) {
    newInst->setPredicate(predicate);
  }

  return newInst;
}

// Create a send instruction needed for generating spill/fill code.
// We always set the NoMask flag and use a null predicate and conditional
// modifier.
G4_INST *SpillManagerGRF::createSendInst(G4_ExecSize execSize,
                                         G4_DstRegRegion *postDst,
                                         G4_SrcRegRegion *payload, G4_Imm *desc,
                                         SFID funcID, bool isWrite,
                                         unsigned option) {
  // ToDo: create exDesc in createSendMsgDesc()
  uint32_t exDesc = G4_SendDescRaw::createExtDesc(funcID);
  auto msgDesc = builder_->createSendMsgDesc(
      funcID, (uint32_t)desc->getInt(), exDesc, 0,
      isWrite ? SendAccess::WRITE_ONLY : SendAccess::READ_ONLY, nullptr);
  auto sendInst = builder_->createSendInst(
      NULL, G4_send, execSize, postDst, payload, desc, option, msgDesc, true);
  sendInst->inheritDIFrom(curInst);

  return sendInst;
}

// Create the send instructions to fill in the value of spillRangeDcl into
// fillRangeDcl in aligned portions.
static int getNextSize(int height, bool useHWordMsg, const IR_Builder &irb) {
  bool has8GRFMessage =
      useHWordMsg && irb.getPlatform() >= GENX_SKL && irb.getGRFSize() == 32;
  if (has8GRFMessage && height >= 8) {
    return 8;
  } else if (height >= 4) {
    return 4;
  } else if (height >= 2) {
    return 2;
  } else if (height >= 1) {
    return 1;
  }
  return 0;
}

void SpillManagerGRF::sendInSpilledRegVarPortions(G4_Declare *fillRangeDcl,
                                                  G4_Declare *mRangeDcl,
                                                  unsigned regOff,
                                                  unsigned height,
                                                  unsigned srcRegOff) {
  if ((useScratchMsg_ && mRangeDcl == builder_->getBuiltinR0()) ||
      !headerNeeded()) {
    // Skip initializing message header
  } else {
    // Initialize the message header with the spill disp for portion.
    int offset = getDisp(fillRangeDcl->getRegVar()) +
                 regOff * builder_->numEltPerGRF<Type_UB>();
    getSpillOffset(offset);

    unsigned segmentDisp = offset / OWORD_BYTE_SIZE;
    G4_Imm *segmentDispImm = builder_->createImm(segmentDisp, Type_UD);
    G4_DstRegRegion *mHeaderOffsetDstRegion =
        createMHeaderBlockOffsetDstRegion(mRangeDcl->getRegVar());

    if (builder_->getIsKernel() == false) {
      createAddFPInst(g4::SIMD1, mHeaderOffsetDstRegion, segmentDispImm);
    } else {
      createMovInst(g4::SIMD1, mHeaderOffsetDstRegion, segmentDispImm);
    }
  }

  // Read in the portions using a greedy approach.
  int currentStride = getNextSize(height, useScratchMsg_, *builder_);

  if (currentStride) {
    if (gra.useLscForSpillFill) {
      createLSCFill(fillRangeDcl, regOff, currentStride, srcRegOff);
    } else {
      createFillSendInstr(fillRangeDcl, mRangeDcl, regOff, currentStride,
                          srcRegOff);
    }

    if (height - currentStride > 0) {
      sendInSpilledRegVarPortions(
          fillRangeDcl, mRangeDcl, regOff + currentStride,
          height - currentStride, srcRegOff + currentStride);
    }
  }
}

// Check if we need to perform the pre-load of the spilled region's
// segment from spill memory. A pre-load is required under the following
// circumstances:
//        - for partial writes - horizontal stride greater than one, and when
//          the emask and predicate can possibly disable channels (for now if
//        predicates or condition modofoers are present then we conservatively
//        assume a partial write)
//        - write's where the segment is larger than the actaully written region
//        (either because the spill offset for the region or its size is not
//         oword or dword aligned for writing the exact region)
bool SpillManagerGRF::shouldPreloadSpillRange(G4_INST *instContext,
                                              G4_BB *parentBB) {
  // Check for partial and unaligned regions and add pre-load code, if
  // necessary.
  auto spilledRangeRegion = instContext->getDst();
  G4_ExecSize execSize = instContext->getExecSize();

  if (isPartialRegion(spilledRangeRegion, execSize) ||
      isUnalignedRegion(spilledRangeRegion, execSize) ||
      instContext->isPartialWriteForSpill(!parentBB->isAllLaneActive(),
                                          usesOWOrLSC(spilledRangeRegion))) {
    // special check for scalar variables: no need for pre-fill if instruction
    // writes to whole variable and is not predicated
    auto spilledDcl = spilledRangeRegion->getTopDcl()->getRootDeclare();
    if (execSize == g4::SIMD1 &&
        spilledRangeRegion->getTypeSize() == spilledDcl->getByteSize() &&
        !instContext->getPredicate()) {
      // ToDo: investigate why we are spilling so many scalar variables
      return false;
    }
    return true;
  }
  // No pre-load for whole and aligned region writes
  else {
    return false;
  }
}

// Create the send instruction to perform the pre-load of the spilled region's
// segment into spill memory.
void SpillManagerGRF::preloadSpillRange(G4_Declare *spillRangeDcl,
                                        G4_Declare *mRangeDcl,
                                        G4_DstRegRegion *spilledRangeRegion,
                                        G4_ExecSize execSize) {
  // When execSize is 32, regions <32, 32, 1> or <64; 32, 2> are invalid.
  // Use a uniform region descriptor <stride; 1, 0>. Note that stride could
  // be 0 when execsize is 1.
  uint16_t hstride = spilledRangeRegion->getHorzStride();
  const RegionDesc *rDesc = builder_->createRegionDesc(execSize, hstride, 1, 0);

  G4_SrcRegRegion *preloadRegion = builder_->createSrc(
      spillRangeDcl->getRegVar(), REG_ORIGIN,
      spilledRangeRegion->getSubRegOff(), rDesc, spilledRangeRegion->getType());

  if (useScratchMsg_) {
    // src region's base refers to the filled region's base
    // The size of src region is equal to number of rows that
    // have to be filled, starting at the reg offset specified
    // in the original operand. For eg,
    // Let the spilled operand be V40(3,3)
    //
    // => mov (1) V40(3,3)<1>:ud    V30(0,0)<0;1,0>:ud
    // When this will be replaced with a preload fill,
    // => mov (1) TM_GRF_V40_0(0,0)<1>:ud   V30(0,0)<0;1,0>:ud
    // => send (16) SP_V40_0(0,0)<1>:ud ...                            <--- load
    // V40's 3rd row in SP_V40_0
    // => mov (1) SP_V40_0(0,3)<1>:ud   TM_GRF_V40_0(0,0)<8;8,1>:ud <--- overlay
    // => send (16) null ...                                        <--- store
    // V40's updated 3rd row to memory
    //
    // Since the filled register's register offset is 0,0 in first
    // send instruction, this change is made when creating the operand
    // itself.

    // Attach preloadRegion to dummy mov so getLeftBound/getRightBound won't
    // crash when called from crossGRF in createFillSendMsgDesc
    builder_->createMov(execSize, builder_->createNullDst(Type_UD),
                        preloadRegion, InstOpt_NoOpt, false);
  }

  if (gra.useLscForSpillFill) {
    createLSCFill(spillRangeDcl, preloadRegion, execSize);
  } else {
    createFillSendInstr(spillRangeDcl, mRangeDcl, preloadRegion, execSize);
  }
}

G4_SrcRegRegion *vISA::getSpillFillHeader(IR_Builder &builder,
                                          G4_Declare *decl) {
  if (builder.supportsLSC()) {
    // LSC in its current incarnation needs a header to store the address
    return builder.createSrcRegRegion(builder.getSpillFillHeader(),
                                      builder.getRegionStride1());
  }
  return builder.createSrcRegRegion(decl, builder.getRegionStride1());
}

// Create the send instruction to perform the spill of the spilled regvars's
// segment into spill memory.
// regOff - Offset of sub-spill. If one spill is split into more than one spill,
// this is the offset of them, unit in register size
//  spillOff - Offset of the original variable being spilled, unit in register
//  size.
G4_INST *SpillManagerGRF::createSpillSendInstr(G4_Declare *spillRangeDcl,
                                               G4_Declare *mRangeDcl,
                                               unsigned regOff, unsigned height,
                                               unsigned spillOff) {
  G4_ExecSize execSize(0);

  G4_Imm *messageDescImm = NULL;

  if (useScratchMsg_) {
    G4_RegVar *r = spillRangeDcl->getRegVar();
    G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(r);
    messageDescImm = createSpillSendMsgDesc(spillOff, height, execSize,
                                            rvar->getBaseRegVar());
#ifdef _DEBUG
    int offset =
        (messageDescImm->getInt() & 0xFFF) * builder_->numEltPerGRF<Type_UB>();
    vISA_ASSERT(offset >= globalScratchOffset, "incorrect offset");
#endif
  } else {
    messageDescImm = createSpillSendMsgDesc(regOff, height, execSize);
  }

  G4_DstRegRegion *postDst =
      builder_->createNullDst(execSize > g4::SIMD8 ? Type_UW : Type_UD);

  G4_INST *sendInst = NULL;
  if (useSplitSend()) {
    auto headerOpnd = getSpillFillHeader(*builder_, mRangeDcl);
    G4_SrcRegRegion *srcOpnd =
        createBlockSpillRangeSrcRegion(spillRangeDcl->getRegVar(), regOff);

    auto off = G4_SpillIntrinsic::InvalidOffset;
    G4_Declare *fp = nullptr;
    if (useScratchMsg_)
      off = (messageDescImm->getInt() & 0xfff);
    else {
      if (builder_->usesStack()) {
        G4_RegVar *r = spillRangeDcl->getRegVar();
        G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(r);
        int offset = getDisp(rvar->getBaseRegVar());
        getSpillOffset(offset);
        // message expects offsets to be in HWord
        off = (offset + spillOff * builder_->getGRFSize()) >>
              SCRATCH_SPACE_ADDRESS_UNIT;
        if (builder_->usesStack())
          fp = builder_->kernel.fg.getFramePtrDcl();

        if (!fp && offset < SCRATCH_MSG_LIMIT)
          headerOpnd = builder_->createSrcRegRegion(
              builder_->getBuiltinR0(), builder_->getRegionStride1());
      }
    }
    sendInst =
        builder_->createSpill(postDst, headerOpnd, srcOpnd, execSize, height,
                              off, fp, InstOpt_WriteEnable, true);
    sendInst->inheritDIFrom(curInst);
  } else {
    G4_SrcRegRegion *payload = builder_->createSrc(
        mRangeDcl->getRegVar(), 0, 0, builder_->getRegionStride1(), Type_UD);
    sendInst = createSendInst(execSize, postDst, payload, messageDescImm,
                              SFID::DP_DC0, true, InstOpt_WriteEnable);
  }

  return sendInst;
}

// Create the send instruction to perform the spill of the spilled region's
// segment into spill memory.
G4_INST *
SpillManagerGRF::createSpillSendInstr(G4_Declare *spillRangeDcl,
                                      G4_Declare *mRangeDcl,
                                      G4_DstRegRegion *spilledRangeRegion,
                                      G4_ExecSize execSize, unsigned option) {

  G4_DstRegRegion *postDst =
      builder_->createNullDst(execSize > g4::SIMD8 ? Type_UW : Type_UD);

  G4_INST *sendInst = NULL;
  if (useSplitSend()) {
    unsigned extMsgLength = spillRangeDcl->getNumRows();
    const RegionDesc *region = builder_->getRegionStride1();
    auto headerOpnd = getSpillFillHeader(*builder_, mRangeDcl);
    G4_SrcRegRegion *srcOpnd =
        builder_->createSrcRegRegion(spillRangeDcl, region);

    auto off = G4_SpillIntrinsic::InvalidOffset;
    G4_Declare *fp = nullptr;
    auto spillExecSize = execSize;
    if (useScratchMsg_) {
      auto [messageDescImm, retSize] =
          createSpillSendMsgDesc(spilledRangeRegion, execSize);
      spillExecSize = retSize;
      off = (messageDescImm->getInt() & 0xfff);
    } else {
      if (builder_->usesStack()) {
        G4_RegVar *r = spillRangeDcl->getRegVar();
        G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(r);
        int offset = getDisp(rvar->getBaseRegVar());
        getSpillOffset(offset);
        // message expects offsets to be in HWord
        auto regOff = spilledRangeRegion->getRegOff();
        off = (offset + regOff * builder_->getGRFSize()) >>
              SCRATCH_SPACE_ADDRESS_UNIT;
        if (builder_->usesStack())
          fp = builder_->kernel.fg.getFramePtrDcl();

        if (!fp && offset < SCRATCH_MSG_LIMIT)
          headerOpnd = builder_->createSrcRegRegion(
              builder_->getBuiltinR0(), builder_->getRegionStride1());
      }
    }
    sendInst = builder_->createSpill(
        postDst, headerOpnd, srcOpnd, spillExecSize, (uint16_t)extMsgLength,
        off, fp, static_cast<G4_InstOption>(option), true);
    sendInst->inheritDIFrom(curInst);
  } else {
    auto [messageDescImm, spillExecSize] =
        createSpillSendMsgDesc(spilledRangeRegion, execSize);
    G4_SrcRegRegion *payload = builder_->createSrc(
        mRangeDcl->getRegVar(), 0, 0, builder_->getRegionStride1(), Type_UD);
    sendInst =
        createSendInst(spillExecSize, postDst, payload, messageDescImm,
                       SFID::DP_DC0, true, static_cast<G4_InstOption>(option));
  }

  return sendInst;
}

// Create the message description for a fill send instruction for filled
// regvars.
G4_Imm *SpillManagerGRF::createFillSendMsgDesc(unsigned regOff, unsigned height,
                                               G4_ExecSize &execSize,
                                               G4_RegVar *base) {
  unsigned message = 0;

  if (useScratchMsg_) {
    unsigned segmentByteSize = height * builder_->numEltPerGRF<Type_UB>();
    unsigned responseLength =
        cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
    message = responseLength << getSendRspLengthBitOffset();
    unsigned headerPresent = 0x80000;
    message |= SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT << getSendMsgLengthBitOffset();
    message |= headerPresent;

    message |= (1 << SCRATCH_MSG_DESC_CATEORY);
    message |= (0 << SCRATCH_MSG_INVALIDATE_AFTER_READ);
    unsigned blocksize_encoding =
        getScratchBlocksizeEncoding(height, *builder_);

    message |= (blocksize_encoding << SCRATCH_MSG_DESC_BLOCK_SIZE);

    int offset = getDisp(base);
    getSpillOffset(offset);
    // message expects offsets to be in HWord
    message |= (offset + regOff * builder_->getGRFSize()) >>
               SCRATCH_SPACE_ADDRESS_UNIT;

    execSize = g4::SIMD16;
  } else {
    unsigned segmentByteSize = height * builder_->numEltPerGRF<Type_UB>();
    unsigned statelessSurfaceIndex = 0xFF;
    unsigned responseLength =
        cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
    responseLength = responseLength << getSendRspLengthBitOffset();
    message = statelessSurfaceIndex | responseLength;

    unsigned headerPresent = 0x80000;
    message |= headerPresent;
    unsigned messageType = getSendOwordReadType();
    message |= messageType << getSendReadTypeBitOffset();
    unsigned messageLength = OWORD_PAYLOAD_HEADER_MIN_HEIGHT;
    message |= messageLength << getSendMsgLengthBitOffset();
    unsigned segmentOwordSize = cdiv(segmentByteSize, OWORD_BYTE_SIZE);
    message |= blockSendBlockSizeCode(segmentOwordSize);
    execSize =
        G4_ExecSize(LIMIT_SEND_EXEC_SIZE(segmentOwordSize * DWORD_BYTE_SIZE));
  }
  return builder_->createImm(message, Type_UD);
}

// Create the message description for a fill send instruction for filled
// source regions.
template <class REGION_TYPE>
G4_Imm *SpillManagerGRF::createFillSendMsgDesc(REGION_TYPE *filledRangeRegion,
                                               G4_ExecSize execSize) {
  unsigned message = 0;

  if (useScratchMsg_) {
    unsigned segmentByteSize = getSegmentByteSize(filledRangeRegion, execSize);
    if (filledRangeRegion->crossGRF(*builder_)) {
      segmentByteSize = 2 * builder_->numEltPerGRF<Type_UB>();
    }

    unsigned responseLength =
        cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
    message = responseLength << getSendRspLengthBitOffset();

    unsigned headerPresent = 0x80000;
    message |= headerPresent;

    message |=
        (SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT << getSendMsgLengthBitOffset());
    message |= (1 << SCRATCH_MSG_DESC_CATEORY);
    message |= (0 << SCRATCH_MSG_INVALIDATE_AFTER_READ);
    unsigned blocksize_encoding =
        getScratchBlocksizeEncoding(responseLength, *builder_);

    message |= (blocksize_encoding << SCRATCH_MSG_DESC_BLOCK_SIZE);
    int offset = getRegionDisp(filledRangeRegion);
    getSpillOffset(offset);
    message |= offset >> SCRATCH_SPACE_ADDRESS_UNIT;
  } else {
    unsigned segmentByteSize = getSegmentByteSize(filledRangeRegion, execSize);
    unsigned statelessSurfaceIndex = 0xFF;
    unsigned responseLength =
        cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
    responseLength = responseLength << getSendRspLengthBitOffset();
    message = statelessSurfaceIndex | responseLength;

    unsigned headerPresent = 0x80000;
    message |= headerPresent;
    unsigned messageType = getSendOwordReadType();
    message |= messageType << getSendReadTypeBitOffset();
    unsigned messageLength = OWORD_PAYLOAD_HEADER_MIN_HEIGHT;
    message |= messageLength << getSendMsgLengthBitOffset();
    unsigned segmentOwordSize = cdiv(segmentByteSize, OWORD_BYTE_SIZE);
    message |= blockSendBlockSizeCode(segmentOwordSize);
  }
  return builder_->createImm(message, Type_UD);
}

// Create the send instruction to perform the fill of the spilled regvars's
// segment from spill memory.
// spillOff - spill offset to the fillRangeDcl, in unit of grf size
G4_INST *SpillManagerGRF::createFillSendInstr(G4_Declare *fillRangeDcl,
                                              G4_Declare *mRangeDcl,
                                              unsigned regOff, unsigned height,
                                              unsigned spillOff) {
  G4_ExecSize execSize{0};

  G4_Imm *messageDescImm = NULL;

  if (useScratchMsg_) {
    G4_RegVar *r = fillRangeDcl->getRegVar();
    G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(r);
    messageDescImm = createFillSendMsgDesc(spillOff, height, execSize,
                                           rvar->getBaseRegVar());
#ifdef _DEBUG
    int offset =
        (messageDescImm->getInt() & 0xFFF) * builder_->numEltPerGRF<Type_UB>();
    vISA_ASSERT(offset >= globalScratchOffset, "incorrect offset");
#endif
  } else {
    messageDescImm = createFillSendMsgDesc(regOff, height, execSize);
  }

  G4_DstRegRegion *postDst = builder_->createDst(
      fillRangeDcl->getRegVar(), (short)regOff, SUBREG_ORIGIN, DEF_HORIZ_STRIDE,
      (execSize > 8) ? Type_UW : Type_UD);

  auto payload = getSpillFillHeader(*builder_, mRangeDcl);

  unsigned int off = G4_FillIntrinsic::InvalidOffset;
  G4_Declare *fp = nullptr;
  if (useScratchMsg_)
    off = (messageDescImm->getInt() & 0xfff);
  else {
    if (builder_->usesStack()) {
      // compute hword offset to emit later when expanding spill/fill intrinsic
      G4_RegVar *r = fillRangeDcl->getRegVar();
      G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(r);
      int offset = getDisp(rvar->getBaseRegVar());
      getSpillOffset(offset);
      // message expects offsets to be in HWord
      off = (offset + spillOff * builder_->getGRFSize()) >>
            SCRATCH_SPACE_ADDRESS_UNIT;
      if (builder_->usesStack())
        fp = builder_->kernel.fg.getFramePtrDcl();

      if (!fp && offset < SCRATCH_MSG_LIMIT)
        payload = builder_->createSrcRegRegion(builder_->getBuiltinR0(),
                                               builder_->getRegionStride1());
    }
  }
  auto fillInst = builder_->createFill(payload, postDst, execSize, height, off,
                                       fp, InstOpt_WriteEnable, true);
  fillInst->inheritDIFrom(curInst);
  return fillInst;
}

// Create the send instruction to perform the fill of the filled region's
// segment into fill memory.
G4_INST *SpillManagerGRF::createFillSendInstr(
    G4_Declare *fillRangeDcl, G4_Declare *mRangeDcl,
    G4_SrcRegRegion *filledRangeRegion, G4_ExecSize execSize) {
  auto oldExecSize = execSize;

  if (useScratchMsg_) {
    execSize = g4::SIMD16;
  }

  G4_DstRegRegion *postDst =
      builder_->createDst(fillRangeDcl->getRegVar(), 0, SUBREG_ORIGIN,
                          DEF_HORIZ_STRIDE, (execSize > 8) ? Type_UW : Type_UD);

  auto payload = getSpillFillHeader(*builder_, mRangeDcl);

  unsigned int off = G4_FillIntrinsic::InvalidOffset;
  unsigned segmentByteSize = getSegmentByteSize(filledRangeRegion, oldExecSize);
  G4_Declare *fp = nullptr;
  if (useScratchMsg_) {
    G4_Imm *messageDescImm =
        createFillSendMsgDesc(filledRangeRegion, oldExecSize);

    off = (messageDescImm->getInt() & 0xfff);
    if (filledRangeRegion->crossGRF(*builder_)) {
      segmentByteSize = 2 * builder_->numEltPerGRF<Type_UB>();
    }
  } else {
    if (builder_->usesStack()) {
      // compute hword offset to emit later when expanding spill/fill intrinsic
      int offset = getRegionDisp(filledRangeRegion);
      getSpillOffset(offset);
      off = offset >> SCRATCH_SPACE_ADDRESS_UNIT;
      if (builder_->usesStack())
        fp = builder_->kernel.fg.getFramePtrDcl();

      if (!fp && offset < SCRATCH_MSG_LIMIT)
        payload = builder_->createSrcRegRegion(builder_->getBuiltinR0(),
                                               builder_->getRegionStride1());
    }
  }

  unsigned responseLength =
      cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
  auto fillInst =
      builder_->createFill(payload, postDst, execSize, responseLength, off, fp,
                           InstOpt_WriteEnable, true);
  fillInst->inheritDIFrom(curInst);
  return fillInst;
}

// LSC versions of spill/fill, gra.useLscForSpillFill must be true.
G4_SrcRegRegion *SpillManagerGRF::getLSCSpillFillHeader(const G4_Declare *fp,
                                                        int offset) {
  if (!fp && offset < SCRATCH_MSG_LIMIT &&
      !gra.useLscForNonStackCallSpillFill) {
    // Use the legacy non-LSC scratch message with R0 as its header.
    return builder_->createSrcRegRegion(builder_->getBuiltinR0(),
                                        builder_->getRegionStride1());
  }
  // Use LSC for spill/fill; a temp GRF is needed for the address payload.
  return builder_->createSrcRegRegion(builder_->getSpillFillHeader(),
                                      builder_->getRegionStride1());
}

// Create the send instruction to perform the spill of the spilled regvars's
// segment into spill memory.
//
// regOff - Offset of sub-spill. If one spill is splitted into more than one
// spill, this is the offset of them, unit in register size spillOff - Offset of
// the original variable being spilled, unit in register size.
G4_INST *SpillManagerGRF::createLSCSpill(G4_Declare *spillRangeDcl,
                                         unsigned regOff, unsigned height,
                                         unsigned spillOff) {
  G4_ExecSize execSize(16);

  G4_DstRegRegion *postDst = builder_->createNullDst(Type_UD);

  G4_SrcRegRegion *srcOpnd =
      createBlockSpillRangeSrcRegion(spillRangeDcl->getRegVar(), regOff);
  G4_Declare *fp =
      builder_->usesStack() ? builder_->kernel.fg.getFramePtrDcl() : nullptr;

  G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(spillRangeDcl->getRegVar());
  int offset = getDisp(rvar->getBaseRegVar());
  getSpillOffset(offset);
  uint32_t totalByteOffset = (offset + spillOff * builder_->getGRFSize());
  // message expects offsets to be in HWord
  uint32_t offsetHwords = totalByteOffset >> SCRATCH_SPACE_ADDRESS_UNIT;

  G4_SrcRegRegion *header = getLSCSpillFillHeader(fp, totalByteOffset);
  auto sendInst =
      builder_->createSpill(postDst, header, srcOpnd, execSize, height,
                            offsetHwords, fp, InstOpt_WriteEnable, true);
  sendInst->inheritDIFrom(curInst);

  return sendInst;
}

// Create the send instruction to perform the spill of the spilled region's
// segment into spill memory.
G4_INST *SpillManagerGRF::createLSCSpill(G4_Declare *spillRangeDcl,
                                         G4_DstRegRegion *spilledRangeRegion,
                                         G4_ExecSize execSize, unsigned option,
                                         bool isScatter) {
  G4_DstRegRegion *postDst = builder_->createNullDst(
      isScatter ? spilledRangeRegion->getType() : Type_UD);

  unsigned extMsgLength = spillRangeDcl->getNumRows();
  const RegionDesc *region = builder_->getRegionStride1();
  G4_SrcRegRegion *srcOpnd =
      builder_->createSrcRegRegion(spillRangeDcl, region);

  G4_Declare *fp =
      builder_->usesStack() ? builder_->kernel.fg.getFramePtrDcl() : nullptr;

  G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(spillRangeDcl->getRegVar());
  int offset = getDisp(rvar->getBaseRegVar());
  getSpillOffset(offset);
  // message expects offsets to be in HWord
  auto regOff = spilledRangeRegion->getRegOff();
  uint32_t totalByteOffset = (offset + regOff * builder_->getGRFSize());
  uint32_t offsetHwords = totalByteOffset >> SCRATCH_SPACE_ADDRESS_UNIT;

  G4_SrcRegRegion *header = getLSCSpillFillHeader(fp, totalByteOffset);
  auto sendInst = builder_->createSpill(
      postDst, header, srcOpnd, execSize, (uint16_t)extMsgLength, offsetHwords,
      fp, static_cast<G4_InstOption>(option), true, isScatter);
  sendInst->inheritDIFrom(curInst);

  return sendInst;
}

// Create the send instruction to perform the fill of the spilled regvars's
// segment from spill memory.
// spillOff - spill offset to the fillRangeDcl, in unit of grf size
G4_INST *SpillManagerGRF::createLSCFill(G4_Declare *fillRangeDcl,
                                        unsigned regOff, unsigned height,
                                        unsigned spillOff) {
  G4_DstRegRegion *postDst =
      builder_->createDst(fillRangeDcl->getRegVar(), (short)regOff,
                          SUBREG_ORIGIN, DEF_HORIZ_STRIDE, Type_UD);

  G4_Declare *fp =
      builder_->usesStack() ? builder_->kernel.fg.getFramePtrDcl() : nullptr;

  // compute hword offset to emit later when expanding spill/fill intrinsic
  G4_RegVar *r = fillRangeDcl->getRegVar();
  G4_RegVarTmp *rvar = static_cast<G4_RegVarTmp *>(r);
  int offset = getDisp(rvar->getBaseRegVar());
  getSpillOffset(offset);
  uint32_t totalByteOffset = (offset + spillOff * builder_->getGRFSize());
  // fill intrinsic expects offsets to be in HWord
  uint32_t offsetHwords = totalByteOffset >> SCRATCH_SPACE_ADDRESS_UNIT;

  G4_SrcRegRegion *header = getLSCSpillFillHeader(fp, totalByteOffset);
  auto fillInst =
      builder_->createFill(header, postDst, g4::SIMD16, height, offsetHwords,
                           fp, InstOpt_WriteEnable, true);
  fillInst->inheritDIFrom(curInst);
  return fillInst;
}

// Create the send instruction to perform the fill of the filled region's
// segment into fill memory.
G4_INST *SpillManagerGRF::createLSCFill(G4_Declare *fillRangeDcl,
                                        G4_SrcRegRegion *filledRangeRegion,
                                        G4_ExecSize execSize) {
  auto oldExecSize = execSize;

  G4_DstRegRegion *postDst = builder_->createDst(
      fillRangeDcl->getRegVar(), 0, SUBREG_ORIGIN, DEF_HORIZ_STRIDE, Type_UD);

  unsigned segmentByteSize = getSegmentByteSize(filledRangeRegion, oldExecSize);
  G4_Declare *fp =
      builder_->usesStack() ? builder_->kernel.fg.getFramePtrDcl() : nullptr;

  // compute hword offset to emit later when expanding spill/fill intrinsic
  int offset = getRegionDisp(filledRangeRegion);
  getSpillOffset(offset);
  uint32_t offsetHwords = offset >> SCRATCH_SPACE_ADDRESS_UNIT;

  unsigned responseLength =
      cdiv(segmentByteSize, builder_->numEltPerGRF<Type_UB>());
  G4_SrcRegRegion *header = getLSCSpillFillHeader(fp, offset);
  auto fillInst =
      builder_->createFill(header, postDst, execSize, responseLength,
                           offsetHwords, fp, InstOpt_WriteEnable, true);
  fillInst->inheritDIFrom(curInst);
  return fillInst;
}

// Replace the reference to the spilled region with a reference to an
// equivalent reference to the spill range region.
void SpillManagerGRF::replaceSpilledRange(G4_Declare *spillRangeDcl,
                                          G4_DstRegRegion *spilledRegion,
                                          G4_INST *spilledInst,
                                          uint32_t subRegOff) {
  // we need to preserve accRegSel if it's set
  G4_DstRegRegion *tmpRangeDstRegion = builder_->createDst(
      spillRangeDcl->getRegVar(), REG_ORIGIN, subRegOff,
      spilledRegion->getHorzStride(), spilledRegion->getType(),
      spilledRegion->getAccRegSel());
  spilledInst->setDest(tmpRangeDstRegion);
}

// Replace the reference to the filled region with a reference to an
// equivalent reference to the fill range region.
void SpillManagerGRF::replaceFilledRange(G4_Declare *fillRangeDcl,
                                         G4_SrcRegRegion *filledRegion,
                                         G4_INST *filledInst) {
  G4_ExecSize execSize = isMultiRegComprSource(filledRegion, filledInst)
                             ? G4_ExecSize(filledInst->getExecSize() / 2)
                             : filledInst->getExecSize();

  for (int i = 0, numSrc = filledInst->getNumSrc(); i < numSrc; i++) {
    G4_Operand *src = filledInst->getSrc(i);

    if (src && src->isSrcRegRegion()) {
      G4_SrcRegRegion *srcRgn = src->asSrcRegRegion();
      if (*srcRgn == *filledRegion) {
        G4_SrcRegRegion *fillRangeSrcRegion = createFillRangeSrcRegion(
            fillRangeDcl->getRegVar(), filledRegion, execSize);
        filledInst->setSrc(fillRangeSrcRegion, i);
      }
    }
  }
}

// Create the send instructions to write out the spillRangeDcl in aligned
// portions.
void SpillManagerGRF::sendOutSpilledRegVarPortions(G4_Declare *spillRangeDcl,
                                                   G4_Declare *mRangeDcl,
                                                   unsigned regOff,
                                                   unsigned height,
                                                   unsigned srcRegOff) {
  if (!headerNeeded()) {
    // No need to make a copy of offset because when using
    // scratch msg descriptor, the offset is part of send
    // msg descriptor and not the header.
  } else {
    // Initialize the message header with the spill disp for portion.
    int offset = getDisp(spillRangeDcl->getRegVar()) +
                 regOff * builder_->numEltPerGRF<Type_UB>();
    getSpillOffset(offset);
    unsigned segmentDisp = offset / OWORD_BYTE_SIZE;

    G4_Imm *segmentDispImm = builder_->createImm(segmentDisp, Type_UD);
    G4_DstRegRegion *mHeaderOffsetDstRegion =
        createMHeaderBlockOffsetDstRegion(mRangeDcl->getRegVar());

    if (builder_->getIsKernel() == false) {
      createAddFPInst(g4::SIMD1, mHeaderOffsetDstRegion, segmentDispImm);
    } else {
      createMovInst(g4::SIMD1, mHeaderOffsetDstRegion, segmentDispImm);
    }
  }

  // Write out the portions using a greedy approach.
  int currentStride = getNextSize(height, useScratchMsg_, *builder_);

  if (currentStride) {
    initMWritePayload(spillRangeDcl, mRangeDcl, regOff, currentStride);

    if (gra.useLscForSpillFill) {
      createLSCSpill(spillRangeDcl, regOff, currentStride, srcRegOff);
    } else {
      createSpillSendInstr(spillRangeDcl, mRangeDcl, regOff, currentStride,
                           srcRegOff);
    }

    if (height - currentStride > 0) {
      sendOutSpilledRegVarPortions(
          spillRangeDcl, mRangeDcl, regOff + currentStride,
          height - currentStride, srcRegOff + currentStride);
    }
  }
}

bool SpillManagerGRF::checkDefUseDomRel(G4_DstRegRegion *dst, G4_BB *defBB) {
  if (!refs.isUniqueDef(dst))
    return false;

  auto dcl = dst->getTopDcl();

  // check whether this def dominates all its uses
  auto uses = refs.getUses(dcl);

  for (auto &use : *uses) {
    auto useBB = std::get<1>(use);

    // check if def dominates use
    if (!defBB->dominates(useBB))
      return false;

    if (defBB == useBB) {
      // defBB dominates useBB since its the same BB.
      // ensure def instruction appears lexically before use BB.
      auto useInst = std::get<0>(use);
      if (dst->getInst()->getLexicalId() > useInst->getLexicalId())
        return false;
    }
  }

  // if def is in loop then ensure all uses are in same loop level
  // or inner loop nest of def's closest loop.
  auto defLoop = gra.kernel.fg.getLoops().getInnerMostLoop(defBB);
  if (defLoop) {
    // since def is in loop, check whether uses are also in same loop.
    for (auto &use : *uses) {
      auto useBB = std::get<1>(use);
      auto useLoop = gra.kernel.fg.getLoops().getInnerMostLoop(useBB);
      if (!useLoop)
        return false;

      if (!useLoop->fullSubset(defLoop))
        return false;
    }
  }

  return true;
}

bool SpillManagerGRF::checkUniqueDefAligned(G4_DstRegRegion *dst,
                                            G4_BB *defBB) {
  // return true if dst is unique definition considering alignment
  // for spill code.

  if (!refs.isUniqueDef(dst))
    return false;

  // dst dcl may have multiple defs. As long as each def defines
  // different part of the variable, each def is marked as unique.
  // However, spill/fill is done on GRF granularity. So although
  // defs are unique in following sequence, we still need RMW for
  // 2nd def:
  //
  // .decl V361 type=w size=32
  //
  // add (M1, 8) V361(0,0)<1>   V358(0,0)<1;1,0>   0x10:w
  // add (M1, 8) V361(0,8)<1>   V358(0,0)<1;1,0>   0x18:w
  //
  // Return false if any other dominating def exists that defines
  // part of same row of variable dst.
  auto dcl = dst->getTopDcl();

  if (dcl->getAddressed())
    return false;

  auto defs = refs.getDefs(dcl);
  unsigned int GRFSize = builder_->numEltPerGRF<Type_UB>();
  unsigned int lb = dst->getLeftBound();
  unsigned int rb = dst->getRightBound();
  unsigned int startRow = lb / GRFSize;
  unsigned int endRow = rb / GRFSize;

  for (auto &def : *defs) {
    // check whether dst and def write same row
    auto otherDefInst = std::get<0>(def);

    if (otherDefInst == dst->getInst())
      continue;

    auto otherDefDstRgn = otherDefInst->getDst();
    unsigned int otherLb = otherDefDstRgn->getLeftBound();
    unsigned int otherRb = otherDefDstRgn->getRightBound();
    unsigned int otherTypeSize = otherDefDstRgn->getTypeSize();
    bool commonRow = false;
    for (unsigned int i = otherLb; i <= otherRb; i += otherTypeSize) {
      auto rowWritten = i / GRFSize;
      if (rowWritten >= startRow && rowWritten <= endRow) {
        commonRow = true;
        break;
      }
    }

    // No common row between defs, so it is safe to skip fill
    // wrt current def. Check with next def.
    if (!commonRow)
      continue;

    auto otherDefBB = std::get<1>(def);

    if (!defBB->dominates(otherDefBB))
      return false;

    if (defBB == otherDefBB) {
      if (dst->getInst()->getLexicalId() > otherDefInst->getLexicalId())
        return false;
    }
  }

  return true;
}

bool SpillManagerGRF::isFirstLexicalDef(G4_DstRegRegion *dst) {
  // Check whether dst is lexically first def
  auto dcl = dst->getTopDcl();
  auto *defs = refs.getDefs(dcl);

  // Check whether any def has lower lexical id than dst
  for (auto& def : *defs) {
    auto *defInst = std::get<0>(def);
    if (defInst->getLexicalId() < dst->getInst()->getLexicalId())
      return false;
  }

  return true;
}

// This function checks whether each spill dst region requires a
// read-modify-write operation when inserting spill code. Dominator/unique defs
// don't require redundant read operation. Dst regions that do not need RMW are
// added to a set. This functionality isnt needed for functional correctness.
// This function is executed before inserting spill code because we need all dst
// regions of dcl available to decide whether read is redundant. If this is
// executed when inserting spill then dst regions of dcl appearing earlier than
// current one would be translated to spill code already. Spill/fill code
// insertion replaces dst region of spills with new temp region. This makes it
// difficult to check whether current dst and an earlier spilled dst write to
// same GRF row.
void SpillManagerGRF::updateRMWNeeded() {
  if (!gra.kernel.getOption(vISA_SkipRedundantFillInRMW))
    return;

  auto isRMWNeededForSpilledDst = [&](G4_BB *bb,
                                      G4_DstRegRegion *spilledRegion) {
    auto isUniqueDef = checkUniqueDefAligned(spilledRegion, bb);

    // Check0 : Def is NoMask, -- checked in isPartialWriteForSpill()
    // Check1 : Def is unique def,
    // Check2 : Def is in loop L and all use(s) of dcl are in loop L or it's
    //          inner loop nest,
    // Check3 : Flowgraph is reducible
    // Check4 : Dcl is not a split around loop temp
    // Check5 : bb is entryBB and spilledRegion is lexically first definition
    // RMW_Not_Needed = Check5 || ((Check0 || (Check1 && Check2 && Check3)) &&
    // Check4)
    bool RMW_Needed = true;

    // Reason for Check4:
    // ********************
    // Before:
    // Loop_Header:
    // V10:uq = ...
    // ...
    // jmpi Loop_Header
    // ...
    // = V10
    // ********************
    // After split around loop:
    //
    // (W) LOOP_TMP = V10
    // Loop_Header:
    // LOOP_TMP:uq = ...
    // ...
    // jmpi Loop_Header
    // (W) V10 = LOOP_TMP
    // ...
    // = V10
    // ********************
    // Since V10 is spilled already, spill/fill code is inserted as:
    // (Note that program no longer has direct references to V10)
    //
    // (W) FILL_TMP = Fill from V10 offset
    // (W) LOOP_TMP = FILL_TMP
    // Loop_Header:
    // LOOP_TMP:uq = ...
    // ...
    // jmpi Loop_Header
    // (W) SPILL_TMP = LOOP_TMP
    // (W) Spill SPILL_TMP to V10 offset
    // ...
    // (W) FILL_TMP1 = Fill from V10 offset
    // = FILL_TMP1
    // ********************
    //
    // If LOOP_TMP is spilled in later iteration, we need to check whether
    // RMW is needed for its def in the loop body. But by this iteration
    // all original references to V10 have already been transformed to
    // temporary ranges, so we cannot easily determine dominance relation
    // between LOOP_TMP and other V10 references. If LOOP_TMP doesn't
    // dominate all defs and uses then it would be illegal to skip RMW. Hence,
    // we conservatively assume RMW is required for LOOP_TMP.
    if (gra.splitResults.count(spilledRegion->getTopDcl()) == 0) {
      if (isUniqueDef && builder_->kernel.fg.isReducible() &&
          checkDefUseDomRel(spilledRegion, bb)) {
        RMW_Needed = false;
      }
    }

    // Check5
    if (RMW_Needed && bb == builder_->kernel.fg.getEntryBB()) {
      RMW_Needed = !isFirstLexicalDef(spilledRegion);
    }

    return RMW_Needed;
  };

  // First pass to setup lexical ids of instruction so dominator relation can be
  // computed correctly intra-BB.
  unsigned int lexId = 0;
  for (auto bb : gra.kernel.fg.getBBList()) {
    for (auto inst : bb->getInstList()) {
      inst->setLexicalId(lexId++);
    }
  }

  for (auto bb : gra.kernel.fg.getBBList()) {
    for (auto inst : bb->getInstList()) {
      if (inst->isPseudoKill())
        continue;

      auto dst = inst->getDst();
      if (!dst)
        continue;

      if (!dst->getBase()->isRegVar())
        continue;

      auto dstRegVar = dst->getBase()->asRegVar();
      if (dstRegVar && shouldSpillRegister(dstRegVar)) {
        if (getRFType(dstRegVar) != G4_GRF)
          continue;

        auto RMW_Needed = isRMWNeededForSpilledDst(bb, dst);
        if (!RMW_Needed) {
          // Any spilled dst region that doesnt need RMW
          // is added to noRMWNeeded set. This set is later
          // checked when inserting spill/fill code.
          noRMWNeeded.insert(dst);
        }
      }
    }
  }
}

// Return true if spill code for spilledRegion requires OW or LSC.
bool SpillManagerGRF::usesOWOrLSC(G4_DstRegRegion *spilledRegion) {
  auto inst = spilledRegion->getInst();

  // Use LSC always
  if (gra.useLscForNonStackCallSpillFill)
    return true;

  // * platform supports LSC and/or OW
  // * but we favor HW scratch, offset permitting
  //
  // If offset exceeds encoding limit, we emit OW/LSC instead.
  int spillOffset = (int)getSegmentDisp(spilledRegion, inst->getExecSize());
  getSpillOffset(spillOffset);
  return spillOffset >= SCRATCH_MSG_LIMIT;
}

// Create the code to create the spill range and save it to spill memory.
void SpillManagerGRF::insertSpillRangeCode(INST_LIST::iterator spilledInstIter,
                                           G4_BB *bb) {
  G4_ExecSize execSize = (*spilledInstIter)->getExecSize();
  G4_Declare *replacementRangeDcl;
  builder_->instList.clear();

  bool optimizeSplitLLR = false;
  G4_INST *inst = *spilledInstIter;
  G4_INST *spillSendInst = NULL;
  auto spilledRegion = inst->getDst();

  auto spillDcl = spilledRegion->getTopDcl()->getRootDeclare();
  if (!isScalarImmRespill(spillDcl) &&
      scalarImmSpill.find(spillDcl) != scalarImmSpill.end()) {
    // do not spill scalar immediate values
    bb->erase(spilledInstIter);
    return;
  }

  auto checkRMWNeeded = [this, spilledRegion]() {
    return noRMWNeeded.find(spilledRegion) == noRMWNeeded.end();
  };

  auto dstFullOverlapSrc = [this, inst]() {
    // For inst, check whether dst fully overlaps any source.
    // Return true if there's an overlap.
    // This is useful in deciding whether scatter should be used
    // or block spill should be used. When there's full overlap,
    // a fill is emitted for the source. So even if inst doesn't
    // use NoMask, it's preferable to use block spill.
    auto *dstDcl = inst->getDst()->getTopDcl();
    auto dstLb = inst->getDst()->getLeftBound();
    auto dstRb = inst->getDst()->getRightBound();
    for (unsigned int i = 0; i != inst->getNumSrc(); ++i) {
      auto *src = inst->getSrc(i);
      if (!src || src->getTopDcl() != dstDcl)
        continue;
      auto srcLb = src->getLeftBound();
      auto srcRb = src->getRightBound();
      if (dstLb <= srcLb && dstRb <= srcRb)
        return true;
    }
    return false;
  };

  auto isScatterSpillCandidate = [this, inst, dstFullOverlapSrc]() {
    // Conditions for scatter spill: inst can't be NoMask,
    // element size is W/DW/Q, isn't dst partial region, and
    // inst isn't predicated
    auto elemSz = inst->getDst()->getElemSize();
    auto fillAvailable = dstFullOverlapSrc();
    return gra.useLscForScatterSpill && !inst->isWriteEnableInst() &&
           (elemSz == 2 || elemSz == 4 || elemSz == 8) &&
           !isPartialRegion(inst->getDst(), inst->getExecSize()) &&
           !inst->getPredicate() && !fillAvailable;
  };


  // subreg offset for new dst that replaces the spilled dst
  auto newSubregOff = 0;

  if (inst->isSend() || inst->isDpas()) {
    // Handle send instructions (special treatment)
    // Create the spill range for the whole post destination, assign spill
    // offset to the spill range and create the instructions to load the
    // save the spill range to spill memory.
    INST_LIST::iterator sendOutIter = spilledInstIter;
    vASSERT(getRFType(spilledRegion) == G4_GRF);
    G4_Declare *spillRangeDcl = createPostDstSpillRangeDeclare(*sendOutIter);
    G4_Declare *mRangeDcl =
        createAndInitMHeader((G4_RegVarTransient *)spillRangeDcl->getRegVar());

    bool needRMW = inst->isPartialWriteForSpill(!bb->isAllLaneActive(),
                                                usesOWOrLSC(spilledRegion)) &&
                   checkRMWNeeded();
    if (needRMW) {
      sendInSpilledRegVarPortions(spillRangeDcl, mRangeDcl, 0,
                                  spillRangeDcl->getNumRows(),
                                  spilledRegion->getRegOff());

      INST_LIST::iterator insertPos = sendOutIter;
      splice(bb, insertPos, builder_->instList, curInst->getVISAId());
    }

    sendOutSpilledRegVarPortions(spillRangeDcl, mRangeDcl, 0,
                                 spillRangeDcl->getNumRows(),
                                 spilledRegion->getRegOff());

    replacementRangeDcl = spillRangeDcl;
  } else {
    // Handle other regular single/multi destination register instructions.
    // Create the spill range for the destination region, assign spill
    // offset to the spill range and create the instructions to load the
    // save the spill range to spill memory.

    // Create the segment aligned spill range
    G4_Declare *spillRangeDcl =
        createSpillRangeDeclare(spilledRegion, execSize, *spilledInstIter);

    // Create and initialize the message header
    G4_Declare *mRangeDcl = createAndInitMHeader(spilledRegion, execSize);

    // Unaligned region specific handling.
    unsigned int spillSendOption = InstOpt_WriteEnable;

    auto preloadNeeded = shouldPreloadSpillRange(*spilledInstIter, bb);
    auto scatterSpillCandidate = isScatterSpillCandidate();
    auto needsRMW = checkRMWNeeded();
    // Scatter spill is used only when the spill needs RMW.
    // If spill doesn't need RMW then we can use block spill as those
    // can be coalesced with nearby block spills.
    // If a fill was emitted then there's no need to use scatter as
    // we can use block spill that can be coalesced.
    auto useScatter = (scatterSpillCandidate && needsRMW);

    if (preloadNeeded && needsRMW && !scatterSpillCandidate) {

      // Preload the segment aligned spill range from memory to use
      // as an overlay

      preloadSpillRange(spillRangeDcl, mRangeDcl, spilledRegion, execSize);

      // Create the temporary range to use as a replacement range.

      G4_Declare *tmpRangeDcl =
          createTemporaryRangeDeclare(spilledRegion, execSize);

      // Copy out the value in the temporary range into its
      // location in the spill range.

      G4_DstRegRegion *spillRangeDstRegion = createSpillRangeDstRegion(
          spillRangeDcl->getRegVar(), spilledRegion, execSize);

      G4_SrcRegRegion *tmpRangeSrcRegion = createTemporaryRangeSrcRegion(
          tmpRangeDcl->getRegVar(), spilledRegion, execSize);

      // NOTE: Never use a predicate for the final mov if the spilled
      //       instruction was a sel (even in a SIMD CF context).

      G4_Predicate *predicate = ((*spilledInstIter)->opcode() != G4_sel)
                                    ? (*spilledInstIter)->getPredicate()
                                    : nullptr;

      if (tmpRangeSrcRegion->getType() == spillRangeDstRegion->getType() &&
          IS_TYPE_FLOAT_ALL(tmpRangeSrcRegion->getType())) {
        // use int copy when possible as floating-point copy moves may need
        // further legalization
        auto equivIntTy = floatToSameWidthIntType(tmpRangeSrcRegion->getType());
        tmpRangeSrcRegion->setType(*builder_, equivIntTy);
        spillRangeDstRegion->setType(*builder_, equivIntTy);
      }

      createMovInst(execSize, spillRangeDstRegion, tmpRangeSrcRegion,
                    builder_->duplicateOperand(predicate),
                    (*spilledInstIter)->getMaskOption());

      replacementRangeDcl = tmpRangeDcl;
      // maintain the spilled dst's subreg to not break the regioning
      // restriction
      newSubregOff = spilledRegion->getSubRegOff();
    } else {
      // We're here because:
      // 1. preloadNeeded = false AND checkRMWNeeded = true OR
      // 2. preloadNeeded = true AND checkRMWNeeded = false OR
      // 3. both are false
      //
      // Case (1) occurs when:
      // Def uses dword type and writes entire row. But def doesnt define
      // complete variable, ie it isnt a kill. For such cases, we need to
      // use def's EM on spill msg.
      //
      // Case (2) occurs when:
      // Def is partial but it is unique in the program. For such cases,
      // we should use WriteEnable msg.
      //
      // Case (3) occurs when:
      // Def uses dword type and write entire row. Def defines complete
      // variable. We can use either EM.

      // Aligned regions do not need a temporary range.
      LocalLiveRange *spilledLLR =
          gra.getLocalLR(spilledRegion->getBase()->asRegVar()->getDeclare());
      if (spilledLLR && spilledLLR->getSplit()) {
        // if we are spilling the dest of a copy move introduced by local
        // live-range splitting, we can spill the source value instead and
        // delete the move ToDo: we should generalize this to cover all moves
        G4_SrcRegRegion *srcRegion = inst->getSrc(0)->asSrcRegRegion();
        G4_Declare *srcDcl = srcRegion->getBase()->asRegVar()->getDeclare();
        unsigned int lb = srcRegion->getLeftBound();
        unsigned int rb = srcRegion->getRightBound();

        G4_RegVar *regVar = NULL;
        if (srcRegion->getBase()->isRegVar()) {
          regVar = getRegVar(srcRegion);
        }

        if (gra.getSubRegAlign(srcDcl) == builder_->getGRFAlign() &&
            lb % builder_->numEltPerGRF<Type_UB>() == 0 &&
            (rb + 1) % builder_->numEltPerGRF<Type_UB>() == 0 &&
            (rb - lb + 1) == spillRangeDcl->getByteSize() && regVar &&
            !shouldSpillRegister(regVar)) {
          optimizeSplitLLR = true;
        }
      }

      replacementRangeDcl = spillRangeDcl;
      // maintain the spilled dst's subreg since the spill is done on a per-GRF
      // basis
      newSubregOff = spilledRegion->getSubRegOff();

      if (preloadNeeded && isUnalignedRegion(spilledRegion, execSize)) {
        // A dst region may be not need pre-fill, however, if it is unaligned,
        // we need to use non-zero sub-reg offset in newly created spill dcl.
        // This section of code computes sub-reg offset to use for such cases.
        // It is insufficient to simply use spilledRegion's sub-reg offset in
        // case the region dcl is an alias of another dcl. This typically
        // happens when 2 scalar dcls are merged by merge scalar pass, merged
        // dcl is spilled, and dominating def writes non-zeroth element.
        unsigned segmentDisp =
            getEncAlignedSegmentDisp(spilledRegion, execSize);
        unsigned regionDisp = getRegionDisp(spilledRegion);
        vASSERT(regionDisp >= segmentDisp);
        unsigned short subRegOff =
            (regionDisp - segmentDisp) / spilledRegion->getElemSize();
        vASSERT((regionDisp - segmentDisp) % spilledRegion->getElemSize() == 0);
        vASSERT(subRegOff * spilledRegion->getElemSize() +
                    getRegionByteSize(spilledRegion, execSize) <=
                2u * builder_->numEltPerGRF<Type_UB>());
        newSubregOff = subRegOff;
      }

      if ((!bb->isAllLaneActive() && !preloadNeeded) || useScatter) {
        spillSendOption = (*spilledInstIter)->getMaskOption();
      }
    }

    // Save the spill range to memory.

    initMWritePayload(spillRangeDcl, mRangeDcl, spilledRegion, execSize);

    if (gra.useLscForSpillFill) {
      spillSendInst = createLSCSpill(spillRangeDcl, spilledRegion, execSize,
                                     spillSendOption, useScatter);
    } else {
      spillSendInst = createSpillSendInstr(
          spillRangeDcl, mRangeDcl, spilledRegion, execSize, spillSendOption);
    }

    if (failSafeSpill_ && !builder_->avoidDstSrcOverlap()) {
      spillRegOffset_ = spillRegStart_;
    }
  }

  if (builder_->getOption(vISA_DoSplitOnSpill)) {
    if (inst->isRawMov()) {
      // check whether mov is copy in loop preheader or exit
      auto it = gra.splitResults.find(inst->getSrc(0)->getTopDcl());
      if (it != gra.splitResults.end()) {
        if ((*it).second.origDcl == spillDcl) {
          // srcRegion is a split var temp
          // this is a copy in either preheader or loop exit.
          // add it to list so we know it shouldnt be optimized
          // by spill cleanup.
          for (auto addedInst : builder_->instList) {
            (*it).second.insts[bb].insert(addedInst);
          }
        }
      }
    }
  }

  // Replace the spilled range with the spill range and insert spill
  // instructions.

  INST_LIST::iterator insertPos = std::next(spilledInstIter);
  replaceSpilledRange(replacementRangeDcl, spilledRegion, *spilledInstIter,
                      newSubregOff);

  splice(bb, insertPos, builder_->instList, curInst->getVISAId());

  if (optimizeSplitLLR && spillSendInst && spillSendInst->isSplitSend()) {
    // delete the move and spill the source instead. Note that we can't do this
    // if split send is not enabled, as payload contains header
    bb->erase(spilledInstIter);
    unsigned int pos = 1;
    spillSendInst->setSrc(inst->getSrc(0), pos);
  } else {
    splice(bb, spilledInstIter, builder_->instList, curInst->getVISAId());
  }
}

bool SpillManagerGRF::isScalarImmRespill(G4_Declare* spillDcl) const
{
  return gra.scalarSpills.find(spillDcl) != gra.scalarSpills.end();
}

bool SpillManagerGRF::immFill(G4_SrcRegRegion *filledRegion,
                              INST_LIST::iterator filledInstIter, G4_BB *bb,
                              G4_Declare *spillDcl) {
  if (isScalarImmRespill(spillDcl)) {
    // Don't rematerialize spillDcl if it's a spilled dcl from
    // earlier RA iteration.
    return false;
  }

  G4_INST *inst = *filledInstIter;
  auto sisIt = scalarImmSpill.find(spillDcl);
  if (sisIt != scalarImmSpill.end()) {
    G4_Declare *tempDcl = nullptr;
    auto &nearbyFill = scalarImmFillCache[spillDcl];
    if (!failSafeSpill_ && std::get<0>(nearbyFill) == bb &&
        (inst->getLexicalId() - std::get<2>(nearbyFill)) <=
            scalarImmReuseDistance) {
      tempDcl = std::get<1>(nearbyFill)->getDst()->getTopDcl();
    } else {
      // re-materialize the scalar immediate value
      auto dstType = sisIt->second.first;
      auto *imm = sisIt->second.second;
      tempDcl = builder_->createTempVar(1, dstType, spillDcl->getSubRegAlign());
      auto movInst = builder_->createMov(
          g4::SIMD1, builder_->createDstRegRegion(tempDcl, 1), imm,
          InstOpt_WriteEnable, false);
      bb->insertBefore(filledInstIter, movInst);
      nearbyFill = std::make_tuple(bb, movInst, inst->getLexicalId());
      // tempDcl is fill dcl that rematerializes scalar immediate.
      // If tempDcl spills in later RA iteration we shouldn't
      // try to rematerialize the value. Instead we should
      // insert regular spill/fill code for it.
      gra.scalarSpills.insert(tempDcl);
      vASSERT(!filledRegion->isIndirect());
    }
    auto newSrc = builder_->createSrc(
        tempDcl->getRegVar(), filledRegion->getRegOff(),
        filledRegion->getSubRegOff(), filledRegion->getRegion(),
        filledRegion->getType(), filledRegion->getAccRegSel());
    newSrc->setModifier(filledRegion->getModifier());
    int i = 0;
    for (; i < inst->getNumSrc(); ++i) {
      if (inst->getSrc(i) == filledRegion) {
        break;
      }
    }
    inst->setSrc(newSrc, i);

    if (failSafeSpill_) {
      if (!gra.kernel.getOption(vISA_NewFailSafeRA)) {
        tempDcl->getRegVar()->setPhyReg(
            builder_->phyregpool.getGreg(spillRegOffset_), 0);
        spillRegOffset_ += 1;
      } else {
        tempDcl->getRegVar()->setPhyReg(
            builder_->phyregpool.getGreg(context.getFreeGRF(1)), 0);
      }
    }
    return true;
  }
  return false;
}

// Create the code to create the GRF fill range and load it to spill memory.
void SpillManagerGRF::insertFillGRFRangeCode(G4_SrcRegRegion *filledRegion,
                                             INST_LIST::iterator filledInstIter,
                                             G4_BB *bb) {
  G4_ExecSize execSize = (*filledInstIter)->getExecSize();

  // Create the fill range, assign spill offset to the fill range and
  // create the instructions to load the fill range from spill memory.

  G4_Declare *fillRangeDcl = nullptr;

  bool optimizeSplitLLR = false;
  G4_INST *inst = *filledInstIter;
  vISA_ASSERT(!inst->isSpillIntrinsic(), "must take send path");
  auto dstRegion = inst->getDst();
  G4_INST *fillSendInst = nullptr;
  auto spillDcl = filledRegion->getTopDcl()->getRootDeclare();

  if (immFill(filledRegion, filledInstIter, bb, spillDcl)) {
    return;
  }

  {
    fillRangeDcl =
        createGRFFillRangeDeclare(filledRegion, execSize, *filledInstIter);
    G4_Declare *mRangeDcl = createAndInitMHeader(filledRegion, execSize);

    if (gra.useLscForSpillFill) {
      fillSendInst =
          createLSCFill(fillRangeDcl, filledRegion, execSize);
    } else {
      fillSendInst =
          createFillSendInstr(fillRangeDcl, mRangeDcl, filledRegion, execSize);
    }

    LocalLiveRange *filledLLR =
        gra.getLocalLR(filledRegion->getBase()->asRegVar()->getDeclare());
    if (filledLLR && filledLLR->getSplit()) {
      G4_Declare *dstDcl = dstRegion->getBase()->asRegVar()->getDeclare();
      unsigned int lb = dstRegion->getLeftBound();
      unsigned int rb = dstRegion->getRightBound();

      if (gra.getSubRegAlign(dstDcl) == builder_->getGRFAlign() &&
          lb % builder_->numEltPerGRF<Type_UB>() == 0 &&
          (rb + 1) % builder_->numEltPerGRF<Type_UB>() == 0 &&
          (rb - lb + 1) == fillRangeDcl->getByteSize()) {
        optimizeSplitLLR = true;
      }
    }
  }

  if (builder_->getOption(vISA_DoSplitOnSpill)) {
    if (inst->isRawMov()) {
      // check whether mov is copy in loop preheader or exit
      auto it = gra.splitResults.find(dstRegion->getTopDcl());
      if (it != gra.splitResults.end()) {
        if ((*it).second.origDcl == filledRegion->getTopDcl()) {
          // dstRegion is a split var temp
          // this is a copy in either preheader or loop exit.
          // add it to list so we know it shouldnt be optimized
          // by spill cleanup.
          for (auto addedInst : builder_->instList) {
            (*it).second.insts[bb].insert(addedInst);
          }
        }
      }
    }
  }

  // Replace the spilled range with the fill range and insert spill
  // instructions.
  replaceFilledRange(fillRangeDcl, filledRegion, *filledInstIter);
  INST_LIST::iterator insertPos = filledInstIter;

  splice(bb, insertPos, builder_->instList, curInst->getVISAId());
  if (optimizeSplitLLR) {
    INST_LIST::iterator nextIter = filledInstIter;
    INST_LIST::iterator prevIter = filledInstIter;
    nextIter++;
    prevIter--;
    prevIter--;
    bb->erase(filledInstIter);
    fillSendInst->setDest(dstRegion);
    G4_INST *prevInst = (*prevIter);
    if (prevInst->isPseudoKill() &&
        GetTopDclFromRegRegion(prevInst->getDst()) == fillRangeDcl) {
      prevInst->setDest(builder_->createDst(
          GetTopDclFromRegRegion(dstRegion)->getRegVar(), 0, 0, 1, Type_UD));
    }
  }
}

// Create the code to create the GRF fill range and load it to spill memory.
void SpillManagerGRF::insertSendFillRangeCode(
    G4_SrcRegRegion *filledRegion, INST_LIST::iterator filledInstIter,
    G4_BB *bb) {
  G4_INST *sendInst = *filledInstIter;
  auto spillDcl = filledRegion->getTopDcl()->getRootDeclare();

  if (immFill(filledRegion, filledInstIter, bb, spillDcl)) {
    return;
  }

  unsigned width =
      builder_->numEltPerGRF<Type_UB>() / filledRegion->getElemSize();

  // Create the fill range, assign spill offset to the fill range

  G4_Declare *fillGRFRangeDcl =
      createSendFillRangeDeclare(filledRegion, sendInst);

  // Create the instructions to load the fill range from spill memory.

  G4_Declare *mRangeDcl = createMRangeDeclare(filledRegion, G4_ExecSize(width));
  initMHeader(mRangeDcl);
  sendInSpilledRegVarPortions(fillGRFRangeDcl, mRangeDcl, 0,
                              fillGRFRangeDcl->getNumRows(),
                              filledRegion->getRegOff());

  // Replace the spilled range with the fill range and insert spill
  // instructions.

  replaceFilledRange(fillGRFRangeDcl, filledRegion, *filledInstIter);
  INST_LIST::iterator insertPos = filledInstIter;

  splice(bb, insertPos, builder_->instList, curInst->getVISAId());
}

G4_Declare *SpillManagerGRF::getOrCreateAddrSpillFillDcl(
    G4_RegVar *addrDcl, G4_Declare *spilledAddrTakenDcl, G4_Kernel *kernel) {
  auto pointsToSet = gra.pointsToAnalysis.getAllInPointsToAddrExps(addrDcl);
  G4_Declare *temp = nullptr;
  bool created = false;

  // Create a spill/fill declare for the AddrExps which are assigned to same
  // address varaible and with same addressed varaible. Note that we are trying
  // to capture senorious (A1, 1:&V1), (A2, 2::&V1), where "1:" and "2:" means
  // different AddrExp. IGC is trying to use different address registers.
  // Scenarios   (A1, 1:&V1), (A1, 2:&V1) may happen, by should be rare. In this
  // case, only one declare will be created.
  std::vector<G4_AddrExp *> newAddExpList;
  for (const auto &pt : *pointsToSet) {
    G4_AddrExp *addrExp = pt.exp;
    G4_Declare *dcl = addrExp->getRegVar()->getDeclare();
    while (dcl->getAliasDeclare()) {
      dcl = dcl->getAliasDeclare();
    }

    // The variable V is spilled
    if (dcl == spilledAddrTakenDcl) {
      G4_AddrExp *currentAddrExp = getAddrTakenSpillFill(addrExp);

      // Either all are created, or none.
      if (created) {
        // Either all addr expressoins are null, or all are not null.
        vASSERT(currentAddrExp == nullptr);
      }

      if (currentAddrExp != nullptr) {
        return currentAddrExp->getRegVar()->getDeclare();
        ;
      }

      // Create the spill fill variable
      if (!created) {
        // If spilledAddrTakenDcl already has a spill/fill range created, return
        // it. Else create new one and return it.
        const char *dclName = kernel->fg.builder->getNameString(
            32, "ADDR_SP_FL_V%d_%d", spilledAddrTakenDcl->getDeclId(),
            getAddrSpillFillIndex());

        // temp is created of sub-class G4_RegVarTmp so that is
        // assigned infinite spill cost when coloring.
        temp = kernel->fg.builder->createDeclare(
            dclName, G4_GRF, spilledAddrTakenDcl->getNumElems(),
            spilledAddrTakenDcl->getNumRows(),
            spilledAddrTakenDcl->getElemType(), DeclareType::Tmp,
            spilledAddrTakenDcl->getRegVar());
        temp->setAddrSpillFill();
        G4_AddrExp *newAddExp = builder_->createAddrExp(
            temp->getRegVar(), addrExp->getOffset(), addrExp->getType());
        setAddrTakenSpillFill(addrExp, newAddExp);
        newAddExpList.push_back(newAddExp);
        created = true;
      } else {
        G4_AddrExp *newAddExp = builder_->createAddrExp(
            temp->getRegVar(), addrExp->getOffset(), addrExp->getType());
        setAddrTakenSpillFill(addrExp, newAddExp);
        newAddExpList.push_back(newAddExp);
      }
    }
  }
  for (auto newAddExp : newAddExpList) {
    gra.pointsToAnalysis.patchPointsToSet(addrDcl, newAddExp,
                                          newAddExp->getOffset());
  }

  return temp;
}

// For each address taken register spill find an available physical register
// and assign it to the decl. This physical register will be used for inserting
// spill/fill code for indirect reference instructions that point to the
// spilled range.
// Return true if enough registers found, false if sufficient registers
// unavailable.
bool SpillManagerGRF::handleAddrTakenSpills(
    G4_Kernel *kernel, PointsToAnalysis &pointsToAnalysis) {
  bool success = true;
  unsigned int numAddrTakenSpills = 0;

  for (const LiveRange *lr : *spilledLRs_) {
    if (lvInfo_->isAddressSensitive(lr->getVar()->getId())) {
      numAddrTakenSpills++;
    }
  }

  if (numAddrTakenSpills > 0) {
    insertAddrTakenSpillFill(kernel, pointsToAnalysis);
    prunePointsTo(kernel, pointsToAnalysis);
  }

  return success;
}

unsigned int
SpillManagerGRF::handleAddrTakenLSSpills(G4_Kernel *kernel,
                                         PointsToAnalysis &pointsToAnalysis) {
  unsigned int numAddrTakenSpills = 0;

  for (LSLiveRange *lr : *spilledLSLRs_) {
    if (lvInfo_->isAddressSensitive(lr->getTopDcl()->getRegVar()->getId())) {
      numAddrTakenSpills++;
    }
  }

  if (numAddrTakenSpills > 0) {
    insertAddrTakenLSSpillFill(kernel, pointsToAnalysis);
    prunePointsToLS(kernel, pointsToAnalysis);
  }

  return numAddrTakenSpills;
}

// Insert spill and fill code for indirect GRF accesses
void SpillManagerGRF::insertAddrTakenSpillAndFillCode(
    G4_Kernel *kernel, G4_BB *bb, INST_LIST::iterator inst_it, G4_Operand *opnd,
    PointsToAnalysis &pointsToAnalysis, bool spill, unsigned int bbid) {
  curInst = (*inst_it);
  INST_LIST::iterator next_inst_it = ++inst_it;
  inst_it--;
  bool BBhasSpillCode = false;

  // Check whether spill operand points to any spilled range
  for (const LiveRange *lr : *spilledLRs_) {
    G4_RegVar *var = nullptr;

    if (opnd->isDstRegRegion() && opnd->asDstRegRegion()->getBase()->asRegVar())
      var = opnd->asDstRegRegion()->getBase()->asRegVar();

    if (opnd->isSrcRegRegion() && opnd->asSrcRegRegion()->getBase()->asRegVar())
      var = opnd->asSrcRegRegion()->getBase()->asRegVar();

    vISA_ASSERT(var != NULL, "Fill operand is neither a source nor dst region");

    if (var && pointsToAnalysis.isPresentInPointsTo(var, lr->getVar())) {
      BBhasSpillCode = true;
      unsigned int numrows = lr->getDcl()->getNumRows();
      G4_Declare *temp = getOrCreateAddrSpillFillDcl(var, lr->getDcl(), kernel);

      if (failSafeSpill_) {
        if (!kernel->getOption(vISA_NewFailSafeRA) &&
            !temp->getRegVar()->getPhyReg()) {
          temp->getRegVar()->setPhyReg(
              builder_->phyregpool.getGreg(spillRegOffset_), 0);
          spillRegOffset_ += numrows;
        } else {
          context.setInst(curInst, bb);
          context.prev = inst_it;
          if (curInst == bb->front())
            context.prev = bb->begin();
          else
            --context.prev;
          context.next = next_inst_it;
          context.setAddrDcl(var->getDeclare());
          if (!temp->getRegVar()->getPhyReg()) {
            // choose GRFs to assign to new range
            temp->getRegVar()->setPhyReg(
                builder_->phyregpool.getGreg(context.getFreeGRFIndir(numrows)),
                0);
          }
          context.markClobbered(
              temp->getRegVar()->getPhyReg()->asGreg()->getRegNum(), numrows);
          context.resetAddrDcl();
        }
      }

      if (numrows > 1 ||
          (lr->getDcl()->getNumElems() * lr->getDcl()->getElemSize() ==
           builder_->getGRFSize())) {
        if (useScratchMsg_ || useSplitSend()) {
          G4_Declare *fillGRFRangeDcl = temp;
          G4_Declare *mRangeDcl = createAndInitMHeader(
              (G4_RegVarTransient *)temp->getRegVar()->getBaseRegVar());

          kernel->fg.builder->createPseudoKill(temp, PseudoKillType::Other,
                                               true);

          sendInSpilledRegVarPortions(fillGRFRangeDcl, mRangeDcl, 0,
                                      temp->getNumRows(), 0);

          splice(bb, inst_it, builder_->instList, curInst->getVISAId());

          if (spill) {
            sendOutSpilledRegVarPortions(temp, mRangeDcl, 0, temp->getNumRows(),
                                         0);

            splice(bb, next_inst_it, builder_->instList, curInst->getVISAId());
          }
        } else {

          for (unsigned int i = 0; i < numrows; i++) {
            G4_INST *inst;
            const RegionDesc *rd = kernel->fg.builder->getRegionStride1();
            G4_ExecSize curExSize{builder_->numEltPerGRF<Type_UD>()};

            if ((i + 1) < numrows)
              curExSize = G4_ExecSize(builder_->numEltPerGRF<Type_UD>() * 2);

            G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
                lr->getVar(), (short)i, 0, rd, Type_F);

            G4_DstRegRegion *dstRex = kernel->fg.builder->createDst(
                temp->getRegVar(), (short)i, 0, 1, Type_F);

            inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                                 InstOpt_WriteEnable, false);

            bb->insertBefore(inst_it, inst);

            if (spill) {
              // Also insert spill code
              G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
                  temp->getRegVar(), (short)i, 0, rd, Type_F);

              G4_DstRegRegion *dstRex = kernel->fg.builder->createDst(
                  lr->getVar(), (short)i, 0, 1, Type_F);

              inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                                   InstOpt_WriteEnable, false);

              bb->insertBefore(next_inst_it, inst);
            }

            // If 2 rows were processed then increment induction var suitably
            if (curExSize == 16)
              i++;
          }
        }

        // Update points to
        // Note: points2 set should be updated after inserting fill code,
        // however, this sets a bit in liveness bit-vector that
        // causes the temp variable to be marked as live-out from
        // that BB. A general fix should treat address taken variables
        // more accurately wrt liveness so they don't escape via
        // unfeasible paths.
        // pointsToAnalysis.addFillToPointsTo(bbid, var, temp->getRegVar());
      } else if (numrows == 1) {
        // Insert spill/fill when there decl uses a single row, that too not
        // completely
        G4_ExecSize curExSize = g4::SIMD16;
        unsigned short numbytes =
            lr->getDcl()->getNumElems() * lr->getDcl()->getElemSize();

        // temp->setAddressed();
        short off = 0;

        while (numbytes > 0) {
          G4_INST *inst;
          G4_Type type = Type_W;

          if (numbytes >= 16)
            curExSize = g4::SIMD8;
          else if (numbytes >= 8 && numbytes < 16)
            curExSize = g4::SIMD4;
          else if (numbytes >= 4 && numbytes < 8)
            curExSize = g4::SIMD2;
          else if (numbytes >= 2 && numbytes < 4)
            curExSize = g4::SIMD1;
          else if (numbytes == 1) {
            // If a region has odd number of bytes, copy last byte in final
            // iteration
            curExSize = g4::SIMD1;
            type = Type_UB;
          } else {
            vISA_ASSERT(false, "Cannot emit SIMD1 for byte");
            curExSize = G4_ExecSize(0);
          }

          const RegionDesc *rd = kernel->fg.builder->getRegionStride1();

          G4_SrcRegRegion *srcRex =
              kernel->fg.builder->createSrc(lr->getVar(), 0, off, rd, type);

          G4_DstRegRegion *dstRex =
              kernel->fg.builder->createDst(temp->getRegVar(), 0, off, 1, type);

          inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                               InstOpt_WriteEnable, false);

          bb->insertBefore(inst_it, inst);

          if (spill) {
            // Also insert spill code
            G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
                temp->getRegVar(), 0, off, rd, type);

            G4_DstRegRegion *dstRex =
                kernel->fg.builder->createDst(lr->getVar(), 0, off, 1, type);

            inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                                 InstOpt_WriteEnable, false);

            bb->insertBefore(next_inst_it, inst);
          }

          off += curExSize;
          numbytes -= curExSize * 2;
        }

        // Update points to
        // pointsToAnalysis.addFillToPointsTo(bbid, var, temp->getRegVar());
      }

      if (!spill) {
        // Insert pseudo_use node so that liveness keeps the
        // filled variable live through the indirect access.
        // Not required for spill because for spill we will
        // anyway insert a ues of the variable to emit store.
        const RegionDesc *rd = kernel->fg.builder->getRegionScalar();

        G4_SrcRegRegion *pseudoUseSrc =
            kernel->fg.builder->createSrc(temp->getRegVar(), 0, 0, rd, Type_F);

        G4_INST *pseudoUseInst =
            kernel->fg.builder->createInternalIntrinsicInst(
                nullptr, Intrinsic::Use, g4::SIMD1, nullptr, pseudoUseSrc,
                nullptr, nullptr, InstOpt_NoOpt);

        bb->insertBefore(next_inst_it, pseudoUseInst);
      }

      if (failSafeSpill_ && builder_->getOption(vISA_NewFailSafeRA)) {
        context.insertPushPop(gra.useLscForSpillFill);
      }
    }
  }

  if (BBhasSpillCode)
    gra.addSpillCodeInBB(bb);
}

// Insert spill and fill code for indirect GRF accesses
void SpillManagerGRF::insertAddrTakenLSSpillAndFillCode(
    G4_Kernel *kernel, G4_BB *bb, INST_LIST::iterator inst_it, G4_Operand *opnd,
    PointsToAnalysis &pointsToAnalysis, bool spill, unsigned int bbid) {
  curInst = (*inst_it);
  INST_LIST::iterator next_inst_it = ++inst_it;
  inst_it--;

  // Check whether spill operand points to any spilled range
  for (LSLiveRange *lr : *spilledLSLRs_) {
    G4_RegVar *var = nullptr;

    if (opnd->isDstRegRegion() && opnd->asDstRegRegion()->getBase()->asRegVar())
      var = opnd->asDstRegRegion()->getBase()->asRegVar();

    if (opnd->isSrcRegRegion() && opnd->asSrcRegRegion()->getBase()->asRegVar())
      var = opnd->asSrcRegRegion()->getBase()->asRegVar();

    vISA_ASSERT(var != NULL, "Fill operand is neither a source nor dst region");

    if (var && pointsToAnalysis.isPresentInPointsTo(
                   var, lr->getTopDcl()->getRegVar())) {
      unsigned int numrows = lr->getTopDcl()->getNumRows();
      G4_Declare *temp =
          getOrCreateAddrSpillFillDcl(var, lr->getTopDcl(), kernel);
      vISA_ASSERT(temp != nullptr,
                  "Failed to get the fill variable for indirect GRF access");
      if (failSafeSpill_ && temp->getRegVar()->getPhyReg() == NULL) {

        temp->getRegVar()->setPhyReg(
            builder_->phyregpool.getGreg(spillRegOffset_), 0);
        spillRegOffset_ += numrows;
      }

      if (numrows > 1 ||
          (lr->getTopDcl()->getNumElems() * lr->getTopDcl()->getElemSize() ==
           builder_->getGRFSize())) {
        if (useScratchMsg_ || useSplitSend()) {
          G4_Declare *fillGRFRangeDcl = temp;
          G4_Declare *mRangeDcl = createAndInitMHeader(
              (G4_RegVarTransient *)temp->getRegVar()->getBaseRegVar());

          sendInSpilledRegVarPortions(fillGRFRangeDcl, mRangeDcl, 0,
                                      temp->getNumRows(), 0);

          splice(bb, inst_it, builder_->instList, curInst->getVISAId());

          if (spill) {
            sendOutSpilledRegVarPortions(temp, mRangeDcl, 0, temp->getNumRows(),
                                         0);

            splice(bb, next_inst_it, builder_->instList, curInst->getVISAId());
          }
        } else {

          for (unsigned int i = 0; i < numrows; i++) {
            G4_INST *inst;
            const RegionDesc *rd = kernel->fg.builder->getRegionStride1();
            G4_ExecSize curExSize{builder_->numEltPerGRF<Type_UD>()};

            if ((i + 1) < numrows)
              curExSize = G4_ExecSize(builder_->numEltPerGRF<Type_UD>() * 2);

            G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
                lr->getTopDcl()->getRegVar(), (short)i, 0, rd, Type_F);

            G4_DstRegRegion *dstRex = kernel->fg.builder->createDst(
                temp->getRegVar(), (short)i, 0, 1, Type_F);

            inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                                 InstOpt_WriteEnable, false);

            bb->insertBefore(inst_it, inst);

            if (spill) {
              // Also insert spill code
              G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
                  temp->getRegVar(), (short)i, 0, rd, Type_F);

              G4_DstRegRegion *dstRex = kernel->fg.builder->createDst(
                  lr->getTopDcl()->getRegVar(), (short)i, 0, 1, Type_F);

              inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                                   InstOpt_WriteEnable, false);

              bb->insertBefore(next_inst_it, inst);
            }

            // If 2 rows were processed then increment induction var suitably
            if (curExSize == 16)
              i++;
          }
        }

        // Update points to
        // Note: points2 set should be updated after inserting fill code,
        // however, this sets a bit in liveness bit-vector that
        // causes the temp variable to be marked as live-out from
        // that BB. A general fix should treat address taken variables
        // more accurately wrt liveness so they don't escape via
        // unfeasible paths.
        // pointsToAnalysis.addFillToPointsTo(bbid, var, temp->getRegVar());
      } else if (numrows == 1) {
        // Insert spill/fill when there decl uses a single row, that too not
        // completely
        G4_ExecSize curExSize = g4::SIMD16;
        unsigned short numbytes =
            lr->getTopDcl()->getNumElems() * lr->getTopDcl()->getElemSize();

        // temp->setAddressed();
        short off = 0;

        while (numbytes > 0) {
          G4_INST *inst;
          G4_Type type = Type_W;

          if (numbytes >= 16)
            curExSize = g4::SIMD8;
          else if (numbytes >= 8 && numbytes < 16)
            curExSize = g4::SIMD4;
          else if (numbytes >= 4 && numbytes < 8)
            curExSize = g4::SIMD2;
          else if (numbytes >= 2 && numbytes < 4)
            curExSize = g4::SIMD1;
          else if (numbytes == 1) {
            // If a region has odd number of bytes, copy last byte in final
            // iteration
            curExSize = g4::SIMD1;
            type = Type_UB;
          } else {
            vISA_ASSERT(false, "Cannot emit SIMD1 for byte");
            curExSize = G4_ExecSize(0);
          }

          const RegionDesc *rd = kernel->fg.builder->getRegionStride1();

          G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
              lr->getTopDcl()->getRegVar(), 0, off, rd, type);

          G4_DstRegRegion *dstRex =
              kernel->fg.builder->createDst(temp->getRegVar(), 0, off, 1, type);

          inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                               InstOpt_WriteEnable, false);

          bb->insertBefore(inst_it, inst);

          if (spill) {
            // Also insert spill code
            G4_SrcRegRegion *srcRex = kernel->fg.builder->createSrc(
                temp->getRegVar(), 0, off, rd, type);

            G4_DstRegRegion *dstRex = kernel->fg.builder->createDst(
                lr->getTopDcl()->getRegVar(), 0, off, 1, type);

            inst = kernel->fg.builder->createMov(curExSize, dstRex, srcRex,
                                                 InstOpt_WriteEnable, false);

            bb->insertBefore(next_inst_it, inst);
          }

          off += curExSize;
          numbytes -= curExSize * 2;
        }

        // Update points to
        // pointsToAnalysis.addFillToPointsTo(bbid, var, temp->getRegVar());
      }

      if (!spill) {
        // Insert pseudo_use node so that liveness keeps the
        // filled variable live through the indirect access.
        // Not required for spill because for spill we will
        // anyway insert a ues of the variable to emit store.
        const RegionDesc *rd = kernel->fg.builder->getRegionScalar();

        G4_SrcRegRegion *pseudoUseSrc =
            kernel->fg.builder->createSrc(temp->getRegVar(), 0, 0, rd, Type_F);

        G4_INST *pseudoUseInst =
            kernel->fg.builder->createInternalIntrinsicInst(
                nullptr, Intrinsic::Use, g4::SIMD1, nullptr, pseudoUseSrc,
                nullptr, nullptr, InstOpt_NoOpt);

        bb->insertBefore(next_inst_it, pseudoUseInst);
      }
    }
  }
}

// Insert any spill/fills for address taken
void SpillManagerGRF::insertAddrTakenSpillFill(
    G4_Kernel *kernel, PointsToAnalysis &pointsToAnalysis) {
  if (failSafeSpill_) {
    if (kernel->getOption(vISA_NewFailSafeRA)) {
      context.markIndirIntfs();
    }
  }

  for (auto bb : kernel->fg) {
    for (INST_LIST_ITER inst_it = bb->begin(); inst_it != bb->end();
         inst_it++) {
      G4_INST *curInst = (*inst_it);

      if (failSafeSpill_) {
        spillRegOffset_ = indrSpillRegStart_;
      }

      // Handle indirect destination
      G4_DstRegRegion *dst = curInst->getDst();

      if (dst && dst->getRegAccess() == IndirGRF) {
        insertAddrTakenSpillAndFillCode(kernel, bb, inst_it, dst,
                                        pointsToAnalysis, true, bb->getId());
      }

      for (int i = 0, numSrc = curInst->getNumSrc(); i < numSrc; i++) {
        G4_Operand *src = curInst->getSrc(i);

        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getRegAccess() == IndirGRF) {
          insertAddrTakenSpillAndFillCode(kernel, bb, inst_it, src,
                                          pointsToAnalysis, false, bb->getId());
        }
      }
    }
  }
}

void SpillManagerGRF::insertAddrTakenLSSpillFill(
    G4_Kernel *kernel, PointsToAnalysis &pointsToAnalysis) {
  for (auto bb : kernel->fg) {
    for (INST_LIST_ITER inst_it = bb->begin(); inst_it != bb->end();
         inst_it++) {
      G4_INST *curInst = (*inst_it);

      if (failSafeSpill_) {
        spillRegOffset_ = indrSpillRegStart_;
      }

      // Handle indirect destination
      G4_DstRegRegion *dst = curInst->getDst();

      if (dst && dst->getRegAccess() == IndirGRF) {
        insertAddrTakenLSSpillAndFillCode(kernel, bb, inst_it, dst,
                                          pointsToAnalysis, true, bb->getId());
      }

      for (int i = 0, numSrc = curInst->getNumSrc(); i < numSrc; i++) {
        G4_Operand *src = curInst->getSrc(i);

        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getRegAccess() == IndirGRF) {
          insertAddrTakenLSSpillAndFillCode(
              kernel, bb, inst_it, src, pointsToAnalysis, false, bb->getId());
        }
      }
    }
  }
}

// For address spill/fill code inserted remove from points of each indirect
// operand the original regvar that is spilled.
void SpillManagerGRF::prunePointsTo(G4_Kernel *kernel,
                                    PointsToAnalysis &pointsToAnalysis) {
  for (auto bb : kernel->fg) {
    for (INST_LIST_ITER inst_it = bb->begin(); inst_it != bb->end();
         inst_it++) {
      G4_INST *curInst = (*inst_it);
      std::stack<G4_Operand *> st;

      // Handle indirect destination
      G4_DstRegRegion *dst = curInst->getDst();

      if (dst && dst->getRegAccess() == IndirGRF) {
        st.push(dst);
      }

      for (int i = 0, numSrc = curInst->getNumSrc(); i < numSrc; i++) {
        G4_Operand *src = curInst->getSrc(i);

        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getRegAccess() == IndirGRF) {
          st.push(src);
        }

        // Replace the variable in the address expression with fill variable
        if (src && src->isAddrExp()) {
          G4_AddrExp *addExp = getAddrTakenSpillFill(src->asAddrExp());
          if (addExp != nullptr) {
            curInst->setSrc(addExp, i);
          }
        }
      }

      while (st.size() > 0) {
        G4_Operand *cur = st.top();
        st.pop();

        // Check whether spill operand points to any spilled range
        for (const LiveRange *lr : *spilledLRs_) {
          G4_RegVar *var = nullptr;

          if (cur->isDstRegRegion() &&
              cur->asDstRegRegion()->getBase()->asRegVar())
            var = cur->asDstRegRegion()->getBase()->asRegVar();

          if (cur->isSrcRegRegion() &&
              cur->asSrcRegRegion()->getBase()->asRegVar())
            var = cur->asSrcRegRegion()->getBase()->asRegVar();

          vISA_ASSERT(var != nullptr,
                      "Operand is neither a source nor dst region");

          if (var && pointsToAnalysis.isPresentInPointsTo(var, lr->getVar())) {
            // Remove this from points to
            pointsToAnalysis.removeFromPointsTo(var, lr->getVar());
          }
        }
      }
    }
  }
}

void SpillManagerGRF::prunePointsToLS(G4_Kernel *kernel,
                                      PointsToAnalysis &pointsToAnalysis) {
  for (auto bb : kernel->fg) {
    for (INST_LIST_ITER inst_it = bb->begin(); inst_it != bb->end();
         inst_it++) {
      G4_INST *curInst = (*inst_it);
      std::stack<G4_Operand *> st;

      // Handle indirect destination
      G4_DstRegRegion *dst = curInst->getDst();

      if (dst && dst->getRegAccess() == IndirGRF) {
        st.push(dst);
      }

      for (int i = 0, numSrc = curInst->getNumSrc(); i < numSrc; i++) {
        G4_Operand *src = curInst->getSrc(i);

        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getRegAccess() == IndirGRF) {
          st.push(src);
        }

        // Replace the variable in the address expression with fill variable
        if (src && src->isAddrExp()) {
          G4_AddrExp *addExp = getAddrTakenSpillFill(src->asAddrExp());
          if (addExp != nullptr) {
            curInst->setSrc(addExp, i);
          }
        }
      }

      while (st.size() > 0) {
        G4_Operand *cur = st.top();
        st.pop();

        // Check whether spill operand points to any spilled range
        for (LSLiveRange *lr : *spilledLSLRs_) {
          G4_RegVar *var = nullptr;

          if (cur->isDstRegRegion() &&
              cur->asDstRegRegion()->getBase()->asRegVar())
            var = cur->asDstRegRegion()->getBase()->asRegVar();

          if (cur->isSrcRegRegion() &&
              cur->asSrcRegRegion()->getBase()->asRegVar())
            var = cur->asSrcRegRegion()->getBase()->asRegVar();

          vISA_ASSERT(var != NULL,
                      "Operand is neither a source nor dst region");

          if (var && pointsToAnalysis.isPresentInPointsTo(
                         var, lr->getTopDcl()->getRegVar())) {
            // Remove this from points to
            pointsToAnalysis.removeFromPointsTo(var,
                                                lr->getTopDcl()->getRegVar());
          }
        }
      }
    }
  }
}

void SpillManagerGRF::immMovSpillAnalysis() {
  if (!builder_->getOption(vISA_FillConstOpt))
    return;

  std::unordered_set<G4_Declare *> spilledDcl;
  scalarImmSpill.clear();

  for (auto bb : gra.kernel.fg) {
    for (auto inst : *bb) {
      if (inst->isPseudoKill())
        continue;
      auto dst = inst->getDst();
      auto dcl = dst && dst->getTopDcl() ? dst->getTopDcl()->getRootDeclare()
                                         : nullptr;
      if (!dcl || dcl->getAddressed() || dcl->getNumElems() != 1 ||
          !shouldSpillRegister(dcl->getRegVar())) {
        // declare must be a scalar without address taken
        continue;
      }
      if (spilledDcl.count(dcl)) {
        // this spilled declare is defined more than once
        scalarImmSpill.erase(dcl);
        continue;
      }
      spilledDcl.insert(dcl);
      if (immFillCandidate(inst)) {
        scalarImmSpill[dcl] =
            std::make_pair(dst->getType(), inst->getSrc(0)->asImm());
      }
    }
  }
}

bool vISA::isEOTSpillWithFailSafeRA(const IR_Builder &builder,
                                    const LiveRange *lr, bool isFailSafeIter) {
  bool needsEOTGRF = lr->getEOTSrc() && builder.hasEOTGRFBinding();
  if (isFailSafeIter && needsEOTGRF &&
      (lr->getVar()->isRegVarTransient() || lr->getVar()->isRegVarTmp() ||
       lr->getIsInfiniteSpillCost()))
    return true;
  return false;
}

// Insert spill/fill code for all registers that have not been assigned
// physical registers in the current iteration of the graph coloring
// allocator.
// returns false if spill fails somehow
bool SpillManagerGRF::insertSpillFillCode(G4_Kernel *kernel,
                                          PointsToAnalysis &pointsToAnalysis) {
  immMovSpillAnalysis();

  //  Set the spill flag of all spilled regvars.
  for (const LiveRange *lr : *spilledLRs_) {

    // Ignore request to spill/fill the spill/fill ranges
    // as it does not help the allocator.
    if (shouldSpillRegister(lr->getVar()) == false) {
      if (isEOTSpillWithFailSafeRA(*builder_, lr, failSafeSpill_)) {
        if (!builder_->getOption(vISA_NewFailSafeRA)) {
          lr->getVar()->setPhyReg(
              builder_->phyregpool.getGreg(
                  spillRegStart_ > (kernel->getNumRegTotal() - 16)
                      ? spillRegStart_
                      : (kernel->getNumRegTotal() - 16)),
              0);
        }
        continue;
      }
      return false;
    } else {
      lr->getVar()->getDeclare()->setSpillFlag();
      gra.incRA.markForIntfUpdate(lr->getDcl());
    }
  }

  if (doSpillSpaceCompression) {
    // cache spilling intervals in sorted order so we can use these
    // for spill compression.
    for (auto& segment : spillIntf_->getAugmentation().getSortedLiveIntervals()) {
      auto *dcl = segment.dcl;
      if (dcl->isSpilled())
        spillingIntervals.push_back(dcl);
    }
  }

  if (failSafeSpill_ && builder_->getOption(vISA_NewFailSafeRA)) {
    context.computeAllBusy();
  }

  // Handle address taken spills
  bool success = handleAddrTakenSpills(kernel, pointsToAnalysis);

  if (!success) {
    // FIXME: this should be an assert?
    VISA_DEBUG(std::cout << "Enough physical register not available for "
                            "handling address taken spills\n");
    return false;
  }

  if (kernel->getOption(vISA_DoSplitOnSpill)) {
    // remove all spilled splits
    for (const LiveRange *lr : *spilledLRs_) {
      auto dcl = lr->getDcl();
      // check whether spilled variable is one of split vars
      if (gra.splitResults.find(dcl) == gra.splitResults.end())
        continue;

      gra.incRA.markForIntfUpdate(dcl);
      LoopVarSplit::removeAllSplitInsts(&gra, dcl);
    }
  }

  // Insert spill/fill code for all basic blocks.
  updateRMWNeeded();
  FlowGraph &fg = kernel->fg;

  unsigned int id = 0;
  for (BB_LIST_ITER it = fg.begin(); it != fg.end(); it++) {
    bbId_ = (*it)->getId();
    INST_LIST::iterator jt = (*it)->begin();
    bool BBhasSpillCode = false;

    while (jt != (*it)->end()) {
      INST_LIST::iterator kt = jt;
      ++kt;
      G4_INST *inst = *jt;

      curInst = inst;
      curInst->setLexicalId(id++);

      if (failSafeSpill_) {
        spillRegOffset_ = spillRegStart_;
        if (kernel->getOption(vISA_NewFailSafeRA)) {
          context.setInst(curInst, (*it));
          context.next = kt;
          if ((*it)->front() == inst)
            context.prev = (*it)->begin();
          else {
            auto prev = jt;
            context.prev = --prev;
          }
        }
      }

      // Insert spill code, when the target is a spilled register.

      if (inst->getDst()) {
        G4_RegVar *regVar = nullptr;
        if (inst->getDst()->getBase()->isRegVar()) {
          regVar = getRegVar(inst->getDst());
        }

        if (regVar && shouldSpillRegister(regVar)) {
          if (getRFType(regVar) == G4_GRF) {
            if (inst->isPseudoKill()) {
              (*it)->erase(jt);
              jt = kt;
              continue;
            }
            insertSpillRangeCode(jt, (*it));
            BBhasSpillCode = true;
          } else {
            vASSERT(false);
          }
        }
      }

      // Insert fill code, when the source is a spilled register.

      for (unsigned i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
        if (inst->getSrc(i) && inst->getSrc(i)->isSrcRegRegion()) {
          auto srcRR = inst->getSrc(i)->asSrcRegRegion();
          G4_RegVar *regVar = nullptr;
          if (srcRR->getBase()->isRegVar()) {
            regVar = getRegVar(srcRR);
          }

          if (regVar && shouldSpillRegister(regVar)) {
            if (inst->isLifeTimeEnd()) {
              (*it)->erase(jt);
              break;
            }
            bool useSendFill = (inst->isSend() && i == 0) || inst->isDpas() ||
                               (inst->isSplitSend() && i == 1) ||
                               (inst->isSpillIntrinsic());

            if (useSendFill) {
              // this path may be taken if current instruction is a spill
              // intrinsic. for eg, V81 below is not spilled in 1st RA
              // iteration:
              // clang-format off
              // mov (16)             SP_GRF_V167_0(0,0)<1>:w   V81(0,0)<1;1,0>:w
              // (W) intrinsic.spill.1 (16)  Scratch[0x32]  R0_Copy0(0,0)<1;1,0>:ud  SP_GRF_V167_0(0,0)<1;1,0>:w
              // mov (16)             SP_GRF_V167_1(0,0)<1>:w  V81(1,0)<1;1,0>:w
              // (W) intrinsic.spill.1 (16)  Scratch[1x32]  R0_Copy0(0,0)<1;1,0>:ud  SP_GRF_V167_1(0,0)<1;1,0>:w
              // mov (16)             SP_GRF_V167_2(0,0)<1>:w  V81(2,0)<1;1,0>:w
              // (W) intrinsic.spill.1 (16)  Scratch[2x32]  R0_Copy0(0,0)<1;1,0>:ud  SP_GRF_V167_2(0,0)<1;1,0>:w
              // mov (16)             SP_GRF_V167_3(0,0)<1>:w  V81(3,0)<1;1,0>:w
              // (W) intrinsic.spill.1 (16)  Scratch[3x32]  R0_Copy0(0,0)<1;1,0>:ud  SP_GRF_V167_3(0,0)<1;1,0>:w
              //
              // ==> spill cleanup emits (notice spill range V81 appears in
              // spill intrinsic but is not spilled itself):
              //
              // (W) intrinsic.spill.4 (16)  Scratch[0x32]  R0_Copy0(0,0)<1;1,0>:ud  V81(0,0)<1;1,0>:ud
              //
              // in next RA iteration assume V81 spills. so we should emit:
              //
              // (W) intrinsic.fill.4 (16)  FL_Send_V81_0(0,0)<1>:uw  R0_Copy0(0,0)<1;1,0>:ud  Scratch[88x32]
              // (W) intrinsic.spill.4 (16)  Scratch[0x32]  R0_Copy0(0,0)<1;1,0>:ud  FL_Send_V81_0(0,0)<1;1,0>:ud
              // clang-format on
              //
              // V81 appears in spill intrinsic instruction as an optimization
              // earlier even though it wasnt spilled in 1st RA iteration.
              // however, since it spills in later RA iteration, we should
              // handle it like send.
              //
              // If we don't handle it like send then the intrinsic.fill would
              // use incorrect size as non-send fill code only looks at filled
              // region properties like hstride, exec size, elem size. See:
              // getSegmentByteSize().
              insertSendFillRangeCode(srcRR, jt, *it);
              BBhasSpillCode = true;
            } else if (getRFType(regVar) == G4_GRF) {
              insertFillGRFRangeCode(srcRR, jt, *it);
              BBhasSpillCode = true;
            } else
              vASSERT(false);
          }
        }
      }

      if (failSafeSpill_ && builder_->getOption(vISA_NewFailSafeRA)) {
        context.insertPushPop(gra.useLscForSpillFill);
      }

      jt = kt;
    }

    if (BBhasSpillCode)
      gra.addSpillCodeInBB(*it);
  }

  bbId_ = UINT_MAX;

  // Calculate the spill memory used in this iteration

  for (auto spill : *spilledLRs_) {
    unsigned disp = spill->getVar()->getDisp();

    if (spill->getVar()->isSpilled()) {
      if (disp != UINT_MAX) {
        nextSpillOffset_ =
            std::max(nextSpillOffset_, disp + getByteSize(spill->getVar()));
      }
    }
  }

  return true;
}

void SpillManagerGRF::expireRanges(unsigned int idx,
                                   std::list<LSLiveRange *> *liveList) {
  // active list is sorted in ascending order of starting index

  while (liveList->size() > 0) {
    unsigned int endIdx;
    LSLiveRange *lr = liveList->front();

    lr->getLastRef(endIdx);

    if (endIdx <= idx) {
      VISA_DEBUG_VERBOSE(std::cout << "Expiring range "
                                   << lr->getTopDcl()->getName() << "\n");
      // Remove range from active list
      liveList->pop_front();
      lr->setActiveLR(false);
    } else {
      // As soon as we find first range that ends after ids break loop
      break;
    }
  }

  return;
}

void SpillManagerGRF::updateActiveList(LSLiveRange *lr,
                                       std::list<LSLiveRange *> *liveList) {
  bool done = false;
  unsigned int newlr_end;

  lr->getLastRef(newlr_end);

  for (auto active_it = liveList->begin(); active_it != liveList->end();
       active_it++) {
    unsigned int end_idx;
    LSLiveRange *active_lr = (*active_it);

    active_lr->getLastRef(end_idx);

    if (end_idx > newlr_end) {
      liveList->insert(active_it, lr);
      done = true;
      break;
    }
  }

  if (done == false)
    liveList->push_back(lr);
}

bool SpillManagerGRF::spillLiveRanges(G4_Kernel *kernel) {
  // Set the spill flag of all spilled regvars.
  for (LSLiveRange *lr : *spilledLSLRs_) {
    lr->getTopDcl()->setSpillFlag();
  }

  // Handle address taken spills
  unsigned addrSpillNum = handleAddrTakenLSSpills(kernel, gra.pointsToAnalysis);

  if (addrSpillNum) {
    for (auto spill : *spilledLSLRs_) {
      unsigned disp = spill->getTopDcl()->getRegVar()->getDisp();

      if (spill->getTopDcl()->getRegVar()->isSpilled()) {
        if (disp != UINT_MAX) {
          nextSpillOffset_ =
              std::max(nextSpillOffset_,
                       disp + getByteSize(spill->getTopDcl()->getRegVar()));
        }
      }
    }
  }

  // Insert spill/fill code for all basic blocks.
  FlowGraph &fg = kernel->fg;
  for (BB_LIST_ITER it = fg.begin(); it != fg.end(); it++) {
    bbId_ = (*it)->getId();
    INST_LIST::iterator jt = (*it)->begin();

    while (jt != (*it)->end()) {
      INST_LIST::iterator kt = jt;
      ++kt;
      G4_INST *inst = *jt;
      curInst = inst;

      if (failSafeSpill_) {
        spillRegOffset_ = spillRegStart_;
      }

      // Insert spill code, when the target is a spilled register.
      if (inst->getDst()) {
        G4_RegVar *regVar = nullptr;
        if (inst->getDst()->getBase()->isRegVar()) {
          regVar = getRegVar(inst->getDst());
        }

        if (regVar && regVar->getDeclare()->isSpilled()) {
          G4_Declare *dcl = regVar->getDeclare();
          while (dcl->getAliasDeclare()) {
            dcl = dcl->getAliasDeclare();
          }

          if (getRFType(regVar) == G4_GRF) {
            if (inst->isPseudoKill()) {
              (*it)->erase(jt);
              jt = kt;
              continue;
            }

            insertSpillRangeCode(jt, (*it));
          } else {
            vASSERT(false);
          }
        }
      }

      // Insert fill code, when the source is a spilled register.
      for (unsigned i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
        if (inst->getSrc(i) && inst->getSrc(i)->isSrcRegRegion()) {
          auto srcRR = inst->getSrc(i)->asSrcRegRegion();
          G4_RegVar *regVar = nullptr;
          if (srcRR->getBase()->isRegVar()) {
            regVar = getRegVar(srcRR);
          }

          if (regVar && regVar->getDeclare()->isSpilled()) {
            G4_Declare *dcl = regVar->getDeclare();
            while (dcl->getAliasDeclare()) {
              dcl = dcl->getAliasDeclare();
            }

            if (inst->isLifeTimeEnd()) {
              (*it)->erase(jt);
              break;
            }
            bool mayExceedTwoGRF = (inst->isSend() && i == 0) ||
                                   inst->isDpas() ||
                                   (inst->isSplitSend() && i == 1);

            if (mayExceedTwoGRF) {
              insertSendFillRangeCode(srcRR, jt, *it);
            } else if (getRFType(regVar) == G4_GRF)
              insertFillGRFRangeCode(srcRR, jt, *it);
            else
              vASSERT(false);
          }
        }
      }

      jt = kt;
    }
  }

  bbId_ = UINT_MAX;

  // Calculate the spill memory used in this iteration
  for (auto spill : (*spilledLSLRs_)) {
    unsigned disp = spill->getTopDcl()->getRegVar()->getDisp();

    if (spill->getTopDcl()->getRegVar()->isSpilled()) {
      if (disp != UINT_MAX) {
        nextSpillOffset_ =
            std::max(nextSpillOffset_,
                     disp + getByteSize(spill->getTopDcl()->getRegVar()));
      }
    }
  }

  return true;
}

//
// For XeHP_SDV and later, scratch surface is used for the vISA stack.  This
// means when the scratch message cannot be used for spill/fill (e.g., stack
// call), a0.2 will be used as the message descriptor for the spill/fill. As
// address RA is done before GRF, we don't know if a0.2 is live at the point of
// the spill/fill inst and thus may need to preserve its value. The good news is
// that all spill/fill may share the same A0, so we only need to save/restore A0
// when it's actually referenced in the BB.
//
void GlobalRA::saveRestoreA0(G4_BB *bb) {
  G4_Declare *tmpDcl = nullptr;
  unsigned int subReg = 0;
  if (kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc()) {
    // Use r126.6:ud for storing old a0.2 as it isn't caller/callee save
    tmpDcl = builder.kernel.fg.getScratchRegDcl();
    subReg = 6;
  } else {
    vISA_ASSERT(builder.hasValidOldA0Dot2(), "old a0.2 not saved");
    tmpDcl = builder.getOldA0Dot2Temp();
    subReg = 0;
  }

  auto usesAddr = [](G4_INST *inst) {
    // ToDo: handle send with A0 msg desc better.
    if (inst->isSpillIntrinsic() || inst->isFillIntrinsic()) {
      return false;
    }
    if (inst->getDst() &&
        (inst->getDst()->isIndirect() || inst->getDst()->isDirectAddress())) {
      return true;
    }
    for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
      if (!inst->getSrc(i) || !inst->getSrc(i)->isSrcRegRegion())
        continue;
      auto src = inst->getSrc(i)->asSrcRegRegion();
      if (src->isDirectAddress() || src->isIndirect())
        return true;
    }
    return false;
  };

  // a0.2 is spilled to r126.6 (r126 is scratch reg reserved for stack call)
  auto a0SaveMov = [this, tmpDcl, subReg]() {
    auto dstSave =
        builder.createDst(tmpDcl->getRegVar(), 0, subReg, 1, Type_UD);
    auto srcSave = builder.createSrc(builder.getBuiltinA0Dot2()->getRegVar(), 0,
                                     0, builder.getRegionScalar(), Type_UD);
    auto saveInst = builder.createMov(g4::SIMD1, dstSave, srcSave,
                                      InstOpt_WriteEnable, false);
    return saveInst;
  };

  auto a0RestoreMov = [this, tmpDcl, subReg]() {
    auto dstRestore = builder.createDstRegRegion(builder.getBuiltinA0Dot2(), 1);
    auto srcRestore = builder.createSrc(tmpDcl->getRegVar(), 0, subReg,
                                        builder.getRegionScalar(), Type_UD);
    auto restoreInst = builder.createMov(g4::SIMD1, dstRestore, srcRestore,
                                         InstOpt_WriteEnable, false);
    return restoreInst;
  };

  auto a0SSOMove = [this]() {
    // SSO is stored in r126.7
    auto dst = builder.createDstRegRegion(builder.getBuiltinA0Dot2(), 1);
    auto SSOsrc =
        builder.createSrc(builder.getSpillSurfaceOffset()->getRegVar(), 0, 0,
                          builder.getRegionScalar(), Type_UD);
    {
      // shr (1) a0.2   SSO   0x4 {NM}
      auto imm4 = builder.createImm(4, Type_UD);
      return builder.createBinOp(G4_shr, g4::SIMD1, dst, SSOsrc, imm4,
                                 InstOpt_WriteEnable, false);
    }
  };

  auto isPrologOrEpilog = [this](G4_INST *inst) {
    // a0 is a caller save register. Don't save/restore it if it is used in
    // callee save/restore sequence or for frame descriptor spill instruction.
    if (inst == kernel.fg.builder->getFDSpillInst())
      return false;

    if (calleeSaveInsts.find(inst) != calleeSaveInsts.end() ||
        calleeRestoreInsts.find(inst) != calleeRestoreInsts.end())
      return false;

    return true;
  };

  bool hasActiveSpillFill = false;

  for (auto instIt = bb->begin(); instIt != bb->end(); ++instIt) {
    auto inst = (*instIt);

    if (inst->isSpillIntrinsic() || inst->isFillIntrinsic()) {
      if (!hasActiveSpillFill) {
        // save a0.2 to addrSpillLoc, then overwrite it with the scratch surface
        // offset
        if (isPrologOrEpilog(inst)) {
          auto addrSpill = a0SaveMov();
          bb->insertBefore(instIt, addrSpill);
        }
        auto a0SSO = a0SSOMove();
        bb->insertBefore(instIt, a0SSO);
        // Need Call WA.
        // NoMask WA: save/restore code does not need NoMask WA.
        if (EUFusionCallWANeeded()) {
          addEUFusionCallWAInst(a0SSO);
        }
        hasActiveSpillFill = true;
      }
    } else if (hasActiveSpillFill && usesAddr(inst)) {
      // restore A0
      auto addrFill = a0RestoreMov();
      bb->insertBefore(instIt, addrFill);
      hasActiveSpillFill = false;
    }
  }

  if (hasActiveSpillFill && !bb->isLastInstEOT() && !bb->isEndWithFRet()) {
    // restore A0 before BB exit. BB is guaranteed to be non-empty as there's at
    // least one spill/fill If last inst is branch, insert restore before it.
    // Otherwise insert it as last inst
    auto endIt = bb->back()->isCFInst() ? std::prev(bb->end()) : bb->end();
    bb->insertBefore(endIt, a0RestoreMov());
  }
}

static uint32_t computeSpillMsgDesc(unsigned int payloadSize,
                                    unsigned int offsetInGrfUnits,
                                    const IR_Builder &irb) {
  // Compute msg descriptor given payload size and offset.
  unsigned headerPresent = 0x80000;
  uint32_t message = headerPresent;
  unsigned msgLength = SCRATCH_PAYLOAD_HEADER_MAX_HEIGHT;
  message |= (msgLength << getSendMsgLengthBitOffset());
  message |= (1 << SCRATCH_MSG_DESC_CATEORY);
  message |= (1 << SCRATCH_MSG_DESC_CHANNEL_MODE);
  message |= (1 << SCRATCH_MSG_DESC_OPERATION_MODE);
  unsigned blocksize_encoding = getScratchBlocksizeEncoding(payloadSize, irb);
  message |= (blocksize_encoding << SCRATCH_MSG_DESC_BLOCK_SIZE);
  int offset = offsetInGrfUnits;
  message |= offset;

  return message;
}

static uint32_t computeFillMsgDesc(unsigned int payloadSize,
                                   unsigned int offsetInGrfUnits,
                                   const IR_Builder &irb) {
  // Compute msg descriptor given payload size and offset.
  unsigned headerPresent = 0x80000;
  uint32_t message = headerPresent;
  unsigned msgLength = 1;
  message |= (msgLength << getSendMsgLengthBitOffset());
  message |= (1 << SCRATCH_MSG_DESC_CATEORY);
  message |= (0 << SCRATCH_MSG_INVALIDATE_AFTER_READ);
  unsigned blocksize_encoding = getScratchBlocksizeEncoding(payloadSize, irb);
  message |= (blocksize_encoding << SCRATCH_MSG_DESC_BLOCK_SIZE);
  message |= offsetInGrfUnits;

  return message;
}

// Returns payload size in units of GRF rows
static unsigned int getPayloadSizeGRF(unsigned int numRows) {
  if (numRows >= 8)
    return 8u;

  if (numRows >= 4)
    return 4u;

  if (numRows >= 2)
    return 2u;

  return 1u;
}

static unsigned int getPayloadSizeOword(unsigned int numOwords) {
  if (numOwords >= 8)
    return 8u;

  if (numOwords >= 4)
    return 4u;

  if (numOwords >= 2)
    return 2u;

  return 1u;
}

unsigned int GlobalRA::owordToGRFSize(unsigned int numOwords,
                                      const IR_Builder &builder) {
  unsigned int GRFSize =
      numOwords / (2 * (builder.numEltPerGRF<Type_UB>() / HWORD_BYTE_SIZE));

  return GRFSize;
}

unsigned int GlobalRA::hwordToGRFSize(unsigned int numHwords,
                                      const IR_Builder &builder) {
  return owordToGRFSize(numHwords * 2, builder);
}

unsigned int GlobalRA::GRFToHwordSize(unsigned int numGRFs,
                                      const IR_Builder &builder) {
  return GRFSizeToOwords(numGRFs, builder) / 2;
}

unsigned int GlobalRA::GRFSizeToOwords(unsigned int numGRFs,
                                       const IR_Builder &builder) {
  return numGRFs * (builder.numEltPerGRF<Type_UB>() / OWORD_BYTE_SIZE);
}

unsigned int GlobalRA::getHWordByteSize() { return HWORD_BYTE_SIZE; }

bool Interval::intervalsOverlap(const Interval &second) const {
  return !(start->getLexicalId() > second.end->getLexicalId() ||
           second.start->getLexicalId() > end->getLexicalId());
}

static G4_INST *createSpillFillAddr(IR_Builder &builder, G4_Declare *addr,
                                    G4_Declare *fp, int offset) {
  auto imm = builder.createImm(offset, Type_UD);
  auto dst = builder.createDstRegRegion(addr, 1);
  if (fp) {
    auto src0 = builder.createSrcRegRegion(fp, builder.getRegionScalar());
    return builder.createBinOp(G4_add, g4::SIMD1, dst, src0, imm,
                               InstOpt_WriteEnable, true);
  } else {
    return builder.createMov(g4::SIMD1, dst, imm, InstOpt_WriteEnable, true);
  }
}

static std::string makeSpillFillComment(const char *spillFill,
                                        const char *toFrom, const char *base,
                                        uint32_t spillOffset, const char *of,
                                        unsigned grfSize) {
  std::stringstream comment;
  comment << spillFill << " " << toFrom << " ";
  comment << base << "[" << spillOffset / grfSize << "*" << (int)grfSize << "]";
  if (!of || *of == 0) // some have "" as name
    of = "?";
  comment << " of " << of;
  return comment.str();
}

void GlobalRA::expandSpillLSC(G4_BB *bb, INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt)->asSpillIntrinsic();
  // offset into scratch surface in bytes
  auto spillOffset = inst->getOffsetInBytes();
  uint32_t numRows = inst->getNumRows();
  auto payload = inst->getSrc(1)->asSrcRegRegion();
  auto rowOffset = payload->getRegOff();

  LSC_OP op = LSC_STORE;
  LSC_SFID lscSfid = LSC_UGM;
  LSC_CACHE_OPTS cacheOpts{LSC_CACHING_DEFAULT, LSC_CACHING_DEFAULT};
  LSC_L1_L3_CC store_cc =
      (LSC_L1_L3_CC)builder->getuint32Option(vISA_lscSpillStoreCCOverride);
  if (store_cc != LSC_CACHING_DEFAULT) {
    cacheOpts = convertLSCLoadStoreCacheControlEnum(store_cc, false);
  }

  LSC_ADDR addrInfo;
  addrInfo.type = LSC_ADDR_TYPE_SS; // Scratch memory
  addrInfo.immScale = 1;
  addrInfo.immOffset = 0;
  addrInfo.size = LSC_ADDR_SIZE_32b;
  if (canUseLscImmediateOffsetSpillFill) {
    // spillOffset must be Dword aligned
    // spillOffset must be in range [0, SPILL_FILL_IMMOFF_MAX * 2)
    vISA_ASSERT(spillOffset % 4 == 0 && spillOffset < SPILL_FILL_IMMOFF_MAX * 2,
                "invalid immediate offset");

    // immOffset range for SS: [-2^16, 2^16-1]
    addrInfo.immOffset = spillOffset - SPILL_FILL_IMMOFF_MAX;
  }

  builder->instList.clear();
  while (numRows > 0) {
    auto numGRFToWrite = getPayloadSizeGRF(numRows);

    G4_Declare *spillAddr = inst->getFP() ? kernel.fg.scratchRegDcl
                                          : inst->getHeader()->getTopDcl();
    if (!canUseLscImmediateOffsetSpillFill)
    {
      // need to calculate spill address
      createSpillFillAddr(*builder, spillAddr, inst->getFP(), spillOffset);
    }

    unsigned int elemSize = 4;
    LSC_DATA_SHAPE dataShape;
    dataShape.size = LSC_DATA_SIZE_32b;
    if (builder->getGRFSize() > 32 && numGRFToWrite > 4) {
      if (inst->isWriteEnableInst()) {
        elemSize = 8;
        dataShape.size = LSC_DATA_SIZE_64b;
      } else {
        // don't change type if instruction isn't WriteEnable
        numGRFToWrite = 4;
      }
    }
    dataShape.order = LSC_DATA_ORDER_TRANSPOSE;
    dataShape.elems = builder->lscGetElementNum(
        numGRFToWrite * builder->getGRFSize() / elemSize);

    auto src0Addr =
        builder->createSrcRegRegion(spillAddr, builder->getRegionStride1());
    auto payloadToUse = builder->createSrcWithNewRegOff(payload, rowOffset);

    auto surface = builder->createSrcRegRegion(builder->getSpillSurfaceOffset(),
                                               builder->getRegionScalar());

    G4_DstRegRegion *postDst = builder->createNullDst(Type_UD);
    G4_SendDescRaw *desc = builder->createLscMsgDesc(
        op, lscSfid, EXEC_SIZE_1, cacheOpts, addrInfo, dataShape, surface, 0, 1,
        LdStAttrs::SCRATCH_SURFACE);

    auto sendInst = builder->createLscSendInst(
        nullptr, postDst, src0Addr, payloadToUse, g4::SIMD1, desc,
        inst->getOption(), LSC_ADDR_TYPE_SS, 0x0, false);

    sendInst->addComment(makeSpillFillComment(
        "spill", "to", inst->getFP() ? "FP" : "offset", spillOffset,
        payload->getTopDcl()->getName(), builder->getGRFSize()));

    numRows -= numGRFToWrite;
    rowOffset += numGRFToWrite;
    spillOffset += numGRFToWrite * builder->getGRFSize();
    if (canUseLscImmediateOffsetSpillFill) {
      addrInfo.immOffset = spillOffset - SPILL_FILL_IMMOFF_MAX;
    }
  }

  if (inst->getFP() && kernel.getOption(vISA_GenerateDebugInfo)) {
    kernel.getKernelDebugInfo()->updateExpandedIntrinsic(
        inst->asSpillIntrinsic(), builder->instList);
  }

  // Call WA and NoMask WA are mutual exclusive.
  if (getEUFusionCallWAInsts().count(inst) > 0) {
    removeEUFusionCallWAInst(inst);
    for (auto inst : builder->instList)
      addEUFusionCallWAInst(inst);
  } else if (getEUFusionNoMaskWAInsts().count(inst) > 0) {
    // no NoMask WA needed for stack call spill/fill
    removeEUFusionNoMaskWAInst(inst);
    if (!inst->getFP() && inst->isWriteEnableInst()) {
      for (auto inst : builder->instList)
        addEUFusionNoMaskWAInst(bb, inst);
    }
  }

  splice(bb, instIt, builder->instList, inst->getVISAId());
} // expandSpillLSC

void GlobalRA::expandScatterSpillLSC(G4_BB *bb, INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt)->asSpillIntrinsic();
  // offset into scratch surface in bytes
  auto spillOffset = inst->getOffsetInBytes();
  auto payload = inst->getSrc(1)->asSrcRegRegion();
  auto rowOffset = payload->getRegOff();

  // Max elements to write in LSC scatter store is 32 (SIMD32)
  // Scatter spill intrinsics are expanded to either SIMD8, SIMD16 or SIMD32
  G4_ExecSize execSize(inst->getExecSize());
  vISA_ASSERT(execSize == 8 || execSize == 16 || execSize == 32,
              "Execution size not supported for scatter spill");

  LSC_OP op = LSC_STORE;
  LSC_SFID lscSfid = LSC_UGM;
  LSC_CACHE_OPTS cacheOpts{LSC_CACHING_DEFAULT, LSC_CACHING_DEFAULT};
  LSC_L1_L3_CC store_cc =
      (LSC_L1_L3_CC)builder->getuint32Option(vISA_lscSpillStoreCCOverride);
  if (store_cc != LSC_CACHING_DEFAULT) {
    cacheOpts = convertLSCLoadStoreCacheControlEnum(store_cc, false);
  }

  // Set the LSC address info
  LSC_ADDR addrInfo;
  addrInfo.type = LSC_ADDR_TYPE_SS; // Scratch memory
  addrInfo.immScale = 1;
  addrInfo.immOffset = 0;
  addrInfo.size = LSC_ADDR_SIZE_32b;
  unsigned int addrSizeInBytes = 4;

  // Set the LSC data shape
  LSC_DATA_SHAPE dataShape;
  dataShape.order = LSC_DATA_ORDER_NONTRANSPOSE;
  dataShape.elems = LSC_DATA_ELEMS_1;

  auto elemSz = inst->getDst()->getTypeSize();
  switch (elemSz) {
  case 2:
    dataShape.size = LSC_DATA_SIZE_16b;
    break;
  case 4:
    dataShape.size = LSC_DATA_SIZE_32b;
    break;
  case 8:
    dataShape.size = LSC_DATA_SIZE_64b;
    break;
  default:
    vISA_ASSERT(false, "Data size not supported");
  }

  unsigned numGRFAddressToWrite =
      execSize * addrSizeInBytes / builder->getGRFSize();
  builder->instList.clear();

  // Add spill offset to vector of addresses
  G4_Declare *baseAddresses = builder->getScatterSpillBaseAddress();
  G4_Declare *spillAddresses = builder->getScatterSpillAddress();
  G4_INST *addA0 = builder->createBinOp(
      G4_add, execSize,
      builder->createDst(spillAddresses->getRegVar(), 0, 0, 1, Type_D),
      builder->createSrcRegRegion(baseAddresses, builder->getRegionStride1()),
      builder->createImm(spillOffset, Type_W), inst->getOption(), false);
  bb->insertBefore(instIt, addA0);

  auto payloadToUse = builder->createSrcWithNewRegOff(payload, rowOffset);
  auto surface = builder->createSrcRegRegion(builder->getSpillSurfaceOffset(),
                                             builder->getRegionScalar());

  G4_DstRegRegion *postDst =
      builder->createNullDst(inst->getDst()->getType());
  G4_SendDescRaw *desc = builder->createLscMsgDesc(
      op, lscSfid, Get_VISA_Exec_Size_From_Raw_Size(execSize), cacheOpts,
      addrInfo, dataShape, surface, 0, numGRFAddressToWrite,
      LdStAttrs::SCRATCH_SURFACE);
  auto src0Addr =
      builder->createSrcRegRegion(spillAddresses, builder->getRegionStride1());

  auto sendInst = builder->createLscSendInst(
      nullptr, postDst, src0Addr, payloadToUse, execSize, desc,
      inst->getOption(), LSC_ADDR_TYPE_SS, 0x0, false);

  sendInst->addComment(makeSpillFillComment(
      "scatter spill", "to", inst->getFP() ? "FP" : "offset", spillOffset,
      payload->getTopDcl()->getName(), builder->getGRFSize()));

  if (inst->getFP() && kernel.getOption(vISA_GenerateDebugInfo)) {
    kernel.getKernelDebugInfo()->updateExpandedIntrinsic(
        inst->asSpillIntrinsic(), builder->instList);
  }

  splice(bb, instIt, builder->instList, inst->getVISAId());
}

void GlobalRA::expandFillLSC(G4_BB *bb, INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt)->asFillIntrinsic();
  // offset into scratch surface in bytes
  auto fillOffset = inst->getOffsetInBytes();
  uint32_t numRows = inst->getNumRows();
  auto rowOffset = inst->getDst()->getRegOff();

  LSC_OP op = LSC_LOAD;
  LSC_SFID lscSfid = LSC_UGM;
  LSC_CACHE_OPTS cacheOpts{LSC_CACHING_DEFAULT, LSC_CACHING_DEFAULT};
  LSC_L1_L3_CC ld_cc =
      (LSC_L1_L3_CC)builder->getuint32Option(vISA_lscSpillLoadCCOverride);
  if (ld_cc != LSC_CACHING_DEFAULT) {
    cacheOpts = convertLSCLoadStoreCacheControlEnum(ld_cc, true);
  }

  LSC_ADDR addrInfo;
  addrInfo.type = LSC_ADDR_TYPE_SS; // Scratch memory
  addrInfo.immScale = 1;
  addrInfo.immOffset = 0;
  addrInfo.size = LSC_ADDR_SIZE_32b;
  if (canUseLscImmediateOffsetSpillFill) {
    // fillOffset must be Dword aligned
    // fillOffset must be in range [0, SPILL_FILL_IMMOFF_MAX * 2)
    vISA_ASSERT(fillOffset % 4 == 0 && fillOffset < SPILL_FILL_IMMOFF_MAX * 2,
                "invalid immediate offset");

    // immOffset range for SS: [-2^16, 2^16-1]
    addrInfo.immOffset = fillOffset - SPILL_FILL_IMMOFF_MAX;
  }

  builder->instList.clear();

  while (numRows > 0) {
    unsigned int elemSize = 4;
    unsigned responseLength = getPayloadSizeGRF(numRows);
    LSC_DATA_SHAPE dataShape;
    dataShape.size = LSC_DATA_SIZE_32b;
    if (builder->getGRFSize() > 32 && responseLength > 4) {
      if (inst->isWriteEnableInst()) {
        elemSize = 8;
        dataShape.size = LSC_DATA_SIZE_64b;
      } else {
        // don't change type if instruction isn't WriteEnable
        responseLength = 4;
      }
    }
    dataShape.order = LSC_DATA_ORDER_TRANSPOSE;
    dataShape.elems = builder->lscGetElementNum(
        responseLength * builder->getGRFSize() / elemSize);
    G4_Declare *fillAddr = inst->getFP() ? kernel.fg.scratchRegDcl
                                         : inst->getHeader()->getTopDcl();
    if (!canUseLscImmediateOffsetSpillFill)
    {
      // need to calculate fill address
      createSpillFillAddr(*builder, fillAddr, inst->getFP(), fillOffset);
    }
    auto dstRead = builder->createDst(inst->getDst()->getTopDcl()->getRegVar(),
                                      (short)rowOffset, 0, 1, Type_UD);

    auto surface = builder->createSrcRegRegion(builder->getSpillSurfaceOffset(),
                                               builder->getRegionScalar());

    G4_SendDescRaw *desc = builder->createLscMsgDesc(
        op, lscSfid, EXEC_SIZE_1, cacheOpts, addrInfo, dataShape, surface,
        responseLength, 1, LdStAttrs::SCRATCH_SURFACE);

    auto sendInst = builder->createLscSendInst(
        nullptr, dstRead,
        builder->createSrcRegRegion(fillAddr, builder->getRegionScalar()),
        nullptr, g4::SIMD1, desc, inst->getOption(), LSC_ADDR_TYPE_SS, 0x0,
        false);

    sendInst->addComment(makeSpillFillComment(
        "fill", "from", inst->getFP() ? "FP" : "offset", fillOffset,
        dstRead->getTopDcl()->getName(), builder->getGRFSize()));

    numRows -= responseLength;
    rowOffset += responseLength;
    fillOffset += responseLength * builder->getGRFSize();
    if (canUseLscImmediateOffsetSpillFill) {
      addrInfo.immOffset = fillOffset - SPILL_FILL_IMMOFF_MAX;
    }
  }

  if (inst->getFP() && kernel.getOption(vISA_GenerateDebugInfo)) {
    kernel.getKernelDebugInfo()->updateExpandedIntrinsic(
        inst->asFillIntrinsic(), builder->instList);
  }

  // Call WA and NoMask WA are mutual exclusive.
  if (getEUFusionCallWAInsts().count(inst) > 0) {
    removeEUFusionCallWAInst(inst);
    for (auto inst : builder->instList)
      addEUFusionCallWAInst(inst);
  } else if (getEUFusionNoMaskWAInsts().count(inst) > 0) {
    removeEUFusionNoMaskWAInst(inst);
    // no WA needed for stack call spill/fill
    if (!inst->getFP() && inst->isWriteEnableInst()) {
      for (auto inst : builder->instList)
        addEUFusionNoMaskWAInst(bb, inst);
    }
  }

  splice(bb, instIt, builder->instList, inst->getVISAId());
}

void GlobalRA::insertSlot1HwordR0Set(G4_BB *bb, INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  G4_INST *inst = (*instIt);

  if (slot1SetR0.count(inst)) {
    // Insert
    //   (W)    add (1|M0)    r0.5:ud    r0.5:ud    0x400:ud
    // to make r0.5 point at slot#1 scratch surface.
    G4_DstRegRegion* r0_5Dst = builder->createDst(
        builder->getBuiltinR0()->getRegVar(), 0, 5, 1, Type_UD);
    G4_Imm* addImm = builder->createImm(0x400, Type_UD);
    G4_SrcRegRegion *r0_5Src = builder->createSrc(
        builder->getBuiltinR0()->getRegVar(), 0, 5,
        builder->getRegionScalar(), Type_UD);
    G4_InstOption options =
        bb->isAllLaneActive() ? InstOpt_NoOpt : InstOpt_WriteEnable;
    G4_INST *addInst = builder->createBinOp(
        G4_opcode::G4_add, g4::SIMD1, r0_5Dst, r0_5Src, addImm,
        options, false);

    bb->insertBefore(instIt, addInst);

    if (EUFusionNoMaskWANeeded() && options & InstOpt_WriteEnable) {
      addEUFusionNoMaskWAInst(bb, addInst);
    }
  }
}

void GlobalRA::insertSlot1HwordR0Reset(G4_BB *bb, INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  G4_INST *inst = (*instIt);

  if (slot1ResetR0.count(inst)) {
    // Insert
    //   (W)    add (1|M0)    r0.5:ud    r0.5:ud    -1024:d
    // to reset modification done by `insertSlot1HwordR0Set` and make r0.5
    // point to slot#1 scratch surface for private memory access.
    G4_DstRegRegion* r0_5Dst = builder->createDst(
        builder->getBuiltinR0()->getRegVar(), 0, 5, 1, Type_UD);
    G4_Imm *addImm = builder->createImm(-0x400, Type_D);
    G4_SrcRegRegion *r0_5Src = builder->createSrc(
        builder->getBuiltinR0()->getRegVar(), 0, 5,
        builder->getRegionScalar(), Type_UD);
    G4_InstOption options =
        bb->isAllLaneActive() ? InstOpt_NoOpt : InstOpt_WriteEnable;
    G4_INST *addInst = builder->createBinOp(
        G4_opcode::G4_add, g4::SIMD1, r0_5Dst, r0_5Src, addImm,
        options, false);

    bb->insertBefore(instIt, addInst);

    if (EUFusionNoMaskWANeeded() && options & InstOpt_WriteEnable) {
      addEUFusionNoMaskWAInst(bb, addInst);
    }
  }
}

void GlobalRA::expandSpillNonStackcall(uint32_t numRows, uint32_t offset,
                                       short rowOffset, G4_SrcRegRegion *header,
                                       G4_SrcRegRegion *payload, G4_BB *bb,
                                       INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt);

  if (offset == G4_SpillIntrinsic::InvalidOffset) {
    // oword msg
    auto payloadToUse = builder->createSrcRegRegion(*payload);
    auto [spillMsgDesc, execSize] =
        SpillManagerGRF::createSpillSendMsgDescOWord(*builder, numRows);
    G4_INST *sendInst = nullptr;
    // Use bindless for XeHP_SDV and later
    if (builder->hasScratchSurface()) {
      G4_Imm *descImm =
          createMsgDesc(GRFSizeToOwords(numRows, *builder), true, true);
      // Update BTI to 251
      auto spillMsgDesc = descImm->getInt();
      spillMsgDesc = spillMsgDesc & 0xffffff00;
      spillMsgDesc |= 251;

      auto msgDesc = builder->createWriteMsgDesc(
          SFID::DP_DC0, (uint32_t)spillMsgDesc, numRows);
      G4_Imm *msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);

      // a0 is set by saveRestoreA0()
      auto a0Src = builder->createSrcRegRegion(builder->getBuiltinA0Dot2(),
                                               builder->getRegionScalar());
      sendInst = builder->createInternalSplitSendInst(
          execSize, inst->getDst(), header, payloadToUse, msgDescImm,
          inst->getOption(), msgDesc, a0Src);
    } else {
      G4_SendDescRaw *msgDesc = kernel.fg.builder->createSendMsgDesc(
          spillMsgDesc & 0x000FFFFFu, 0, 1, SFID::DP_DC0, numRows, 0,
          SendAccess::WRITE_ONLY);
      G4_Imm *msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);
      G4_Imm *extDesc = builder->createImm(msgDesc->getExtendedDesc(), Type_UD);
      sendInst = builder->createInternalSplitSendInst(
          execSize, inst->getDst(), header, payloadToUse, msgDescImm,
          inst->getOption(), msgDesc, extDesc);
    }
    instIt = bb->insertBefore(instIt, sendInst);
    if (EUFusionNoMaskWANeeded() && sendInst->isWriteEnableInst()) {
      addEUFusionNoMaskWAInst(bb, sendInst);
    }
  } else {
    INST_LIST_ITER origInstIt = instIt;
    insertSlot1HwordR0Set(bb, instIt);

    while (numRows >= 1) {
      auto payloadToUse = builder->createSrcWithNewRegOff(payload, rowOffset);

      auto region = builder->getRegionStride1();

      uint32_t spillMsgDesc =
          computeSpillMsgDesc(getPayloadSizeGRF(numRows), offset, *builder);
      auto msgDesc = builder->createWriteMsgDesc(SFID::DP_DC0, spillMsgDesc,
                                                 getPayloadSizeGRF(numRows));
      G4_Imm *msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);

      G4_SrcRegRegion *headerOpnd =
          builder->createSrcRegRegion(builder->getBuiltinR0(), region);
      G4_Imm *extDesc = builder->createImm(msgDesc->getExtendedDesc(), Type_UD);
      G4_ExecSize execSize = numRows > 1 ? g4::SIMD16 : g4::SIMD8;

      auto sendInst = builder->createInternalSplitSendInst(
          execSize, inst->getDst(), headerOpnd, payloadToUse, msgDescImm,
          inst->getOption(), msgDesc, extDesc);

      std::stringstream comments;
      comments << "scratch space spill: "
               << payloadToUse->getTopDcl()->getName() << " from offset["
               << offset << "x32]";
      sendInst->addComment(comments.str());

      instIt = bb->insertBefore(instIt, sendInst);

      if (EUFusionNoMaskWANeeded() && sendInst->isWriteEnableInst()) {
        addEUFusionNoMaskWAInst(bb, sendInst);
      }

      numRows -= getPayloadSizeGRF(numRows);
      offset += getPayloadSizeGRF(numRows);
      rowOffset += getPayloadSizeGRF(numRows);
    }

    insertSlot1HwordR0Reset(bb, origInstIt);
  }
}

void GlobalRA::expandSpillStackcall(uint32_t numRows, uint32_t offset,
                                    short rowOffset, G4_SrcRegRegion *payload,
                                    G4_BB *bb, INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt);

  auto spillIt = instIt;

  // Use oword ld for stackcall. Lower intrinsic to:
  // (W)      add(1 | M0)         r126.2 < 1 > :ud  r125.7 < 0; 1, 0 > : ud  0x0
  // : ud (W)      sends(8 | M0)         null : ud       r126 payload - src2
  // 0x4A      0x20A02FF
  G4_Operand *src0 = nullptr;
  G4_Imm *src1 = nullptr;
  G4_Declare *scratchRegDcl = builder->kernel.fg.scratchRegDcl;
  G4_Declare *framePtr = inst->asSpillIntrinsic()->getFP();

  // convert hword to oword offset
  auto numRowsOword = numRows * 2;
  auto offsetOword = offset * 2;
  auto rowOffsetOword = rowOffset * 2;

  while (numRowsOword >= 1) {
    auto createOwordSpill = [&](unsigned int owordSize,
                                G4_SrcRegRegion *payloadToUse) {
      G4_ExecSize execSize = (owordSize > 2) ? g4::SIMD16 : g4::SIMD8;
      G4_DstRegRegion *dst =
          builder->createNullDst((execSize > g4::SIMD8) ? Type_UW : Type_UD);
      auto sendSrc0 =
          builder->createSrc(scratchRegDcl->getRegVar(), 0, 0,
                             builder->rgnpool.createRegion(8, 8, 1), Type_UD);
      unsigned messageLength = owordToGRFSize(owordSize, *builder);
      G4_Imm *descImm = createMsgDesc(owordSize, true, true);
      G4_INST *sendInst = nullptr;
      // Use bindless for XeHP_SDV and later
      if (builder->getPlatform() >= Xe_XeHPSDV) {
        // Update BTI to 251
        auto spillMsgDesc = descImm->getInt();
        spillMsgDesc = spillMsgDesc & 0xffffff00;
        spillMsgDesc |= 251;

        auto msgDesc = builder->createWriteMsgDesc(
            SFID::DP_DC0, (uint32_t)spillMsgDesc, messageLength);
        G4_Imm *msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);

        // a0 is set by saveRestoreA0()
        auto a0Src = builder->createSrcRegRegion(builder->getBuiltinA0Dot2(),
                                                 builder->getRegionScalar());
        sendInst = builder->createInternalSplitSendInst(
            execSize, inst->getDst(), sendSrc0, payloadToUse, msgDescImm,
            inst->getOption(), msgDesc, a0Src);
      } else {
        auto msgDesc = builder->createWriteMsgDesc(
            SFID::DP_DC0, (uint32_t)descImm->getInt(), messageLength);
        G4_Imm *msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);
        G4_Imm *extDesc =
            builder->createImm(msgDesc->getExtendedDesc(), Type_UD);
        sendInst = builder->createInternalSplitSendInst(
            execSize, dst, sendSrc0, payloadToUse, msgDescImm,
            inst->getOption() | InstOpt_WriteEnable, msgDesc, extDesc);
      }
      return sendInst;
    };

    auto payloadSizeInOwords = getPayloadSizeOword(numRowsOword);

    auto payloadToUse =
        builder->createSrcWithNewRegOff(payload, rowOffsetOword / 2);

    G4_DstRegRegion *dst =
        builder->createDst(scratchRegDcl->getRegVar(), 0, 2, 1, Type_UD);

    G4_INST *hdrSetInst = nullptr;
    if (inst->asSpillIntrinsic()->isOffsetValid()) {
      // Skip header if spill module emits its own header
      if (framePtr) {
        src0 = builder->createSrc(framePtr->getRegVar(), 0, 0,
                                  builder->getRegionScalar(), Type_UD);
        src1 = builder->createImm(offsetOword, Type_UD);
        hdrSetInst = builder->createBinOp(G4_add, g4::SIMD1, dst, src0, src1,
                                          InstOpt_WriteEnable, false);
      } else {
        src0 = builder->createImm(offsetOword, Type_UD);
        hdrSetInst = builder->createMov(g4::SIMD1, dst, src0,
                                        InstOpt_WriteEnable, false);
      }

      bb->insertBefore(spillIt, hdrSetInst);
    }

    auto spillSends = createOwordSpill(payloadSizeInOwords, payloadToUse);
    std::stringstream comments;
    comments << "stack spill: " << payload->getTopDcl()->getName() << " to FP["
             << inst->asSpillIntrinsic()->getOffset() << "x32]";
    spillSends->addComment(comments.str());

    bb->insertBefore(spillIt, spillSends);

    if (getEUFusionCallWAInsts().count(inst) > 0) {
      removeEUFusionCallWAInst(inst);
      addEUFusionCallWAInst(spillSends);
      if (hdrSetInst)
        addEUFusionCallWAInst(hdrSetInst);
    }

    if (kernel.getOption(vISA_GenerateDebugInfo)) {
      INST_LIST expandedInsts = {hdrSetInst, spillSends};
      kernel.getKernelDebugInfo()->updateExpandedIntrinsic(
          inst->asSpillIntrinsic(), expandedInsts);
    }

    numRowsOword -= payloadSizeInOwords;
    offsetOword += payloadSizeInOwords;
    rowOffsetOword += payloadSizeInOwords;
  }
}

// Non-stack call:
//  sends <-- scratch - default, supported
//  send  <-- scratch - disable split send using compiler option, not supported
//  by intrinsic send  <-- non-scratch - used when scratch space usage is very
//  high, supported

//  Stack call :
//  sends <-- non-scratch - default spill, supported
//  send  <-- non-scratch - default fill, supported
void GlobalRA::expandSpillIntrinsic(G4_BB *bb) {
  // spill (1) null:ud   bitmask:ud   r0:ud   payload:ud
  for (auto instIt = bb->begin(); instIt != bb->end();) {
    auto inst = (*instIt);
    if (inst->isSpillIntrinsic()) {
      bool isOffBP = inst->asSpillIntrinsic()->isOffBP();
      uint32_t numRows = inst->asSpillIntrinsic()->getNumRows();
      uint32_t offset = inst->asSpillIntrinsic()->getOffset() *
                        (builder.numEltPerGRF<Type_UB>() / HWORD_BYTE_SIZE);
      auto header = inst->getSrc(0)->asSrcRegRegion();
      auto payload = inst->getSrc(1)->asSrcRegRegion();
      auto spillIt = instIt;

      auto rowOffset = payload->getRegOff();
      if (useLscForNonStackCallSpillFill || spillFillIntrinUsesLSC(inst) ||
          useLscForScatterSpill) {
        if (inst->asSpillIntrinsic()->isScatterSpill())
          expandScatterSpillLSC(bb, instIt);
        else
          expandSpillLSC(bb, instIt);
      } else {
        if (!isOffBP) {
          expandSpillNonStackcall(numRows, offset, rowOffset, header, payload,
                                  bb, instIt);
        } else {
          expandSpillStackcall(numRows, offset, rowOffset, payload, bb, instIt);
        }
      }
      numGRFSpill++;
      instIt = bb->erase(spillIt);
      continue;
    }
    instIt++;
  }
}

void GlobalRA::expandFillNonStackcall(uint32_t numRows, uint32_t offset,
                                      short rowOffset, G4_SrcRegRegion *header,
                                      G4_DstRegRegion *resultRgn, G4_BB *bb,
                                      INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt);

  if (offset == G4_FillIntrinsic::InvalidOffset) {
    // oword msg
    G4_ExecSize execSize = g4::SIMD16;
    auto numRowsOword = GRFSizeToOwords(numRows, *builder);
    auto fillDst =
        builder->createDst(resultRgn->getBase(), rowOffset, 0,
                           resultRgn->getHorzStride(), resultRgn->getType());
    auto sendSrc0 =
        builder->createSrc(header->getBase(), 0, 0,
                           builder->rgnpool.createRegion(8, 8, 1), Type_UD);
    G4_Imm *desc = createMsgDesc(numRowsOword, false, false);
    G4_INST *sendInst = nullptr;
    auto sfId = SFID::DP_DC0;

    // Use bindless for XeHP_SDV and later
    if (builder->hasScratchSurface()) {
      // Update BTI to 251
      auto newDesc = desc->getInt() & 0xffffff00;
      newDesc |= 251;
      desc = builder->createImm(newDesc, Type_UD);

      auto msgDesc = builder->createReadMsgDesc(sfId, (uint32_t)desc->getInt());
      G4_Operand *msgDescOpnd = builder->createImm(msgDesc->getDesc(), Type_UD);

      // a0 is set by saveRestoreA0()
      auto src1 = builder->createSrc(builder->getBuiltinA0Dot2()->getRegVar(),
                                     0, 0, builder->getRegionScalar(), Type_UD);

      sendInst = builder->createInternalSplitSendInst(
          execSize, fillDst, sendSrc0, nullptr, msgDescOpnd,
          InstOpt_WriteEnable, msgDesc, src1);
    } else {
      auto msgDesc = builder->createReadMsgDesc(sfId, (uint32_t)desc->getInt());
      G4_Operand *msgDescOpnd = builder->createImm(msgDesc->getDesc(), Type_UD);
      sendInst = builder->createInternalSendInst(nullptr, G4_send, execSize,
                                                 fillDst, sendSrc0, msgDescOpnd,
                                                 InstOpt_WriteEnable, msgDesc);
    }
    instIt = bb->insertBefore(instIt, sendInst);

    if (EUFusionNoMaskWANeeded() && sendInst->isWriteEnableInst()) {
      addEUFusionNoMaskWAInst(bb, sendInst);
    }
  } else {
    INST_LIST_ITER origInstIt = instIt;
    insertSlot1HwordR0Set(bb, instIt);

    while (numRows >= 1) {
      auto fillDst =
          builder->createDst(resultRgn->getBase(), rowOffset, 0,
                             resultRgn->getHorzStride(), resultRgn->getType());

      auto region = builder->getRegionStride1();
      G4_SrcRegRegion *headerOpnd =
          builder->createSrcRegRegion(builder->getBuiltinR0(), region);

      uint32_t fillMsgDesc =
          computeFillMsgDesc(getPayloadSizeGRF(numRows), offset, *builder);

      G4_SendDescRaw *msgDesc = kernel.fg.builder->createSendMsgDesc(
          fillMsgDesc, getPayloadSizeGRF(numRows), 1, SFID::DP_DC0, 0, 0,
          SendAccess::READ_ONLY);

      G4_Imm *msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);

      auto sendInst = builder->createInternalSendInst(
          nullptr, G4_send, g4::SIMD16, fillDst, headerOpnd, msgDescImm,
          inst->getOption(), msgDesc);

      std::stringstream comments;
      comments << "scratch space fill: "
               << inst->getDst()->getTopDcl()->getName() << " from offset["
               << offset << "x32]";
      sendInst->addComment(comments.str());

      instIt = bb->insertBefore(instIt, sendInst);

      if (EUFusionNoMaskWANeeded() && sendInst->isWriteEnableInst()) {
        addEUFusionNoMaskWAInst(bb, sendInst);
      }

      numRows -= getPayloadSizeGRF(numRows);
      offset += getPayloadSizeGRF(numRows);
      rowOffset += getPayloadSizeGRF(numRows);
    }

    insertSlot1HwordR0Reset(bb, origInstIt);
  }
}

void GlobalRA::expandFillStackcall(uint32_t numRows, uint32_t offset,
                                   short rowOffset, G4_SrcRegRegion *header,
                                   G4_DstRegRegion *resultRgn, G4_BB *bb,
                                   INST_LIST_ITER &instIt) {
  auto &builder = kernel.fg.builder;
  auto inst = (*instIt);
  auto fillIt = instIt;

  // Use oword ld for stackcall. Lower intrinsic to:
  // add (1) r126.2<1>:d FP<0;1,0>:d offset
  //  send (16) r[startReg]<1>:uw r126 0xa desc:ud
  G4_Operand *src0 = nullptr;
  G4_Imm *src1 = nullptr;
  G4_Declare *scratchRegDcl = builder->kernel.fg.scratchRegDcl;
  G4_Declare *framePtr = inst->asFillIntrinsic()->getFP();

  // convert hword to oword offset
  auto numRowsOword = numRows * 2;
  auto offsetOword = offset * 2;
  auto rowOffsetOword = rowOffset * 2;

  while (numRowsOword >= 1) {
    auto createOwordFill = [&](unsigned int owordSize,
                               G4_DstRegRegion *fillVar) {
      G4_ExecSize execSize = (owordSize > 2) ? g4::SIMD16 : g4::SIMD8;
      auto sendSrc0 =
          builder->createSrc(scratchRegDcl->getRegVar(), 0, 0,
                             builder->rgnpool.createRegion(8, 8, 1), Type_UD);
      G4_Imm *desc = createMsgDesc(owordSize, false, false);
      G4_INST *sendInst = nullptr;
      auto sfId = SFID::DP_DC0;

      // Use bindless for XeHP_SDV and later
      if (builder->getPlatform() >= Xe_XeHPSDV) {
        // Update BTI to 251
        auto newDesc = desc->getInt() & 0xffffff00;
        newDesc |= 251;
        desc = builder->createImm(newDesc, Type_UD);

        auto msgDesc =
            builder->createReadMsgDesc(sfId, (uint32_t)desc->getInt());
        G4_Operand *msgDescOpnd =
            builder->createImm(msgDesc->getDesc(), Type_UD);

        // a0 is set by saveRestoreA0()
        auto src1 =
            builder->createSrc(builder->getBuiltinA0Dot2()->getRegVar(), 0, 0,
                               builder->getRegionScalar(), Type_UD);

        sendInst = builder->createInternalSplitSendInst(
            execSize, fillVar, sendSrc0, nullptr, msgDescOpnd,
            InstOpt_WriteEnable, msgDesc, src1);
      } else {
        auto msgDesc =
            builder->createReadMsgDesc(SFID::DP_DC0, (uint32_t)desc->getInt());
        auto msgDescImm = builder->createImm(msgDesc->getDesc(), Type_UD);
        sendInst = builder->createInternalSendInst(
            nullptr, G4_send, execSize, fillVar, sendSrc0, msgDescImm,
            InstOpt_WriteEnable, msgDesc);
      }
      return sendInst;
    };

    auto respSizeInOwords = getPayloadSizeOword(numRowsOword);
    auto fillDst =
        builder->createDst(resultRgn->getBase(), rowOffsetOword / 2, 0,
                           resultRgn->getHorzStride(), resultRgn->getType());

    G4_DstRegRegion *dst =
        builder->createDst(scratchRegDcl->getRegVar(), 0, 2, 1, Type_UD);

    G4_INST *hdrSetInst = nullptr;
    if (inst->asFillIntrinsic()->isOffsetValid()) {
      // Skip header if spill module emits its own header
      if (framePtr) {
        src0 = builder->createSrc(framePtr->getRegVar(), 0, 0,
                                  builder->getRegionScalar(), Type_UD);
        src1 = builder->createImm(offsetOword, Type_UD);
        hdrSetInst = builder->createBinOp(G4_add, g4::SIMD1, dst, src0, src1,
                                          InstOpt_WriteEnable, false);
      } else {
        src0 = builder->createImm(offsetOword, Type_UD);
        hdrSetInst = builder->createMov(g4::SIMD1, dst, src0,
                                        InstOpt_WriteEnable, false);
      }

      bb->insertBefore(fillIt, hdrSetInst);
    }

    auto fillSends = createOwordFill(respSizeInOwords, fillDst);

    if (getEUFusionCallWAInsts().count(inst) > 0) {
      removeEUFusionCallWAInst(inst);
      addEUFusionCallWAInst(fillSends);
      if (hdrSetInst)
        addEUFusionCallWAInst(hdrSetInst);
    }

    std::stringstream comments;
    comments << "stack fill: " << resultRgn->getTopDcl()->getName()
             << " from FP[" << inst->asFillIntrinsic()->getOffset() << "x32]";
    fillSends->addComment(comments.str());

    bb->insertBefore(fillIt, fillSends);

    if (kernel.getOption(vISA_GenerateDebugInfo)) {
      INST_LIST expandedInsts = {hdrSetInst, fillSends};
      kernel.getKernelDebugInfo()->updateExpandedIntrinsic(
          inst->asFillIntrinsic(), expandedInsts);
    }

    numRowsOword -= respSizeInOwords;
    offsetOword += respSizeInOwords;
    rowOffsetOword += respSizeInOwords;
  }
}

bool GlobalRA::spillFillIntrinUsesLSC(G4_INST *spillFillIntrin) {
  G4_Declare *headerDcl = nullptr;
  if (!spillFillIntrin)
    return false;

  if (spillFillIntrin->isFillIntrinsic())
    headerDcl = spillFillIntrin->asFillIntrinsic()->getHeader()->getTopDcl();
  else if (spillFillIntrin->isSpillIntrinsic())
    headerDcl = spillFillIntrin->asSpillIntrinsic()->getHeader()->getTopDcl();

  if (useLscForSpillFill &&
      headerDcl != builder.getBuiltinR0()->getRootDeclare()) {
    return true;
  }
  return false;
}

void GlobalRA::markSlot1HwordSpillFill(G4_BB *bb) {
  if (useLscForNonStackCallSpillFill ||
      !kernel.getBoolKernelAttr(Attributes::ATTR_SepSpillPvtSS))
    return;

  bool isSet = false;
  G4_INST *prevSetInst = nullptr;
  G4_Declare *builtinR0 = builder.getBuiltinR0()->getRootDeclare();
  unsigned builtinR0RegNum =
      builtinR0->getRegVar()->getPhyReg()->asGreg()->getRegNum();

  for (auto instIt = bb->begin(); instIt != bb->end(); ++instIt) {
    G4_INST *inst = (*instIt);
    if (inst->isFillIntrinsic()) {
      G4_FillIntrinsic *fillInst = inst->asFillIntrinsic();

      if (!spillFillIntrinUsesLSC(inst) && !fillInst->isOffBP() &&
          fillInst->isOffsetValid()) {
        if (!isSet) {
          slot1SetR0.insert(inst);
          isSet = true;
        }
        prevSetInst = inst;

        // Special case of builtin r0 being overwritten by the fill instruction.
        // In this case the register shouldn't be reset from slot1 after the
        // fill because the physical register got reused and builtin r0 is no
        // longer alive.
        // Example IR illustrating the problem:
        //   //.declare FL (r0.0)
        //   (W) intrinsic.fill.1 (8)  FL(0,0)<1>:ud r0.0<1;1,0>:ud
        //                             Scratch[0x32]
        //       mov (8)               M2(0,0)<1>:f FL(0,0)<1;1,0>:f
        //       mov (8)               M2(1,0)<1>:f FL(0,0)<1;1,0>:f
        //       mov (8)               M2(2,0)<1>:f FL(0,0)<1;1,0>:f
        //       mov (8)               M2(3,0)<1>:f FL(0,0)<1;1,0>:f
        //       sendsc (8)            null:ud M2(0,0) null 0x25:ud
        //                             0x8031400:ud {EOT} // render target write
        G4_VarBase *dstVarBase = fillInst->getDst()->getBase();

        vASSERT(dstVarBase);
        G4_VarBase *dstPhyReg = dstVarBase->asRegVar()->getPhyReg();

        vASSERT(dstPhyReg);
        unsigned dstRegNum = dstPhyReg->asGreg()->getRegNum();

        if (dstRegNum <= builtinR0RegNum &&
            builtinR0RegNum < dstRegNum + fillInst->getNumRows()) {
          isSet = false;
          prevSetInst = nullptr;
        }
      }
    } else if (inst->isSpillIntrinsic()) {
      G4_SpillIntrinsic *spillInst = inst->asSpillIntrinsic();

      if (!spillFillIntrinUsesLSC(inst) && !spillInst->isOffBP() &&
          spillInst->isOffsetValid()) {
        if (!isSet) {
          slot1SetR0.insert(inst);
          isSet = true;
        }
        prevSetInst = inst;
      }
    } else if (isSet) {
      // Check instruction for r0 usage.
      // If r0 is used, add previous spill/fill instruction to reset list.
      if (G4_Operand *dstOpnd = inst->getDst()) {
        G4_Declare *dstDecl = dstOpnd->getTopDcl();
        if (dstDecl && dstDecl->getRootDeclare() == builtinR0) {
          isSet = false;
          break;
        }
      }

      unsigned srcNum = static_cast<unsigned>(inst->getNumSrc());
      for (unsigned srcIdx = 0; srcIdx < srcNum; ++srcIdx) {
        G4_Operand *srcOpnd = inst->getSrc(srcIdx);
        G4_Declare *srcDecl = srcOpnd->getTopDcl();
        if (srcDecl && srcDecl->getRootDeclare() == builtinR0) {
          isSet = false;
          break;
        }
      }

      if (!isSet) {
        slot1ResetR0.insert(prevSetInst);
      }
    }
  }

  // End of the block with r0.5 pointing to slot1,
  // mark last spill/fill to reset it.
  if (isSet) {
    slot1ResetR0.insert(prevSetInst);
  }
}


void GlobalRA::expandFillIntrinsic(G4_BB *bb) {
  // fill (1) fill_var:ud     bitmask:ud     offset:ud
  for (auto instIt = bb->begin(); instIt != bb->end();) {
    auto inst = (*instIt);
    if (inst->isFillIntrinsic()) {
      bool isOffBP = inst->asFillIntrinsic()->isOffBP();
      uint32_t numRows = inst->asFillIntrinsic()->getNumRows();
      uint32_t offset = inst->asFillIntrinsic()->getOffset() *
                        (builder.numEltPerGRF<Type_UB>() / HWORD_BYTE_SIZE);
      auto header = inst->getSrc(0)->asSrcRegRegion();
      auto resultRgn = inst->getDst();
      auto fillIt = instIt;

      auto rowOffset = resultRgn->getRegOff();
      if (useLscForNonStackCallSpillFill || spillFillIntrinUsesLSC(inst)) {
        expandFillLSC(bb, instIt);
      } else {
        if (!isOffBP) {
          expandFillNonStackcall(numRows, offset, rowOffset, header, resultRgn,
                                 bb, instIt);
        } else {
          expandFillStackcall(numRows, offset, rowOffset, header, resultRgn, bb,
                              instIt);
        }
      }
      numGRFFill++;
      instIt = bb->erase(fillIt);
      continue;
    }
    instIt++;
  }
}


// Initialize address for immediate offset usage in LSC spill/fill messages
void GlobalRA::initAddrRegForImmOffUseNonStackCall() {
  // create a tmp register and store value 0x10000 for immediate offset usage
  // in non-stackcall spill/fill
  //    mov spillHeader 0x10000
  G4_BB *entryBB = builder.kernel.fg.getEntryBB();
  auto iter = std::find_if(entryBB->begin(), entryBB->end(),
                           [](G4_INST *inst) { return !inst->isLabel(); });

  auto movInst = builder.createMov(
      g4::SIMD1, builder.createDstRegRegion(builder.getSpillFillHeader(), 1),
      builder.createImm(0x10000, Type_UD), InstOpt_WriteEnable, false);
  entryBB->insertBefore(iter, movInst);
}

void GlobalRA::expandSpillFillIntrinsics(unsigned int spillSizeInBytes) {

  auto globalScratchOffset =
      kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);
  bool hasStackCall =
      kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc();

  // turn off immediate offset if the spill size is larger than 128k for non
  // stack call. Such test should be rare and don't think it needs to be fast.
  if (!hasStackCall &&
      ((spillSizeInBytes + globalScratchOffset) > SPILL_FILL_IMMOFF_MAX * 2))
    canUseLscImmediateOffsetSpillFill = false;

  // No need to init address reg for immediate offset usage if there is no
  // scratch message
  if (canUseLscImmediateOffsetSpillFill &&
      ((!hasStackCall && spillSizeInBytes > 0)))
    initAddrRegForImmOffUseNonStackCall();


  for (auto bb : kernel.fg) {
    if (builder.hasScratchSurface() &&
        (hasStackCall || kernel.fg.builder->hasValidOldA0Dot2() ||
         (useLscForSpillFill &&
          (spillSizeInBytes + globalScratchOffset) >= SCRATCH_MSG_LIMIT &&
          spillSizeInBytes > 0) ||
         (useLscForNonStackCallSpillFill && spillSizeInBytes > 0)
    // Following cases exist:
    // a. XeHP_SDV without stackcall => use hword scratch msg
    // b. XeHP_SDV without stackcall => using oword block msg
    // c. XeHP_SDV with stackcall
    // d. DG2+ without stackcall => hword scratch msg (illegal in Xe2+)
    // e. DG2+ without stackcall => using LSC
    // f. DG2+ with stackcall    => using LSC
    //
    // (a), (d) are similar to SKL with hword scratch msg.
    //
    // (c), (f):
    // a0.2 is saved/restored from r126.6:ud
    // SSO is saved in r126.7:ud (in replaceSSO function)
    // XeHP_SDV uses oword msg, DG2+ uses LSC msg
    // For DG2+, offset is computed in r126.0
    //
    // (b):
    // oword header is prepared in a temp variable, allocated by RA
    // a0.2 is saved/restored in oldA0Dot2(0,0) whenever required
    // SSO is allocated to a live-out temp (not tied to r126.7:ud)
    //
    // (e):
    // LSC msg is used for spill/fill
    // Spill offset is computed in spillHeader(0,0)
    // a0.2 is saved/restored in oldA0Dot2(0,0) whenever required
    // spillHeader is marked as live-out
    //
    // When needed:
    // SSO is marked as live-out
    // r0 is stored in r127
    //
             )) {
      saveRestoreA0(bb);
    }
    markSlot1HwordSpillFill(bb);
    expandSpillIntrinsic(bb);
    expandFillIntrinsic(bb);
  }
}

BoundedRA::BoundedRA(GlobalRA &ra, const LiveRangeVec *l)
    : gra(ra), kernel(ra.kernel), lrs(l) {}

void vISA::BoundedRA::markBusyGRFs() {
  vASSERT(lrs);
  auto dst = curInst->getDst();
  if (dst && dst->isDstRegRegion() && dst->getTopDcl() &&
      dst->getTopDcl()->useGRF()) {
    if (!dst->isIndirect()) {
      auto id = dst->getTopDcl()->getRegVar()->getId();
      bool isPartaker = dst->getTopDcl()->getRegVar()->isRegAllocPartaker();
      auto phyReg = dst->getTopDcl()->getRegVar()->getPhyReg();
      if (!phyReg && isPartaker)
        phyReg = (*lrs)[id]->getPhyReg();
      if (phyReg && phyReg->isGreg()) {
        auto regLB =
            phyReg->asGreg()->getRegNum() * kernel.numEltPerGRF<Type_UB>();
        regLB += dst->getTopDcl()->getRegVar()->getPhyRegOff() *
                 TypeSize(dst->getType());
        regLB += dst->getLeftBound();
        auto regRB = regLB + dst->getRightBound() - dst->getLeftBound();
        auto startGRF = regLB / kernel.numEltPerGRF<Type_UB>();
        auto endGRF = regRB / kernel.numEltPerGRF<Type_UB>();
        for (unsigned int reg = startGRF; reg != (endGRF + 1); ++reg)
          markGRF(reg);
      } else if (isPartaker)
        markForbidden((*lrs)[id]);
    } else if (dst->isIndirect()) {
      auto &p2a = gra.pointsToAnalysis;
      auto pointees = p2a.getAllInPointsTo(dst->getTopDcl()->getRegVar());
      for (auto &pointee : *pointees) {
        if (!pointee.var->isRegAllocPartaker())
          continue;
        auto id = pointee.var->getId();
        auto phyReg = pointee.var->getPhyReg();
        if (!phyReg)
          phyReg = (*lrs)[id]->getPhyReg();
        if (phyReg) {
          auto regLB =
              phyReg->asGreg()->getRegNum() * kernel.numEltPerGRF<Type_UB>();
          auto regRB =
              regLB +
              pointee.var->getDeclare()->getRootDeclare()->getByteSize();
          auto startGRF = regLB / kernel.numEltPerGRF<Type_UB>();
          auto endGRF = regRB / kernel.numEltPerGRF<Type_UB>();
          for (unsigned int reg = startGRF; reg != (endGRF + 1); ++reg)
            markGRF(reg);
        } else
          markForbidden((*lrs)[id]);
      }
    }
  }

  for (unsigned int i = 0; i != curInst->getNumSrc(); ++i) {
    auto src = curInst->getSrc(i);
    if (src && src->isSrcRegRegion()) {
      if (!src->asSrcRegRegion()->isIndirect() &&
          src->asSrcRegRegion()->getTopDcl() &&
          src->asSrcRegRegion()->getTopDcl()->useGRF()) {
        auto id = src->getTopDcl()->getRegVar()->getId();
        bool isPartaker = src->getTopDcl()->getRegVar()->isRegAllocPartaker();
        auto phyReg = src->getTopDcl()->getRegVar()->getPhyReg();
        if (!phyReg && isPartaker)
          phyReg = (*lrs)[id]->getPhyReg();
        if (phyReg && phyReg->isGreg()) {
          auto regLB =
              phyReg->asGreg()->getRegNum() * kernel.numEltPerGRF<Type_UB>();
          regLB += src->getTopDcl()->getRegVar()->getPhyRegOff() *
                   TypeSize(src->getType());
          regLB += src->getLeftBound();
          auto regRB = regLB + src->getRightBound() - src->getLeftBound();
          auto startGRF = regLB / kernel.numEltPerGRF<Type_UB>();
          auto endGRF = regRB / kernel.numEltPerGRF<Type_UB>();
          for (unsigned int reg = startGRF; reg != (endGRF + 1); ++reg)
            markGRF(reg);
        } else if (isPartaker)
          markForbidden((*lrs)[id]);
      } else if (src->asSrcRegRegion()->isIndirect()) {
        auto &p2a = gra.pointsToAnalysis;
        auto pointees = p2a.getAllInPointsTo(src->getTopDcl()->getRegVar());
        for (auto &pointee : *pointees) {
          if (!pointee.var->isRegAllocPartaker())
            continue;
          auto id = pointee.var->getId();
          auto phyReg = pointee.var->getPhyReg();
          if (!phyReg)
            phyReg = (*lrs)[id]->getPhyReg();
          if (phyReg) {
            auto regLB =
                phyReg->asGreg()->getRegNum() * kernel.numEltPerGRF<Type_UB>();
            auto regRB =
                regLB +
                pointee.var->getDeclare()->getRootDeclare()->getByteSize();
            auto startGRF = regLB / kernel.numEltPerGRF<Type_UB>();
            auto endGRF = regRB / kernel.numEltPerGRF<Type_UB>();
            for (unsigned int reg = startGRF; reg != (endGRF + 1); ++reg)
              markGRF(reg);
          } else
            markForbidden((*lrs)[id]);
        }
      }
    }
  }
}

void BoundedRA::markUniversalForbidden() {
  vASSERT(lrs);
  auto markPhyReg = [&](G4_Declare *dcl) {
    if (dcl->getRegVar() && dcl->getRegVar()->getPhyReg())
      markGRF(dcl->getRegVar()->getPhyReg()->asGreg()->getRegNum());
    else if (dcl->getRegVar()->isRegAllocPartaker())
      if (auto reg = (*lrs)[dcl->getRegVar()->getId()]->getPhyReg())
        markGRF(reg->asGreg()->getRegNum());
  };
  // r0 is special and shouldn't be allocated to temps
  markGRF(0);

  // BuiltInR0 may be needed by spill/fill instruction
  markPhyReg(kernel.fg.builder->getBuiltinR0());

  // spill/fill header may be clobbered by spill/fill instruction
  if (gra.builder.hasValidSpillFillHeader()) {
    markPhyReg(kernel.fg.builder->getSpillFillHeader());
  }

  // a0.2 may be copied to special GRF to preserve it across
  // the spill/fill instruction. So forbid allocation to temp
  // GRF that holds old a0.2 value.
  if (gra.builder.hasValidOldA0Dot2()) {
    markPhyReg(kernel.fg.builder->getOldA0Dot2Temp());
  }
}

void BoundedRA::markForbidden(LiveRange *lr) {
  auto totalRegs = gra.kernel.getNumRegTotal();
  const BitSet *forbidden = lr->getForbidden();
  // We've 0 reserved GRFs if an RA iteration was converted
  // to fail safe. But we may have non-zero reserved GRFs
  // if fail safe was set before running RA iteration.
  auto numReserved =
      (reservedGRFStart == NOT_FOUND) ? 0 : gra.getNumReservedGRFs();
  auto isReservedGRF = [&](unsigned int reg) {
    return (numReserved > 0 && reg >= reservedGRFStart &&
            reg < (reservedGRFStart + numReserved));
  };
  for (unsigned int i = 0; i != totalRegs; ++i) {
    if (!isReservedGRF(i) && forbidden && forbidden->isSet(i))
      markGRF(i);
  }

  markUniversalForbidden();
}

void BoundedRA::markGRFs(unsigned int reg, unsigned int num) {
  for (unsigned int r = reg; r != (reg + num); ++r) {
    markGRF(r);
    // Reserved  GRFs shouldnt be marked as clobbered
    if (reservedGRFStart != NOT_FOUND && reg >= reservedGRFStart &&
        reg < (reservedGRFStart + gra.getNumReservedGRFs()))
      continue;
    clobberedGRFs[curInst].insert(r);
  }
}

void BoundedRA::insertPushPop(bool useLSCMsg) {
  // List of clobbered GRFs is available.
  // prev and next iters are available.
  // Insert push (spill) and pop (fill) from clobbered physical GRFs here.
  auto cIt = clobberedGRFs.find(curInst);
  if (cIt == clobberedGRFs.end() || (*cIt).second.size() == 0)
    return;

  auto &clobbered = clobberedGRFs[curInst];
  // list of <leading GRF, # GRFs>
  std::list<std::pair<unsigned int, unsigned int>> segments;
  unsigned int maxGRFSpillFill = 4;
  // HWord message supports max size of 8 HWords.
  // For platforms with 32-byte GRF, 8GRF r/w is supported.
  // 8GRFs are supported for HWord and OWord messages.
  if (kernel.getGRFSize() == 32)
    maxGRFSpillFill = 8;
  // Stack call functions never use HWord message. So r/w of
  // 8 GRFs is supported when using stack call with LSC when
  // GRF size > 32 bytes.
  else if ((kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc()) &&
           useLSCMsg)
    maxGRFSpillFill = 8;
  // Non-stack call kernel may use either HWord scratch message or LSC.
  // If kernel uses LSC then max supported r/w size is 8 GRFs.
  else if (gra.useLscForNonStackCallSpillFill)
    maxGRFSpillFill = 8;

  auto segmentClobbered = [&]() {
    for (auto grf : clobbered) {
      if (segments.size() > 0 &&
          (segments.back().first + segments.back().second) == grf) {
        segments.back().second += 1;
        continue;
      }
      segments.push_back(std::make_pair(grf, 1));
    }

    // Ensure each segment size is power of 2
    for (auto it = segments.begin(); it != segments.end();) {
      auto &sz = (*it).second;
      if (sz == 1 || sz == 2 || sz == 4 || (sz == 8 && maxGRFSpillFill >= 8)) {
        ++it;
        continue;
      }
      // non-power of 2 found
      auto grf = (*it).first;
      if (sz > 8 && maxGRFSpillFill >= 8) {
        it = segments.insert(it, std::make_pair(grf + 8, sz - 8));
        sz = 8;
        continue;
      } else if (sz > 4) {
        it = segments.insert(it, std::make_pair(grf + 4, sz - 4));
        sz = 4;
        continue;
      } else if (sz > 2) {
        it = segments.insert(it, std::make_pair(grf + 2, sz - 2));
        sz = 2;
        continue;
      }
      ++it;
    }
  };

  // Aim to minimize # spill/fill instructions.
  segmentClobbered();

  G4_Declare *fp =
      kernel.fg.builder->usesStack() ? kernel.fg.getFramePtrDcl() : nullptr;
  auto *builder = kernel.fg.builder;
  const unsigned int DclSize = 16;

  for (auto &segment : segments) {
    G4_SrcRegRegion *headerOpnd = nullptr;
    G4_SrcRegRegion *headerOpnd1 = nullptr;
    G4_INST *movInst = nullptr;

    unsigned int off = spillOffset;
    off += segment.first * kernel.numEltPerGRF<Type_UB>();
    if (off < SCRATCH_MSG_LIMIT && !gra.useLscForNonStackCallSpillFill) {
      // Stack call, HWord cases can take BuiltInR0 as header
      headerOpnd = builder->createSrcRegRegion(builder->getBuiltinR0(),
                                               builder->getRegionStride1());
      headerOpnd1 = builder->createSrcRegRegion(builder->getBuiltinR0(),
                                                builder->getRegionStride1());
      off = off >> SCRATCH_SPACE_ADDRESS_UNIT;
    } else if (useLSCMsg) {
      // LSC needs its own spill/fill header
      headerOpnd = getSpillFillHeader(*builder, nullptr);
      headerOpnd1 = getSpillFillHeader(*builder, nullptr);
      off = off >> SCRATCH_SPACE_ADDRESS_UNIT;
    } else {
      // off is beyond HWord addressable range
      // LSC is not available on platform
      // Use OWord. Header needs to be initialized separately when using OWord.
      vISA_ASSERT(reservedGRFStart != NOT_FOUND,
                  "expecting valid reserved GRF");
      auto *immOpnd = builder->createImm(off / OWORD_BYTE_SIZE, Type_UD);
      auto *tmp = builder->createDeclare(
          "TMP", G4_GRF, kernel.numEltPerGRF<Type_UD>(), 1, Type_UD);
      tmp->getRegVar()->setPhyReg(builder->phyregpool.getGreg(reservedGRFStart),
                                  0);
      auto *dstMov = builder->createDstRegRegion(tmp, 1);
      movInst = builder->createMov(G4_ExecSize(1), dstMov, immOpnd,
                                   InstOpt_WriteEnable, false);
      movInst->inheritDIFrom(curInst);
      headerOpnd =
          builder->createSrcRegRegion(tmp, builder->getRegionStride1());
      headerOpnd1 =
          builder->createSrcRegRegion(tmp, builder->getRegionStride1());
      off = G4_SpillIntrinsic::InvalidOffset;
    }

    G4_ExecSize execSize(16);
    const char *dclName = builder->getNameString(DclSize, "PUSH%d_%d",
                                                 segment.first, segment.second);
    G4_Declare *tmp = builder->createDeclare(
        dclName, G4_GRF, kernel.numEltPerGRF<Type_D>(), segment.second, Type_D);
    tmp->getRegVar()->setPhyReg(builder->phyregpool.getGreg(segment.first), 0);

    // Push
    G4_DstRegRegion *postDst = builder->createNullDst(Type_UD);
    auto srcOpnd = builder->createSrc(tmp->getRegVar(), 0, 0,
                                      builder->getRegionStride1(), Type_D);

    auto spill = builder->createSpill(postDst, headerOpnd, srcOpnd, execSize,
                                      segment.second, off, fp,
                                      InstOpt_WriteEnable, false);

    curBB->insertAfter(prev, spill, false);
    spill->inheritDIFrom(curInst);
    if (movInst)
      curBB->insertAfter(prev, movInst, false);

    if (!(next == curBB->end() && curBB->back()->isEOT())) {
      // Pop
      if (movInst)
        curBB->insertBefore(next, movInst->cloneInst(), false);

      auto dst = builder->createDst(tmp->getRegVar(), 0, 0, 1, Type_D);
      auto fill =
          builder->createFill(headerOpnd1, dst, execSize, segment.second, off,
                              fp, InstOpt_WriteEnable, false);

      curBB->insertBefore(next, fill, false);
      fill->inheritDIFrom(curInst);
    }
  }

  // Reset clobbered after inserting push/pop
  clobbered.clear();
}

void BoundedRA::markIndirIntfs() {
  // In this function we create ref list of all addr
  // dcls and instructions where they appear.
  //
  // A0 -> {List of instructions where r[A0] occurs}
  // A1 -> {List of instructions where r[A1] occurs}

  for (auto bb : kernel.fg) {
    for (INST_LIST_ITER inst_it = bb->begin(); inst_it != bb->end();
         inst_it++) {
      G4_INST *curInst = (*inst_it);

      // Handle indirect destination
      G4_DstRegRegion *dst = curInst->getDst();

      if (dst && dst->getRegAccess() == IndirGRF) {
        setInst(curInst, bb);

        auto topdcl = dst->getTopDcl();
        busyIndir[topdcl].push_back(curInst);
      }

      for (int i = 0, numSrc = curInst->getNumSrc(); i < numSrc; i++) {
        G4_Operand *src = curInst->getSrc(i);

        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->getRegAccess() == IndirGRF) {
          setInst(curInst, bb);

          auto topdcl = src->asSrcRegRegion()->getTopDcl();
          busyIndir[topdcl].push_back(curInst);
        }
      }
    }
  }
}

bool BoundedRA::isFreeIndir(unsigned int r) {
  // A0 = &V10
  // A1 = &V11
  // A2 = &V12
  //
  // Assume V10, V11, V12 are spilled
  //
  //                             Busy:
  // r1 = r[A1] + r2             r1, r2 -  (1)
  // r5 = r[A2] + r10            r5, r10 - (2)
  // r20 = r[A1] + r3            r20, r3 - (3)
  // r[A2] = r[A1] + r6          r6      - (4)
  // r[A3] = r[A2] + r12         r12     - (5)
  //
  // Busy for r[A1] -> (1) + (3) + (4)
  // Busy for r[A2] -> (2) + (4) + (5)
  // Busy for r[A3] -> (5)

  // When choosing a GRF to use for an indirect
  // operand, we need to lookup a data structure to
  // find free GRFs. It is not sufficient to find free
  // GRF from current instruction only because the
  // chosen GRF has to be free in all instructions
  // where the indirect appears. For eg, in above
  // sequence we cannot use r6 to load r[A1] in (1)
  // even though r6 is not busy in (1) - because it's
  // busy in (4).

  vISA_ASSERT(addrDcl, "expecting non-nullptr addrDcl");
  auto &refs = busyIndir[addrDcl];

  for (auto ref : refs) {
    if (!isFreeGRFOtherInst(r, ref))
      return false;
  }

  return true;
}