File: Optimizer.cpp

package info (click to toggle)
intel-graphics-compiler 1.0.17791.18-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 102,312 kB
  • sloc: cpp: 935,343; lisp: 286,143; ansic: 16,196; python: 3,279; yacc: 2,487; lex: 1,642; pascal: 300; sh: 174; makefile: 27
file content (8567 lines) | stat: -rw-r--r-- 292,694 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
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2022 Intel Corporation

SPDX-License-Identifier: MIT

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

#include "Optimizer.h"
#include "Assertions.h"
#include "G4_Opcode.h"
#include "G4_Verifier.hpp"
#include "Timer.h"
#include "ifcvt.h"
#include "Common_BinaryEncoding.h"
#include "DebugInfo.h"
#include "FlowGraph.h"
#include "Passes/AccSubstitution.hpp"
#include "PointsToAnalysis.h"
#include "Passes/InstCombine.hpp"
#include "Passes/LVN.hpp"
#include "Passes/MergeScalars.hpp"
#include "Passes/SendFusion.hpp"
#include "Passes/StaticProfiling.hpp"

// clang-format off
#include "common/LLVMWarningsPush.hpp"
#include "llvm/Support/Allocator.h"
#include "common/LLVMWarningsPop.hpp"
// clang-format on

#include <algorithm>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <map>
#include <random>
#include <sstream>
#include <tuple>
#include <vector>

using namespace vISA;

void Optimizer::LVN() {
  // Run a simple LVN pass that replaces redundant
  // immediate loads in current BB. Also this pass
  // does not optimize operations like a
  // conventional VN pass because those require
  // more compile time, and are presumably already
  // done by FE generating VISA. This pass catches
  // redundancies that got introduced mainly by HW
  // conformity or due to VISA lowering.
  int numInstsRemoved = 0;
  PointsToAnalysis p(kernel.Declares, kernel.fg.getNumBB());
  p.doPointsToAnalysis(kernel.fg);
  for (auto bb : kernel.fg) {
    ::LVN lvn(fg, bb, *fg.builder, p);
    lvn.doLVN();
    numInstsRemoved += lvn.getNumInstsRemoved();
    numInstsRemoved += ::LVN::removeRedundantSamplerMovs(kernel, bb);
  }

  VISA_DEBUG({
    std::cout << "===== LVN ====="
              << "\n";
    std::cout << "Number of instructions removed: " << numInstsRemoved << "\n"
              << "\n";
  });
}

// helper functions

static int getDstSubReg(G4_DstRegRegion *dst) {
  int dstSubReg;
  if (dst->getBase()->isPhyReg()) {
    dstSubReg = dst->getSubRegOff();
  } else {
    dstSubReg = dst->getSubRegOff() +
                static_cast<G4_RegVar *>(dst->getBase())->getPhyRegOff();
  }

  return dstSubReg;
}

static int getSrcSubReg(G4_Operand *src) {
  vISA_ASSERT(src->isSrcRegRegion(), "expect Src Reg Region");
  int srcSubReg;
  if (src->asSrcRegRegion()->getBase()->isPhyReg()) {
    srcSubReg = src->asSrcRegRegion()->getSubRegOff();
  } else {
    srcSubReg = src->asSrcRegRegion()->getSubRegOff() +
                static_cast<G4_RegVar *>(src->asSrcRegRegion()->getBase())
                    ->getPhyRegOff();
  }
  return srcSubReg;
}

//
// determine if fall-through jump is needed
//
// also remove redundant jumps
//   if there is no predicate applied to a jump and its target is its fall
//   though BB, remove the jump instruction.

void Optimizer::insertFallThroughJump() {

  fg.setPhysicalPredSucc();
  for (BB_LIST_ITER it = fg.begin(); it != fg.end();) {
    G4_BB *bb = *it;
    BB_LIST_ITER next = ++it;
    //
    // determine if the current bb needs a fall through jump
    // check if the fall-through bb follows the current bb
    //
    G4_BB *fb = bb->fallThroughBB();
    if (fb && (next == fg.end() || // bb is the last bb
               fb != (*next))) {
      // This is bogus in SIMD CF, as bad things happen when you randomly insert
      // jumps in the middle of SIMD CF
    } else if (next != fg.end()) {
      // do not remove a jmpi if it's the target of an indirect jmp
      // this makes the code more readable
      if (!(*next)->empty() && (*next)->front()->isLabel() && !bb->empty() &&
          bb->back()->opcode() == G4_jmpi &&
          bb->back()->getPredicate() == NULL &&
          !fg.isIndirectJmpTarget(bb->back())) {
        if ((*next)->front()->getSrc(0) == bb->back()->getSrc(0)) {
          std::list<G4_INST *>::iterator it = bb->end();
          it--;
          bb->erase(it);
        }
      }
    }
    it = next;
  }
}

void Optimizer::forceAssignRegs() {
  const char *rawStr =
      builder.getOptions()->getOptionCstr(vISA_ForceAssignRhysicalReg);
  if (!rawStr)
    return;

  llvm::StringRef line(rawStr);
  llvm::SmallVector<llvm::StringRef, 4> assignments;
  line.split(assignments, ',');
  std::map<std::string /*decl name or id*/,
           std::pair<int /*reg*/, int /*subreg*/>> forceAssign;
  for (llvm::StringRef assignment : assignments) {
    llvm::StringRef decl, reg, subreg;
    std::tie(decl, reg) = assignment.split(':');
    std::tie(reg, subreg) = reg.split('.');
    int regNum = std::stoi(reg.str());
    int subregNum = subreg.empty() ? 0 : std::stoi(subreg.str());
    forceAssign[decl.str()] = std::make_pair(regNum, subregNum);
  }

  for (G4_Declare *dcl : kernel.Declares) {
    int reg, subreg;
    // skip forcing register assignment for the decl if both name and id are
    // not specified in the option. Name will be used if both are given.
    auto it = forceAssign.find(dcl->getName());
    if (it == forceAssign.end()) {
      it = forceAssign.find(std::to_string(dcl->getDeclId()));
      if (it == forceAssign.end())
        continue;
    }
    std::tie(reg, subreg) = it->second;
    dcl->getRegVar()->setPhyReg(builder.phyregpool.getGreg(reg), subreg);
    VISA_DEBUG({
        std::cerr << "Force assigning Decl : " << it->first
                  << " to r" << reg << "." << subreg << "\n";
        dcl->dump();
    });
  }
}

void Optimizer::forceSpillVars() {
  const char *rawStr =
      builder.getOptions()->getOptionCstr(vISA_ForceSpillVariables);
  if (!rawStr)
     return;

  llvm::StringRef line(rawStr);
  llvm::SmallVector<llvm::StringRef, 4> vars;
  line.split(vars, ',');
  std::vector<int> token;

  for (llvm::StringRef var : vars)
    token.push_back(std::stoi(var.str()));

  for (G4_Declare *dcl : kernel.Declares) {
    if (std::find(token.begin(), token.end(), dcl->getDeclId()) !=
        token.end()) {
      dcl->setForceSpilled();
    }
  }
}

void Optimizer::preRegAlloc() {
  forceAssignRegs();
  forceSpillVars();
}

void Optimizer::regAlloc() {

  fg.prepareTraversal();

  // realR0 and BuiltInR0 are 2 different dcls.
  // realR0 is always tied to physical r0.
  // if copy of r0 isnt needed then set latter to r0 as well.
  // if copy of r0 is required, then let RA decide allocation of BuiltInR0.
  if (!R0CopyNeeded()) {
    // when no copy is needed, make BuiltInR0 an alias of realR0
    builder.getBuiltinR0()->setAliasDeclare(builder.getRealR0(), 0);
    builder.getBuiltinR0()->getRegVar()->setPhyReg(
        builder.getRealR0()->getRegVar()->getPhyReg(), 0);
  }

  //
  // assign registers
  //
  int status = ::regAlloc(builder, builder.phyregpool, kernel);
  if (status == VISA_EARLY_EXIT) {
    EarlyExited = true;
  } else if (status != VISA_SUCCESS) {
    RAFail = true;
  }
}

// HW debugging needs to zero certain ARF registers such as a0, acc, etc.
// Here, we zero a0 and acc on entry to a kernel.
void Optimizer::zeroSomeARF() {
  if (builder.getIsKernel()) {
    // The first BB is not necessarily the kernel's entry when kernel needs to
    // load its payload!
    G4_BB *mainBB = fg.getEntryBB();
    if (builder.loadThreadPayload()) {
      // Make sure to skip prolog BBs to insert into the 1st BB of a kernel.
      //   [perThreadBB:]
      //   crossThreadBB:
      //   main:
      if (G4_BB *crossThreadBB = kernel.getCrossThreadPayloadBB()) {
        vASSERT(crossThreadBB->Succs.size() == 1);
        mainBB = crossThreadBB->Succs.front();
      } else if (G4_BB *perThreadBB = kernel.getPerThreadPayloadBB()) {
        vASSERT(perThreadBB->Succs.size() == 1);
        mainBB = perThreadBB->Succs.front();
      }
    }

    INST_LIST_ITER insertBeforePos = mainBB->getFirstInsertPos();

    // Zero all address ARF
    G4_DstRegRegion *A0Dst =
        builder.createDst(builder.phyregpool.getAddrReg(), 0, 0, 1, Type_UD);
    G4_INST *zeroA0 =
        builder.createMov(g4::SIMD8, A0Dst, builder.createImm(0, Type_UD),
                          InstOpt_WriteEnable, false);
    (void)mainBB->insertBefore(insertBeforePos, zeroA0);

    // Zero acc ARF (at least two, some platform has more).
    G4_DstRegRegion *Acc0Dst =
        builder.createDst(builder.phyregpool.getAcc0Reg(), 0, 0, 1, Type_UD);
    G4_INST *zeroAcc0 = builder.createMov(builder.getNativeExecSize(), Acc0Dst,
                                          builder.createImm(0, Type_UD),
                                          InstOpt_WriteEnable, false);
    (void)mainBB->insertBefore(insertBeforePos, zeroAcc0);

    G4_DstRegRegion *Acc1Dst =
        builder.createDst(builder.phyregpool.getAcc1Reg(), 0, 0, 1, Type_UD);
    G4_INST *zeroAcc1 = builder.createMov(builder.getNativeExecSize(), Acc1Dst,
                                          builder.createImm(0, Type_UD),
                                          InstOpt_WriteEnable, false);
    (void)mainBB->insertBefore(insertBeforePos, zeroAcc1);

    // Zero flags
    int num32bitFlags = (int)(builder.getNumFlagRegisters() / 2);
    for (int i = 0; i < num32bitFlags; ++i) {
      G4_DstRegRegion *flagDst = builder.createDst(
          builder.phyregpool.getFlagAreg(i), 0, 0, 1, Type_UD);
      G4_INST *zeroFlag =
          builder.createMov(g4::SIMD1, flagDst, builder.createImm(0, Type_UD),
                            InstOpt_WriteEnable, false);
      (void)mainBB->insertBefore(insertBeforePos, zeroFlag);
    }
  }
}

void Optimizer::addSWSBInfo() {
  if (builder.hasDPAS() && builder.hasDPASFuseRSWA()) {
    // Currently the DPASFuseRSWA is tied to SWSB, so we make the
    // preparation work the first part of addSWSBInfo.
    prepareDPASFuseRSWA();
  }

  bool do_fcall_wa = builder.hasFusedEU() &&
                     builder.getuint32Option(vISA_fusedCallWA) == 1 &&
                     (kernel.fg.getHasStackCalls() || kernel.hasIndirectCall());

  if (do_fcall_wa) {
    // Need to be done before SWSB
    finishFusedCallWA_preSWSB();
  }

  if (!builder.hasSWSB()) {
    if (do_fcall_wa) {
      finishFusedCallWA();
    }
    return;
  }

  if (!builder.getOption(vISA_forceDebugSWSB)) {
    SWSB swsb(kernel);
    swsb.SWSBGenerator();
  } else {
    forceDebugSWSB(&kernel);
  }

  if (builder.getOptions()->getuInt32Option(vISA_SWSBTokenBarrier) != 0) {
    singleInstStallSWSB(
        &kernel, builder.getOptions()->getuInt32Option(vISA_SWSBTokenBarrier),
        0, true);
  }

  if (builder.getOptions()->getuInt32Option(vISA_SWSBInstStall) != 0) {
    singleInstStallSWSB(
        &kernel, builder.getOptions()->getuInt32Option(vISA_SWSBInstStall),
        builder.getOptions()->getuInt32Option(vISA_SWSBInstStallEnd), false);
  }

  if (do_fcall_wa) {
    // Need to be done when code is stable (no add, no delete).
    finishFusedCallWA();
  } else if (kernel.hasIndirectCall() && !builder.supportCallaRegSrc()) {
    adjustIndirectCallOffsetAfterSWSBSet();
  }
  return;
}

// Common pass for HW debug functions
void Optimizer::HWDebug() {
  if (builder.getOption(vISA_InsertHashMovs))
    insertHashMovs();
}

void Optimizer::insertHashMovs() {
  // As per request from IGC team, we want to conditionally insert
  // two mov instructions like following:
  //
  // send ... {EOT}
  // mov (16) null<1>:d        lo32 {NoMask}
  // mov (16) null<1>:d        hi32 {NoMask}
  //
  bool hashAtPrologue = kernel.getOption(vISA_HashMovsAtPrologue);
  for (G4_BB *bb : kernel.fg) {
    for (auto it = bb->begin(); it != bb->end(); ++it) {
      auto inst = (*it);
      if (inst->isEOT() || hashAtPrologue) {
        auto insertBefore = it;
        if (inst->isLabel())
          ++insertBefore;
        // We have to insert new instructions after EOT.
        // Lexically, EOT could even be in the middle
        // of the program.
        auto insertHashMovInsts = [&](uint64_t hashVal) {
          G4_INST *lo;
          G4_INST *hi;
          lo = kernel.fg.builder->createMov(
              g4::SIMD16, kernel.fg.builder->createNullDst(Type_UD),
              kernel.fg.builder->createImm((unsigned int)(hashVal & 0xffffffff),
                                           Type_UD),
              InstOpt_WriteEnable, false);

          hi = kernel.fg.builder->createMov(
              g4::SIMD16, kernel.fg.builder->createNullDst(Type_UD),
              kernel.fg.builder->createImm(
                  (unsigned int)((hashVal >> 32) & 0xffffffff), Type_UD),
              InstOpt_WriteEnable, false);
          // Option: -hashmovs hi lo
          //   To be consistent, 'mov hi' goes before 'mov lo'
          if (hashAtPrologue) {
            bb->insertBefore(insertBefore, hi);
            bb->insertBefore(insertBefore, lo);
          } else {
            bb->push_back(hi);
            bb->push_back(lo);
          }
        };

        // This func is called when vISA_HashVal is set by user;
        // but vISA_HashVal1 is still optional.
        uint64_t hashVal = builder.getOptions()->getuInt64Option(vISA_HashVal);
        insertHashMovInsts(hashVal);
        // vISA_HashVal1 is an extra hash value used to distinguish each entry
        // in the module. That works for IGC as IGC invokes vISA for each
        // kernel. However, VC invokes vISA for the whole module, so here we use
        // an unique id for the purpose. Note that if vISA_HashVal1 is given,
        // the value would still be used to emit the extra hash.
        if (builder.getOptions()->isOptionSetByUser(vISA_HashVal1)) {
          uint64_t hashVal1 =
            builder.getOptions()->getuInt64Option(vISA_HashVal1);
          insertHashMovInsts(hashVal1);
        } else if (kernel.getKernelType() == VISA_CM) {
          insertHashMovInsts(kernel.getFunctionId());
        }
        return;
      }
    }
  }
}

//
// Break a sample instruction
// send.smpl (16) dst src0 src1
// into
// (P1) send.smpl (16) dst src0 src1
// (~P1) send.smpl (16) dst src0 src1
// where P1 is 0x5555 (i.e., pixels with even x coordinates)
// Ideally this would only affect 3d textures, but at
// the moment it will affect 2d array textures as well.
//
// P1 is initialized per BB before the first sample inst; we could make it per
// shader but I'm worried about flag spill this works for SIMD8 and SIMD32
// shaders as well.
//
void Optimizer::cloneSampleInst() {
  bool cloneSample = builder.getOption(vISA_enableCloneSampleInst) &&
                     VISA_WA_CHECK(builder.getPWaTable(), Wa_14014414195);
  bool cloneEvaluateSample = builder.getOption(vISA_cloneEvaluateSampleInst);
  if (!cloneSample && !cloneEvaluateSample) {
    return;
  }

  bool isSIMD32 = kernel.getSimdSize() == 32;
  for (auto &&bb : kernel.fg) {
    auto tmpFlag = builder.createTempFlag(isSIMD32 ? 2 : 1);
    auto hasSample = false;
    for (auto I = bb->begin(), E = bb->end(); I != E;) {
      auto Next = std::next(I);
      auto inst = *I;
      if (inst->isSend() && inst->getMsgDesc()->getSFID() == SFID::SAMPLER &&
          inst->getMsgDescRaw() != nullptr &&
          inst->getExecSize() >= builder.getNativeExecSize()) {
        G4_InstSend *sendInst = inst->asSendInst();
        G4_Operand *src0 = sendInst->getSrc(0);

        unsigned int messageSizeInBytes =
            src0->getRightBound() - src0->getLeftBound() + 1;
        if (sendInst->isSplitSend()) {
          G4_Operand *src1 = sendInst->getSrc(1);
          messageSizeInBytes +=
              src1->getRightBound() - src1->getLeftBound() + 1;
        }
        if (sendInst->getMsgDescRaw()->isHeaderPresent()) {
          messageSizeInBytes -= kernel.getGRFSize();
        }
        unsigned int numParams = messageSizeInBytes / kernel.getGRFSize() *
                                 builder.getNativeExecSize() /
                                 inst->getExecSize();
        bool isEval = sendInst->getMsgDesc()->getDstLenRegs() == 0;
        uint32_t messageType =
            sendInst->getMsgDescRaw()->getSamplerMessageType();
        vISA_ASSERT(!inst->getPredicate(),
                    "do not handle predicated sampler inst for now");
        if (!isEval && cloneSample && messageType == 0 && numParams == 3) {
          if (!hasSample) {
            hasSample = true;
            auto flagInit = builder.createMov(
                g4::SIMD1,
                builder.createDst(tmpFlag->getRegVar(),
                                  isSIMD32 ? Type_UD : Type_UW),
                builder.createImm(isSIMD32 ? 0x55555555 : 0x5555,
                                  isSIMD32 ? Type_UD : Type_UW),
                InstOpt_WriteEnable, false);
            bb->insertBefore(I, flagInit);
          }
          auto newInst = inst->cloneInst();
          inst->setPredicate(
              builder.createPredicate(PredState_Plus, tmpFlag->getRegVar(), 0));
          newInst->setPredicate(builder.createPredicate(
              PredState_Minus, tmpFlag->getRegVar(), 0));
          auto newInstIt = bb->insertAfter(I, newInst);

          uint16_t rspLen =
              inst->asSendInst()->getMsgDescRaw()->ResponseLength();
          // If Pixel Null Mask feedback is requested sampler message
          // has header, all data channels enabled and an additional
          // GRF of writeback payload with Pixel Null Mask.
          // Possible message response lengths are:
          // - 5 GRFs for all simd8 messages and for simd16 messages
          //   with 16-bit return format
          // - 9 GRFs for simd16 message with 32-bit return format
          // It is enough to check send's response length to determine
          // if Pixel Null Mask feedback is enabled.
          vASSERT(inst->getExecSize() == g4::SIMD8 ||
                  inst->getExecSize() == g4::SIMD16);
          uint16_t pixelNullMaskRspLen =
              (inst->getExecSize() == g4::SIMD16 &&
               !sendInst->getMsgDescRaw()->is16BitReturn())
                  ? 9
                  : 5;

          if (sendInst->getMsgDescRaw()->isHeaderPresent() &&
              rspLen == pixelNullMaskRspLen) {
            // Pixel Null Mask is in the first word of the last GRF
            // of send's writeback message. This mask has bits set
            // to 0 for pixels in which a null page was source for
            // at least one texel. Otherwise bits are set to 1.

            // Create a copy of Pixel Null Mask from the first send
            // writeback message and AND it with the mask from the
            // second send.
            G4_Declare *maskCopy = builder.createTempVar(1, Type_UW, Any);
            G4_Declare *maskAlias = builder.createTempVar(1, Type_UW, Any);
            maskAlias->setAliasDeclare(
                inst->getDst()->getBase()->asRegVar()->getDeclare(),
                (inst->getDst()->getRegOff() + rspLen - 1) *
                    kernel.numEltPerGRF<Type_UB>());
            G4_SrcRegRegion *src = builder.createSrcRegRegion(
                maskAlias, builder.getRegionScalar());
            G4_DstRegRegion *dst =
                builder.createDst(maskCopy->getRegVar(), Type_UW);
            G4_INST *movInst = builder.createMov(g4::SIMD1, dst, src,
                                                 InstOpt_WriteEnable, false);
            bb->insertAfter(I, movInst);
            G4_SrcRegRegion *src0 = builder.createSrcRegRegion(*src);
            G4_SrcRegRegion *src1 =
                builder.createSrcRegRegion(maskCopy, builder.getRegionScalar());
            dst = builder.createDst(maskAlias->getRegVar(), Type_UW);
            G4_INST *andInst = builder.createBinOp(
                G4_and, g4::SIMD1, dst, src0, src1, InstOpt_WriteEnable, false);
            bb->insertAfter(newInstIt, andInst);
          }
        } else if (isEval && cloneEvaluateSample && messageType != 0x1F) {
          // 0x1F is the opcode for sampler cache flush
          uint32_t newExecSize =
              (messageType == VISA_3D_SAMPLE_L || messageType == VISA_3D_LD)
                  ? 8
                  : 1;
          uint32_t mask = (1 << newExecSize) - 1;
          auto evalTmpFlag = builder.createTempFlag(isSIMD32 ? 2 : 1);
          auto flagInit = builder.createMov(
              g4::SIMD1,
              builder.createDst(evalTmpFlag->getRegVar(),
                                isSIMD32 ? Type_UD : Type_UW),
              builder.createImm(mask, isSIMD32 ? Type_UD : Type_UW),
              InstOpt_WriteEnable, false);
          bb->insertBefore(I, flagInit);
          inst->setPredicate(builder.createPredicate(
              PredState_Plus, evalTmpFlag->getRegVar(), 0));
          unsigned numInsts = kernel.getSimdSize() / newExecSize;
          for (unsigned int i = 1; i < numInsts; i++) {
            auto newInst = inst->cloneInst();
            bb->insertAfter(I, newInst);
            evalTmpFlag = builder.createTempFlag(isSIMD32 ? 2 : 1);
            flagInit = builder.createMov(
                g4::SIMD1,
                builder.createDst(evalTmpFlag->getRegVar(),
                                  isSIMD32 ? Type_UD : Type_UW),
                builder.createImm(mask << (i * newExecSize),
                                  isSIMD32 ? Type_UD : Type_UW),
                InstOpt_WriteEnable, false);
            newInst->setPredicate(builder.createPredicate(
                PredState_Plus, evalTmpFlag->getRegVar(), 0));
            bb->insertAfter(I, flagInit);
          }
        }
      }
      I = Next;
    }
  }
}

void Optimizer::removeLifetimeOps() {
  // Call this function after RA only.

  // Remove all pseudo_kill and lifetime.end
  // instructions.
  // Also remove pseudo_use instructions.
  for (G4_BB *bb : kernel.fg) {
    bb->erase(std::remove_if(bb->begin(), bb->end(),
                             [](G4_INST *inst) {
                               return inst->isPseudoKill() ||
                                      inst->isLifeTimeEnd() ||
                                      inst->isPseudoUse();
                             }),
              bb->end());
  }
}

void Optimizer::runPass(PassIndex Index) {
  const PassInfo &PI = Passes[Index];

  // Do not execute.
  if ((PI.Option != vISA_EnableAlways && !builder.getOption(PI.Option)) ||
      EarlyExited)
    return;

  std::string Name = PI.Name;

#ifndef DLL_MODE
  if (StopBeforePass == Name) {
    EarlyExited = true;
    kernel.dumpToConsole();
    return;
  }
#endif // DLL_MODE

  setCurrentDebugPass(PI.Name);

  if (PI.Timer != TimerID::NUM_TIMERS)
    startTimer(PI.Timer);

  kernel.dumpToFile("before." + Name);

  // Execute pass.
  (this->*(PI.Pass))();

  if (PI.Timer != TimerID::NUM_TIMERS)
    stopTimer(PI.Timer);

  kernel.dumpToFile("after." + Name);
#ifndef DLL_MODE
  // Only check for stop-after in offline build as it's intended for vISA
  // debugging only. Note that stop-after does not work if the pass is not
  // executed.
  if (StopAfterPass == Name || EarlyExited) {
    EarlyExited = true;
    kernel.dumpToConsole();
  }
#endif // DLL_MODE

#ifdef _DEBUG
  bool skipVerify = Index == PI_regAlloc && (RAFail || EarlyExited);
  if (!skipVerify) {
    verifyG4Kernel(kernel, Index, true, G4Verifier::VC_ASSERT);
  }
#endif
  setCurrentDebugPass(nullptr);
}

void Optimizer::initOptimizations() {
#define OPT_INITIALIZE_PASS(Name, Option, Timer)                                   \
  Passes[PI_##Name] = PassInfo(&Optimizer::Name, "" #Name, Option, Timer)

  // To initialize a pass, the member function name is the first argument.
  // This member function must return void and take no argument.
  //
  // The second argument is the corresponding option to enable this pass.
  // If it always runs then use vISA_EnableAlways.
  //
  // The third argument is the intended timer for this pass. If no timing
  // is necessary, then TIMER_NUM_TIMERS can be used.
  //
  OPT_INITIALIZE_PASS(cleanMessageHeader, vISA_LocalCleanMessageHeader,
                  TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(forceNoMaskOnM0, vISA_forceNoMaskOnM0, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(sendFusion, vISA_EnableSendFusion, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(renameRegister, vISA_LocalRenameRegister, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(localDefHoisting, vISA_LocalDefHoist, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(localCopyPropagation, vISA_LocalCopyProp, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(localInstCombine, vISA_LocalInstCombine, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(removePartialMovs, vISA_RemovePartialMovs,
                  TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(cselPeepHoleOpt, vISA_enableCSEL, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(optimizeLogicOperation, vISA_EnableAlways,
                  TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(EmulateInt64Add, vISA_EnableAlways, TimerID::HW_CONFORMITY);
  OPT_INITIALIZE_PASS(HWConformityChk, vISA_EnableAlways, TimerID::HW_CONFORMITY);
  OPT_INITIALIZE_PASS(preRA_Schedule, vISA_preRA_Schedule,
                  TimerID::PRERA_SCHEDULING);
  OPT_INITIALIZE_PASS(preRA_HWWorkaround, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(preRegAlloc, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(regAlloc, vISA_EnableAlways, TimerID::TOTAL_RA);
  OPT_INITIALIZE_PASS(removeLifetimeOps, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(postRA_HWWorkaround, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(removeRedundMov, vISA_removeRedundMov, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(removeEmptyBlocks, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(insertFallThroughJump, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(reassignBlockIDs, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(evalAddrExp, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(FoldAddrImmediate, vISA_FoldAddrImmed, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(localSchedule, vISA_LocalScheduling, TimerID::SCHEDULING);
  OPT_INITIALIZE_PASS(HWWorkaround, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(fixEndIfWhileLabels, vISA_EnableAlways, TimerID::NUM_TIMERS);
  OPT_INITIALIZE_PASS(HWDebug, vISA_EnableAlways, TimerID::NUM_TIMERS);
  OPT_INITIALIZE_PASS(insertDummyMovForHWRSWA, vISA_InsertDummyMovForHWRSWA,
                  TimerID::NUM_TIMERS);
  OPT_INITIALIZE_PASS(insertDummyCompactInst, vISA_InsertDummyCompactInst,
                  TimerID::NUM_TIMERS);
  OPT_INITIALIZE_PASS(mergeScalarInst, vISA_MergeScalar, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(lowerMadSequence, vISA_EnableMACOpt, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(LVN, vISA_LVN, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(ifCvt, vISA_ifCvt, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(dumpPayload, vISA_dumpPayload, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(normalizeRegion, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(collectStats, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(createR0Copy, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(initializePayload, vISA_InitPayload, TimerID::NUM_TIMERS);
  OPT_INITIALIZE_PASS(cleanupBindless, vISA_enableCleanupBindless,
                  TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(cleanupA0Movs, vISA_enableCleanupA0Movs,
                  TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(countGRFUsage, vISA_PrintRegUsage, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(changeMoveType, vISA_ChangeMoveType, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(accSubBeforeRA, vISA_accSubBeforeRA, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(accSubPostSchedule, vISA_accSubstitution, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(dce, vISA_EnableDCE, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(reassociateConst, vISA_reassociate, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(split4GRFVars, vISA_split4GRFVar, TimerID::OPTIMIZER);
  OPT_INITIALIZE_PASS(loadThreadPayload, vISA_loadThreadPayload,
                  TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(addFFIDProlog, vISA_addFFIDProlog, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(addEmaskSetupProlog, vISA_addEmaskSetupProlog,
                  TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(insertFenceBeforeEOT, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(insertScratchReadBeforeEOT, vISA_clearScratchWritesBeforeEOT,
                  TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(mapOrphans, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(legalizeType, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(analyzeMove, vISA_analyzeMove, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(removeIntrinsics, vISA_EnableAlways, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(expandMulPostSchedule, vISA_expandMulPostSchedule,
                  TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(zeroSomeARF, vISA_zeroSomeARF, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(addSWSBInfo, vISA_addSWSBInfo, TimerID::SWSB);
  OPT_INITIALIZE_PASS(expandMadwPostSchedule, vISA_expandMadwPostSchedule,
                  TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(ACCSchedule, vISA_PreSchedForAcc, TimerID::PRERA_SCHEDULING);
  OPT_INITIALIZE_PASS(staticProfiling, vISA_staticProfiling, TimerID::MISC_OPTS);
  OPT_INITIALIZE_PASS(sinkBarrierWait, vISA_SinkBarrierWait,
                  TimerID::OPTIMIZER);

  // Verify all passes are initialized.
#ifdef _DEBUG
  for (unsigned i = 0; i < PI_NUM_PASSES; ++i) {
    vISA_ASSERT(Passes[i].Pass, "uninitialized pass");
  }
#endif
}

// simple heuristics to decide if it's profitable to do copy propagation for the
// move add more as necessary
bool Optimizer::isCopyPropProfitable(G4_INST *movInst) const {
  vISA_ASSERT(movInst->opcode() == G4_mov, "expected a move instruction");

  // if inst is a simd16 W/HF packing, we don't want to optimize it if
  // there are >=2 simd16 mad uses, since it will slow down the mad.
  // for gen9 additionally check for simd8 mad as it doesn't support strided
  // regions
  auto dst = movInst->getDst();
  auto src0 = movInst->getSrc(0);
  auto hasStrideSource = dst->getHorzStride() == 1 && src0->isSrcRegRegion() &&
                         !(src0->asSrcRegRegion()->getRegion()->isContiguous(
                               movInst->getExecSize()) ||
                           src0->asSrcRegRegion()->getRegion()->isScalar());

  hasStrideSource &=
      movInst->getExecSize() == g4::SIMD16 ||
      (!builder.hasAlign1Ternary() && movInst->getExecSize() == g4::SIMD8);

  auto hasNSIMD16or8MadUse = [](G4_INST *movInst, int N, bool checkSIMD8) {
    int numMadUses = 0;
    for (auto iter = movInst->use_begin(), iterEnd = movInst->use_end();
         iter != iterEnd; ++iter) {
      auto use = *iter;
      auto inst = use.first;
      if (inst->opcode() == G4_pseudo_mad &&
          (inst->getExecSize() == g4::SIMD16 ||
           (checkSIMD8 && inst->getExecSize() == g4::SIMD8))) {
        ++numMadUses;
        if (numMadUses == N) {
          return true;
        }
      }
    }
    return false;
  };

  if (hasStrideSource) {
    if (hasNSIMD16or8MadUse(movInst, 2, true)) {
      return false;
    }
  }

  // another condition where copy prop may be not profitable:
  // mov is from HF to F and dst is used in simd16 mad.
  // copy propagating away the move results in mix mode mad which is bad for
  // bank conflicts
  if (dst->getType() == Type_F && src0->getType() == Type_HF) {
    if (hasNSIMD16or8MadUse(movInst, 4, false)) {
      return false;
    }
  }
  return true;
}

void Optimizer::accSubPostSchedule() {
  if (!builder.doAccSub() || !builder.getOption(vISA_doAccSubAfterSchedule)) {
    return;
  }

  kernel.fg.resetLocalDataFlowData();
  kernel.fg.localDataFlowAnalysis();

  if (builder.getOption(vISA_localizationForAccSub)) {
    HWConformity hwConf(builder, kernel);
    for (auto bb : kernel.fg) {
      hwConf.localizeForAcc(bb);
    }

    kernel.fg.resetLocalDataFlowData();
    kernel.fg.localDataFlowAnalysis();
  }

  AccSubPass accSub(builder, kernel);
  accSub.run();
}


void Optimizer::accSubBeforeRA() {
  if (!builder.doAccSub() || !builder.getOption(vISA_doAccSubAfterSchedule)) {
    return;
  }

  kernel.fg.resetLocalDataFlowData();
  kernel.fg.localDataFlowAnalysis();

  if (builder.getOption(vISA_localizationForAccSub)) {
    HWConformity hwConf(builder, kernel);
    for (auto bb : kernel.fg) {
      hwConf.localizeForAcc(bb);
    }

    kernel.fg.resetLocalDataFlowData();
    kernel.fg.localDataFlowAnalysis();
  }

  AccSubPass accSub(builder, kernel);
  accSub.run();
}

bool Optimizer::R0CopyNeeded() {
  if (!builder.canReadR0()) {
    // If r0 cannot be read then r0 has to be copied
    // and cannot be said to be preserved in r0. In
    // other words, these 2 are mutually exclusive
    // options.
    vISA_ASSERT(!kernel.getOption(vISA_PreserveR0InR0),
                "opposing options for r0 detected");
    return true;
  }

  if (kernel.getOption(vISA_PreserveR0InR0)) {
    return false;
  }

  if (builder.getIsKernel() && kernel.fg.getHasStackCalls()) {
    // As per VISA ABI, last register in GRF file should
    // contain copy of r0.
    return true;
  }

  return false;
}

int Optimizer::optimization() {
#ifndef DLL_MODE
  if (StopAfterPass == "CFGConstruction") {
    EarlyExited = true;
    kernel.dumpToConsole();
  }
#endif // DLL_MODE

  // remove redundant message headers.
  runPass(PI_cleanMessageHeader);

  // Set NoMask inst's mask offset to 0 if possible
  runPass(PI_forceNoMaskOnM0);


  runPass(PI_sendFusion);

  // rename registers.
  runPass(PI_renameRegister);

  runPass(PI_localDefHoisting);

  runPass(PI_removePartialMovs);

  runPass(PI_cleanupA0Movs);

  // remove redundant movs and fold some other patterns
  runPass(PI_localCopyPropagation);

  // fold some binary operations
  runPass(PI_localInstCombine);

  runPass(PI_mergeScalarInst);

  runPass(PI_cselPeepHoleOpt);

  runPass(PI_reassociateConst);

  runPass(PI_lowerMadSequence);

  // optimize logic operantions
  runPass(PI_optimizeLogicOperation);

  // Dead code elimination
  runPass(PI_dce);

  // Emulate 64 Int add if needed
  runPass(PI_EmulateInt64Add);

  // HW conformity check
  runPass(PI_HWConformityChk);

  // Local Value Numbering
  runPass(PI_LVN);

  // this must be run after copy prop cleans up the moves
  runPass(PI_cleanupBindless);

  runPass(PI_split4GRFVars);

  runPass(PI_insertFenceBeforeEOT);


  // PreRA scheduling
  runPass(PI_preRA_Schedule);

  // HW workaround before RA
  runPass(PI_preRA_HWWorkaround);

  if (builder.enableACCBeforRA() && builder.enablePreSchedACC()) {
    runPass(PI_ACCSchedule);
  }

  if (builder.enableACCBeforRA() && !builder.enablePreSchedACC()) {
    runPass(PI_accSubBeforeRA);
  }

  runPass(PI_preRegAlloc);

  // perform register allocation
  runPass(PI_regAlloc);
  if (RAFail) {
    return VISA_SPILL;
  }

  runPass(PI_removeLifetimeOps);

  // HW workaround after RA
  runPass(PI_postRA_HWWorkaround);

  //
  // if a fall-through BB does not immediately follow its predecessor
  // in the code layout, then insert a jump-to-fall-through in the predecessor
  //
  runPass(PI_insertFallThroughJump);

  // Run if-conversion to convert short if-blocks.
  runPass(PI_ifCvt);

  //
  // re-assign block ID so that we can use id to determine the ordering of
  // two blocks in the code layout
  //
  runPass(PI_reassignBlockIDs);

  runPass(PI_FoldAddrImmediate);

  // FIXME houjenko: Disable local scheduling due to issues when
  // using extra regiser that may corrupt unknown liveout
  if (!builder.getIsPayload()) {
    runPass(PI_localSchedule);
  }

  if (!builder.enableACCBeforRA() && !builder.enablePreSchedACC()) {
    runPass(PI_expandMulPostSchedule);

    runPass(PI_expandMadwPostSchedule);

    runPass(PI_accSubPostSchedule);
  }

  runPass(PI_legalizeType);

  runPass(PI_changeMoveType);

  // No pass after this should expect def-use to be preserved as this pass
  // removes raw movs with identical src/dst physical GRFs.
  runPass(PI_removeRedundMov);

  // remove any placeholders blocks inserted to aid regalloc
  // run this pass after reRA pass otherwise CFG can become
  // invalid (funcInfo, calleeInfo may point to bad initBB).
  runPass(PI_removeEmptyBlocks);

  runPass(PI_insertScratchReadBeforeEOT);

  runPass(PI_sinkBarrierWait);
  // HW workaround
  runPass(PI_HWWorkaround);

  runPass(PI_normalizeRegion);

  runPass(PI_countGRFUsage);

  runPass(PI_dumpPayload);

  // this must be the last step of the optimization so as to not violate
  // the CFG assumption
  runPass(PI_fixEndIfWhileLabels);

  runPass(PI_HWDebug);

  runPass(PI_insertDummyMovForHWRSWA);

  runPass(PI_collectStats);

  // Create a copy of R0 at the top of kernel.
  // This must be done after all other optimizer
  // passes except for loadThreadPlayoad
  runPass(PI_createR0Copy);

  runPass(PI_initializePayload);

  runPass(PI_loadThreadPayload);

  runPass(PI_addFFIDProlog);

  runPass(PI_addEmaskSetupProlog);

  // Insert a dummy compact instruction if requested for SKL+
  runPass(PI_insertDummyCompactInst);

  runPass(PI_mapOrphans);

  runPass(PI_analyzeMove);

  runPass(PI_removeIntrinsics);

  runPass(PI_zeroSomeARF);

  //-----------------------------------------------------------------------------------------------------------------
  //------NOTE!!!! No instruction change(add/remove, or operand associated
  // change) is allowed after SWSB-------------
  //-----------------------------------------------------------------------------------------------------------------
  runPass(PI_addSWSBInfo);


  runPass(PI_staticProfiling);

  if (EarlyExited) {
    return VISA_EARLY_EXIT;
  }
  return VISA_SUCCESS;
}

//  When constructing CFG we have the assumption that a label must be the first
//  instruction in a bb.  During structure analysis, however, we may end up with
//  a bb that starts with multiple endifs if the bb is the target of multiple
//  gotos that have been converted to an if. Instead of creating a BB for each
//  of the endif, we associate each endif with a label and emit them only at the
//  very end.
//
//  For break and continue, UIP must be the lable directly attached to the while
//  op. If not, create such a label
//
//  DO
//    IF
//      P =
//      CONT L1
//    ENDIF L1
//    IF
//      BREAK L2
//    ENDIF L1
//  L1
//  (P) WHILE
//  L2
//
//  will be transfered into
//
//  DO
//    IF
//      P =
//      Spill <- P
//      CONT L3         // UIP becomes L3
//    ENDIF L1
//    IF
//      BREAK L3        // UIP becomes L3
//    ENDIF L1
//  L1                  // existing label
//  P <- fill
//  L3                  // new label
//  (P) WHILE
//  L2
//
void Optimizer::fixEndIfWhileLabels() {
  for (BB_LIST_CITER iter = fg.cbegin(), bend = fg.cend(); iter != bend;
       ++iter) {
    G4_BB *bb = *iter;
    INST_LIST_ITER iter2 = bb->begin();
    INST_LIST_ITER iend = bb->end();
    while (iter2 != iend) {
      INST_LIST_ITER currIter = iter2;
      ++iter2;

      G4_INST *inst = *currIter;
      G4_Label *endifLabel = fg.getLabelForEndif(inst);
      if (endifLabel) {
        G4_INST *labelInst = fg.createNewLabelInst(endifLabel);
        bb->insertBefore(currIter, labelInst);
      }
    }
  }

  // Patch labels if necessary.
  for (G4_BB *bb : fg) {
    if (bb->empty())
      continue;

    G4_INST *inst = bb->back();
    G4_opcode opc = inst->opcode();
    if (opc != G4_cont && opc != G4_break)
      continue;

    // The matching while BB.
    G4_BB *whileBB = nullptr;
    if (opc == G4_cont) {
      // The whileBB is the first successor bb, if this is continue.
      whileBB = bb->Succs.front();
    } else {
      // For break, the whileBB should be the physical predecessor of
      // break's first successor bb.
      for (G4_BB *succBB : bb->Succs) {
        if (succBB->getPhysicalPred() &&
            (!succBB->getPhysicalPred()->empty()) &&
            (succBB->getPhysicalPred()->back()->opcode() == G4_while)) {
          whileBB = succBB->getPhysicalPred();
          break;
        }
      }
    }

    if (whileBB == nullptr || whileBB->empty() ||
        whileBB->back()->opcode() != G4_while) {
      vISA_ASSERT(false, "can not find while BB");
      continue;
    }

    // If while instruction is following the label, then no need
    // to insert a new uip label, just use the existing one.
    G4_InstCF *instCF = inst->asCFInst();
    auto whileIter = std::prev(whileBB->end());
    G4_INST *prevInst = *std::prev(whileIter);
    if (prevInst->isLabel()) {
      instCF->setUip(prevInst->getLabel());
    } else {
      std::string NewUipName = instCF->getUipLabelStr();
      NewUipName += "_UIP";
      G4_Label *label = builder.createLabel(NewUipName, LABEL_BLOCK);
      instCF->setUip(label);

      G4_INST *newInst = fg.createNewLabelInst(label);

      whileBB->insertBefore(whileIter, newInst);
    }
  }
}

// Fold address register into address register offset, such that we can same one
// instruction that computes: add a0.0 a0.0 immed; mul dst r[a0.0, 0] src2
//-->
// mul dst r[a0.0, immed] src2

// The condition is that immed is in range [-512..511] and it is dividable
// by 32. This is a local OPT. For simplicity, only execsize 1 is considered.
// Since physical registers are alreasy assigned, we use the info directly here
// without check.

void Optimizer::reverseOffsetProp(AddrSubReg_Node addrRegInfo[8], int subReg,
                                  unsigned int srcNum, INST_LIST_ITER lastIter,
                                  INST_LIST_ITER iend) {
  if (addrRegInfo[subReg].usedImmed && addrRegInfo[subReg].canUseImmed) {
    INST_LIST_ITER iter;
    G4_INST *inst;
    G4_Operand *inst_src;
    G4_DstRegRegion *inst_dst;
    for (iter = addrRegInfo[subReg].iter; iter != lastIter; ++iter) {
      if (iter == lastIter)
        break;
      inst = *iter;
      if (inst->isDead())
        continue;
      inst_dst = inst->getDst();
      if (inst_dst && inst_dst->getRegAccess() != Direct) {
        int subReg1 = getDstSubReg(inst_dst);

        short currOff = inst_dst->getAddrImm();
        if (subReg1 == subReg) {
          // create a new dst
          G4_DstRegRegion tmpRgn(*inst_dst);
          G4_DstRegRegion *newDst = &tmpRgn;
          newDst->setImmAddrOff(
              short(currOff - addrRegInfo[subReg].immAddrOff));
          inst->setDest(builder.createDstRegRegion(*newDst));
        }
      }
      for (int i = 0; i < inst->getNumSrc(); i++) {
        inst_src = inst->getSrc(i);
        if (inst_src && inst_src->isSrcRegRegion() &&
            inst_src->asSrcRegRegion()->getRegAccess() != Direct) {
          int subReg1 = getSrcSubReg(inst_src);

          short currOff = inst_src->asSrcRegRegion()->getAddrImm();
          if (subReg1 == subReg) {
            G4_SrcRegRegion tmpRgn(*inst_src->asSrcRegRegion());
            G4_SrcRegRegion *newSrc = &tmpRgn;
            newSrc->setImmAddrOff(
                short(currOff - addrRegInfo[subReg].immAddrOff));
            inst->setSrc(builder.createSrcRegRegion(*newSrc), i);
          }
        }
      }
    }
    // Immed has been propagated to srcs before this src in *ii, also reverse
    // this
    if (srcNum > 0) {
      inst = *lastIter;
      for (unsigned i = 0; i < srcNum; i++) {
        inst_src = inst->getSrc(i);
        if (inst_src && inst_src->isSrcRegRegion() &&
            inst_src->asSrcRegRegion()->getRegAccess() != Direct) {
          int subReg1 = getSrcSubReg(inst_src);

          short currOff = inst_src->asSrcRegRegion()->getAddrImm();
          if (subReg1 == subReg) {
            G4_SrcRegRegion tmpRgn(*inst_src->asSrcRegRegion());
            G4_SrcRegRegion *newSrc = &tmpRgn;
            newSrc->setImmAddrOff(
                short(currOff - addrRegInfo[subReg].immAddrOff));
            inst->setSrc(builder.createSrcRegRegion(*newSrc), i);
          }
        }
      }
    }
  }

  addrRegInfo[subReg].immAddrOff = 0;
  addrRegInfo[subReg].iter = iend;
  addrRegInfo[subReg].canRemoveInst = false;
  addrRegInfo[subReg].canUseImmed = false;
  addrRegInfo[subReg].usedImmed = false;
}


void Optimizer::FoldAddrImmediate() {
  AddrSubReg_Node *addrRegInfo =
      new AddrSubReg_Node[builder.getNumAddrRegisters()];
  int dst_subReg = 0, src0_subReg = 0;
  G4_DstRegRegion *dst;
  G4_Operand *src0, *src1;
  unsigned num_srcs;

  for (G4_BB *bb : fg) {
    INST_LIST_ITER ii, iend(bb->end());
    // reset address offset info
    for (unsigned i = 0; i < builder.getNumAddrRegisters(); i++) {
      addrRegInfo[i].subReg = 0;
      addrRegInfo[i].immAddrOff = 0;
      addrRegInfo[i].iter = iend;
      addrRegInfo[i].canRemoveInst = false;
      addrRegInfo[i].canUseImmed = false;
      addrRegInfo[i].usedImmed = false;
    }
    for (ii = bb->begin(); ii != iend; ii++) {
      G4_INST *inst = *ii;
      if (inst->isDead()) {
        continue;
      }
      num_srcs = inst->getNumSrc();
      dst = inst->getDst();
      if (dst) {
        dst_subReg = getDstSubReg(dst);
      }
      src0 = inst->getSrc(0);
      if (src0 && src0->isSrcRegRegion()) {
        src0_subReg = getSrcSubReg(src0);
      }
      src1 = inst->getSrc(1);

      if (dst && dst->isDirectA0() && src0 && src0->isSrcRegRegion() &&
          src0->asSrcRegRegion()->isDirectA0() && !src1) {
        continue;
      }

      if (inst->opcode() == G4_add && inst->getExecSize() == g4::SIMD1 &&
          !inst->getPredicate() && (src1->isImm() && !src1->isRelocImm()) &&
          dst && dst->isDirectA0() && src0 && src0->isSrcRegRegion() &&
          src0->asSrcRegRegion()->isDirectA0() && dst_subReg == src0_subReg) {
        // since there is use of a0.x here, we can not remove the former def of
        // a0.x reverse immed offset propagation
        reverseOffsetProp(addrRegInfo, dst_subReg, 0, ii, iend);

        int64_t offset = src1->asImm()->getImm();
        if (offset >= -512 && offset <= 511 && offset % 0x20 == 0) {
          // this kills the previous def on a0.x
          if (addrRegInfo[dst_subReg].canRemoveInst &&
              addrRegInfo[dst_subReg].iter != iend) {
            // mark dead
            (*(addrRegInfo[dst_subReg].iter))->markDead();
          }
          addrRegInfo[dst_subReg].subReg = dst_subReg;
          addrRegInfo[dst_subReg].immAddrOff = (short)offset;
          addrRegInfo[dst_subReg].iter = ii;
          addrRegInfo[dst_subReg].canRemoveInst = true;
          addrRegInfo[dst_subReg].canUseImmed = true;
          addrRegInfo[dst_subReg].usedImmed = false;
        }
      } else {
        G4_Operand *src;
        // if there is any direct use of addr reg, the ADD inst can not be
        // removed
        for (unsigned i = 0; i < num_srcs; i++) {
          src = inst->getSrc(i);
          if (src && src->isSrcRegRegion() &&
              src->asSrcRegRegion()->isDirectA0()) {
            // TODO: show if an inst is generated for spill code
            // if there is no regVar for this srcRegion, the physical register
            // is hard-wired in input or generated by spillCode. in this case,
            // the subregister info is in the subRegOff of G4_SrcRegRegion this
            // also applies to dst register
            int subReg = getSrcSubReg(src);

            // it is possible that several elements are used
            int width, hstride, vstride, outerloop = 1;
            width = src->asSrcRegRegion()->getRegion()->width;
            hstride = src->asSrcRegRegion()->getRegion()->horzStride;
            vstride = src->asSrcRegRegion()->getRegion()->vertStride;
            if (vstride != 0) {
              outerloop = inst->getExecSize() / vstride;
            }

            for (int k = 0; k < outerloop; k++) {
              for (int j = 0; j < width; j++) {
                int currSubreg = subReg + k * vstride + j * hstride;
                // there may be inst whose src or dst addr immediate offset are
                // already changed reverse the change
                reverseOffsetProp(addrRegInfo, currSubreg, i, ii, iend);
              }
            }
          }
        }
        // use of address register in index region
        for (unsigned i = 0; i < num_srcs; i++) {
          src = inst->getSrc(i);
          if (src && src->isSrcRegRegion() &&
              src->asSrcRegRegion()->getRegAccess() != Direct) {
            int subReg = getSrcSubReg(src);

            // if VxH is used and more than one sub registers are used in
            // addressing do not fold the immediate even though they have the
            // same immediate value
            unsigned short vertStride =
                src->asSrcRegRegion()->getRegion()->vertStride;
            if (vertStride == UNDEFINED_SHORT ||
                (vertStride > 0 &&
                 (unsigned short)inst->getExecSize() / vertStride > 1)) {
              int numSubReg = 0;
              if (vertStride == UNDEFINED_SHORT) {
                numSubReg = inst->getExecSize() /
                            src->asSrcRegRegion()->getRegion()->width;
              } else {
                numSubReg = 1; // inst->getExecSize()/vertStride;
              }
              for (int j = subReg; j < subReg + numSubReg; j++) {
                reverseOffsetProp(addrRegInfo, j, i, ii, iend);
              }
            } else {
              // we check the existing address reg imm offset.
              short currOff = src->asSrcRegRegion()->getAddrImm();
              if (addrRegInfo[subReg].canUseImmed) {
                if (currOff % 0x20 == 0 &&
                    (currOff + addrRegInfo[subReg].immAddrOff) <= 511 &&
                    (currOff + addrRegInfo[subReg].immAddrOff) >= -512) {
                  G4_SrcRegRegion tmpRgn(*src->asSrcRegRegion());
                  G4_SrcRegRegion *newSrc = &tmpRgn;
                  newSrc->setImmAddrOff(
                      short(currOff + addrRegInfo[subReg].immAddrOff));
                  inst->setSrc(builder.createSrcRegRegion(*newSrc), i);

                  addrRegInfo[subReg].usedImmed = true;
                } else {
                  // if the offset can not be folded into all uses of a0.0,
                  // reverse the former folding
                  reverseOffsetProp(addrRegInfo, subReg, i, ii, iend);
                }
              }
            }
          }
        }
        if (dst) {
          // make sure the addr reg is not redefined
          // direct access to a0.x
          if (dst->isDirectA0()) {
            int width, hstride;
            width = inst->getExecSize();
            hstride = dst->getHorzStride();

            for (int j = 0; j < width; j++) {
              int currSubreg = dst_subReg + j * hstride;
              // this kills the previous def on a0.x
              if (addrRegInfo[currSubreg].iter != iend &&
                  addrRegInfo[currSubreg].canRemoveInst) {
                // mark dead
                (*(addrRegInfo[currSubreg].iter))->markDead();
              }
              addrRegInfo[currSubreg].immAddrOff = 0;
              addrRegInfo[currSubreg].iter = iend;
              addrRegInfo[currSubreg].canRemoveInst = false;
              addrRegInfo[currSubreg].canUseImmed = false;
              addrRegInfo[currSubreg].usedImmed = false;
            }
          }
          // check if dst is indirectly addressed
          else if (dst->getRegAccess() != Direct) {
            short currOff = dst->getAddrImm();
            if (addrRegInfo[dst_subReg].canUseImmed) {
              if (currOff % 0x20 == 0 &&
                  (currOff + addrRegInfo[dst_subReg].immAddrOff) <= 511 &&
                  (currOff + addrRegInfo[dst_subReg].immAddrOff) >= -512) {
                // create a new dst
                G4_DstRegRegion tmpRgn(*dst);
                G4_DstRegRegion *newDst = &tmpRgn;
                newDst->setImmAddrOff(
                    short(currOff + addrRegInfo[dst_subReg].immAddrOff));
                inst->setDest(builder.createDstRegRegion(*newDst));
                addrRegInfo[dst_subReg].usedImmed = true;
              } else {
                // if the offset can not be folded into all uses of a0.0,
                // reverse the former folding
                reverseOffsetProp(addrRegInfo, dst_subReg, 0, ii, iend);
              }
            }
          }
        }
      }
    }

    // if a def lives out of this BB, we can not delete the defining inst
    for (unsigned i = 0; i < builder.getNumAddrRegisters(); i++) {
      // reverse immed offset propagation
      reverseOffsetProp(addrRegInfo, i, 0, iend, iend);
    }
    // remove the ADD instructions that marked as dead
    for (ii = bb->begin(); ii != bb->end();) {
      G4_INST *inst = *ii;
      INST_LIST_ITER curr = ii++;
      if (inst->isDead()) {
        bb->erase(curr);
      }
    }
  }

  delete[] addrRegInfo;
}
G4_SrcModifier Optimizer::mergeModifier(G4_Operand *src, G4_Operand *use) {
  if ((src == NULL || !src->isSrcRegRegion()) && use && use->isSrcRegRegion()) {
    return use->asSrcRegRegion()->getModifier();
  } else if ((use == NULL || !use->isSrcRegRegion()) && src &&
             src->isSrcRegRegion()) {
    return src->asSrcRegRegion()->getModifier();
  } else if (src && src->isSrcRegRegion() && use && use->isSrcRegRegion()) {
    G4_SrcModifier mod1 = src->asSrcRegRegion()->getModifier(),
                   mod2 = use->asSrcRegRegion()->getModifier();
    if (mod2 == Mod_Abs || mod2 == Mod_Minus_Abs) {
      return mod2;
    } else if (mod2 == Mod_src_undef) {
      return mod1;
    } else {
      // mod2 == Minus
      if (mod1 == Mod_Minus) {
        return Mod_src_undef;
      } else if (mod1 == Mod_Abs) {
        return Mod_Minus_Abs;
      } else if (mod1 == Mod_Minus_Abs) {
        return Mod_Abs;
      } else {
        return mod2;
      }
    }
  } else {
    return Mod_src_undef;
  }
}

// Prevent sinking in presence of lifetime.end for any src op.
// For eg,
// add V33, V32, 0x1
// ...
// lifetime.end V32 <-- This prevents sinking of add to mov
// ...
// pseudo_kill V34 <-- This prevents hoisting of V34 to add dst
// mov V34, V33
//
static bool checkLifetime(G4_INST *defInst, G4_INST *inst) {
  // Check whether current instruction ends any src opnd of op
  if (!inst->isLifeTimeEnd())
    return true;

  G4_RegVar *Var = GetTopDclFromRegRegion(inst->getSrc(0))->getRegVar();
  // Check whether lifetime op corresponds to any operand of current inst.
  if (defInst->getPredicate()) {
    G4_RegVar *opndVar =
        defInst->getPredicate()->asPredicate()->getBase()->asRegVar();
    if (opndVar == Var)
      return false;
  }
  if (defInst->getCondMod()) {
    G4_RegVar *opndVar =
        defInst->getCondMod()->asCondMod()->getBase()->asRegVar();
    if (opndVar == Var)
      return false;
  }
  if (defInst->getDst() && !defInst->getDst()->isNullReg()) {
    G4_RegVar *opndVar = GetTopDclFromRegRegion(defInst->getDst())->getRegVar();
    if (opndVar == Var)
      return false;
  }
  for (unsigned int srcOpnd = 0, numSrc = defInst->getNumSrc();
       srcOpnd < numSrc; srcOpnd++) {
    G4_Operand *src = defInst->getSrc(srcOpnd);
    if (src && src->isSrcRegRegion()) {
      G4_RegVar *opndVar = GetTopDclFromRegRegion(src)->getRegVar();
      if (opndVar == Var)
        return false;
    }
  }

  return true;
}

//
// Sink definition towards its use.
//
// For example, without sinking the def instruction once, use cannot
// be hoisted, since there is a data dependency between the middle
// instruction and the last move.
//
// def: shr (1) V39(0,0)<1>:ud V38(0,0)<0;1,0>:d 0x4:w {Align1, Q1}
//      mov (8) V68(0,0)<1>:ud r0.0<8;8,1>:ud {Align1, NoMask}
// use: mov (1) V68(0,2)<1>:ud V39(0,0)<0;1,0>:ud {Align1, NoMask}
//
// after sinking, it becomes
//
//      mov (8) V68(0,0)<1>:ud r0.0<8;8,1>:ud {Align1, NoMask}
// def: shr (1) V39(0,0)<1>:ud V38(0,0)<0;1,0>:d 0x4:w {Align1, Q1}
// use: mov (1) V68(0,2)<1>:ud V39(0,0)<0;1,0>:ud {Align1, NoMask}
//
// which makes local def hoisting possible.
//
// The third argument 'other' points to the first instruction (upwards) that
// has data-dependency with the use instruction.
//
static bool canSink(G4_BB *bb, INST_LIST_RITER revIter, INST_LIST_RITER other) {
  // The use instruction.
  G4_INST *inst = *revIter;

  // Currently we do not handle multiple definition for this optimization.
  if (inst->def_size() != 1)
    return false;

  // Find its def instruction.
  G4_INST *defInst = inst->def_back().first;

  vISA_ASSERT(*other != defInst, "iterator points to def already");

  // Walk up to check if sinking is safe.
  INST_LIST_RITER it = other;

  while (*it != defInst) {
    if ((*it)->isWAWdep(defInst) || (*it)->isRAWdep(defInst) ||
        (*it)->isWARdep(defInst))
      return false;

    if (!checkLifetime(defInst, *it))
      return false;

    // move towards to defInst.
    ++it;
  }

  // At this point, there is no data dependency and sinking is safe.
  //
  // We do sinking right here.
  //
  vISA_ASSERT(*it == defInst, "iterator out of sync");

  // Both 'other' and 'it' are reverse iterators, and sinking is through
  // forward iterators. The fisrt base should not be decremented by 1,
  // otherwise, the instruction will be inserted before not after.
  bb->insertBefore(other.base(), defInst);
  bb->erase(--it.base());

  return true;
}

static bool canHoist(FlowGraph &fg, G4_BB *bb, INST_LIST_RITER revIter) {
  G4_INST *inst = *revIter;

  if (inst->isMixedMode() && fg.builder->getOption(vISA_DisableleHFOpt))
    return false;
  // Cannot hoist if this is not a move, or it is a global operand.
  if (inst->opcode() != G4_mov ||
      fg.globalOpndHT.isOpndGlobal(inst->getSrc(0)) ||
      !inst->canHoist(!bb->isAllLaneActive(), fg.builder->getOptions())) {
    return false;
  }

  if (auto Dst = inst->getDst()) {
    G4_Declare *Dcl = Dst->getTopDcl();
    // Do not do def-hoisting for setting flags which is likely to increase flag
    // register pressure.
    if (Dcl && Dcl->getRegFile() == G4_RegFileKind::G4_FLAG) {
      return false;
    }


    if (Dcl && Dcl->getRegFile() == G4_RegFileKind::G4_ADDRESS &&
        Dcl->getRegVar() && Dcl->getRegVar()->getPhyReg()) {
      // Dont def-hoist if dst is hardwired to address register.
      // Doing so extends live-range of assigned register a0.
      // Given that the machine has single addr register, a0,
      // it may even cause address RA to fail due to uncolorable
      // graph.
      return false;
    }

    if (!fg.builder->hasByteALU() && Dst->getTypeSize() == 1) {
      return false;
    }
  }

  // Now check each definition of src(0)
  for (auto I = inst->def_begin(), E = inst->def_end(); I != E; ++I) {
    vISA_ASSERT(I->second == Opnd_src0, "invalid use-def chain");
    if (!inst->canHoistTo(I->first, !bb->isAllLaneActive()))
      return false;

    auto defInst = I->first;
    if (fg.globalOpndHT.isOpndGlobal(defInst->getDst())) {
      return false;
    }

    auto defSrc0 = defInst->getSrc(0);
    if (inst->getDst()->getType() == Type_BF &&
        (defSrc0->getType() != Type_F ||
         (defInst->isMov() &&
          defSrc0->isSrcRegRegion() &&
          defSrc0->asSrcRegRegion()->hasModifier()))) {
      // we currently don't handle conversion to BF from other type than float
      // As F->BF does not support srcMod, cannot hoist if definst has mod.
      return false;
    }

    // Further check data-dependency, that is, no other instruction
    // should have WAR or WAW dependency with this inst.
    //
    //   defInst
    //
    //   other inst
    //
    //   inst <-- revIter
    //
    INST_LIST_RITER other = revIter;
    ++other;

    // Measure the distance in between
    unsigned distance = 0;

    // Walkup until hits its defining instruction.
    while (*other != I->first) {
      // FIXME: remove duplicate computations for multiple definitions.
      if (inst->isWAWdep(*other) || inst->isWARdep(*other)) {
        break;
      }
      ++other;
      ++distance;
    }

// Check the distance first, if this is too far then the following
// sinking optimization is very expensive.
#define MAX_DEF_HOIST_DIST 160
    if (distance > MAX_DEF_HOIST_DIST)
      return false;

    // There is a data dependency.
    if (*other != I->first) {
      // check if sinking is possible.
      if (!canSink(bb, revIter, other))
        return false;
    }
  }
  return true;
}

static G4_DstRegRegion *buildNewDstOperand(FlowGraph &fg, G4_INST *inst,
                                           G4_INST *defInst) {
  G4_Operand *src = inst->getSrc(0);
  G4_DstRegRegion *dst = inst->getDst();

  G4_Type srcType = src->getType();
  G4_Type dstType = dst->getType();
  G4_DstRegRegion *dstRegion = dst;
  bool indirectDst = (dstRegion->getRegAccess() != Direct);
  unsigned char srcElSize = (unsigned char)TypeSize(srcType);

  G4_DstRegRegion *defDstRegion = defInst->getDst();
  G4_DstRegRegion *newDstOpnd = dst;

  unsigned char defDstElSize = (unsigned char)defDstRegion->getTypeSize();
  G4_CmpRelation rel = src->compareOperand(defDstRegion, *fg.builder);
  G4_Type defDstType = defDstRegion->getType();

  unsigned char dstElSize = (unsigned char)TypeSize(dstType);
  unsigned short dstHS = dst->getHorzStride();

  if (rel == Rel_gt || srcElSize != defDstElSize ||
      (defInst->getSaturate() && srcType != defDstType) || inst->isRawMov() ||
      (dstType != defDstType &&
       (IS_FTYPE(defDstType) ||
        (IS_FTYPE(dstType) && defDstType != srcType)))) {
    unsigned short regOff = 0, subRegOff = 0;
    if (rel == Rel_gt) {
      // compute new dst for defInst
      // get dst portion based on src region
      unsigned defDstLB = defDstRegion->getLeftBound();

      unsigned srcLB = src->getLeftBound();
      const RegionDesc *srcRegionDesc = src->asSrcRegRegion()->getRegion();
      bool contRegion = srcRegionDesc->isContiguous(inst->getExecSize());

      uint32_t dist = defDstLB - srcLB, dstDist = 0, tempLen = 0;
      if (src->asSrcRegRegion()->isScalar() || contRegion) {
        // mov (1) V18(0,0)[1]:b 0x73:w [Align1]
        // mov (1) V18(0,1)[1]:b 0x61:w [Align1]
        // mov (1) V18(0,2)[1]:b 0x70:w [Align1]
        // mov (1) V18(0,3)[1]:b 0:w [Align1]
        // mov (1) V20(1,0)[1]:ud V18(0,0)[0;1,0]:ud [Align1]
        // length of subregoff part
        tempLen = dstRegion->getSubRegOff() * dstElSize + dist * dstHS;

        if (tempLen >= fg.builder->numEltPerGRF<Type_UB>()) {
          regOff = dst->getRegOff() + 1;
          subRegOff =
              (unsigned short)((tempLen - fg.builder->numEltPerGRF<Type_UB>()) /
                               defDstElSize);
        } else {
          regOff = dst->getRegOff();
          subRegOff = (unsigned short)tempLen / defDstElSize;
        }
      } else {
        // mov (16) V18(0,0)[1]:b 0x73:w [Align1]
        // mov (16) V18(0,16)[1]:b 0x61:w [Align1]
        // mov (16) V18(1,0)[1]:b 0x70:w [Align1]
        // mov (16) V18(1,16)[1]:b 0:w [Align1]
        // mov (32) V20(1,0)[1]:b V18(0,0)[32;16,1]:b [Align1]
        // mov (32) V20(2,0)[1]:b V18(0,16)[32;16,1]:b [Align1]

        // Compute the linear index of the first element from defInst's dst
        // in useInst's src.
        //
        // mov <2> V50(0, 14)<1>:b 0xa:w                  <- defInst
        // mov <16> V51(0, 9)<2>:b V50(0, 0)<0; 16, 2>:b  <- useInst
        //
        // Starting from left bound difference, dist = 14.
        //
        // FirstEltIndex is 7 = 14 / 2. With this index, we can compute
        // the register offset and sub-register offset in useInst's dst.
        //
        // In the above example, there is only a single row. In general
        // there may have multiple rows in useInst's src region.
        //
        // (1) convert difference in number of elements.
        vISA_ASSERT(dist % srcElSize == 0, "unexpected difference");
        dist = dist / srcElSize;

        // (2) compute row and column index, by default a single row.
        unsigned rowIndex = 0, colIndex = dist;
        if (srcRegionDesc->vertStride > 0) {
          rowIndex = dist / srcRegionDesc->vertStride;
          colIndex = dist % srcRegionDesc->vertStride;
        }

        // (3) compute the final linear index.
        vISA_ASSERT(srcRegionDesc->horzStride == 0 ||
                        colIndex % srcRegionDesc->horzStride == 0,
                    "invalid region");
        unsigned FirstEltIndex = rowIndex * srcRegionDesc->width +
                                 (srcRegionDesc->horzStride == 0
                                      ? colIndex
                                      : (colIndex / srcRegionDesc->horzStride));

        // (4) compute the register and subregister offet in useInst's dst.
        dstDist = FirstEltIndex * dstElSize * dstHS;
        tempLen = dstDist + dst->getSubRegOff() * dstElSize;
        regOff =
            (unsigned short)(dst->getRegOff() +
                             tempLen / fg.builder->numEltPerGRF<Type_UB>());

        subRegOff =
            (unsigned short)(tempLen % fg.builder->numEltPerGRF<Type_UB>()) /
            defDstElSize;
      }

      unsigned short defDstHS = defDstRegion->getHorzStride();
      if (!indirectDst) {
        newDstOpnd =
            fg.builder->createDst(dst->getBase(), regOff, subRegOff,
                                  dstHS * defDstHS, defDstRegion->getType());
      } else {
        newDstOpnd = fg.builder->createIndirectDst(
            dst->getBase(), dst->getSubRegOff(), dstHS * defDstHS,
            defDstRegion->getType(), (int16_t)dst->getAddrImm() + tempLen);
      }
    } else {
      unsigned char scale = dstElSize / defDstElSize;

      // If instruction that gets def hoisted is just re-interpretation of bits,
      // doesn't do conversion, then I think original type of the defInst
      // should be used. This preserves the original behavior.
      //
      // mov (8) V57(0,0)[1]:hf V52(0,0)[8;8,1]:f [Align1, Q1] %21
      // mov (8) V58(0,0)[1]:w  V59(0,0)[8;8,1]:w [Align1, Q1] %22
      if (dst->getType() == src->getType()) {
        if (!indirectDst) {
          newDstOpnd = fg.builder->createDst(
              dst->getBase(), dst->getRegOff(),
              (scale == 0 ? dst->getSubRegOff() / (defDstElSize / dstElSize)
                          : dst->getSubRegOff() * scale),
              dstHS, defDstRegion->getType());
        } else {
          newDstOpnd = fg.builder->createIndirectDst(
              dst->getBase(), dst->getSubRegOff(), dstHS,
              defDstRegion->getType(), dst->getAddrImm());
        }
      } else {
        if (!indirectDst) {
          newDstOpnd =
              fg.builder->createDst(dst->getBase(), dst->getRegOff(),
                                    dst->getSubRegOff(), dstHS, dst->getType());
        } else {
          newDstOpnd = fg.builder->createIndirectDst(
              dst->getBase(), dst->getSubRegOff(), dstHS, dst->getType(),
              dst->getAddrImm());
        }
      }
    }
  }
  return newDstOpnd;
}

//
//  inst0:   op0  rx<2>(0), ry0, ry1
//  inst1:   op1  rx<2>(1), ry2, ry3
//  inst2:   mov  rz<1>(0), rx<0, 0>(8; 8, 1)
//
// ==>
//
//  inst0:   op0, rz<2>(0), ry0, ry1
//  inst1:   op1, rz<2>(1), ry2, ry3
//  inst2:   mov  rz<1>(0), rx<0, 0>(8; 8, 1)  (to be deleted)
//
// Def-use/use-def chains will be updated as follows:
//
// (0) all use-defs remain the same for inst0 and inst1.
//
// (1) remove all use-defs of inst2. (They must be from inst0 and inst1,
//     which is the pre-condition of doHoisting.)
//
// (2) remove all def-uses of inst0 and inst1 from dst.
//
// (3) remove all def-uses of inst2.
//
// (4) add new def-uses to inst0 and inst1.
//
static void doHoisting(FlowGraph &fg, G4_BB *bb, INST_LIST_RITER revIter) {
  G4_INST *inst = *revIter;

  for (auto I = inst->def_begin(), E = inst->def_end(); I != E; ++I) {
    G4_INST *defInst = I->first;

    // Build a new dst operand for each def instruction.
    G4_DstRegRegion *newDst = buildNewDstOperand(fg, inst, defInst);

    // Update the defInst with a new operand and set attributes properly.
    if (inst->def_size() == 1) {
      defInst->setDest(newDst);
    } else {
      defInst->setDest(fg.builder->duplicateOperand(newDst)->asDstRegRegion());
    }

    // (4) for each def-use of inst, add it to defInst, if it is
    // an effective use.
    for (auto UI = inst->use_begin(), UE = inst->use_end(); UI != UE; ++UI) {
      G4_Operand *UseOpnd = UI->first->getOperand(UI->second);
      // this comparison is necessary, since uses of inst's dst may be
      // different from those from defInst's dst.
      G4_CmpRelation rel =
          defInst->getDst()->compareOperand(UseOpnd, *fg.builder);
      if (rel != Rel_disjoint) {
        defInst->addDefUse(UI->first, UI->second);
      }
    }

    if (inst->getPredicate()) {
      vISA_ASSERT(inst->def_size() == 1, "multiple defs not implemented");
      // Remove existing definitions on defInst[opnd_pred].
      defInst->removeDefUse(Opnd_pred);

      defInst->setPredicate(inst->getPredicate());

      // (4) Transfer definitions of inst[opnd_pred] to definitions of
      // defInst[opnd_pred].
      inst->transferDef(defInst, Opnd_pred, Opnd_pred);
    }
    if (inst->getSrc(0)->asSrcRegRegion()->isScalar() &&
        inst->getExecSize() > g4::SIMD1) {
      defInst->setExecSize(
          G4_ExecSize(defInst->getExecSize() * inst->getExecSize()));
    }
    defInst->setSaturate(inst->getSaturate() || defInst->getSaturate());
    if (!bb->isAllLaneActive()) {
      // set writeEnable of dstInst to be off
      defInst->setOptions((defInst->getOption() & ~0xFFF000C) |
                          (inst->getMaskOption()));
    }
  }

  // (1), (2), (3) Remove all defs/uses and it is ready to be deleted.
  inst->removeAllDefs();
  inst->removeAllUses();
}

void Optimizer::localDefHoisting() {
  unsigned numDefHoisted = 0;
  for (auto bb : fg) {
    for (auto I = bb->rbegin(); I != bb->rend(); /* empty */) {
      if (canHoist(fg, bb, I)) {
        doHoisting(fg, bb, I);
        ++numDefHoisted;

        // list::erase does not take a reverse_iterator.
        //
        // The base iterator is an iterator of the same type as the one
        // used to construct the reverse_iterator, but pointing to the
        // element next to the one that the reverse_iterator is currently
        // pointing to (a reverse_iterator has always an offset of -1
        // with respect to its base iterator).
        I = INST_LIST::reverse_iterator(bb->erase(--I.base()));
      } else {
        ++I;
      }
    }
  }

  VISA_DEBUG({
    std::cout
        << "             === Local Definition Hoisting Optimization ===\n";
    std::cout << "Number of defs hoisted: " << numDefHoisted << "\n";
  });
}

//
// Do very simple const only reassociation to fold const values
// e.g.,
// V2 = V1 + K1
// V3 = V2 + K2
// -->
// V3 = V1 + (K1 + K2)
// we only search one level (+ and +, * and *) for now as more complex
// reassociation should be taken care of by IGC earlier. also only do it for
// integer type for now
//
void Optimizer::reassociateConst() {
  for (auto BB : fg) {
    for (auto iter = BB->begin(), iterEnd = BB->end(); iter != iterEnd;
         ++iter) {
      G4_INST *inst = *iter;
      if (inst->opcode() != G4_add && inst->opcode() != G4_mul) {
        continue;
      }
      auto isSrc1Const = [](G4_INST *inst) {
        if (!IS_INT(inst->getDst()->getType())) {
          return false;
        }
        if (!inst->getSrc(0)->isImm() && inst->getSrc(1)->isImm()) {
          return true;
        } else if (inst->getSrc(0)->isImm() && !inst->getSrc(1)->isImm()) {
          inst->swapSrc(0, 1);
          inst->swapDefUse(); // swap def/use for src0 and src1
          return true;
        }
        return false;
      };
      if (!isSrc1Const(inst)) {
        continue;
      }
      auto src0Def = inst->getSingleDef(Opnd_src0);
      if (!src0Def) {
        continue;
      }

      auto isGoodSrc0Def = [isSrc1Const](G4_INST *def, G4_INST *use,
                                         const IR_Builder &builder) {
        vISA_ASSERT(use->getSrc(0)->isSrcRegRegion(),
                    "expect src0 to be src region");
        if (def->opcode() != use->opcode()) {
          return false;
        }
        if (def->getSaturate() || def->getPredicate() || def->getCondMod() ||
            def->getMaskOffset() != use->getMaskOffset()) {
          return false;
        }
        if (!isSrc1Const(def)) {
          return false;
        }
        auto useSrc = use->getSrc(0)->asSrcRegRegion();
        if (useSrc->hasModifier() ||
            def->getDst()->getTypeSize() != useSrc->getTypeSize() ||
            def->getDst()->compareOperand(useSrc, builder) != Rel_eq) {
          // make sure def fully defines use and have the same integer type size
          // (signed-ness should not matter)
          return false;
        }
        if (def->getDst()->compareOperand(def->getSrc(0), builder) !=
            Rel_disjoint) {
          // can't sink source if def overwrites it
          return false;
        }
        // additionally check for the use inst that dst type size is >= src type
        // size otherwise the first add may truncate upper bits due to overflow,
        // which makes reassociation unsafe
        if (useSrc->getTypeSize() < use->getDst()->getTypeSize()) {
          return false;
        }

        return true;
      };

      if (isGoodSrc0Def(src0Def, inst, builder) &&
          !chkFwdOutputHazard(src0Def, iter)) {
        // std::cout << "reassociate: \n";
        // src0Def->dump();
        // inst->dump();
        G4_Imm *constOne = src0Def->getSrc(1)->asImm();
        G4_Imm *constTwo = inst->getSrc(1)->asImm();
        G4_Imm *resultImm =
            builder.foldConstVal(constOne, constTwo, inst->opcode());

        if (resultImm) {
          inst->setSrc(builder.duplicateOperand(src0Def->getSrc(0)), 0);
          inst->setSrc(resultImm, 1);
          inst->removeDefUse(Opnd_src0);
          src0Def->copyDef(inst, Opnd_src0, Opnd_src0);
          // ToDo: remove this when DCE pass is enabled
          if (src0Def->use_size() == 0 &&
              !fg.globalOpndHT.isOpndGlobal(src0Def->getDst()) &&
              !src0Def->getDst()->isIndirect()) {
            src0Def->markDead();
            src0Def->removeAllDefs();
          }
          // std::cout << "--> new inst:\t";
          // inst->dump();
        }
      }
    }
    BB->erase(std::remove_if(BB->begin(), BB->end(),
                             [](G4_INST *inst) { return inst->isDead(); }),
              BB->end());
  }
}

static void hoistUseInst(G4_BB *bb, G4_INST *inst, INST_LIST_ITER forwardIter,
                         bool &canRemove) {
  // check if we can move the use inst up.
  // currently we do not handle multiple use for this optimization
  G4_INST *useInst = inst->use_front().first;
  if (inst->hasOneUse()) {
    forwardIter--;
    INST_LIST_ITER backwardIter = forwardIter;
    INST_LIST_ITER instListEnd = bb->end();
    while (backwardIter != instListEnd && *backwardIter != useInst) {
      backwardIter++;
    }

    INST_LIST_ITER useInstIter = backwardIter;
    backwardIter--;
    while (backwardIter != forwardIter) {
      if (useInst->isWAWdep(*backwardIter) ||
          useInst->isRAWdep(*backwardIter) ||
          useInst->isWARdep(*backwardIter)) {
        break;
      }
      backwardIter--;
    }
    if (backwardIter != forwardIter) {
      canRemove = false;
    } else {
      // hoisting
      backwardIter++;
      bb->insertBefore(backwardIter, useInst);
      bb->erase(useInstIter);
    }
  } else {
    canRemove = false;
  }
}

// conver modifier(imm)
template <class T>
static typename std::enable_if<std::is_floating_point<T>::value, T>::type
getImmValue(T imm, G4_SrcModifier modifier) {
  switch (modifier) {
  case Mod_Minus:
    return -imm;
  case Mod_Abs:
    return std::abs(imm);
  case Mod_Minus_Abs:
    return -(std::abs(imm));
  case Mod_Not:
    vISA_ASSERT_UNREACHABLE("unexpected not modifier for floating types");
    return imm;
  default:
    return imm;
  }
}

template <class T>
static typename std::enable_if<std::is_integral<T>::value, T>::type
getImmValue(T imm, G4_SrcModifier modifier) {
  switch (modifier) {
  case Mod_Minus:
    return -imm;
  case Mod_Abs:
    return std::llabs(imm);
  case Mod_Minus_Abs:
    return -(std::llabs(imm));
  case Mod_Not:
    return ~imm;
  default:
    return imm;
  }
}

// Source operand of the MOV instruction is already known being able to be
// propagated into all its uses. But, due to the dependency issue, it cannot be
// propagated. Try to propagate the type if a narrower type could be used.
static bool propagateType(IR_Builder &Builder, G4_BB *BB, G4_INST *Mov,
                          G4_INST::MovType MT) {
  // Only propagate type if a narrower type could be used.
  if (MT != G4_INST::ZExt && MT != G4_INST::SExt)
    return false;

  G4_DstRegRegion *Dst = Mov->getDst();
  if (Dst->isIndirect())
    return false;

  // Check all propagation types are the same.
  G4_Type PT = Type_UNDEF;
  for (auto UI = Mov->use_begin(), UE = Mov->use_end(); UI != UE; ++UI) {
    auto Use = UI->first;
    auto OpndNum = UI->second;
    auto Opnd = Use->getOperand(OpndNum);
    if (!Opnd->isSrcRegRegion())
      return false;
    if (Opnd->asSrcRegRegion()->isIndirect())
      return false;
    G4_Type PropType = Use->getPropType(OpndNum, MT, Mov);
    if (PropType == Type_UNDEF)
      return false;
    if (PT != Type_UNDEF && PT != PropType)
      return false;
    PT = PropType;
  }
  if (PT == Type_UNDEF)
    return false;
  // Create a new destination of MOV of the propagation type.
  // Consider both execution size and the dst horizontal stride to calculate
  // the number of elements needed, so that we have the enough var size when
  // creating the temp var.
  unsigned NumElt = Mov->getExecSize() * Dst->getHorzStride();
  auto NewDcl = Builder.createTempVar(NumElt, PT, Any);
  auto NewDst = Builder.createDstRegRegion(NewDcl, Dst->getHorzStride());
  Mov->setDest(NewDst);
  // Propagate type
  for (auto UI = Mov->use_begin(), UE = Mov->use_end(); UI != UE; ++UI) {
    auto Use = UI->first;
    auto OpndNum = UI->second;
    auto Opnd = Use->getOperand(OpndNum)->asSrcRegRegion();
    auto NewOpnd = Builder.createSrcRegRegion(NewDcl, Opnd->getRegion());
    Use->setSrc(NewOpnd, OpndNum - 1);
  }
  return true;
}

static unsigned getMaskSize(G4_INST *Inst, Gen4_Operand_Number OpNum) {
  G4_Operand *Opnd = Inst->getOperand(OpNum);
  vISA_ASSERT(Opnd, "null opnd");

  if (Opnd) {
    G4_Declare *Dcl = Opnd->getTopDcl();
    if (Dcl == nullptr) {
      // There is no top declaration for this operand, so this is ARF.
      return 32;
    }
    return Dcl->getRegVar()->isFlag() ? Dcl->getNumberFlagElements()
                                      : Dcl->getByteSize();
  }

  return 0;
}

void Optimizer::removePartialMovs() {
  auto IsValidCandidate = [](G4_Operand *dst, G4_Operand *src, int execSize) {
    if (dst->isDstRegRegion() && src->isSrcRegRegion()) {
      unsigned short dstSize, sourceSize;
      dstSize =
          dst->getTopDcl()->getTotalElems() * dst->getTopDcl()->getElemSize();
      sourceSize =
          src->getTopDcl()->getTotalElems() * src->getTopDcl()->getElemSize();

      if (!src->asSrcRegRegion()->getRegion()->isSingleStride(execSize)) {
        return false;
      }
      if (dst->asDstRegRegion()->getHorzStride() != 1 && execSize != 1) {
        return false;
      }
      if (src->getRightBound() - src->getLeftBound() !=
          dst->getRightBound() - dst->getLeftBound()) {
        return false;
      }
      if (dstSize != sourceSize) {
        return false;
      }
      return true;
    }

    // Common cases should be covered.
    return false;
  };

  auto IsSameDstSrc = [](G4_Operand *dst, G4_Operand *src) {
    if (dst->isDstRegRegion() && src->isSrcRegRegion()) {
      if (dst->getTopDcl() != src->getTopDcl()) {
        return false;
      }

      unsigned short dstSize, sourceSize;
      dstSize =
          dst->getTopDcl()->getTotalElems() * dst->getTopDcl()->getElemSize();
      sourceSize =
          src->getTopDcl()->getTotalElems() * src->getTopDcl()->getElemSize();

      if (dst->asDstRegRegion()->getHorzStride() != 1) {
        return false;
      }
      if (src->getRightBound() - src->getLeftBound() !=
          dst->getRightBound() - dst->getLeftBound()) {
        return false;
      }
      if (dstSize != sourceSize) {
        return false;
      }
      return true;
    }

    // Common cases should be covered.
    return false;
  };

  auto IsStatelessSend = [](G4_INST *inst) {
    if (!inst->isSend()) {
      return false;
    }
    auto msgDesc = inst->asSendInst()->getMsgDesc();

    if (!msgDesc->isLSC() || msgDesc->isSLM() || !inst->getMsgDescRaw()) {
      return false;
    }

    if (inst->getMsgDescRaw()) {
      uint32_t desc = inst->getMsgDescRaw()->getDesc();

      if ((desc >> 29) & 0x3) {
        return false;
      }
    }

    return true;
  };

  for (G4_BB *bb : fg) {
    bb->resetLocalIds();

    INST_LIST_ITER ii = bb->begin(), iend(bb->end());
    while (ii != iend) {
      INST_LIST_ITER firstIt = ii;
      G4_INST *inst1 = *ii;
      G4_Operand *dst1 = inst1->getDst();
      G4_Operand *src1 = inst1->getSrc(0);
      if (inst1->opcode() != G4_mov || !dst1) {
        ii++;
        continue;
      }
      ii++;
      if (ii == iend) {
        break;
      }
      INST_LIST_ITER secondIt = ii;
      G4_INST *inst2 = *ii;
      G4_Operand *dst2 = inst2->getDst();
      G4_Operand *src2 = inst2->getSrc(0);
      if (inst2->opcode() != G4_mov || !dst2) {
        continue;
      }
      ii++;
      if (ii == iend) {
        break;
      }
      INST_LIST_ITER thirdIt = ii;
      G4_INST *inst3 = *ii;
      G4_Operand *dst3 = inst3->getDst();
      G4_Operand *src3 = inst3->getSrc(0);
      if (ii == iend) {
        break;
      }
      if (inst3->opcode() != G4_mov || !dst3) {
        continue;
      }

      if (inst1->getDst()->getTopDcl()->getRegFile() != G4_GRF ||
          inst2->getDst()->getTopDcl()->getRegFile() != G4_GRF ||
          inst3->getDst()->getTopDcl()->getRegFile() != G4_GRF) {
        continue;
      }

      // All three instructions can be propagated
      G4_INST::MovType MT1 = inst1->canPropagate();
      G4_INST::MovType MT2 = inst2->canPropagate();
      G4_INST::MovType MT3 = inst3->canPropagate();
      if (MT1 == G4_INST::SuperMov || MT2 == G4_INST::SuperMov ||
          MT3 == G4_INST::SuperMov) {
        continue;
      }

      // Constraints for each instruction
      if (!IsValidCandidate(dst1, src1, inst1->getExecSize()) ||
          !IsValidCandidate(dst2, src2, inst2->getExecSize()) ||
          !IsValidCandidate(dst3, src3, inst3->getExecSize())) {
        continue;
      }

      // Profitable
      if (!isCopyPropProfitable(inst1) || !isCopyPropProfitable(inst2) ||
          !isCopyPropProfitable(inst3)) {
        continue;
      }

      // Same declare in both dst and src for inst1 and inst2
      if (src1->getTopDcl() != src2->getTopDcl() ||
          dst1->getTopDcl() != dst2->getTopDcl()) {
        continue;
      }

      // Used in same single instruction inst3
      if (inst1->use_size() != 1 || inst2->use_size() != 1 ||
          inst3->use_size() != 1 ||
          inst1->use_begin()->first != inst2->use_begin()->first ||
          inst1->def_begin()->first != inst2->def_begin()->first ||
          inst1->use_begin()->first != inst3) {
        continue;
      }

      // Same mask order, to avoid the reverting
      BitSet srcMask(getMaskSize(inst1, Opnd_src0), 0);
      BitSet dstMask(getMaskSize(inst1, Opnd_src0), 0);
      src1->updateFootPrint(srcMask, true, builder);
      dst1->updateFootPrint(dstMask, true, builder);
      if (dstMask != srcMask) {
        continue;
      }
      src2->updateFootPrint(srcMask, true, builder);
      dst2->updateFootPrint(dstMask, true, builder);
      if (dstMask != srcMask) {
        continue;
      }

      // Check if use can be propgated.
      G4_INST *useInst = inst3->use_begin()->first;
      Gen4_Operand_Number opndNum = inst3->use_begin()->second;
      if (!inst3->canPropagateTo(
              useInst, opndNum, MT3, !bb->isAllLaneActive(),
              IsStatelessSend(useInst) &&
                  IsSameDstSrc(inst3->getDst(),
                               useInst->getSrc(opndNum - 1)))) {
        continue;
      }

      // Propgation for the define to use
      G4_INST *defInst = inst1->def_begin()->first;
      G4_Operand *useSrc = useInst->getSrc(opndNum - 1);
      G4_Operand *new_src_opnd = builder.createSrcRegRegion(
          Mod_src_undef, src1->asSrcRegRegion()->getRegAccess(),
          src1->asSrcRegRegion()->getBase(),
          src1->asSrcRegRegion()->getRegOff(),
          src1->asSrcRegRegion()->getSubRegOff(),
          useSrc->asSrcRegRegion()->getRegion(), useSrc->getType());
      useInst->setSrc(new_src_opnd, opndNum - 1);
      inst1->copyDefsTo(useInst, true);
      inst3->copyUsesTo(defInst, true);

      inst1->removeAllDefs();
      inst1->removeAllUses();
      inst2->removeAllDefs();
      inst2->removeAllUses();
      inst3->removeAllDefs();
      inst3->removeAllUses();

      ii++;
      bb->erase(firstIt);
      bb->erase(secondIt);
      bb->erase(thirdIt);
    }
  }
}

void Optimizer::localCopyPropagation() {
  for (G4_BB *bb : fg) {
    bb->resetLocalIds();

    INST_LIST_ITER ii = bb->begin(), iend(bb->end());
    while (ii != iend) {
      G4_INST *inst = *ii;
      G4_Operand *dst = inst->getDst();
      if (!dst) {
        ii++;
        continue;
      }

      builder.doConsFolding(inst);
      inst = builder.doMathConsFolding(ii);
      builder.doSimplification(inst);

      G4_INST::MovType MT = inst->canPropagate();
      // Skip super mov.
      if (MT == G4_INST::SuperMov) {
        ii++;
        continue;
      }

      if (!isCopyPropProfitable(inst)) {
        ++ii;
        continue;
      }
      bool canRemove = true;

      // check if each use may be copy propagated.
      USE_EDGE_LIST_ITER iter, iend1(inst->use_end());
      for (iter = inst->use_begin(); iter != iend1; iter++) {
        G4_INST *useInst = iter->first;
        Gen4_Operand_Number opndNum = iter->second;

        if (inst->getDst()->isDirectA0() && useInst->isSplitSend() &&
            VISA_WA_CHECK(builder.getPWaTable(),
                          WaSendSEnableIndirectMsgDesc)) {
          canRemove = false;
          break;
        }

        if (!inst->canPropagateTo(useInst, opndNum, MT,
                                  !bb->isAllLaneActive())) {
          canRemove = false;
          break;
        }

        // Make sure there is no lifetime.end for src0 of the move inst
        INST_LIST_ITER cpIter = ii;
        cpIter++;
        while (*cpIter != useInst) {
          // Detect patterns like:
          //
          // mov A, B
          // ...
          // lifetime.end B
          // op C, A, D
          //
          // Because of presence of lifetime.end B, copy propagation for inst
          // mov A, B
          // cannot be done

          if ((*cpIter)->isLifeTimeEnd()) {
            // Check whether lifetime end is for same opnd
            G4_Declare *lifetimeEndTopDcl =
                GetTopDclFromRegRegion((*cpIter)->getSrc(0));
            G4_Declare *curInstDstTopDcl =
                GetTopDclFromRegRegion((*ii)->getDst());

            if (lifetimeEndTopDcl == curInstDstTopDcl) {
              canRemove = false;
              break;
            }
          }

          //
          // Following instructions may use acc0 register in HWComformity,
          // if any of them appear in the propagation range, it may have
          // correctness issue.
          //  Such as in following case:
          // addc
          // mov  V1, acc0
          // mulh
          // add   V2, V1, V3
          // Since HW conformity will replace mulh with mul + acc0 dst,
          // the propagation acc0 through V1 will introduce correctness
          // issue.
          //
          if (inst->getSrc(0)->isAccReg() &&
              ((*cpIter)->opcode() == G4_mul ||
               (*cpIter)->opcode() == G4_mulh ||
               (*cpIter)->opcode() == G4_pln ||
               (*cpIter)->opcode() == G4_pseudo_sada2 ||
               (*cpIter)->opcode() == G4_madw ||
               (*cpIter)->opcode() == G4_subb ||
               (*cpIter)->opcode() == G4_addc)) {
            canRemove = false;
            break;
          }

          cpIter++;
        }
      } // for uses

      if (canRemove && inst->getSrc(0)->isSrcRegRegion()) {
        // check for anti-dependencies for src0 of the move instruction
        bool def_use_in_between = false;

        G4_INST *lastUse = inst->use_front().first;
        for (USE_EDGE_LIST_ITER iter = inst->use_begin(),
                                uend = inst->use_end();
             iter != uend; ++iter) {
          G4_INST *useInst = iter->first;
          if (useInst->getLocalId() > lastUse->getLocalId()) {
            lastUse = useInst;
          }
        }

        INST_LIST_ITER forwardIter = ii;
        forwardIter++;
        INST_LIST_ITER instListEnd = bb->end();

        while (!def_use_in_between && forwardIter != instListEnd &&
               *forwardIter != lastUse) {
          if ((*forwardIter)->isWARdep(inst)) {
            def_use_in_between = true;
            break;
          }
          forwardIter++;
        }

        // check if hoisting is possible
        if (def_use_in_between) {
          hoistUseInst(bb, inst, forwardIter, canRemove);
        }

        if (!canRemove) {
          // Check whether the type could be propagated instead to demote
          // type if possible.
          propagateType(builder, bb, inst, MT);
        }
      }

      if (!canRemove) {
        ii++;
        continue;
      }

      G4_Operand *src = inst->getSrc(0);
      // do propagation
      for (iter = inst->use_begin(); iter != iend1; /* empty */) {
        G4_INST *useInst = (*iter).first;
        Gen4_Operand_Number opndNum = (*iter).second;
        G4_Operand *use = useInst->getOperand(opndNum);
        G4_Type propType = useInst->getPropType(opndNum, MT, inst);

        // replace use with def
        if (src->isImm()) {
          auto newImmVal =
              G4_Imm::typecastVals(src->asImm()->getImm(), propType);
          G4_Imm *newImm = builder.createImm(newImmVal, propType);
          G4_SrcModifier modifier = use->asSrcRegRegion()->getModifier();
          if (modifier != Mod_src_undef) {
            if (IS_TYPE_FLOAT_ALL(propType)) {
              if (propType == Type_DF) {
                double imm = getImmValue(newImm->getDouble(), modifier);
                newImm = builder.createDFImm(imm);
              } else {
                float imm = getImmValue(newImm->getFloat(), modifier);
                newImm = builder.createImm(imm);
              }
            } else {
              int64_t imm = getImmValue(newImm->getImm(), modifier);
              newImm = builder.createImm(imm, propType);
            }
          }
          useInst->setSrc(newImm, opndNum - 1);
        } else {
          if (use == NULL) {
            break;
          }
          G4_SrcModifier new_mod = mergeModifier(src, use);

          unsigned use_elsize = use->getTypeSize();
          unsigned dstElSize = inst->getDst()->getTypeSize();
          const RegionDesc *rd = src->asSrcRegRegion()->getRegion();
          G4_Operand *new_src_opnd = NULL;
          bool new_src = false;
          unsigned char scale = 1, newExecSize = useInst->getExecSize();

          // Compute the composed region if exists.
          auto getComposedRegion =
              [=](unsigned dStride, unsigned ex1, const RegionDesc *rd1,
                  unsigned ex2, const RegionDesc *rd2) -> const RegionDesc * {
            // Easy cases.
            if (rd1->isScalar())
              return rd1;
            else if (rd2->isScalar())
              return rd2;
            else if (dStride == 1 && rd1->isContiguous(ex1))
              return rd2;
            else if (dStride == 1 && rd2->isContiguous(ex2))
              return rd1;

            // rd1 and rd2 must be single strided. Use a non-zero
            // invalid stride value as the initial value, which
            // simplifies and unifies the checking.
            uint16_t stride1 = 64;
            if (rd1->isContiguous(ex1))
              stride1 = 1;
            else
              rd1->isSingleNonUnitStride(ex1, stride1);

            uint16_t stride2 = 64;
            if (rd2->isContiguous(ex2))
              stride2 = 1;
            else
              rd2->isSingleNonUnitStride(ex2, stride2);

            // All are single strided; the composition is the product of
            // strides.
            if (stride1 * stride2 * dStride <= 32)
              return builder.createRegionDesc(
                  (uint16_t)ex2, stride1 * stride2 * dStride, 1, 0);

            // Should be unreachable, since the legality check
            // before should reject cases that are difficult to do
            // composition. Assert?
            return nullptr;
          };

          if (MT == G4_INST::Trunc) {
            G4_DstRegRegion *dst = inst->getDst();
            G4_SrcRegRegion *src0 = src->asSrcRegRegion();
            unsigned typeSizeRatio = src0->getTypeSize() / dst->getTypeSize();
            unsigned numElt =
                src0->isScalar() ? 1 : inst->getExecSize() * typeSizeRatio;
            // src0 region is guaranteed to be scalar/contiguous due to
            // canPropagate() check earlier
            const RegionDesc *region =
                src0->isScalar()
                    ? builder.getRegionScalar()
                    : builder.createRegionDesc(
                          useInst->getExecSize(),
                          (uint16_t)inst->getExecSize() * typeSizeRatio,
                          inst->getExecSize(), (uint16_t)typeSizeRatio);
            if (src0->isIndirect()) {
              new_src_opnd = builder.createIndirectSrc(
                  new_mod, src0->getBase(), src0->getRegOff(),
                  src0->getSubRegOff() * typeSizeRatio, region, propType,
                  src0->getAddrImm());
            } else {
              G4_Declare *newDcl =
                  builder.createTempVar(numElt, inst->getDst()->getType(), Any);
              newDcl->setAliasDeclare(src0->getBase()->asRegVar()->getDeclare(),
                                      0);

              new_src_opnd = builder.createSrcRegRegion(
                  new_mod, Direct, newDcl->getRegVar(), src0->getRegOff(),
                  src0->getSubRegOff() * typeSizeRatio, region, propType);
            }
            new_src = true;
          } else if (dstElSize < use_elsize) {
            // FIXME: How could this happen? Revisit later if
            // NoMask is guaranteed.
            // TODO!!! src is aligned to use type. -- should check this.
            new_src = true;
            scale = use_elsize / dstElSize;
            unsigned short vs = rd->vertStride, wd = rd->width;
            // packed word/byte
            if (use->asSrcRegRegion()->isScalar()) {
              rd = builder.getRegionScalar();
            } else if (inst->isComprInst() && vs == wd) {
              rd = builder.getRegionStride1();
            } else {
              rd = builder.createRegionDesc(vs / scale, wd / scale, 1);
            }
          } else if (inst->getExecSize() < useInst->getExecSize() && rd &&
                     use->isSrcRegRegion()) {
            unsigned dStride = inst->getDst()->getHorzStride();
            const RegionDesc *rd2 = use->asSrcRegRegion()->getRegion();
            if (auto compRd = getComposedRegion(dStride, inst->getExecSize(),
                                                rd, newExecSize, rd2)) {
              new_src = true;
              rd = compRd;
            }
          }

          if (new_mod != Mod_src_undef || new_src) {
            // For truncation case, new src operand is already built.
            if (MT != G4_INST::Trunc) {
              new_src_opnd = builder.createSrcRegRegion(
                  new_mod, src->asSrcRegRegion()->getRegAccess(),
                  src->asSrcRegRegion()->getBase(),
                  src->asSrcRegRegion()->getRegOff(),
                  src->asSrcRegRegion()->getSubRegOff() / scale, rd, propType);
              if (src->asSrcRegRegion()->getRegAccess() != Direct) {
                new_src_opnd->asSrcRegRegion()->setImmAddrOff(
                    src->asSrcRegRegion()->getAddrImm());
              }
            }
          } else {
            new_src_opnd = builder.duplicateOperand(src);
            new_src_opnd->asSrcRegRegion()->setModifier(new_mod);
            new_src_opnd->asSrcRegRegion()->setType(builder, propType);
          }
          useInst->setSrc(new_src_opnd, opndNum - 1);
        }

        iter = inst->eraseUse(iter);
        // due to truncation a (partial) def of the move may no longer be a def
        // of the use
        inst->copyDef(useInst, Opnd_src0, opndNum, true);

        builder.doConsFolding(useInst);
      }
      // remove decl corresponding to this def
      // TODO!!! what if there is some alias to this decl?
      // remove MOV inst

      // remove it from the use list of its deflists
      inst->removeDefUse(Opnd_src0);

      INST_LIST_ITER tmp = ii;
      ii++;
      bb->erase(tmp);
    }
  }
}

void Optimizer::localInstCombine() { InstCombine(builder, fg); }

void Optimizer::cselPeepHoleOpt() {
  if (!builder.hasCondModForTernary()) {
    return;
  }
  G4_SrcRegRegion *cmpSrc0 = NULL;
  G4_Operand *cmpSrc1 = NULL;
  for (G4_BB *bb : fg) {
    INST_LIST_ITER ii;
    INST_LIST_ITER nextIter;
    INST_LIST_ITER iiEnd;
    if (bb->empty()) {
      continue;
    }

    bb->resetLocalIds();
    ii = bb->begin();
    iiEnd = bb->end();

    nextIter = ii;

    do {
      ii = nextIter;
      ++nextIter;
      G4_INST *inst = *ii;
      G4_opcode op = inst->opcode();
      bool hasGRFDst = inst->getDst() && !inst->hasNULLDst();
      /*
      csel doesn't have the same semantics for destination
      as cmp instruction
      */
      if (op != G4_cmp || hasGRFDst || inst->getPredicate() || inst->isDead() ||
          !inst->getSrc(0)->isSrcRegRegion()) {
        continue;
      }

      cmpSrc0 = inst->getSrc(0)->asSrcRegRegion();
      cmpSrc1 = inst->getSrc(1);

      G4_CondMod *cModifier = inst->getCondMod();

      // check if dst is global
      if (fg.globalOpndHT.isOpndGlobal(cModifier)) {
        continue;
      }

      /*
      csel instruction implicitly compares src2 to 0
      only supports floats
      no predication
      */

      if (!cmpSrc1->isImm() ||
          (cmpSrc1->asImm()->getImm() != 0 &&
           (cmpSrc1->asImm()->getType() != Type_F ||
            cmpSrc1->asImm()->getFloat() != -0.0f)) ||
          cmpSrc0->getType() != Type_F || cmpSrc0->isImm())
        continue;

      if (inst->getSrc(0)->isRelocImm() || inst->getSrc(1)->isRelocImm()) {
        continue;
      }

      // Only allow single strided regions.
      uint16_t src0Stride = 0;
      if (!cmpSrc0->getRegion()->isSingleStride(inst->getExecSize(),
                                                src0Stride))
        continue;

      /*
          Can do scan until use instruction to see if src0 is modified
          but I think for general case this will suffice. If we are
          not capturing opportunities can revisit.
      */

      if (inst->useEmpty())
        continue;

      int execSize = inst->getExecSize();
      if (execSize == 2)
        continue;

      USE_EDGE_LIST_ITER iter = inst->use_begin();
      USE_EDGE_LIST_ITER endUseList = inst->use_end();

      bool canOpt = true;
      int maxInstID = 0;

      for (; iter != endUseList; ++iter) {
        G4_INST *useInst = (*iter).first;

        if (useInst->getNumSrc() != 2) {
          canOpt = false;
          break;
        }

        maxInstID = std::max(useInst->getLocalId(), maxInstID);
        G4_Operand *dstUse = useInst->getDst();
        G4_Operand *selSrc0 = useInst->getSrc(0);
        G4_Operand *selSrc1 = useInst->getSrc(1);

        if (useInst->opcode() != G4_sel || selSrc0->isImm() ||
            selSrc1->isImm() || selSrc0->getType() != Type_F ||
            selSrc1->getType() != Type_F || dstUse->getType() != Type_F ||
            // 3-src restriction
            !builder.tryToAlignOperand(dstUse, 16) ||
            !builder.tryToAlignOperand(selSrc0, 16) ||
            !builder.tryToAlignOperand(selSrc1, 16)) {
          canOpt = false;
          break;
        }

        //   if inst is NoMask use inst can be anything.
        //   if inst is not NoMask then useInst needs to be subset of inst.
        if (!(inst->getMaskOption() & InstOpt_WriteEnable)) {
          auto isInclusive = [](int lb1, int rb1, int lb2, int rb2) {
            return lb1 <= lb2 && rb1 >= rb2;
          };
          if (!isInclusive(inst->getMaskOffset(),
                           inst->getMaskOffset() + inst->getExecSize(),
                           useInst->getMaskOffset(),
                           useInst->getMaskOffset() + useInst->getExecSize())) {
            canOpt = false;
            break;
          }
        }

        uint8_t numPredDefs = 0;
        DEF_EDGE_LIST_ITER useIter = useInst->def_begin();
        DEF_EDGE_LIST_ITER iterEnd = useInst->def_end();

        //    Just in case some weird code is generated with partial writes to
        //    predicate
        for (; useIter != iterEnd; ++useIter) {
          if ((*useIter).second == Opnd_pred)
            ++numPredDefs;

          // Check whether pseudo_kill for dst exists between cmp and sel
          // cmp.xx.fx.0 (8) ... src0 $0
          // ...
          // pseudo_kill dst
          // (f0) sel (8) dst src1 src2
          //
          // These two cannot be merged because pseudo_kill is in between them

          INST_LIST_ITER cselOptIt = ii;
          cselOptIt++;
          while ((*cselOptIt) != useInst) {
            if ((*cselOptIt)->isLifeTimeEnd()) {
              if (GetTopDclFromRegRegion((*cselOptIt)->getDst()) ==
                  GetTopDclFromRegRegion(useInst->getDst())) {
                canOpt = false;
                break;
              }
            }

            cselOptIt++;
          }
        }

        if (numPredDefs > 1) {
          canOpt = false;
          break;
        }
      }

      INST_LIST_ITER tempInstIter = nextIter;
      // explicit check that cmp sr0 is not over written or partially writen to
      // between cmp and sel.
      for (; tempInstIter != iiEnd; ++tempInstIter) {
        G4_INST *tempInst = *tempInstIter;

        if (tempInst->getLocalId() == maxInstID) {
          break;
        }

        if (!tempInst->getDst())
          continue;

        // also checks for indirect, will return inerference.
        G4_CmpRelation rel =
            tempInst->getDst()->compareOperand(cmpSrc0, builder);
        if (rel != Rel_disjoint) {
          canOpt = false;
          break;
        }
      }

      if (canOpt) {
        for (auto iter = inst->use_begin(); iter != inst->use_end();
             /*empty*/) {
          G4_INST *useInst = (*iter).first;
          G4_CondMod *mod = inst->getCondMod();
          useInst->setOpcode(G4_csel);
          useInst->setSrc(builder.duplicateOperand(inst->getSrc(0)), 2);
          useInst->setCondMod(builder.duplicateOperand(mod));
          useInst->setPredicate(NULL);

          G4_SrcRegRegion *opnd2 = useInst->getSrc(2)->asSrcRegRegion();

          if (!opnd2->isScalar() &&
              inst->getExecSize() > useInst->getExecSize()) {
            // earlier check establishes that useInst mask is equivalent or
            // subset sel instruction
            /*
                case which considering:
                cmp (16)
                sel (8)
            */
            if (useInst->getMaskOffset() != inst->getMaskOffset()) {
              // check elsewhere guarantees this is float.
              G4_Type type = opnd2->getType();
              unsigned short typeSize = TypeSize(type);
              unsigned offset =
                  opnd2->getRegOff() * kernel.numEltPerGRF<Type_UB>() +
                  opnd2->getSubRegOff() * typeSize;
              offset += useInst->getExecSize() * src0Stride * typeSize;

              auto newSrc2 = builder.createSrcRegRegion(
                  opnd2->getModifier(), Direct, opnd2->getBase(),
                  offset / kernel.numEltPerGRF<Type_UB>(),
                  (offset % kernel.numEltPerGRF<Type_UB>()) / typeSize,
                  opnd2->getRegion(), opnd2->getType());
              useInst->setSrc(newSrc2, 2);
            }
          }
          //
          // Modifying useDef links
          //
          // cmp.xx.f0.0 (8) ... src2 $0  <- inst (to be deleted)
          // (f0) sel (8) dst src0 src1   <- useInst
          // =>
          // csel.xx.f0.0 (8) dst src0 src1 src2

          // useInst's predicate becomes NULL.
          iter = inst->eraseUse(iter);

          // inst's src0 becomes useInst's src2.
          inst->copyDef(useInst, Opnd_src0, Opnd_src2);
        }
        vISA_ASSERT(inst->useEmpty(), "all predicate uses are removed.");
        inst->removeAllDefs();
        bb->erase(ii);
      }
    } while (nextIter != iiEnd);
  }
}

// helper function to convert
// and/or p3 p1 p2
// ==>
// (p1) sel t1 1 0
// (p2) sel t2 1 0
// and/or.nz.p3 t1 t2
// if the original inst is NoMask and Q1/H1, we do
// and/or p3 p1 p2
// ==>
// and/or (1) p3 p1 p2
// p3's type is uw for simd8/16 and ud for simd32
static void expandPseudoLogic(IR_Builder &builder, G4_BB *bb,
                              INST_LIST_ITER &iter)

{
  G4_INST *inst = *iter;
  vISA_ASSERT(inst->isPseudoLogic(),
              "inst must be either pseudo_and/or/xor/not");
  INST_LIST_ITER newIter = iter;

  bool isFirstInst = iter == bb->begin();
  if (!isFirstInst) {
    --iter;
  }

  auto canFoldOnSIMD1 = [=, &builder]() {
    if (inst->isWriteEnableInst() &&
        (inst->getMaskOffset() == 0 || inst->getMaskOffset() == 16) &&
        // we can't do this for simd8 inst in simd16 kernels as it will
        // overwrite upper flag bits
        (inst->getExecSize() > g4::SIMD8 ||
         inst->getExecSize() == builder.kernel.getSimdSize())) {
      return true;
    }

    // inst writes the whole flag.
    if (inst->isWriteEnableInst() && inst->getMaskOffset() == 0) {
      auto Dcl = inst->getDst()->getTopDcl();
      if (Dcl && Dcl->getNumberFlagElements() <= inst->getExecSize()) {
        return true;
      }
    }

    return false;
  };

  if (canFoldOnSIMD1()) {
    G4_opcode newOpcode = G4_illegal;
    if (inst->getMaskOffset() == 16) {
      vISA_ASSERT(inst->getExecSize() == g4::SIMD16,
                  "Only support simd16 pseudo-logic instructions");
      // we have to use the upper flag bits (.1) instead
      vISA_ASSERT(inst->getSrc(0)->isSrcRegRegion() &&
                      inst->getSrc(0)->isFlag(),
                  "expect src0 to be flag");
      auto newSrc0 = builder.createSrcWithNewSubRegOff(
          inst->getSrc(0)->asSrcRegRegion(), 1);
      inst->setSrc(newSrc0, 0);
      if (inst->getSrc(1) != nullptr) {
        vISA_ASSERT(inst->getSrc(1)->isSrcRegRegion() &&
                        inst->getSrc(1)->isFlag(),
                    "expect src1 to be flag");
        auto newSrc1 = builder.createSrcWithNewSubRegOff(
            inst->getSrc(1)->asSrcRegRegion(), 1);
        inst->setSrc(newSrc1, 1);
      }
      auto newDst = builder.createDstWithNewSubRegOff(inst->getDst(), 1);
      inst->setDest(newDst);
    }

    switch (inst->opcode()) {
    case G4_pseudo_and:
      newOpcode = G4_and;
      break;
    case G4_pseudo_or:
      newOpcode = G4_or;
      break;
    case G4_pseudo_xor:
      newOpcode = G4_xor;
      break;
    case G4_pseudo_not:
      newOpcode = G4_not;
      break;
    default:
      vISA_ASSERT_UNREACHABLE(
          "unexpected opcode for pseudo-logic instructions");
    }

    inst->setOpcode(newOpcode);
    inst->setExecSize(g4::SIMD1);
  } else {
    G4_ExecSize tmpSize = inst->getExecSize();
    auto LowerOpnd = [=, &builder](Gen4_Operand_Number opNum,
                                   G4_INST *&SI) -> G4_Operand * {
      G4_Operand *Opnd = inst->getOperand(opNum);
      if (Opnd) {
        auto src = Opnd->asSrcRegRegion();
        auto newDcl = builder.createTempVar(tmpSize, Type_UW, Any);
        auto newDst = builder.createDst(newDcl->getRegVar(), 0, 0, 1, Type_UW);
        auto newPred = builder.createPredicate(PredState_Plus, src->getBase(),
                                               src->getSubRegOff());
        auto newSel = builder.createInternalInst(
            newPred, G4_sel, nullptr, g4::NOSAT, tmpSize, newDst,
            builder.createImm(1, Type_UW), builder.createImm(0, Type_UW),
            inst->getOption());
        inst->transferDef(newSel, opNum, Gen4_Operand_Number::Opnd_pred);
        bb->insertBefore(newIter, newSel);
        SI = newSel;
        const RegionDesc *rd = tmpSize == g4::SIMD1
                                   ? builder.getRegionScalar()
                                   : builder.getRegionStride1();
        return builder.createSrcRegRegion(newDcl, rd);
      }
      return Opnd;
    };

    G4_INST *Sel0 = nullptr;
    G4_Operand *logicSrc0 = LowerOpnd(Gen4_Operand_Number::Opnd_src0, Sel0);

    G4_INST *Sel1 = nullptr;
    G4_Operand *logicSrc1 = LowerOpnd(Gen4_Operand_Number::Opnd_src1, Sel1);

    if (logicSrc1 == nullptr) {
      vISA_ASSERT(inst->opcode() == G4_pseudo_not,
                  "Must be a pseudo-not instruction");
      // for not P1 P0
      // we generate
      // (P0) sel V1 1 0
      // xor.P1 null V1 1
      // so that the upper bits would stay zero
      logicSrc1 = builder.createImm(1, Type_UW);
    }

    auto nullDst = builder.createNullDst(Type_UW);
    auto newCondMod =
        builder.createCondMod(Mod_nz, inst->getDst()->getBase()->asRegVar(), 0);
    G4_opcode newOpcode = G4_illegal;
    switch (inst->opcode()) {
    case G4_pseudo_and:
      newOpcode = G4_and;
      break;
    case G4_pseudo_or:
      newOpcode = G4_or;
      break;
    case G4_pseudo_xor:
      newOpcode = G4_xor;
      break;
    case G4_pseudo_not:
      // see comment above
      newOpcode = G4_xor;
      break;
    default:
      vISA_ASSERT_UNREACHABLE(
          "unexpected opcode for pseudo-logic instructions");
    }

    G4_INST *newLogicOp = builder.createInternalInst(
        NULL, newOpcode, newCondMod, g4::NOSAT, tmpSize, nullDst, logicSrc0,
        logicSrc1,
        inst->getOption() // keep the original instruction emask
    );

    // Fix def-use
    if (Sel0 != nullptr) {
      Sel0->addDefUse(newLogicOp, Gen4_Operand_Number::Opnd_src0);
    }
    if (Sel1 != nullptr) {
      Sel1->addDefUse(newLogicOp, Gen4_Operand_Number::Opnd_src1);
    }
    inst->transferUse(newLogicOp);
    bb->insertBefore(newIter, newLogicOp);
    bb->erase(newIter);
  }

  // iter either points to the start or the first expanded instruction.  Caller
  // will advance it to the previous instruction
  if (isFirstInst) {
    iter = bb->begin();
  } else {
    ++iter;
  }
}

// mov(1) P0 Imm(NoMask)
// (P0) mov(esize) r[A0, 0] src0 src1
// == >
// smov(esize) r[A0, 0] src0 src1 Imm
//
// esize is either 8 or 16
bool Optimizer::createSmov(G4_BB *bb, G4_INST *flagMove, G4_INST *next_inst) {
  if ((next_inst->getExecSize() != g4::SIMD8 &&
       next_inst->getExecSize() != g4::SIMD16) ||
      next_inst->getPredicate() == NULL || next_inst->getCondMod() != NULL ||
      next_inst->getSaturate() == true ||
      next_inst->getDst()->getRegAccess() == Direct ||
      next_inst->getDst()->getTypeSize() == 1 ||
      next_inst->getSrc(0)->getTypeSize() == 1 ||
      (builder.getPlatform() < GENX_SKL && builder.getPlatform() != GENX_BDW) ||
      next_inst->getDst()->getTypeSize() <
          next_inst->getSrc(0)->getTypeSize()) {
    return false;
  }

  if (next_inst->getSrc(0)->isSrcRegRegion() &&
      next_inst->getSrc(0)->asSrcRegRegion()->getModifier() != Mod_src_undef) {
    return false;
  }

  if (flagMove->use_size() != 1 || flagMove->use_front().first != next_inst) {
    return false;
  }

  G4_CmpRelation rel =
      flagMove->getDst()->compareOperand(next_inst->getPredicate(), builder);
  if (rel != Rel_eq && !(rel == Rel_gt && next_inst->getMaskOffset() == 0)) {
    return false;
  }

  if (kernel.getKernelType() == VISA_3D || !bb->isAllLaneActive()) {
    if (!flagMove->isWriteEnableInst()) {
      return false;
    }
  }

  next_inst->setOpcode(G4_smov);
  next_inst->setSrc(flagMove->getSrc(0), 1);
  next_inst->setPredicate(nullptr);

  flagMove->removeUseOfInst();
  return true;
}

// Returns true if *iter has an use that is a cmp and we can fold that cmp
// into *iter as a conditional modifier. The cmp instruction is deleted as part
// of folding. Note that iter may be modified to point to the next inst if we
// decide to sync *iter to where the cmp was to work around dependencies
bool Optimizer::foldCmpToCondMod(G4_BB *bb, INST_LIST_ITER &iter) {
  // find a cmp that uses inst dst
  G4_INST *inst = *iter;
  G4_INST *cmpInst = nullptr;
  bool canFold = false;

  if (inst->getCondMod()) {
    return false;
  }

  for (auto UI = inst->use_begin(), UE = inst->use_end(); UI != UE; ++UI) {
    cmpInst = (*UI).first;

    // cmp instruction must be of the form
    // cmp [<op> P0] null src 0
    // where src is singly defined by inst
    if (cmpInst->opcode() == G4_cmp &&
        cmpInst->getExecSize() == inst->getExecSize() &&
        cmpInst->hasNULLDst() && cmpInst->getSrc(0)->isSrcRegRegion() &&
        cmpInst->getSrc(0)->asSrcRegRegion()->getModifier() == Mod_src_undef &&
        cmpInst->def_size() == 1 && !cmpInst->getPredicate() &&
        cmpInst->getSrc(1)->isImm() && cmpInst->getSrc(1)->asImm()->isZero()) {
      canFold = true;
      break;
    }
  }

  if (!canFold) {
    return false;
  }

  // floating point cmp may flush denorms to zero, but mov may not.
  //
  // mov(1|M0) (lt)f0.0 r6.2<1>:f r123.2<0;1,0>:f
  // may not be the same as
  // mov(1|M0)          r6.2<1>:f r123.2<0;1,0>:f
  // cmp(1|M0) (lt)f0.0 null<1>:f 6.2<0;1,0>:f 0x0:f
  // for denorm inputs.
  if (inst->opcode() == G4_mov &&
      IS_TYPE_FLOAT_ALL(cmpInst->getSrc(0)->getType())) {
    return false;
  }

  // If dst is B and exectype is Q, dst is misaligned. This misaligned inst
  // will be split in HWComformity. If a condMod is present, it would be
  // harder to split and may result in wrong code. Here, simply disable folding.
  //
  // For example,
  //    (W) mov (1)     conv_i(0,0)<1>:b   V0040(0,0)<0;1,0>:q
  //    (W) cmp(1)  (eq)P01.0   null<1>:w  conv_i(0, 0)<0;1,0>:b  0:w
  //
  int extypesize = 0;
  (void)inst->getOpExecType(extypesize);
  if (inst->getDst()->getTypeSize() == 1 && extypesize == 8) {
    return false;
  }

  auto cmpIter = std::find(iter, bb->end(), cmpInst);

  // check if cmp instruction is close enough
  constexpr int DISTANCE = 60;
  if (std::distance(iter, cmpIter) > DISTANCE) {
    return false;
  }

  auto isSupportedCondMod = [](G4_CondModifier mod) {
    return mod == Mod_g || mod == Mod_ge || mod == Mod_l || mod == Mod_le ||
           mod == Mod_e || mod == Mod_ne;
  };
  G4_CondModifier mod = cmpInst->getCondMod()->getMod();
  if (!isSupportedCondMod(mod)) {
    return false;
  }

  if (kernel.getKernelType() == VISA_3D || !bb->isAllLaneActive()) {
    // Make sure masks of both instructions are same
    if (inst->getMaskOption() != cmpInst->getMaskOption()) {
      return false;
    }
  }

  auto getUnsignedTy = [](G4_Type Ty) {
    switch (Ty) {
    case Type_D:
      return Type_UD;
    case Type_W:
      return Type_UW;
    case Type_B:
      return Type_UB;
    case Type_Q:
      return Type_UQ;
    case Type_V:
      return Type_UV;
    default:
      break;
    }
    return Ty;
  };

  G4_Type T1 = inst->getDst()->getType();
  G4_Type T2 = cmpInst->getSrc(0)->getType();
  if (getUnsignedTy(T1) != getUnsignedTy(T2)) {
    return false;
  }
  // Skip if the dst needs saturating but it's used as different sign.
  if (inst->getSaturate() && T1 != T2) {
    return false;
  }

  if (chkBwdOutputHazard(iter, cmpIter)) {
    return false;
  }

  G4_Declare *dstDcl = GetTopDclFromRegRegion(inst->getDst());
  if (dstDcl->getAddressed() && chkBwdWAWdep(inst, cmpIter)) {
    return false;
  }

  auto isSafeToSink = [this](INST_LIST_ITER defIter, INST_LIST_ITER beforeIter,
                             int maxDist) {
    G4_INST *inst = *defIter;
    int dist = 0;
    for (auto it = std::next(defIter); it != beforeIter; ++it) {
      if (dist++ >= maxDist)
        return false;
      if (inst->isWAWdep(*it) || inst->isRAWdep(*it) || inst->isWARdep(*it))
        return false;
      if (!checkLifetime(inst, *it))
        return false;
      if (inst->isAccSrcInst() && builder.hasMacMacl() &&
          (*it)->opcode() == G4_mul && IS_DTYPE((*it)->getSrc(0)->getType()) &&
          IS_DTYPE((*it)->getSrc(1)->getType())) {
        // Do not sink instructions with explicit ACC src over mul
        // instructions as mul can be changed to:
        //   mul (8) acc0.0<1>:d src0:d src1:w
        //   mach (8) dst:d src0:d src1:d
        // see HWConformity::generateMacl()
        return false;
      }
    }
    return true;
  };

  // Merge two instructions
  // If legal, use the cmp location as new insert position.
  bool sinkInst = false;

  if (inst->getDst()->compareOperand(cmpInst->getSrc(0), builder) == Rel_eq) {
    if (inst->use_size() == 1) {
      // see if we can replace dst with null
      if (inst->supportsNullDst() &&
          !fg.globalOpndHT.isOpndGlobal(inst->getDst())) {
        inst->setDest(builder.createDst(builder.phyregpool.getNullReg(), 0, 0,
                                        inst->getDst()->getHorzStride(),
                                        inst->getDst()->getType()));
      }
      // Check if it is safe to sink inst right before cmp inst, which lowers
      // flag pressure in general.
      const int MAX_DISTANCE = 20;
      sinkInst = isSafeToSink(iter, cmpIter, MAX_DISTANCE);
    }
    inst->setCondMod(cmpInst->getCondMod());
    inst->setOptions((inst->getOption() & ~InstOpt_Masks) |
                     (cmpInst->getMaskOption()));
    // The sign of dst should follow its use instead of its
    // def. The later is meaningless from how hardware works.
    auto honorSignedness = [](G4_CondModifier mod) {
      switch (mod) {
      case Mod_g:
      case Mod_ge:
      case Mod_l:
      case Mod_le:
        return true;
      default:
        break;
      }
      return false;
    };
    if (honorSignedness(inst->getCondMod()->getMod()))
      inst->getDst()->setType(builder, T2);

    // update def-use
    // since cmp is deleted, we have to
    // -- transfer cmp's use to inst
    // -- remove cmp from its definition's use list
    cmpInst->transferUse(inst, true);
    cmpInst->removeUseOfInst();
    if (!sinkInst) {
      bb->erase(cmpIter);
    } else {
      // Before and <- ii
      //        cmp <- next_iter
      // After  cmp <- ii
      //        and <- next
      std::iter_swap(iter, cmpIter);
      auto nextii = std::next(iter);
      bb->erase(iter);
      iter = nextii;
    }
    return true;
  }
  return false;
}

// Return true  : folding cmp and sel is performed
//        false : no folding is performed.
bool Optimizer::foldCmpSel(G4_BB *BB, G4_INST *selInst,
                           INST_LIST_ITER &selInst_II) {
  vISA_ASSERT(
      (selInst->opcode() == G4_sel && selInst->getPredicate() &&
       selInst->getCondMod() == NULL),
      "foldCmpSel: Inst should be a sel with predicate and without cmod.");
  G4_Predicate *pred = selInst->getPredicate();

  // global predicates are not eligible since folding the cmp removes the def
  if (fg.globalOpndHT.isOpndGlobal(pred)) {
    return false;
  }

  // Needs to find cmp instruction that defines predicate of sel. The cmp is
  // not necessarily right before the sel. To be able to fold the cmp to the
  // sel, we have to check if the cmp can be moved right before the sel. It not,
  // no folding is performed.
  G4_INST *cmpInst = nullptr;
  for (auto DI = selInst->def_begin(), DE = selInst->def_end(); DI != DE;
       ++DI) {
    if ((*DI).second == Opnd_pred) {
      if (cmpInst) { // only handle single def.
        cmpInst = nullptr;
        break;
      }
      cmpInst = (*DI).first;
      if (cmpInst && cmpInst->opcode() != G4_cmp) {
        cmpInst = nullptr;
        break;
      }
    }
  }
  if (!cmpInst) {
    // G4_cmp is not found, skip optimization.
    return false;
  }

  // Do a fast check first. Note that sel w/ cmod
  // does not allow predication. So, we will give up if cmp has predicate.
  bool isSubExecSize = (selInst->getExecSize() < cmpInst->getExecSize());
  bool isSameExecSize = (selInst->getExecSize() == cmpInst->getExecSize());
  if ((!isSameExecSize && !isSubExecSize) ||
      (cmpInst->getDst() && !cmpInst->hasNULLDst()) ||
      cmpInst->use_size() != 1 || cmpInst->getPredicate() != nullptr) {
    return false;
  }

  // Check if two source operands have the same type and value.
  auto IsEqual = [](G4_Operand *opnd1, G4_Operand *opnd2,
                    const IR_Builder &builder) {
    if (opnd1->isImm() && opnd2->isImm())
      return opnd1->asImm()->isEqualTo(opnd2->asImm());
    if (opnd1->compareOperand(opnd2, builder) != Rel_eq)
      return false;
    // footprint does not imply equality.
    // (1) region difference:  r10.0<1;4,2>:f vs r10.0<8;8,1>
    // (2) source modifier: r10.0<0;1,0>:f vs -r10.0<0;1,0>
    //
    if (opnd1->isSrcRegRegion() && opnd2->isSrcRegRegion())
      return opnd1->asSrcRegRegion()->sameSrcRegRegion(
          *opnd2->asSrcRegRegion());

    // Common cases should be covered.
    return false;
  };

  G4_Operand *sel_src0 = selInst->getSrc(0);
  G4_Operand *sel_src1 = selInst->getSrc(1);
  G4_Operand *cmp_src0 = cmpInst->getSrc(0);
  G4_Operand *cmp_src1 = cmpInst->getSrc(1);

  // Normalize SEL's predicate state to Plus.
  if (G4_PredState::PredState_Minus == pred->getState()) {
    selInst->swapSrc(0, 1);
    selInst->swapDefUse();
    pred->setState(G4_PredState::PredState_Plus);
    std::swap(sel_src0, sel_src1);
  }

  // source operands of SEL and CMP are reversed or not.
  bool reversed = false;
  G4_CondMod *condMod = cmpInst->getCondMod();

  auto canFold = [=, &reversed](const IR_Builder &builder) {
    G4_CmpRelation condRel =
        pred->asPredicate()->compareOperand(condMod, builder);
    if (!(condRel == Rel_eq && isSameExecSize) &&
        !(condRel == Rel_lt && isSubExecSize))
      return false;

    if (!cmpInst->isWriteEnableInst() &&
        cmpInst->getMaskOption() != selInst->getMaskOption())
      return false;

    // P = cmp.gt A, B
    // C = (+P) sel A, B  => C = sel.gt A, B
    //
    // P = cmp.ne A, B
    // C = (+P) sel A, B  => C = sel.ne A, B
    //
    if (IsEqual(sel_src0, cmp_src0, builder) &&
        IsEqual(sel_src1, cmp_src1, builder))
      return true;

    // Sel operands are reversed.
    // P = cmp.gt A, B
    // C = (+P) sel B, A  => C = sel.le B, A
    //
    // P = cmp.ne A, B
    // C = (+P) sel B, A  => C = sel.ne B, A
    //
    if (IsEqual(sel_src0, cmp_src1, builder) &&
        IsEqual(sel_src1, cmp_src0, builder)) {
      reversed = true;
      // In case of float cmp with possible NaN operands, should not swap
      // operands.
      if (builder.getOption(vISA_finiteMathOnly) ||
          !IS_TYPE_FLOAT_ALL(cmp_src0->getType())) {
        return true;
      }
    }
    return false;
  };

  if (!canFold(builder)) {
    return false;
  }

  // check if cmpInst can be legally moved right before selInst;
  // if it cannot, we cannot fold cmp to sel!.
  INST_LIST_ITER cmpInst_II = selInst_II;
  while (cmpInst_II != BB->begin()) {
    cmpInst_II--;
    if (*cmpInst_II == cmpInst) {
      break;
    }
  }

  // No local def (possible?)
  if (cmpInst_II == BB->begin()) {
    return false;
  }

  // If cmpInst has no WAR harzard b/w cmpInst and selInst, cmpInst
  // can be moved right before selInst.
  if (chkFwdOutputHazard(cmpInst_II, selInst_II)) {
    return false;
  }

  G4_CondModifier mod = condMod->getMod();
  if (reversed)
    mod = G4_CondMod::getReverseCondMod(mod);
  G4_CondMod *cmod =
      builder.createCondMod(mod, condMod->getBase(), condMod->getSubRegOff());
  selInst->setCondMod(cmod);
  selInst->setPredicate(nullptr);

  // update def-use
  // since cmp is deleted, we have to
  // -- remove def-use between cmp and sel
  // -- transfer cmp's remaining use to sel
  // -- remove cmp and its definitions' use
  selInst->removeDefUse(Opnd_pred);
  cmpInst->transferUse(selInst, true);
  cmpInst->removeUseOfInst();
  BB->erase(cmpInst_II);
  return true;
}

// try to fold a pseudo not instruction into its use(s)
// return true if successful
bool Optimizer::foldPseudoNot(G4_BB *bb, INST_LIST_ITER &iter) {
  G4_INST *notInst = *iter;
  vISA_ASSERT(notInst->opcode() == G4_pseudo_not, "expect not instruction");
  if (notInst->getPredicate() || notInst->getCondMod()) {
    return false;
  }

  G4_DstRegRegion *dst = notInst->getDst();
  if (fg.globalOpndHT.isOpndGlobal(dst)) {
    return false;
  }
  if (!notInst->getSrc(0)->isSrcRegRegion()) {
    return false;
  }

  // unfortunately, def-use chain is not always properly maintained, so we have
  // to skip opt even if we can't find a use
  bool canFold = notInst->use_size() > 0;
  for (auto uses = notInst->use_begin(), end = notInst->use_end(); uses != end;
       ++uses) {
    auto &&use = *uses;
    G4_INST *useInst = use.first;
    Gen4_Operand_Number opndPos = use.second;
    if (!useInst->isLogic() || !G4_INST::isSrcNum(opndPos) ||
        useInst->getSingleDef(opndPos) == nullptr /* not single def */) {
      canFold = false;
      break;
    }

    // sanity check
    vASSERT(useInst->getSingleDef(opndPos) == notInst);

    // check the case where flag is partially used
    G4_SrcRegRegion *opnd =
        useInst->getSrc(G4_INST::getSrcNum(opndPos))->asSrcRegRegion();
    if (dst->compareOperand(opnd, builder) != Rel_eq) {
      canFold = false;
      break;
    }
  }

  if (canFold) {
    G4_SrcRegRegion *origUse = notInst->getSrc(0)->asSrcRegRegion();
    if (notInst->getMaskOffset() == 16) {
      // Fold upper bits
      vASSERT(notInst->getExecSize() == g4::SIMD16);
      origUse = builder.createSrcWithNewSubRegOff(origUse, 1);
      notInst->setSrc(origUse, 0);
    }
    for (auto uses = notInst->use_begin(), uend = notInst->use_end();
         uses != uend; ++uses) {
      auto use = *uses;
      G4_INST *useInst = use.first;
      Gen4_Operand_Number opndPos = use.second;
      G4_SrcRegRegion *opnd =
          useInst->getSrc(G4_INST::getSrcNum(opndPos))->asSrcRegRegion();
      int numNot = 1 + (origUse->getModifier() == Mod_Not ? 1 : 0) +
                   (opnd->getModifier() == Mod_Not ? 1 : 0);
      G4_SrcModifier newModifier = numNot & 0x1 ? Mod_Not : Mod_src_undef;
      G4_SrcRegRegion *newSrc = builder.createSrcRegRegion(*origUse);
      newSrc->setModifier(newModifier);
      useInst->setSrc(newSrc, G4_INST::getSrcNum(opndPos));
    }

    for (auto defs = notInst->def_begin(); defs != notInst->def_end(); ++defs) {
      auto def = *defs;
      G4_INST *defInst = def.first;
      notInst->copyUsesTo(defInst, false);
    }
    notInst->removeAllDefs();
    notInst->removeAllUses();
    bb->erase(iter);
    return true;
  }
  return false;
}

/***
this function optimizes the following cases:

case 1:
cmp.gt.P0 s0 s1
(P0) sel d s0 s1
==>
sel.gt.P0 d s0 s1

case 2:
and dst src0 src1   -- other OPs are also optimized: or, xor...
cmp.nz.P0 NULL dst 0
(P0) ...
==>
and.nz.P0 dst src0 src1
(P0) ...
add/addc instructions also handled in case 2. Few more cond
modifiers supported to such arithmetic instructions.

case 3:
cmp.l.P0 NULL src0 src1
cmp.l.P1 NULL src2 src3
and P2 P0 P1   -- other OPs are also optimized: or, xor...
==>
cmp.l.P2 NULL src0 src1
(P2)cmp.l.P2 NULL src2 src3

case 4:
mov (1) P0 Imm  (NoMask)
(P0) mov (8) r[A0, 0] src0 src1
==>
smov (8) r[A0, 0] src0 src1 Imm

case 5:
pseudo_not (1) P2 P1
and (1) P4 P3 P2
==>
and (1) P4 P3 ~P1
*/

void Optimizer::optimizeLogicOperation() {
  G4_Operand *dst = NULL;
  bool resetLocalIds = false;
  bool doLogicOpt = builder.getOption(vISA_LocalFlagOpt);

  if (!doLogicOpt) {
    // we still need to expand the pseudo logic ops
    for (auto bb : fg) {
      for (auto I = bb->begin(), E = bb->end(); I != E; ++I) {
        auto inst = *I;
        if (inst->isPseudoLogic()) {
          expandPseudoLogic(builder, bb, I);
        }
      }
    }
    return;
  }

  for (G4_BB *bb : fg) {
    INST_LIST_ITER ii;
    if ((bb->begin() == bb->end())) {
      continue;
    }
    resetLocalIds = false;
    ii = bb->end();
    do {
      ii--;
      G4_INST *inst = *ii;
      G4_opcode op = inst->opcode();
      dst = inst->getDst();
      bool nullDst = inst->hasNULLDst();
      G4_Declare *dcl = nullptr;
      if (dst) {
        dcl = dst->getTopDcl();
      }

      if ((op != G4_sel && op != G4_cmp && !inst->canSupportCondMod() &&
           !inst->isPseudoLogic()) ||
          !dst || nullDst || (dcl && dcl->isOutput())) {
        continue;
      }

      INST_LIST_ITER next_iter = std::next(ii);

      if (!resetLocalIds) {
        bb->resetLocalIds();
        resetLocalIds = true;
      }

      // case 5
      if (inst->opcode() == G4_pseudo_not) {
        bool folded = foldPseudoNot(bb, ii);
        if (folded) {
          ii = next_iter;
          continue;
        }
      }

      // case 1
      if (ii != bb->begin() && op == G4_sel && inst->getPredicate() &&
          !inst->getCondMod()) {
        foldCmpSel(bb, inst, ii);
      } else if (builder.hasSmov() && inst->opcode() == G4_mov &&
                 inst->getPredicate() == NULL && inst->getCondMod() == NULL &&
                 inst->getExecSize() == g4::SIMD1 && inst->getSrc(0)->isImm() &&
                 inst->getDst()->isFlag() && next_iter != bb->end() &&
                 (*next_iter)->opcode() == G4_mov) {
        // case 4
        G4_INST *next_inst = *next_iter;
        if (createSmov(bb, inst, next_inst)) {
          bb->erase(ii);
          ii = next_iter;
        }
        continue;
      } else if (!inst->getPredicate() && inst->canSupportCondMod()) {
        // FIXME: why this condition?
        if (op == G4_pseudo_mad && inst->getExecSize() == g4::SIMD1) {
          continue;
        }

        // case 2
        foldCmpToCondMod(bb, ii);
      } else if (inst->getPredicate() == NULL && inst->isPseudoLogic()) {
        bool merged = false;

        if (op == G4_pseudo_and || op == G4_pseudo_or) {
          merged = foldPseudoAndOr(bb, ii);
        }

        // translate the pseudo op
        if (!merged) {
          expandPseudoLogic(builder, bb, ii);
        }
      }
    } while (ii != bb->begin());
  }
}

// see if we can fold a pseudo and/or instruction with previous cmp
// returns true if successful, and ii (inst-list-iter) is also updated
// to the next inst
bool Optimizer::foldPseudoAndOr(G4_BB *bb, INST_LIST_ITER &ii) {
  // case 3

  // optimization should apply even when the dst of the pseudo-and/pseudo-or is
  // global, since we are just hoisting it up, and WAR/WAW checks should be
  // performed as we search for the src0 and src1 inst. Also need to check if
  // the mask option of the pseudo-and/pseudo-or matches with the options of
  // the defining instructions when dst is global.

  G4_INST *inst = *ii;
  // look for def of srcs
  G4_Operand *src0 = inst->getSrc(0);
  G4_Operand *src1 = inst->getSrc(1);

  /*
  Old logic would scan from inst (and/or) up until it encountered
  def instructions that did full write.
  It would scan from def instruction down to inst looking for WAW, WAR
  conflicts between def instruction and intermediate instructions.
  Basically insuring that there were no partial writes in to flag registers
  use by the inst.

  The new code uses defInstList directly, and aborts if there are more then are
  two definitions. Which means there is more then one instruction writing to
  source. Disadvantage of that is that it is less precise. For example if we
  are folding in to closest definition then before it was OK, but now will be
  disallowed.
  */
  int32_t maxSrc1 = 0;
  int32_t maxSrc2 = 0;
  G4_INST *defInstructions[2] = {nullptr, nullptr};
  G4_INST *src0DefInst = nullptr;
  G4_INST *src1DefInst = nullptr;

  // Picks the latest two instructions to compare.
  // local IDs are reset at the beginning of this function.
  if (inst->def_size() < 2) {
    return false;
  }
  // trying to find latest instructions that define src0 and src1
  for (auto I = inst->def_begin(), E = inst->def_end(); I != E; ++I) {
    G4_INST *srcInst = I->first;
    if ((I->second == Opnd_src0) && (srcInst->getLocalId() >= maxSrc1)) {
      maxSrc1 = srcInst->getLocalId();
      defInstructions[0] = srcInst;
      src0DefInst = srcInst;
    } else if ((I->second == Opnd_src1) && (srcInst->getLocalId() >= maxSrc2)) {
      maxSrc2 = srcInst->getLocalId();
      defInstructions[1] = srcInst;
      src1DefInst = srcInst;
    }
  }

  // Making sure that dst of pseudo instruction is not used or defined between
  // pseudo instruction and the first definition of the source
  if (defInstructions[0] && defInstructions[1]) {
    // make defInst[0] the closer def to the pseudo-and/or
    if (maxSrc2 > maxSrc1) {
      std::swap(defInstructions[0], defInstructions[1]);
      std::swap(maxSrc1, maxSrc2);
    }
    // Doing backward scan until earliest src to make sure dst of and/or is not
    // being written to or being read
    /*
    handling case like in spmv_csr
    cmp.lt (M1, 1) P15 V40(0,0)<0;1,0> 0x10:w /// $191
    cmp.lt (M1, 1) P16 V110(0,0)<0;1,0> V34(0,0)<0;1,0> /// $192
    and    (M1, 1) P16 P16 P15 /// $193
    */
    if (chkBwdOutputHazard(defInstructions[1], ii, defInstructions[0])) {
      return false;
    }
  } else {
    return false;
  }

  // check if the defInst can be folded into the pseudo and/or for a given
  // source folding is legal if
  // -- src is the only use of defInst
  // -- def completely defines the src
  // -- def inst does not have predicate
  // -- the defInst closer to the pseudo inst is a cmp without pred
  // -- def inst is not global operand
  // the last condition can be relaxed if defInst is the same as the inst's dst,
  // as they will be the same flag
  if (!(defInstructions[0]->opcode() == G4_cmp &&
        defInstructions[0]->getPredicate() == nullptr)) {
    return false;
  }

  auto checkSource = [this, inst](G4_INST *defInst, G4_Operand *src) {
    if (defInst == nullptr) {
      return false;
    }

    if (defInst->use_size() > 1) {
      return false;
    }
    G4_Operand *curr_dst = defInst->getCondMod()
                               ? defInst->getCondMod()
                               : (G4_Operand *)defInst->getDst();

    G4_CmpRelation rel = curr_dst->compareOperand(src, builder);
    if (rel != Rel_eq ||
        (defInst->getPredicate() && defInst->opcode() != G4_sel)) {
      return false;
    }

    if (fg.globalOpndHT.isOpndGlobal(curr_dst)) {
      G4_DstRegRegion *dst = inst->getDst();
      if (dst->compareOperand(curr_dst, builder) != Rel_eq) {
        return false;
      }
    }

    return true;
  };

  if (!checkSource(src0DefInst, src0) || !checkSource(src1DefInst, src1)) {
    return false;
  }

  // Check if mask options are mismatched between the pseudo-and/pseudo-or and
  // its defining instructions.
  if ((inst->getMaskOption() != src0DefInst->getMaskOption() ||
       inst->getMaskOption() != src1DefInst->getMaskOption()) &&
      fg.globalOpndHT.isOpndGlobal(inst->getDst()) &&
      !fg.builder->alwaysAllowGlobalFlagOpt())
    return false;

  // do the case 3 optimization

  G4_PredState ps =
      (inst->opcode() == G4_pseudo_or) ? PredState_Minus : PredState_Plus;
  G4_INST *first_inst = defInstructions[1];
  G4_INST *second_inst = defInstructions[0];

  // unify subregister according to logic op dst
  G4_VarBase *curr_base = inst->getDst()->getBase()->asRegVar();
  unsigned short curr_subreg = 0;

  G4_Operand *first_def, *second_def;
  G4_VarBase *first_def_base, *second_def_base;
  int first_def_subreg, second_def_subreg;

  // change condmod and predicate of second inst

  if (first_inst->getCondMod()) {
    first_def = first_inst->getCondMod();
    first_def_base = first_def->asCondMod()->getBase();
    first_def_subreg = first_def->asCondMod()->getSubRegOff();
  } else {
    first_def = first_inst->getDst();
    first_def_base = first_def->asDstRegRegion()->getBase()->asRegVar();
    first_def_subreg = 0;
  }

  if (second_inst->getCondMod()) {
    second_def = second_inst->getCondMod();
    second_def_base = second_def->asCondMod()->getBase();
    second_def_subreg = second_def->asCondMod()->getSubRegOff();
  } else {
    second_def = second_inst->getDst();
    second_def_base = second_def->asDstRegRegion()->getBase()->asRegVar();
    second_def_subreg = 0;
  }

  bool change_flag = false;
  if (second_inst->getCondMod() &&
      (second_def_base != curr_base || second_def_subreg != curr_subreg)) {
    change_flag = true;
    G4_CondMod *new_condMod = builder.createCondMod(
        second_inst->getCondMod()->getMod(), curr_base, curr_subreg);

    second_inst->setCondMod(new_condMod);
  }
  // create a predicate

  G4_Predicate *new_pred = builder.createPredicate(ps, curr_base, curr_subreg);

  second_inst->setPredicate(new_pred);

  if (change_flag) {
    for (USE_EDGE_LIST_ITER iter = second_inst->use_begin();
         iter != second_inst->use_end(); ++iter) {
      G4_INST *curr_inst = (*iter).first;
      if (curr_inst == inst) {
        continue;
      }
      if (curr_inst->getPredicate() &&
          (curr_inst->getPredicate()->getBase() != curr_base ||
           curr_inst->getPredicate()->getSubRegOff() != curr_subreg) &&
          curr_inst->getPredicate()->compareOperand(second_def, builder) ==
              Rel_eq) {
        curr_inst->setPredicate(builder.duplicateOperand(new_pred));
      }

      for (int k = 0; k < curr_inst->getNumSrc(); k++) {
        G4_Operand *curr_src = curr_inst->getSrc(k);
        if (curr_src->isSrcRegRegion() &&
            !(curr_inst->isMath() && k == 1 && curr_src->isNullReg())) {
          if (curr_src->asSrcRegRegion()->compareOperand(second_def, builder) ==
              Rel_eq) {
            G4_SrcRegRegion *new_src_opnd = builder.createSrcRegRegion(
                curr_src->asSrcRegRegion()->getModifier(),
                curr_src->asSrcRegRegion()->getRegAccess(),
                inst->getDst()->getBase(), 0, 0,
                curr_src->asSrcRegRegion()->getRegion(),
                curr_src->asSrcRegRegion()->getType());

            curr_inst->setSrc(new_src_opnd, k);
          }
        }
      }
    }
  }

  if (first_def_base != curr_base || first_def_subreg != curr_subreg) {
    if (first_inst->getCondMod() && first_def->isCondMod()) {
      G4_CondMod *new_condMod = builder.createCondMod(
          first_inst->getCondMod()->getMod(), curr_base, curr_subreg);
      first_inst->setCondMod(new_condMod);
    } else {
      first_inst->setDest(builder.duplicateOperand(inst->getDst()));
    }
    for (USE_EDGE_LIST_ITER iter = first_inst->use_begin();
         iter != first_inst->use_end(); ++iter) {
      G4_INST *curr_inst = (*iter).first;
      if (curr_inst == inst) {
        continue;
      }
      if (curr_inst->getPredicate() &&
          (curr_inst->getPredicate()->getBase() != curr_base ||
           curr_inst->getPredicate()->getSubRegOff() != curr_subreg) &&
          curr_inst->getPredicate()->compareOperand(first_def, builder) ==
              Rel_eq) {
        curr_inst->setPredicate(builder.duplicateOperand(new_pred));
      }

      for (int k = 0; k < curr_inst->getNumSrc(); k++) {
        G4_Operand *curr_src = curr_inst->getSrc(k);
        if (curr_src->isSrcRegRegion() &&
            !(curr_inst->isMath() && k == 1 && curr_src->isNullReg())) {
          if (curr_src->asSrcRegRegion()->compareOperand(first_def, builder) ==
              Rel_eq) {
            G4_SrcRegRegion *new_src_opnd = builder.createSrcRegRegion(
                curr_src->asSrcRegRegion()->getModifier(),
                curr_src->asSrcRegRegion()->getRegAccess(), curr_base, 0,
                curr_subreg, curr_src->asSrcRegRegion()->getRegion(),
                curr_src->asSrcRegRegion()->getType());
            curr_inst->setSrc(new_src_opnd, k);
          }
        }
      }
    }
  }

  // update def-use
  // since inst (the pseudo-and/or) is deleted and the same flag is used for
  // first and second inst, we have to
  // -- transfer inst's use to the second_inst
  // -- add def-use between first_inst and second_inst
  // -- remove inst from first_inst and second_inst's use
  inst->transferUse(second_inst, true);
  first_inst->addDefUse(second_inst, Opnd_pred);
  inst->removeUseOfInst();

  INST_LIST_ITER new_iter = ii;
  ++ii;
  bb->erase(new_iter);
  return true;
}

/***  The beginning of message header optimization  ***/

/*
 * reuse the previous header which can save the redundant definitions.
 */
void MSGTable::reusePreviousHeader(G4_INST *dest, G4_INST *source,
                                   G4_INST *mDot2, IR_Builder &builder) {
  if (dest == NULL)
    return;
  if (source != NULL) {
    dest->setDest(builder.duplicateOperand(source->getDst()));
  } else {
    short subRegOff = dest->getDst()->getSubRegOff();
    auto newDst = builder.createDstWithNewSubRegOff(mDot2->getDst(), subRegOff);
    dest->setDest(newDst);
  }
}

/*
 * insert a mov, from the previous header to current header
 * this is only required for the instruction,
 * whose payload size >1 so that we can't directly reuse
 * the previous header. keep a copy from the previous header,
 * so that we only need to update the fields that need to be changed.
 */
void MSGTable::insertHeaderMovInst(G4_INST *source_send, IR_Builder &builder,
                                   G4_BB *bb) {
  G4_INST *inst = NULL;
  INST_LIST_ITER pos;

  switch (first) {
  case HEADER_FULL_REGISTER:
    inst = m;
    pos = m_it;
    break;
  case HEADER_X:
    inst = mDot0;
    pos = mDot0_it;
    break;
  case HEADER_Y:
    inst = mDot1;
    pos = mDot1_it;
    break;
  case HEADER_SIZE:
    inst = mDot2;
    pos = mDot2_it;
    break;
  default:
    vISA_ASSERT_UNREACHABLE(
        "did not catch the first def instruction correctly");
    return;
  }

  // mov(8) m_new<1>, m_old<8;8:1>  {Align1}
  G4_Declare *srcDcl =
      source_send->getSrc(0)->getBase()->asRegVar()->getDeclare();
  G4_SrcRegRegion *newSrcOpnd =
      builder.createSrcRegRegion(srcDcl, builder.getRegionStride1());

  G4_INST *mov =
      builder.createMov(m->getExecSize(), builder.duplicateOperand(m->getDst()),
                        newSrcOpnd, m->getOption(), false);
  bb->insertBefore(pos, mov);

  // maintain def-use.
  //
  // (1) Uses. m is ready to be deleted.
  m->transferUse(mov);

  // (2) Defs
  // The defs should be from definitions for source->send's src(0).
  //
  // mov (8) V244(1,0)<1>:ud V88(0,0)<8;8,1>:ud {Align1, NoMask}
  // mov (8) V244(0,0)<1>:ud r0.0<8;8,1>:ud {Align1, NoMask}
  // mov (1) V244(0,2)<1>:ud 0x1f:ud {Align1, NoMask}
  // mov (1) V244(0,0)<1>:ud 0:uw {Align1, NoMask}
  // mov (1) V244(0,1)<1>:ud 0:uw {Align1, NoMask}
  // add (1) a0.0<1>:ud r1.1<0;1,0>:ud 0x40a8000:ud {Align1, NoMask}
  // source_send:
  // send (8) null<1>:ud V244(0,0)<8;8,1>:ud a0.0<0;1,0>:ud {Align1, NoMask}
  // mov (8) V89(0,0)<1>:d V34_histogram(1,0)<8;8,1>:d {Align1, Q1}
  // mov (8) V246(1,0)<1>:ud V89(0,0)<8;8,1>:ud {Align1, NoMask}
  // mov (8) V246(0,0)<1>:ud V244(0,0)<8;8,1>:ud {Align1, NoMask} <-- mov
  // mov (8) V246(0,0)<1>:ud r0.0<8;8,1>:ud {Align1, NoMask}      <-- m
  //
  // There are more than one defs here.
  //
  // Note that
  //
  // mov (8) V244(1,0)<1>:ud V88(0,0)<8;8,1>:ud {Align1, NoMask}
  //
  // is a definition of send but not for mov. We enable checked
  // while copying defs.
  source_send->copyDef(mov, Opnd_src0, Opnd_src0, /*checked*/ true);
}

/*
 * compare the two instructions
 * they must have:
 * the same instruction opcode, predicate, condmodifier, optionString
 * the same dst, and number of src args
 */
bool Optimizer::isHeaderOptCandidate(G4_INST *dst, G4_INST *src) {
  if (!dst || !src) {
    return true;
  }

  // Compare instructions
  if (dst->opcode() != src->opcode() || dst->getOption() != src->getOption() ||
      dst->getExecSize() != src->getExecSize() ||
      dst->getPredicate() != src->getPredicate() ||
      dst->getCondMod() != src->getCondMod()) {
    return false;
  }

  if (dst->getNumSrc() != src->getNumSrc()) {
    return false;
  }

  // Compare destination args
  G4_Operand *dst_dest = dst->getDst();
  G4_Operand *src_dest = src->getDst();
  if (!dst_dest || !src_dest) {
    return false;
  }

  return true;
}

/*
 * compare the two instructions to see if they are redundent
 * they must have:
 * the same src args
 * the same def
 */
bool Optimizer::isHeaderOptReuse(G4_INST *dst, G4_INST *src) {
  if (!dst && !src) {
    return true;
  }
  if (!dst || !src) {
    return false;
  }

  for (unsigned int i = 0, numSrc = dst->getNumSrc(); i < numSrc; i++) {
    G4_Operand *opnd = dst->getSrc(i);
    if (opnd && opnd->compareOperand(src->getSrc(i), builder) != Rel_eq) {
      return false;
    }
  }

  // The same number of def instructions
  if (dst->def_size() != src->def_size()) {
    return false;
  }

  if (dst->def_size() == 0) {
    return true; // both have no def at all
  }

  for (auto ii = dst->def_begin(); ii != dst->def_end(); ii++) {
    bool sameDef = false;
    for (auto jj = src->def_begin(); jj != src->def_end(); jj++) {
      if ((*ii).first == (*jj).first && (*ii).second == (*jj).second) {
        sameDef = true;
        break; // break the inner jj loop
      }
    }
    if (sameDef == false) {
      return false;
    }
  }
  return true;
}

bool Optimizer::headerOptValidityCheck(MSGTable *dest, MSGTable *source) {
  if (!isHeaderOptCandidate(dest->a0Dot0, source->a0Dot0) ||
      !isHeaderOptCandidate(dest->mDot0, source->mDot0) ||
      !isHeaderOptCandidate(dest->m, source->m) ||
      !isHeaderOptCandidate(dest->mDot1, source->mDot1) ||
      !isHeaderOptCandidate(dest->mDot2, source->mDot2)) {
    return false;
  }

  if (dest->m) {
    if (!(dest->m->hasOneUse() && dest->m->use_front().first == dest->send)) {
      return false;
    }
  }
  if (dest->mDot0) {
    if (!(dest->mDot0->hasOneUse() &&
          dest->mDot0->use_front().first == dest->send)) {
      return false;
    }
  }
  if (dest->mDot1) {
    if (!(dest->mDot1->hasOneUse() &&
          dest->mDot1->use_front().first == dest->send)) {
      return false;
    }
  }
  if (dest->mDot2) {
    if (!(dest->mDot2->hasOneUse() &&
          dest->mDot2->use_front().first == dest->send)) {
      return false;
    }
  }

  if (dest->send && dest->send->getSrc(0) &&
      dest->send->getSrc(0)->getTopDcl() && source->send &&
      source->send->getSrc(0) && source->send->getSrc(0)->getTopDcl()) {
    unsigned short dstSize, sourceSize;
    dstSize = dest->send->getSrc(0)->getTopDcl()->getTotalElems() *
              dest->send->getSrc(0)->getTopDcl()->getElemSize();
    sourceSize = source->send->getSrc(0)->getTopDcl()->getTotalElems() *
                 source->send->getSrc(0)->getTopDcl()->getElemSize();
    if (dstSize != sourceSize) {
      return false;
    }
  }

  return true;
}

// a class to store all presently valid values, each value is an instruction
// if the number of values exceeds the max allowed, the oldest is removed
class InstValues {
  const int maxNumVal;
  std::list<G4_INST *> values;

public:
  InstValues(int maxCount) : maxNumVal(maxCount) {}

  void addValue(G4_INST *inst) {
    if (values.size() == maxNumVal) {
      values.pop_front();
    }
    values.push_back(inst);
  }

  // delete all values that may be invalid after inst
  void deleteValue(G4_INST *inst) {
    if (inst->isOptBarrier()) {
      values.clear();
      return;
    }

    auto hasIndirectGather = [](G4_INST *inst) {
      for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
        auto src = inst->getSrc(i);
        if (src && src->isSrcRegRegion() &&
            src->asSrcRegRegion()->isIndirect() &&
            src->asSrcRegRegion()->getRegion()->isRegionWH()) {
          return true;
        }
      }
      return false;
    };

    if (hasIndirectGather(inst)) {
      // optimization is likely unprofitable due to high address register
      // pressure in this case. more importantly, it may actually cause RA to
      // fail since we don't spill physical a0.0
      values.clear();
      return;
    }

    G4_DstRegRegion *dst = inst->getDst();
    auto interferes = [dst](G4_INST *valInst) {
      const IR_Builder &builder = valInst->getBuilder();
      G4_DstRegRegion *valDst = valInst->getDst();
      if (dst->compareOperand(valDst, builder) != Rel_disjoint) {
        return true;
      }
      for (int i = 0, numSrc = valInst->getNumSrc(); i < numSrc; ++i) {
        G4_Operand *src = valInst->getSrc(i);
        if (src != nullptr &&
            dst->compareOperand(src, builder) != Rel_disjoint) {
          return true;
        }
      }
      return false;
    };
    if (dst != nullptr) {
      values.remove_if(interferes);
    }
  }

  G4_INST *findValue(G4_INST *inst) {
    for (auto valInst : values) {
      if (inst->opcode() != valInst->opcode() ||
          inst->getExecSize() != valInst->getExecSize()) {
        continue;
      }
      // skip flags for now
      if ((inst->getPredicate() || valInst->getPredicate()) ||
          (inst->getCondMod() || valInst->getCondMod())) {
        continue;
      }
      // emask checks
      if (inst->getMaskOffset() != valInst->getMaskOffset() ||
          inst->isWriteEnableInst() ^ valInst->isWriteEnableInst()) {
        continue;
      }
      // all source should be isomorphic (same type/shape)
      bool srcMatch = true;
      for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
        G4_Operand *src = inst->getSrc(i);
        G4_Operand *valSrc = valInst->getSrc(i);
        if (src == nullptr || valSrc == nullptr ||
            src->compareOperand(valSrc, inst->getBuilder()) != Rel_eq) {
          srcMatch = false;
          break;
        }
      }
      if (srcMatch) {
        return valInst;
      }
    }
    return nullptr;
  }

  void clear() { values.clear(); }
};

G4_Operand *Optimizer::updateSendsHeaderReuse(
    std::vector<std::vector<G4_INST *>> &instLookUpTable,
    std::vector<G4_INST *> &iVector, INST_LIST_ITER endIter) {
  int bSize = (int)iVector.size();
  for (auto &Cache : instLookUpTable) {
    if (Cache.size() == bSize) {
      bool match[8] = {false};
      bool anyMatch = false;
      for (int index = 0; index < bSize; ++index) {
        G4_INST *cInst = Cache[index];
        G4_INST *iInst = iVector[index];

        // opcode check
        if (cInst->opcode() != iInst->opcode() ||
            cInst->getExecSize() != iInst->getExecSize()) {
          continue;
        }
        // flag check
        if (cInst->getPredicate() != iInst->getPredicate() ||
            cInst->getCondMod() != iInst->getCondMod()) {
          continue;
        }
        // emask check
        if (cInst->getMaskOffset() != iInst->getMaskOffset() ||
            cInst->isWriteEnableInst() ^ iInst->isWriteEnableInst()) {
          continue;
        }
        // dst check
        G4_DstRegRegion *cDstRgn = cInst->getDst();
        G4_DstRegRegion *iDstRgn = iInst->getDst();
        if (cDstRgn->getRegOff() != iDstRgn->getRegOff() ||
            cDstRgn->getSubRegOff() != iDstRgn->getSubRegOff() ||
            cDstRgn->getHorzStride() != iDstRgn->getHorzStride() ||
            cDstRgn->getRegAccess() != iDstRgn->getRegAccess() ||
            cDstRgn->getType() != iDstRgn->getType()) {
          continue;
        }

        // all source should be isomorphic (same type/shape) and unaltered
        // between declaration and reuse
        bool srcMatch = true;

        for (int iSrc = 0, numSrc = cInst->getNumSrc(); iSrc < numSrc; ++iSrc) {
          G4_Operand *cOpnd = cInst->getSrc(iSrc);
          G4_Operand *iOpnd = iInst->getSrc(iSrc);
          if (cOpnd == nullptr || iOpnd == nullptr ||
              cOpnd->compareOperand(iOpnd, builder) != Rel_eq) {
            srcMatch = false;
            break;
          }
        }

        if (chkBwdWARdep(cInst, endIter))
          srcMatch = false;

        match[index] = srcMatch;
        anyMatch |= srcMatch;
      }

      if (anyMatch) {
        // at least partial match

        for (int index = 0; index < bSize; ++index) {
          G4_INST *cInst = Cache[index];
          G4_INST *iInst = iVector[index];

          // mark it if there is match
          if (match[index]) {
            iInst->markDead();
            continue;
          }

          // create new dst region to replace one in iVector[i]
          G4_DstRegRegion *cDst = cInst->getDst();
          G4_DstRegRegion *iDst = iInst->getDst();
          G4_DstRegRegion *newDstRegion = builder.createDst(
              cDst->getTopDcl()->getRegVar(), iDst->getRegOff(),
              iDst->getSubRegOff(), iDst->getHorzStride(), iDst->getType());
          iInst->setDest(newDstRegion);

          // update the look-up table list
          Cache[index] = iInst;
        }
        return Cache[0]->getDst();
      }
    }
  }
  return nullptr;
}

void Optimizer::cleanupA0Movs() {
  for (auto bb : fg) {
    InstValues values(4);
    for (auto iter = bb->begin(), iterEnd = bb->end(); iter != iterEnd;) {
      G4_INST *inst = *iter;

      auto isDstExtDesc = [](G4_INST *inst) {
        G4_DstRegRegion *dst = inst->getDst();
        if (dst && dst->getTopDcl() && dst->getTopDcl()->isMsgDesc()) {
          // check that its single use is at src3 of split send
          if (inst->use_size() != 1) {
            return false;
          }
          auto use = inst->use_front();
          G4_INST *useInst = use.first;
          if (useInst->isSend()) {
            return true;
          }
        }
        return false;
      };

      if (isDstExtDesc(inst)) {
        G4_INST *valInst = values.findValue(inst);
        if (valInst != nullptr) {
          VISA_DEBUG_VERBOSE({
            std::cout << "can replace \n";
            inst->emit(std::cout);
            std::cout << "\n with \n";
            valInst->emit(std::cout);
            std::cout << "\n";
          });
          for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) {
            // each use is in the form of A0(0,0)<0;1,0>:ud in a send
            G4_INST *useInst = I->first;
            Gen4_Operand_Number num = I->second;
            vISA_ASSERT(useInst->isSend(), "use inst must be a send");
            G4_SrcRegRegion *newExDesc =
                builder.createSrc(valInst->getDst()->getBase(), 0, 0,
                                  builder.getRegionScalar(), Type_UD);
            useInst->setSrc(newExDesc, useInst->getSrcNum(num));
          }
          (*iter)->removeAllDefs();
          (*iter)->transferUse(valInst);
          iter = bb->erase(iter);
          continue;
        } else {
          VISA_DEBUG_VERBOSE({
            std::cout << "add new value:\n";
            inst->emit(std::cout);
            std::cout << "\n";
          });
          // this is necessary since for msg desc we always the physical a0.0,
          // so a new inst will invalidate the previous one
          values.deleteValue(inst);
          values.addValue(inst);
        }
      } else {
        G4_DstRegRegion *dst = inst->getDst();
        if (dst && dst->isDirectAddress()) {
          // If the address register is used for none extdesc
          values.clear();
        } else {
          values.deleteValue(inst);
        }
      }
      ++iter;
    }
  }
}

//
// Perform value numbering on writes to the extended msg descriptor for bindless
// access of the form op (1) a0.2<1>:ud src0 src1 src2 {NoMask} and remove
// redundant instructions.  This is limited to within BB
//
void Optimizer::cleanupBindless() {
  kernel.fg.resetLocalDataFlowData();
  kernel.fg.localDataFlowAnalysis();

  // Perform send header cleanup for bindless sampler/surface
  for (auto bb : fg) {
    std::vector<std::vector<G4_INST *>> instLookUpTable;
    std::vector<G4_INST *> instVector;
    for (auto iter = bb->begin(), iterEnd = bb->end(); iter != iterEnd;
         ++iter) {
      G4_INST *inst = *iter;
      G4_DstRegRegion *dst = inst->getDst();

      if (dst != nullptr && dst->getTopDcl() != nullptr &&
          dst->getTopDcl()->getCapableOfReuse()) {
        // it is header definition instruction
        instVector.push_back(inst);
      }

      if (inst->isSplitSend()) {
        G4_Operand *header = inst->getSrc(0);
        G4_Operand *exDesc = inst->getSrc(3);

        // When header has multiple uses other than send, be conservative and
        // do not reuse the cached value. It could be introduced by
        // optimizations like LVN.
        if (header->getTopDcl() && header->getTopDcl()->getCapableOfReuse() &&
            exDesc->isSrcRegRegion() && !instVector.empty() &&
            std::all_of(instVector.begin(), instVector.end(), [&](G4_INST *i) {
              return i->hasOneUse() && i->use_front().first == inst;
            })) {

          // check if we can reuse cached values.
          G4_Operand *value =
              updateSendsHeaderReuse(instLookUpTable, instVector, iter);
          if (!value) {
            // no found, cache the header
            instLookUpTable.push_back(instVector);
          } else {
            // update sends header src
            G4_SrcRegRegion *newHeaderRgn = builder.createSrc(
                value->getBase(), 0, 0, builder.getRegionStride1(), Type_UD);
            inst->setSrc(newHeaderRgn, 0);
          }
        }
        // clear header def
        instVector.clear();
      } else if (inst->isSend()) {
        instVector.clear();
      }
    }
    bb->erase(std::remove_if(bb->begin(), bb->end(),
                             [](G4_INST *inst) { return inst->isDead(); }),
              bb->end());
  }

  for (auto bb : fg) {
    InstValues values(4);
    for (auto iter = bb->begin(), iterEnd = bb->end(); iter != iterEnd;) {
      G4_INST *inst = *iter;

      auto isDstExtDesc = [](G4_INST *inst) {
        G4_DstRegRegion *dst = inst->getDst();
        if (dst && dst->getTopDcl() && dst->getTopDcl()->isMsgDesc()) {
          // if a use is something other than a send, do not perform the
          // optimization
          for (auto use = inst->use_begin(); use != inst->use_end(); use++) {
            G4_INST* useInst = use->first;
            if (!useInst->isSend())
              return false;
          }
          return true;
        }
        return false;
      };

      if (isDstExtDesc(inst)) {
        G4_INST *valInst = values.findValue(inst);
        if (valInst != nullptr) {
          VISA_DEBUG_VERBOSE({
            std::cout << "can replace \n";
            inst->emit(std::cout);
            std::cout << "\n with \n";
            valInst->emit(std::cout);
            std::cout << "\n";
          });
          for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) {
            // each use is in the form of A0(0,0)<0;1,0>:ud in a send
            G4_INST *useInst = I->first;
            Gen4_Operand_Number num = I->second;
            vISA_ASSERT(useInst->isSend(), "use inst must be a send");
            G4_SrcRegRegion *newExDesc =
                builder.createSrc(valInst->getDst()->getBase(), 0, 0,
                                  builder.getRegionScalar(), Type_UD);
            useInst->setSrc(newExDesc, useInst->getSrcNum(num));
          }
          iter = bb->erase(iter);
          continue;
        } else {
          VISA_DEBUG_VERBOSE({
            std::cout << "add new value:\n";
            inst->emit(std::cout);
            std::cout << "\n";
          });
          // this is necessary since for msg desc we always the physical a0.0,
          // so a new inst will invalidate the previous one
          values.deleteValue(inst);
          values.addValue(inst);
        }
      } else {
        G4_DstRegRegion *dst = inst->getDst();
        if (dst && dst->isDirectAddress()) {
          // If the address register is used for none extdesc
          values.clear();
        } else {
          values.deleteValue(inst);
        }
      }
      ++iter;
    }
  }
}

/*
 * compare the two send and their defs
 * determine whether to remove the redundant mov inst
 * or reuse the previous header
 *
 * 1    mov (8) V152(0,0)<1>:ud r0.0<8;8,1>:ud {Align1, NoMask}
 * 2    mov (1) V152(0,2)<1>:ud 0x7000f:ud {Align1, NoMask}
 * 3    mov (1) V152(0,0)<1>:ud 0:uw {Align1, NoMask}
 * 4    mov (1) V152(0,1)<1>:ud 0:uw {Align1, NoMask}
 * 5    add (1) a0.0<1>:ud r1.0<0;1,0>:ud 0x2490000:ud {Align1, NoMask}
 * 6    send (8) V32_in(0,0)<1>:ud V152(0,0)<8;8,1>:ud a0.0<0;1,0>:ud {Align1,
 * NoMask}
 *
 * 7    mov (8) V154(0,0)<1>:ud r0.0<8;8,1>:ud {Align1, NoMask}
 * 8    mov (1) V152(0,2)<1>:ud 0x1f:ud {Align1, NoMask}
 * 9    mov (1) V154(0,0)<1>:ud 0:uw {Align1, NoMask}
 * 10   mov (1) V154(0,1)<1>:ud 0:uw {Align1, NoMask}
 * 11   add (1) a0.0<1>:ud r1.1<0;1,0>:ud 0x2190000:ud {Align1, NoMask}
 * 12   send (8) V33(0,0)<1>:d V152(0,0)<8;8,1>:ud a0.0<0;1,0>:ud {Align1,
 * NoMask}
 *
 * It is rather tricky to maintain def-use chains for this optimization.
 * The send instruction (Line 12) can reuse Inst[1, 3, 4] and need to
 * keep Inst[8, 11]. The defs for send at line 12 is Inst[1, 3, 4, 8, 11]
 * and the defs for send at line 6 is Inst[1, 2, 3, 4, 5].
 *
 * We take the following approach to maintain def-use.
 *
 * - Starting with initial valid defs, [7, 8, 9, 10, 11].
 *
 * - Each to be removed instruction transfers its use to a proper
 *   previous definition.
 *
 * - Each to be kept instruction remains, even there may have changes
 *   in its definition. For example, dst of move instruction at Line 8
 *   is changed from V154 to V152, but no def-use modification should
 *   be made for this instruction.
 *
 * - No def-use modification should be made to the final send, since
 *   all have been properly set.
 */
void Optimizer::optMessageHeaders(MSGTableList &msgList, G4_BB *bb,
                                  DEFA0 &myA0) {
  unsigned char redundancyCount = 0;
  bool isSameX, isSameY, isSameSize;
  bool replaceOldHeader = false;

  uint16_t payLoadSize;

  MSGTable *dest, *source;
  MSGTable_ITER iter = msgList.begin();

  if (iter == msgList.end()) {
    return;
  }
  dest = *iter; // dest is the front
  iter++;
  if (iter == msgList.end()) {
    return;
  }
  source = *iter; // source is the cached one

  if (!headerOptValidityCheck(dest, source)) {
    return;
  }

  if (isHeaderOptReuse(dest->a0Dot0, myA0.pred) && !myA0.isA0Redef) {
    // Transfer uses of dstDot0 to myA0.pred. This removes uses from
    // dest->a0Dot0 and add to myA0.pred. dest->a0Dot0 to be deleted.
    dest->a0Dot0->transferUse(myA0.pred, /*keepExisting*/ true);
    dest->a0Dot0->markDead();
  }

  payLoadSize = dest->send->getMsgDesc()->getSrc0LenRegs();

  isSameX = isHeaderOptReuse(dest->mDot0, source->mDot0) && !source->isXRedef;

  isSameY = isHeaderOptReuse(dest->mDot1, source->mDot1) && !source->isYRedef;

  isSameSize =
      isHeaderOptReuse(dest->mDot2, source->mDot2) && !source->isSizeRedef;

  if (isSameX && dest->mDot0) {
    redundancyCount++;
  }
  if (isSameY && dest->mDot1) {
    redundancyCount++;
  }
  if (isSameSize && dest->mDot2) {
    redundancyCount++;
  }

  if (payLoadSize > 1 && redundancyCount < MESSAGE_HEADER_THRESHOLD) {
    return; // don't delete if redunant insts >=THRESHold
  };

  if (payLoadSize > 1 && !(redundancyCount == 3 &&
                           dest->send->getSrc(0)->compareOperand(
                               source->send->getSrc(0), builder) == Rel_eq)) {
    dest->insertHeaderMovInst(source->send, builder, bb);
    replaceOldHeader = true;
  }

  { // always remove "mov(8) Mx<1>, r0.0<8;8,1>:ud{Align1}"
    dest->m->markDead();
    if (!replaceOldHeader) {
      dest->m->transferUse(source->m, /*keepExisting*/ true);
      dest->m = source->m;
    }
  }

  if (isSameX && dest->mDot0) {
    dest->mDot0->markDead();
    if (!replaceOldHeader) {
      dest->mDot0->transferUse(source->mDot0, /*keepExisting*/ true);
      dest->mDot0 = source->mDot0;
    }
  } else if (payLoadSize == 1 && dest->mDot0) {
    dest->reusePreviousHeader(dest->mDot0, source->mDot0, source->mDot2,
                              builder);
    if (!replaceOldHeader) {
      source->mDot0 = dest->mDot0;
    }
  }

  if (isSameY && dest->mDot1) {
    dest->mDot1->markDead();
    if (!replaceOldHeader) {
      dest->mDot1->transferUse(source->mDot1, /*keepExisting*/ true);
      dest->mDot1 = source->mDot1;
    }
  } else if (payLoadSize == 1 && dest->mDot1) {
    dest->reusePreviousHeader(dest->mDot1, source->mDot1, source->mDot2,
                              builder);
    if (!replaceOldHeader) {
      source->mDot1 = dest->mDot1;
    }
  }

  if (isSameSize && dest->mDot2) {
    dest->mDot2->markDead();
    if (!replaceOldHeader) {
      dest->mDot2->transferUse(source->mDot2, /*keepExisting*/ true);
      dest->mDot2 = source->mDot2;
    }
  } else if (payLoadSize == 1 && dest->mDot2) {
    dest->reusePreviousHeader(dest->mDot2, source->mDot2, source->mDot2,
                              builder);
    if (!replaceOldHeader) {
      source->mDot2 = dest->mDot2;
    }
  }

  if (payLoadSize == 1) {
    // Check this function's comments for why no def-use changes
    // should be made on resetting src(0).
    G4_Operand *src0 = source->send->getSrc(0);
    dest->send->setSrc(builder.duplicateOperand(src0), 0);
  }

  dest->opt = true;

  return;
}

bool Optimizer::isHeaderCachingCandidate(G4_INST *inst) {
  if (inst->isSend()) {
    return true;
  }

  if (inst->useEmpty()) {
    return false;
  }

  for (USE_EDGE_LIST_ITER iter = inst->use_begin(), iend = inst->use_end();
       iter != iend; ++iter) {
    if ((*iter).first->isSend()) {
      G4_INST *send = (*iter).first;
      G4_Operand *header = send->getSrc(0);
      G4_DstRegRegion *dst = inst->getDst();

      // def to BuiltInA0 is part of header opt
      if (inst->getDst() && inst->getDst()->getBase() &&
          inst->getDst()->getBase()->isRegVar() &&
          inst->getDst()->getBase()->asRegVar() ==
              builder.getBuiltinA0()->getRegVar() &&
          inst->getDst()->getRegOff() == 0 &&
          inst->getDst()->getSubRegOff() == 0) {
        return true;
      }

      // make sure that dst of the current inst is header, not payload
      // header is hard-coded to be 32 bytes
      if (header->getTopDcl() == dst->getTopDcl() &&
          dst->getLeftBound() >= header->getLeftBound() &&
          dst->getRightBound() <=
              header->getLeftBound() + kernel.numEltPerGRF<Type_UB>() - 1) {
        return true;
      }
      return false;
    }
  }

  return false;
}

/*
 * mark the below "and" instruction as redundant;
 * the "and" instruction is the header for a barrier:
 *   and (8) r1.0<1>:ud r0.2<0;1,0>:ud 0xf000000:ud {Align1, NoMask}
 *   send (1) null<1>:ud r1 0x3 0x2000004:ud{Align1}
 *   wait n0:ud {Align1}
 */
void Optimizer::removeRedundantBarrierHeaders(G4_INST *sendInst,
                                              G4_SrcRegRegion *barrierSrc0,
                                              bool first) {
  bool barrier = false;
  G4_SrcRegRegion *src0 = NULL;
  if (!first) // skip the check as already done so for first barrier
  {
    barrier = isBarrierPattern(sendInst, src0);
  }
  if (barrier || first) {
    auto item = sendInst->def_begin();
    G4_INST *andInst = item->first;
    // delete all the uses of andInst
    // addInst and sendInst will have no def and no use
    andInst->removeAllUses();
    // sendInst.src0 (addInst.dst) will be replaced by barrierSend.src0
    // create a new G4_SrcRegRegion, which is a copy of barrierSend.src0
    G4_SrcRegRegion *src = builder.createSrc(
        barrierSrc0->getTopDcl()->getRegVar(), 0, 0, barrierSrc0->getRegion(),
        barrierSrc0->getTopDcl()->getElemType());
    sendInst->setSrc(src, 0);
    andInst->markDead();
  }
}

/*
 * pattern match of a code sequence for ISA_BARRIER:
 *   and (8) r1.0<1>:ud r0.2<0;1,0>:ud 0xf000000:ud {Align1, NoMask}
 *   send (1) null<1>:ud r1 0x3 0x2000004:ud{Align1}
 *   wait n0:ud {Align1}
 */
bool Optimizer::isBarrierPattern(G4_INST *sendInst,
                                 G4_SrcRegRegion *&barrierSendSrc0) {
  /*
   * check G4_send
   */
  G4_SendDescRaw *desc = sendInst->getMsgDescRaw();
  if (!desc)
    return false;
  uint32_t descVal = desc->getDesc();
  if ((desc->getFuncId() == SFID::GATEWAY) &&
      (descVal == (0x1 << 25) + 0x4) && // 0x2000004
      (sendInst->def_size() == 1)) {
    auto item = sendInst->def_begin();
    G4_INST *andInst = item->first; // getting "and" from send's def

    /*
     * check G4_and
     */
    if ((andInst) && (andInst->opcode() == G4_and) &&
        (item->second == Opnd_src0)) {
      G4_Operand *src0 = andInst->getSrc(0);
      G4_Operand *src1 = andInst->getSrc(1);

      bool isSrc0 =
          ((src0->isSrcRegRegion()) && (src0->asSrcRegRegion()->getBase()) &&
           (src0->asSrcRegRegion()->getBase()->isRegVar()) &&
           (src0->asSrcRegRegion()->getBase()->asRegVar() ==
            builder.getBuiltinR0()->getRegVar()) &&
           (src0->asSrcRegRegion()->getRegOff() == 0) &&
           (src0->asSrcRegRegion()->getSubRegOff() == 2)); // r0.2

      bool isSrc1 =
          src1->isImm() && !src1->isRelocImm() &&
          src1->asImm()->getInt() ==
              (builder.getPlatform() >= GENX_SKL ? 0x8F000000 : 0x0F000000);

      if (isSrc0 && isSrc1 && sendInst->getSrc(0) &&
          sendInst->getSrc(0)->isSrcRegRegion()) {
        barrierSendSrc0 = sendInst->getSrc(0)->asSrcRegRegion();
        return true;
      }
    }
  }

  return false;
}

/*
 * add the the barrier header as the top instruction
 */
void Optimizer::hoistBarrierHeaderToTop(G4_SrcRegRegion *barrierSendSrc0) {
  G4_Declare *dcl = barrierSendSrc0->getTopDcl();
  IR_Builder *mybuilder = &builder;

  // below code is copied from translateVISASyncInst() for ISA_BARRIER
  // all other dwords are ignored
  // and (8) r32.0:ud r0.2:ud 0x0F000000

  G4_SrcRegRegion *r0_src_opnd =
      builder.createSrc(mybuilder->getBuiltinR0()->getRegVar(), 0, 2,
                        builder.getRegionScalar(), Type_UD);
  G4_DstRegRegion *dst1_opnd =
      builder.createDst(dcl->getRegVar(), 0, 0, 1, Type_UD);

  G4_Imm *g4Imm = NULL;

  // for SKL+ there are 5 bits for barrierID
  // 5th bit is stored in bit 31 of second dword
  if (builder.getPlatform() < GENX_SKL) {
    g4Imm = builder.createImm(0x0F000000, Type_UD);
  } else {
    g4Imm = builder.createImm(0x8F000000, Type_UD);
  }

  G4_INST *andInst =
      builder.createBinOp(G4_and, g4::SIMD8, dst1_opnd, r0_src_opnd, g4Imm,
                          InstOpt_WriteEnable, false);
  for (auto bb : fg) {
    auto iter = std::find_if(bb->begin(), bb->end(),
                             [](G4_INST *inst) { return !inst->isLabel(); });
    if (iter != bb->end()) {
      bb->insertBefore(iter, andInst);
      return;
    }
  }
}

/*
 * check whether there are new definitions in order to determine redundancy
 */
bool Optimizer::chkNewDefBetweenSends(G4_INST *inst, MSGTableList &msgList,
                                      DEFA0 &myA0) {
  bool isDef = false;
  msgList.unique();

  // check SIMD8 VxH region everytime
  if (inst->getDst() &&
      (inst->getDst()->isIndirect() || inst->getDst()->isDirectAddress())) {
    isDef = myA0.isA0Redef = true;
  } else {
    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->isIndirect() || src->isDirectAddress()) {
        isDef = myA0.isA0Redef = true;
        break;
      }
    }
  }

  if (msgList.size() < 2) {
    return false;
  }
  MSGTable_ITER ii = msgList.begin();
  if (ii == msgList.end()) {
    return false;
  }

  ii++;

  if (ii == msgList.end()) {
    return false;
  }

  MSGTable *last = *(ii);
  if (last == NULL || last->send == NULL) {
    return false;
  }
  G4_Operand *def = inst->getDst();
  if (def == NULL) {
    return false;
  }
  if (last->mDot0 &&
      (def->compareOperand(last->mDot0->getSrc(0), builder) == Rel_eq ||
       (last->mDot0->getSrc(1) &&
        def->compareOperand(last->mDot0->getSrc(1), builder) == Rel_eq) ||
       (last->mDot0->getSrc(2) &&
        def->compareOperand(last->mDot0->getSrc(2), builder) == Rel_eq))) {
    isDef = last->isXRedef = true;
  } else if (last->mDot1 &&
             (def->compareOperand(last->mDot1->getSrc(0), builder) == Rel_eq ||
              (last->mDot1->getSrc(1) &&
               def->compareOperand(last->mDot1->getSrc(1), builder) ==
                   Rel_eq) ||
              (last->mDot1->getSrc(2) &&
               def->compareOperand(last->mDot1->getSrc(2), builder) ==
                   Rel_eq))) {
    isDef = last->isYRedef = true;
  } else if (last->mDot2 &&
             (def->compareOperand(last->mDot2->getSrc(0), builder) == Rel_eq ||
              (last->mDot2->getSrc(1) &&
               def->compareOperand(last->mDot2->getSrc(1), builder) ==
                   Rel_eq) ||
              (last->mDot2->getSrc(2) &&
               def->compareOperand(last->mDot2->getSrc(2), builder) ==
                   Rel_eq))) {
    isDef = last->isSizeRedef = true;
  } else if (last->m &&
             (def->compareOperand(last->m->getSrc(0), builder) == Rel_eq ||
              (last->m->getSrc(1) &&
               def->compareOperand(last->m->getSrc(1), builder) == Rel_eq) ||
              (last->m->getSrc(2) &&
               def->compareOperand(last->m->getSrc(2), builder) == Rel_eq))) {
    isDef = last->isR0Dot0Redef = true;
  }
  return isDef;
}

/*
 * Cache the send and its def into a table for optimization
 */
void Optimizer::addEntryToMessageTable(G4_INST *inst, MSGTableList &msgList,
                                       G4_BB *bb, INST_LIST_ITER ii,
                                       DEFA0 &myA0) {
  MSGTable *item = msgList.front();
  if (inst->isSend()) {
    item->send = inst;
    item->opt = false;
    item->isR0Dot0Redef = false;
    item->isXRedef = false;
    item->isYRedef = false;
    item->isSizeRedef = false;

    if (item->invalid) {
      msgList.pop_front();
    } else if (item->a0Dot0 != NULL && // only def a0.0
               (item->m == NULL || item->mDot2 == NULL)) {
      if (isHeaderOptCandidate(item->a0Dot0, myA0.pred)) {
        if (isHeaderOptReuse(item->a0Dot0, myA0.pred) && !myA0.isA0Redef) {
          // Transfer uses of a0Dot0 to myA0.pred. This removes uses from
          // a0Dot0 and add to myA0.pred. item->a0Dot0 to be deleted.
          item->a0Dot0->transferUse(myA0.pred, /*keepExisting*/ true);
          item->a0Dot0->markDead();
        }
      }
      msgList.pop_front();
    } else if (item->a0Dot0 && item->m && item->mDot2) // complete header def
    {

      msgList.unique();
      if (msgList.size() >= 2) {
        optMessageHeaders(msgList, bb, myA0);
        if (msgList.front()->opt &&
            msgList.front()->send->getMsgDesc()->getSrc0LenRegs() == 1) {
          // keep the oldest send for subsequent read operations
          // but the instruction to define a0.0 needs to be latest
          // msgList.back()->a0Dot0 = msgList.front()->a0Dot0;
          msgList.pop_front(); // delete first element
        } else if (msgList.front()->opt &&
                   msgList.front()->send->getMsgDesc()->getSrc0LenRegs() >= 1) {
          // keep the latest send for subsequent write operations
          msgList.pop_back();
        } else {
          msgList.pop_back();
        }
        myA0.isA0Redef = false;
      }
    } else {
      // not an optimization candidate
      msgList.pop_front();
    }
  } else if (inst->getDst() && inst->getDst()->getBase() &&
             inst->getDst()->getBase()->isRegVar() &&
             inst->getDst()->getBase()->asRegVar() ==
                 builder.getBuiltinA0()->getRegVar() &&
             inst->getDst()->getRegOff() == 0 &&
             inst->getDst()->getSubRegOff() == 0) {
    // is builtInA0.0
    item->a0Dot0 = inst;
    item->a0Dot0_it = ii;

    if (myA0.curr == NULL) {
      myA0.pred = NULL;
      myA0.isA0Redef = false;
    } else if (!myA0.curr->isDead()) {
      // only update the a0 def when we didn't remove it
      myA0.pred = myA0.curr;
      myA0.predIt = myA0.currIt;
    }
    myA0.currIt = ii;
    myA0.curr = inst;
  } else if (inst->getSrc(0)) {
    G4_DstRegRegion *dst = inst->getDst();
    if (dst) {
      if (dst->getRegOff() == 0) {
        // mov(8) m.0, builtInR0.0
        G4_Operand *src = inst->getSrc(0);
        if (dst->getSubRegOff() == 0 && inst->getExecSize() == g4::SIMD8 &&
            src && src->isSrcRegRegion() && src->asSrcRegRegion()->getBase() &&
            src->asSrcRegRegion()->getBase()->isRegVar() &&
            src->asSrcRegRegion()->getBase()->asRegVar() ==
                builder.getBuiltinR0()->getRegVar() &&
            src->asSrcRegRegion()->getRegOff() == 0 &&
            src->asSrcRegRegion()->getSubRegOff() == 0) {
          if (item->first == HEADER_UNDEF)
            item->first = HEADER_FULL_REGISTER;
          item->m = inst;
          item->m_it = ii;
        }
        // mov(1) m.0
        else if (dst->getSubRegOff() == 0 && inst->getExecSize() == g4::SIMD1) {
          if (item->first == HEADER_UNDEF)
            item->first = HEADER_X;
          item->mDot0 = inst;
          item->mDot0_it = ii;
        }
        // mov(1) m.1
        else if (dst->getSubRegOff() == 1 && inst->getExecSize() == g4::SIMD1) {
          if (item->first == HEADER_UNDEF)
            item->first = HEADER_Y;
          item->mDot1 = inst;
          item->mDot1_it = ii;
        }
        // mov(1) m0.2
        else if (dst->getSubRegOff() == 2 && inst->getExecSize() == g4::SIMD1) {
          if (item->first == HEADER_UNDEF)
            item->first = HEADER_SIZE;
          item->mDot2 = inst;
          item->mDot2_it = ii;
        } else {
          // unrecognized update to header
          item->invalid = true;
        }
      }
    }
  }
}

void Optimizer::messageHeaderReport(size_t ic_before, size_t ic_after,
                                    G4_Kernel &kernel) {
  VISA_DEBUG({
    std::cout << "             === Message Header Optimization ===\n";
    std::cout << std::fixed << "\n";
    std::cout << kernel.getName() << " is reduced from " << ic_before << " to "
              << ic_after << " instructions.\n";
    if (((float)(ic_before)) != 0.0) {
      std::cout << std::setprecision(0)
                << (float)((ic_before - ic_after) * 100) / (float)(ic_before)
                << "% instructions of this kernel are removed.\n";
    }
    std::cout << "\n";
  });
}

//
// optimizer for removal of redundant message header instructions
//
void Optimizer::cleanMessageHeader() {
  MSGTableList msgList;
  size_t ic_before = 0;
  size_t ic_after = 0;

  llvm::SpecificBumpPtrAllocator<MSGTable> MSGTableAlloc;
  bool isRedundantBarrier = false;
  G4_SrcRegRegion *barrierSendSrc0 = nullptr;

  for (G4_BB *bb : fg) {
    msgList.clear();
    auto MSGTableMem = MSGTableAlloc.Allocate();
    MSGTable *newItem = new (MSGTableMem) MSGTable();
    // FIXME: memset is suspicious here given MSGTable is not POD.
    memset(newItem, 0, sizeof(MSGTable));
    newItem->first = HEADER_UNDEF;

    msgList.push_front(newItem);
    INST_LIST_ITER ii = bb->begin();
    INST_LIST_ITER iend = bb->end();
    ic_before += bb->size();

    DEFA0 myA0;
    myA0.curr = nullptr;
    myA0.pred = nullptr;
    myA0.isA0Redef = false;

    for (; ii != iend; ii++) {
      G4_INST *inst = *ii;
      if (isHeaderCachingCandidate(inst)) {
        if (inst->opcode() == G4_send && isRedundantBarrier) {
          removeRedundantBarrierHeaders(inst, barrierSendSrc0, false);
        } else if (inst->opcode() == G4_send && !isRedundantBarrier) {
          isRedundantBarrier = isBarrierPattern(inst, barrierSendSrc0);
          if (isRedundantBarrier) {
            removeRedundantBarrierHeaders(inst, barrierSendSrc0, true);
          }
        }

        addEntryToMessageTable(inst, msgList, bb, ii, myA0);
        if (inst->isSend()) {
          auto MSGTableMem = MSGTableAlloc.Allocate();
          MSGTable *item = new (MSGTableMem) MSGTable();
          memset(item, 0, sizeof(MSGTable));
          item->first = HEADER_UNDEF;
          msgList.push_front(item);
        }
      } else {
        chkNewDefBetweenSends(inst, msgList, myA0);
      }
    }

    // Dead code elimination
    for (ii = bb->begin(); ii != bb->end();) {
      G4_INST *inst = *ii;
      INST_LIST_ITER curr = ii++;
      if (inst->isDead()) {
        inst->removeUseOfInst();
        bb->erase(curr);
      }
    }

    ic_after += bb->size();
  }

  messageHeaderReport(ic_before, ic_after, kernel);

  if (isRedundantBarrier) {
    hoistBarrierHeaderToTop(barrierSendSrc0);
  }
  msgList.clear();
}
//  The end of message header optimization

// For NoMask inst with non-zero mask offset, set maskoffset = 0 if possible.
//
// For any NoMask inst with non-zero mask offset, if it does not access any
// ARF and it is not a CF instruction, set its mask offset to zero.
void Optimizer::forceNoMaskOnM0() {
  for (G4_BB *currBB : fg) {
    for (auto &I : *currBB) {
      if (!I->isWriteEnableInst() || I->isCFInst() || I->getPredicate() ||
          I->getCondMod() || I->getMaskOffset() == 0 ||
          I->hasImplicitAccDst() || I->hasImplicitAccSrc())
        continue;

      // skip if I is logical on flag registers.
      // For example:
      //   (W) pseudo_and (16|M16)  P2:uw  P2:uw  P1:uw
      // where P2 is the high 16 bits of a 32-bit flag
      // and M16 cannot be changed to M0.
      if (I->isLogic() || I->isPseudoLogic()) {
        // Only checking dst is enough.
        G4_DstRegRegion *dst = I->getDst();
        if (dst && !dst->isNullReg() && dst->isFlag()) {
          continue;
        }
      }

      I->setMaskOption(InstOpt_M0);
    }
  }
}

void Optimizer::sendFusion() {
  // Potential problem related to noMask WA
  //
  // Send fusion creates the following code:
  //   1. (W)  mov (1|M0)             f1.0<1>:uw   0x0:uw
  //   2.      cmp (8|M0)  (eq)f1.0   null<1>:uw   r0.0<8;8,1>:uw r0.0<8;8,1>:uw
  //   3. (W)  mov (1|M0)             r18.4<1>:uw  f1.0<0;1,0>:uw
  //   4. (W)  mov (2|M0)             r18.8<1>:ub  r18.8<0;1,0>:ub
  //   5. (W)  mov (1|M0)             f0.1<1>:uw   r18.4<0;1,0>:uw
  //      fused send:
  //      (W&f0.1) send.dc1 (16|M0)   r5   r27  r1   0x40      0x02205EFF
  //
  // This code also works if NoMask WA is needed. Actually, this f0.1 behaves
  // the same as NoMask WA.  And it is critical that all of them should be
  // executed without applying NoMask WA. Here is the reason why:
  //     Assume we have a HW bug, no channels are on but it runs thru those
  //     instructions. We have f1.0 be all 0 at the end of 2.  As result, f0.1
  //     will be all zero. And the fused send will not run as its predicate is
  //     false. But if NoMask WA applies to 3 in postRA WA as it thinks it is a
  //     flag spill. (3) becomes:
  //           (3)  (W& f0.0.any8)  mov (1|M0)   r18.4<1>:uw f1.0<0;1,0>:uw
  //     therefore,  this instruction will no longer run, as result, f0.1 has
  //     garbage and it may make the fused send to run, which is wrong.
  //
  // The solutions:
  //  1) turn off send fusion (does it really help?);
  //  2) don't apply WA on those instructions.
  // As those 1-5 are all local definitions, postRA WA should skip them.
  // For now, we will do 2 to minimize potential impacts.
  if (builder.hasFusedEU()) {
    // Turn off send fusion for EU Fusion platforms.
    return;
  }
  (void)doSendFusion(&fg, &mem);
}

G4_SrcRegRegion *IR_Builder::createSubSrcOperand(G4_SrcRegRegion *src,
                                                 uint16_t start, uint8_t size,
                                                 uint16_t newVs,
                                                 uint16_t newWd) {
  const RegionDesc *rd = NULL;
  uint16_t vs = src->getRegion()->vertStride, hs = src->getRegion()->horzStride,
           wd = src->getRegion()->width;
  G4_Type srcType = src->getType();
  // even if src has VxH region, it could have a width that is equal to the new
  // exec_size, meaning that it's really just a 1x1 region.
  auto isVxHRegion = src->getRegion()->isRegionWH() && wd < size;
  if (!isVxHRegion) {
    // r[a0.0,0]<4;2,1> and size is 4 or 1
    if (size < newWd) {
      newWd = size;
    }
    rd = size == 1
             ? getRegionScalar()
             : createRegionDesc(size == newWd ? newWd * hs : newVs, newWd, hs);
    rd = getNormalizedRegion(size, rd);
  }

  if (src->getRegAccess() != Direct) {
    if (isVxHRegion) {
      // just handle <1,0>
      if (start > 0) {
        // Change a0.N to a0.(N+start)
        vISA_ASSERT((start % wd == 0),
                    "illegal starting offset and width combination");
        uint16_t subRegOff = src->getSubRegOff() + start / wd;
        return createIndirectSrc(src->getModifier(), src->getBase(),
                                 src->getRegOff(), subRegOff, src->getRegion(),
                                 src->getType(), src->getAddrImm());
      } else {
        return duplicateOperand(src);
      }
    }

    if (start > 0) {
      short numRows = start / wd;
      short numCols = start % wd;
      short newOff = (numRows * vs + numCols * hs) * TypeSize(srcType);
      auto newSrc = createIndirectSrc(
          src->getModifier(), src->getBase(), src->getRegOff(),
          src->getSubRegOff(), rd, src->getType(), src->getAddrImm() + newOff);
      return newSrc;
    } else {
      G4_SrcRegRegion *newSrc = duplicateOperand(src);
      newSrc->setRegion(*this, rd);
      return newSrc;
    }
  }

  // direct access oprand
  if (src->isAccReg()) {
    switch (srcType) {
    case Type_F:
      // must be acc1.0 as result of simd16 -> 8 split
      vISA_ASSERT(size == 8, "only support simd16->simd8 for now");
      return createSrcRegRegion(src->getModifier(), Direct,
                                phyregpool.getAcc1Reg(), 0, 0, src->getRegion(),
                                srcType);
    case Type_HF: {
      // can be one of acc0.8, acc1.0, acc1.8
      if (src->getBase()->asAreg()->getArchRegType() == AREG_ACC1) {
        start += 16;
      }
      G4_Areg *accReg =
          start >= 16 ? phyregpool.getAcc1Reg() : phyregpool.getAcc0Reg();
      return createSrcRegRegion(src->getModifier(), Direct, accReg, 0,
                                start % 16, src->getRegion(), srcType);
    }
    default:
      // Keep using acc0 for other types.
      return duplicateOperand(src);
    }
  }

  // Since this function creates a new sub src operand based on a start offset,
  // the reg and subreg offsets need to be re-computed.
  uint16_t regOff, subRegOff, subRegOffByte, newSubRegOffByte, newEleOff,
      newEleOffByte, crossGRF;

  newEleOff =
      start * hs +
      (start >= wd && vs != wd * hs ? (start / wd * (vs - wd * hs)) : 0);

  // Linearize offsets into bytes to verify potential GRF crossing
  newEleOffByte = newEleOff * src->getTypeSize();
  subRegOffByte = src->getSubRegOff() * src->getTypeSize();

  // If subreg crosses GRF size, update reg and subreg offset accordingly
  newSubRegOffByte = subRegOffByte + newEleOffByte;
  crossGRF = newSubRegOffByte / kernel.numEltPerGRF<Type_UB>();

  newSubRegOffByte =
      newSubRegOffByte - crossGRF * kernel.numEltPerGRF<Type_UB>();

  // Compute final reg and subreg offsets
  regOff = src->getRegOff() + crossGRF;
  subRegOff = newSubRegOffByte / src->getTypeSize();

  return createSrcRegRegion(src->getModifier(), Direct, src->getBase(), regOff,
                            subRegOff, rd, srcType, src->getAccRegSel());
}

G4_DstRegRegion *IR_Builder::createSubDstOperand(G4_DstRegRegion *dst,
                                                 uint16_t start, uint8_t size) {
  if (dst->getRegAccess() != Direct) {
    if (start > 0) {
      // just change immediate offset
      uint16_t newOff = start * dst->getTypeSize() * dst->getHorzStride();
      G4_DstRegRegion *newDst = duplicateOperand(dst);
      newDst->setImmAddrOff(dst->getAddrImm() + newOff);
      return newDst;
    } else {
      return duplicateOperand(dst);
    }
  }

  uint16_t regOff, subRegOff;
  if (start > 0) {
    G4_Type dstType = dst->getType();
    uint16_t hs = dst->getHorzStride();
    if (dst->isAccReg()) {
      switch (dstType) {
      case Type_F:
        // must be acc1.0 as result of simd16 -> 8 split
        vISA_ASSERT(size == 8, "only support simd16->simd8 for now");
        return createDst(phyregpool.getAcc1Reg(), 0, 0, hs, dstType);
      case Type_HF: {
        // can be one of acc0.8, acc1.0, acc1.8
        if (dst->getBase()->asAreg()->getArchRegType() == AREG_ACC1) {
          start += 16;
        }
        G4_Areg *accReg =
            start >= 16 ? phyregpool.getAcc1Reg() : phyregpool.getAcc0Reg();
        return createDst(accReg, 0, start % 16, hs, dstType);
      }
      default:

        // other types do not support acc1, we have to continue to use acc0
        // whoever doing the split must fix the dependencies later by shuffling
        // instructions so that acc0 does not get overwritten
        return createDstRegRegion(*dst);
      }
    }

    // Linearize offsets into bytes to verify potential GRF crossing
    uint16_t newSubRegOff, newSubRegOffByte, crossGRF;

    newSubRegOff = dst->getSubRegOff() + start * hs;
    newSubRegOffByte = newSubRegOff * TypeSize(dstType);

    crossGRF = newSubRegOffByte / kernel.numEltPerGRF<Type_UB>();
    newSubRegOffByte =
        newSubRegOffByte - crossGRF * kernel.numEltPerGRF<Type_UB>();

    // Compute final reg and subreg offsets
    regOff = dst->getRegOff() + crossGRF;
    subRegOff = newSubRegOffByte / TypeSize(dstType);

    // create a new one
    return createDst(dst->getBase(), regOff, subRegOff, hs, dst->getType(),
                     dst->getAccRegSel());
  } else {
    G4_DstRegRegion *newDst = duplicateOperand(dst);
    return newDst;
  }
}

G4_INST *IR_Builder::makeSplittingInst(G4_INST *inst, G4_ExecSize ExSize) {
  // Instruction's option is reused. Call sites should reset this field
  // properly. FIXME: fix all call sites.
  G4_INST *newInst = NULL;
  G4_opcode op = inst->opcode();
  if (inst->isMath()) {
    newInst = createMathInst(NULL, inst->getSaturate(), ExSize, NULL, NULL,
                             NULL, inst->asMathInst()->getMathCtrl(),
                             inst->getOption(), true);
  } else if (inst->getNumSrc() < 3) {
    newInst = createInternalInst(NULL, op, NULL, inst->getSaturate(), ExSize,
                                 NULL, NULL, NULL, inst->getOption());
  } else {
    newInst = createInternalInst(NULL, op, NULL, inst->getSaturate(), ExSize,
                                 NULL, NULL, NULL, NULL, inst->getOption());
  }

  newInst->inheritDIFrom(inst);

  return newInst;
}

// HW WAs that are done before RA.
void Optimizer::preRA_HWWorkaround() {
  if (builder.hasFusedEUNoMaskWA()) {
    prepareNoMaskWA();
  }

  // Call WA for fused EU
  if (builder.hasFusedEU() && kernel.hasIndirectCall()) {
    applyFusedCallWA();
    // Reset pre- and post-Id after FusedCallWA, which may add new
    // basic blocks.
    kernel.fg.reassignBlockIDs();
    kernel.fg.findBackEdges();
  }

  insertFenceAtEntry();

  cloneSampleInst();

  insertIEEEExceptionTrap();
}

//
// HW WAs that are done right after RA.
//    Sometime, a WA needs both preRA and postRA WA and postRA needs info from
//    preRA (NoMask WA). If doing postWA in HWWorkaround,  some instructions, or
//    even basic blocks (ifcvt), are removed, which could interfere information
//    passing from preRA to postRA. The loss of such the interference can cause
//    postRA WA to fail.  For this purpose, a postRA_HWWorkaround is added. This
//    also means that BBs and insts between preRA pass and postRA pass remain
//    undeleted (is it too strong?).
//
//    Note that for those WAs that should be done after inst scheduling, they
//    should go to HWWorkaround, not here.
//
void Optimizer::postRA_HWWorkaround() {
  if (builder.hasFusedEUNoMaskWA()) {
    applyNoMaskWA();
  }
}

// should only be called post-RA, return true if this operand has overlapping
// GRF with other ToDo: extend to non-GRF operands?
static bool hasOverlappingGRF(G4_Operand *opnd, G4_Operand *other) {
  if (!opnd || !other || !opnd->isGreg() || !other->isGreg())
    return false;
  auto LB = opnd->getLinearizedStart(), RB = opnd->getLinearizedEnd();
  auto otherLB = other->getLinearizedStart(),
       otherRB = other->getLinearizedEnd();
  return !(RB < otherLB || LB > otherRB);
}

// returns for this fence instruction the iterator position where the commit
// move should be inserted. We conservatively assume a commit is needed before
// -- another send
// -- any optimization barrier
// -- any instruction that writes to fence's dst GRF
// If another instruction happens to read dst GRF, then it serves as the commit
// and we don't need the dummy move
std::optional<INST_LIST_ITER>
Optimizer::findFenceCommitPos(INST_LIST_ITER fence, G4_BB *bb) const {
  auto fenceInst = *fence;
  vASSERT(fenceInst->isSend() && fenceInst->asSendInst()->isFence());
  auto dst = fenceInst->getDst();
  auto I = std::next(fence);
  for (auto E = bb->end(); I != E; ++I) {
    G4_INST *inst = *I;
    if (inst->isSend() || inst->isCFInst() || inst->isLabel() ||
        inst->isOptBarrier()) {
      break;
    }
    if (hasOverlappingGRF(dst, inst->getDst())) {
      break;
    }
    for (auto SI = inst->src_begin(), SE = inst->src_end(); SI != SE; ++SI) {
      auto src = *SI;
      if (hasOverlappingGRF(dst, src)) {
        return std::nullopt;
      }
    }
  }
  return I;
}

bool Optimizer::addFenceCommit(INST_LIST_ITER ii, G4_BB *bb,
                               bool scheduleFenceCommit) {
  G4_INST *inst = *ii;
  G4_InstSend *sendInst = inst->asSendInst();
  vASSERT(sendInst);
  if (sendInst && sendInst->getMsgDesc()->getDstLenRegs() > 0) {
    // commit is enabled for the fence, need to generate a move after to make
    // sure the fence is complete mov (8) r1.0<1>:ud r1.0<8;8,1>:ud {NoMask}
    auto nextIter = std::next(ii);
    if (scheduleFenceCommit) {
      auto iter = findFenceCommitPos(ii, bb);
      if (!iter) {
        return false; // skip commit for this fence
      }
      nextIter = *iter;
    }
    auto dst = inst->getDst();
    G4_Declare *fenceDcl = dst->getBase()->asRegVar()->getDeclare();
    G4_DstRegRegion *movDst = builder.createDst(
        builder.phyregpool.getNullReg(), 0, 0, 1, fenceDcl->getElemType());
    G4_SrcRegRegion *movSrc =
        builder.createSrcRegRegion(fenceDcl, builder.createRegionDesc(8, 8, 1));
    G4_INST *movInst = builder.createMov(g4::SIMD8, movDst, movSrc,
                                         InstOpt_WriteEnable, false);
    movInst->addComment("memory fence commit");
    bb->insertBefore(nextIter, movInst);
  } else if (builder.hasFenceControl()) {
    // null dst, use sync.fence instead
    auto nextIter = std::next(ii);
    G4_INST *syncInst = builder.createInternalInst(
        nullptr, G4_sync_fence, nullptr, g4::NOSAT, g4::SIMD1, nullptr,
        builder.createNullSrc(Type_UD), nullptr, InstOpt_NoOpt);
    bb->insertBefore(nextIter, syncInst);
  }
  return true;
}

//
// rewrite source regions to satisfy various HW requirements.  This pass will
// not modify the instructions otherwise
// -- rewrite <1;1,0> to <2;2,1> when possible (exec size > 1, width is not used
// to cross GRF)
//    as HW doesn't allow <1;1,0> to be co-issued
//
void Optimizer::normalizeRegion() {
  for (auto bb : fg) {
    for (auto inst : *bb) {
      if (inst->isCall() || inst->isFCall() ||
          inst->isReturn() || inst->isFReturn()) {
        // Do not rewrite region for call or return,
        // as the effective execution size is 2.
        continue;
      }

      // Do not rewrite region for dpas as HW requires region <1;1,0>
      if (inst->isDpas())
        continue;

      if (inst->getExecSize() == g4::SIMD1) {
        // Replace: mov (1) r64.0<4>:df  r3.0<0;1,0>:df
        // with:    mov (1) r64.0<1>:df  r3.0<0;1,0>:df
        // otherwise, will get incorrect results for HSW, HW mode
        G4_Operand *dst = inst->getDst();
        if (dst != NULL && dst->asDstRegRegion()->getHorzStride() > 1 &&
            dst->getTypeSize() == 8) {
          dst->asDstRegRegion()->setHorzStride(1);
        }
      } else {
        for (int i = 0; i < inst->getNumSrc(); ++i) {
          G4_Operand *src = inst->getSrc(i);
          // Only rewrite direct regions.
          if (src && src->isSrcRegRegion() &&
              src->asSrcRegRegion()->getRegAccess() == Direct) {
            G4_SrcRegRegion *srcRegion = src->asSrcRegRegion();
            if (srcRegion->getRegion()->isContiguous(inst->getExecSize())) {
              srcRegion->rewriteContiguousRegion(builder, i);
            } else if (inst->isAlign1Ternary()) {
              // special checks for 3src inst with single non-unit stride region
              // rewrite it as <s*2;s>
              uint16_t stride = 0;
              if (srcRegion->getRegion()->isSingleNonUnitStride(
                      inst->getExecSize(), stride)) {
                vISA_ASSERT(stride <= 4,
                            "illegal stride for align1 ternary region");
                srcRegion->setRegion(
                    builder,
                    kernel.fg.builder->createRegionDesc(stride * 2, 2, stride));
              }
            }
          }
        }
      }
    }
  }
}

void Optimizer::countGRFUsage() {
  unsigned int maxGRFNum = kernel.getNumRegTotal();
  int count = 0;
  std::vector<bool> GRFUse(maxGRFNum, false);
  for (auto dcl : kernel.Declares) {
    if (!fg.getHasStackCalls() &&
        (builder.isPreDefFEStackVar(dcl) || builder.isPreDefSpillHeader(dcl))) {
      continue;
    }
    if (dcl->getRegVar()->isGreg()) {
      int GRFStart = dcl->getRegVar()->getPhyReg()->asGreg()->getRegNum();
      int numRows = dcl->getNumRows();
      vISA_ASSERT(GRFStart >= 0 && (GRFStart + numRows) <= (int)maxGRFNum,
                  "illegal GRF assignment");
      for (int i = GRFStart; i < GRFStart + numRows; ++i) {
        GRFUse[i] = true;
      }
    }
  }
  for (unsigned int i = 0; i < maxGRFNum; ++i)
    if (GRFUse[i])
      count++;
  fg.builder->getJitInfo()->stats.numGRFUsed = count;
  fg.builder->criticalMsgStream()
      << "\tKernel " << kernel.getName() << " : " << count << " registers\n";
}

//
//  Dump the input payload to start of scratch space.
//  this is strictly for debugging and we do not care if this gets overwritten
//  by other usage of the scratch space (private memory, spill, etc.)
//
void Optimizer::dumpPayload() {
  int inputEnd = 0;
  for (int i = 0, numInput = kernel.fg.builder->getInputCount(); i < numInput;
       ++i) {
    input_info_t *input_info = kernel.fg.builder->getInputArg(i);
    if (inputEnd < input_info->size + input_info->offset) {
      inputEnd = input_info->size + input_info->offset;
    }
  }

  G4_BB *bb = kernel.fg.getEntryBB();
  // iter points to the first non-label inst
  auto iter = bb->begin(), bbEnd = bb->end();
  while (iter != bbEnd) {
    if (!(*iter)->isLabel()) {
      break;
    }
    ++iter;
  }

  int regOffset = (inputEnd + kernel.numEltPerGRF<Type_UB>() - 1) /
                  kernel.numEltPerGRF<Type_UB>();

  static const unsigned SCRATCH_MSG_DESC_CATEGORY = 18;
  static const unsigned SCRATCH_MSG_DESC_OPERATION_MODE = 17;
  static const unsigned SCRATCH_MSG_DESC_CHANNEL_MODE = 16;
  static const unsigned SCRATCH_MSG_DESC_BLOCK_SIZE = 12;

  // write 8 GRFs at a time
  int msgSize = 8;
  for (int i = 1; i < regOffset; i += msgSize) {
    uint16_t extFuncCtrl = 0;
    // both scratch and block read use DC
    SFID funcID = SFID::DP_DC0;

    uint32_t headerPresent = 0x80000;
    uint32_t msgDescImm = headerPresent;
    uint32_t msgLength = 1;
    uint32_t blocksizeEncoding = 0x3; // 8 GRF
    msgDescImm |= (msgLength << getSendMsgLengthBitOffset());
    msgDescImm |= (1 << SCRATCH_MSG_DESC_CATEGORY);
    msgDescImm |= (1 << SCRATCH_MSG_DESC_CHANNEL_MODE);
    msgDescImm |= (1 << SCRATCH_MSG_DESC_OPERATION_MODE);

    msgDescImm |= (blocksizeEncoding << SCRATCH_MSG_DESC_BLOCK_SIZE);
    msgDescImm |= i;

    G4_SendDescRaw *desc = kernel.fg.builder->createSendMsgDesc(
        msgDescImm, 0, 1, funcID, msgSize, extFuncCtrl, SendAccess::WRITE_ONLY);
    const RegionDesc *region = kernel.fg.builder->getRegionStride1();
    G4_SrcRegRegion *headerOpnd = kernel.fg.builder->createSrcRegRegion(
        kernel.fg.builder->getBuiltinR0(), region);
    G4_Declare *tempDcl =
        builder.createHardwiredDeclare(msgSize * 8, Type_UD, i, 0);
    G4_SrcRegRegion *srcOpnd =
        kernel.fg.builder->createSrcRegRegion(tempDcl, region);
    G4_DstRegRegion *dstOpnd = kernel.fg.builder->createNullDst(Type_UD);

    G4_INST *sendInst = kernel.fg.builder->createSplitSendInst(
        nullptr, G4_sends, g4::SIMD16, dstOpnd, headerOpnd, srcOpnd,
        kernel.fg.builder->createImm(msgDescImm, Type_UD), InstOpt_WriteEnable,
        desc, nullptr, true);
    bb->insertBefore(iter, sendInst);
  }
}

// perform simple stat collection (e.g., numSends)
// IR is not modified
void Optimizer::collectStats() {
  uint32_t numSends = 0;
  for (auto bb : fg) {
    for (auto inst : *bb) {
      if (inst->isSend()) {
        numSends++;
      }
      if (!builder.hasDFInst() && inst->isDFInstruction()) {
        builder.setHasDFInst(true);
      }
    }
  }
}

void Optimizer::mapOrphans() {
  auto catchAllCISAOff = builder.debugInfoPlaceholder;
  if (catchAllCISAOff == UNMAPPABLE_VISA_INDEX)
    return;

  for (auto bb : kernel.fg) {
    for (auto inst : *bb) {
      if (inst->getVISAId() == UNMAPPABLE_VISA_INDEX) {
        inst->setVISAId(catchAllCISAOff);
      }
    }
  }
}

G4_Declare *Optimizer::createInstsForCallTargetOffset(InstListType &insts,
                                                      G4_INST *fcall,
                                                      int64_t adjust_off) {
  // create instruction sequence:
  //       add  r2.0  -IP   call_target
  //       add  r2.0  r2.0  adjust_off

  // call's dst must be r125.0, which is reserved at
  // GlobalRA::setABIForStackCallFunctionCalls.
  vASSERT(fcall->getDst()->isGreg());
  // call dst must not be overlapped with r2 which is hardcoded as the new jump
  // target
  vASSERT((fcall->getDst()->getLinearizedStart() /
           kernel.numEltPerGRF<Type_UB>()) != 2);

  // hardcoded add's dst to r2
  // the reg offset must be the same as call's dst reg, and must be 0 (HW
  // restriction)
  uint32_t reg_off = fcall->getDst()->getLinearizedStart() %
                     kernel.numEltPerGRF<Type_UB>() /
                     fcall->getDst()->getTypeSize();

  G4_Declare *add_dst_decl =
      builder.createHardwiredDeclare(1, fcall->getDst()->getType(), 2, reg_off);

  // create the first add instruction
  // add  r2.0  -IP   call_target
  G4_INST *add_inst = builder.createBinOp(
      G4_add, g4::SIMD1, builder.createDstRegRegion(add_dst_decl, 1),
      builder.createSrcRegRegion(Mod_Minus, Direct,
                                 builder.phyregpool.getIpReg(), 0, 0,
                                 builder.getRegionScalar(), Type_UD),
      fcall->getSrc(0), InstOpt_WriteEnable | InstOpt_NoCompact, false);

  if (builder.needIPWA())
    replaceIPWithCall(insts, add_inst);

  // create the second add to add the -ip to adjust_off, adjust_off dependes
  // on how many instructions from the fist add to the jmp instruction, and
  // if it's post-increment (jmpi) or pre-increment (call)
  // add  r2.0  r2.0  adjust_off
  G4_INST *add_inst2 = builder.createBinOp(
      G4_add, g4::SIMD1, builder.createDstRegRegion(add_dst_decl, 1),
      builder.createSrcRegRegion(add_dst_decl, builder.getRegionScalar()),
      builder.createImm(adjust_off, Type_D),
      InstOpt_WriteEnable | InstOpt_NoCompact, false);

  insts.push_back(add_inst);
  insts.push_back(add_inst2);

  return add_dst_decl;
}

void Optimizer::replaceIPWithCall(InstListType &insts, G4_INST *inst_with_ip) {
  // Expand
  //    add    dst      -IP   call_target
  // To
  //    call   dst     _label_ip_wa          // jump to the next instruction
  //  _label_ip_wa:
  //    add    dst     dst     32            // adjust dst to the next 2
  //    instruction's ip ret    dst                           // jump to the
  //    next instruction add    dst     -dst    call_target   // at this
  //    instruction dst is the ip value

  uint32_t reg_num = inst_with_ip->getDst()->getLinearizedStart() /
                     kernel.numEltPerGRF<Type_UB>();
  uint32_t reg_off = inst_with_ip->getDst()->getLinearizedStart() %
                     kernel.numEltPerGRF<Type_UB>() /
                     inst_with_ip->getDst()->getTypeSize();
  // call's dst must have sub-reg num 0 (HW restriction)
  vASSERT(reg_off == 0);
  G4_Declare *dst_decl = builder.createHardwiredDeclare(
      1, inst_with_ip->getDst()->getType(), reg_num, reg_off);

  // call   dst     _label_ip_wa
  // NOTE: create the call and label instructions directly without forming a BB
  // to skip the BB end with call checking (e.g. in SWSB setting) that this is
  // just a fall-throug call and is a temporarily WA
  G4_Label *label = builder.createLocalBlockLabel("ip_wa");
  insts.push_back(builder.createInternalInst(
      nullptr, G4_call, nullptr, g4::NOSAT, g4::SIMD1,
      builder.createDstRegRegion(dst_decl, 1), label, nullptr,
      InstOpt_WriteEnable));
  // _label_ip_wa:
  insts.push_back(builder.createLabelInst(label, false));

  // add    dst     dst     32
  insts.push_back(builder.createBinOp(
      G4_add, g4::SIMD1, builder.createDstRegRegion(dst_decl, 1),
      builder.createSrcRegRegion(dst_decl, builder.getRegionScalar()),
      builder.createImm(32, Type_D), InstOpt_WriteEnable | InstOpt_NoCompact,
      false));

  // ret    dst
  insts.push_back(builder.createInternalInst(
      nullptr, G4_return, nullptr, g4::NOSAT, g4::SIMD1, nullptr,
      builder.createSrcRegRegion(dst_decl, builder.getRegionScalar()), nullptr,
      InstOpt_WriteEnable | InstOpt_NoCompact));

  // update given add instruction's src0 if needed
  if (inst_with_ip->opcode() == G4_add) {
    G4_SrcRegRegion *new_src =
        builder.createSrcRegRegion(dst_decl, builder.getRegionScalar());
    new_src->setModifier(Mod_Minus);
    inst_with_ip->setSrc(new_src, 0);
  }
}

void Optimizer::createInstForJmpiSequence(InstListType &insts, G4_INST *fcall) {
  // SKL workaround for indirect call
  // r125.0 is the return IP (the instruction right after jmpi)
  // r125.1 is the return mask. While we'll replace the ret in callee to jmpi as
  // well, we do not need to consider the return mask here.

  // Do not allow predicate call on jmpi WA
  vASSERT(fcall->getPredicate() == nullptr);

  // calculate the reserved register's num and offset from fcall's dst register
  // (shoud be r125.0)
  vASSERT(fcall->getDst()->isGreg());
  uint32_t reg_num =
      fcall->getDst()->getLinearizedStart() / kernel.numEltPerGRF<Type_UB>();
  uint32_t reg_off = fcall->getDst()->getLinearizedStart() %
                     kernel.numEltPerGRF<Type_UB>() /
                     fcall->getDst()->getTypeSize();

  G4_Declare *new_target_decl =
      createInstsForCallTargetOffset(insts, fcall, -64);

  // add  r125.0   IP   32
  G4_Declare *ret_decl = builder.createHardwiredDeclare(
      1, fcall->getDst()->getType(), reg_num, reg_off);
  insts.push_back(builder.createBinOp(
      G4_add, g4::SIMD1, builder.createDstRegRegion(ret_decl, 1),
      builder.createSrc(builder.phyregpool.getIpReg(), 0, 0,
                        builder.getRegionScalar(), Type_UD),
      builder.createImm(32, Type_UD), InstOpt_WriteEnable | InstOpt_NoCompact,
      false));

  // jmpi r2.0
  // update jump target (src0) to add's dst
  G4_SrcRegRegion *jump_target =
      builder.createSrcRegRegion(new_target_decl, builder.getRegionScalar());
  jump_target->setType(builder, Type_D);
  insts.push_back(
      builder.createJmp(nullptr, jump_target, InstOpt_NoCompact, false));
}

void Optimizer::expandIndirectCallWithRegTarget() {
  if (builder.hasFusedEU() && builder.getuint32Option(vISA_fusedCallWA) == 1) {
    vASSERT(!builder.needReplaceIndirectCallWithJmpi());
    // Relative IP has been applied in fusedCallWA()
    return;
  }

  // check every fcall
  for (auto bb : kernel.fg) {
    if (bb->back()->isFCall()) {
      G4_InstCF *fcall = bb->back()->asCFInst();
      if (fcall->isIndirectCall()) {
        // at this point the call instruction's src0 has the target_address
        // and the call dst is the reserved register (r125.0) for ret
        // All the caller save register should be saved. We usd r2 directly
        // here to calculate the new call's target.
        //
        // expand call
        // From:
        //       call r125.0 call_target
        // To:
        //       add  r2.0  -IP   call_target
        //       add  r2.0  r2.0  -32
        //       call r125.0  r2.0

        // For SKL workaround, expand call
        // From:
        //       call r125.0 call_target
        // To:
        //       add  r2.0     -IP    call_target
        //       add  r2.0     r2.0   -64
        //       add  r125.0   IP     32          // set the return IP
        //       jmpi r2.0
        InstListType expanded_insts;
        if (builder.needReplaceIndirectCallWithJmpi()) {
          createInstForJmpiSequence(expanded_insts, fcall);
        } else {
          G4_Declare *jmp_target_decl =
              createInstsForCallTargetOffset(expanded_insts, fcall, -32);
          // Updated call's target to the new target
          G4_SrcRegRegion *jump_target = builder.createSrcRegRegion(
              jmp_target_decl, builder.getRegionScalar());
          fcall->setSrc(jump_target, 0);
          fcall->setNoCompacted();
        }
        // then insert the expaneded instructions right before the call
        INST_LIST_ITER insert_point = bb->end();
        --insert_point;
        for (auto inst_to_add : expanded_insts) {
          bb->insertBefore(insert_point, inst_to_add);
        }

        // remove call from the instlist for Jmpi WA
        if (builder.needReplaceIndirectCallWithJmpi())
          bb->erase(--bb->end());
      }
    }
  }
}

// Replace ret with jmpi, must be single return
void Optimizer::replaceRetWithJmpi() {
  size_t num_ret = 0;

  for (G4_BB *bb : kernel.fg) {
    if (bb->empty())
      continue;
    if (bb->isEndWithFRet()) {
      ++num_ret;
      G4_INST *ret_inst = bb->back();

      // ret dst's decl
      G4_Declare *ret_reg = ret_inst->getSrc(0)->getTopDcl();

      // calculate the jmpi target offset
      // expand the original ret from:
      //     ret r125.0
      // To:
      //     add   r125.0  -ip   r125.0
      //     add   r125.0  r125.0  -48
      //     jmpi  r125.0

      // add   r125.0  -ip   r125.0
      G4_INST *add0 = builder.createBinOp(
          G4_add, g4::SIMD1, builder.createDstRegRegion(ret_reg, 1),
          builder.createSrcRegRegion(Mod_Minus, Direct,
                                     builder.phyregpool.getIpReg(), 0, 0,
                                     builder.getRegionScalar(), Type_UD),
          builder.createSrcRegRegion(ret_reg, builder.getRegionScalar()),
          InstOpt_WriteEnable | InstOpt_NoCompact, false);

      // add   r125.0  r125.0  -48
      G4_INST *add1 = builder.createBinOp(
          G4_add, g4::SIMD1, builder.createDstRegRegion(ret_reg, 1),
          builder.createSrcRegRegion(ret_reg, builder.getRegionScalar()),
          builder.createImm(-48, Type_D),
          InstOpt_WriteEnable | InstOpt_NoCompact, false);

      // jmpi r125.0
      G4_SrcRegRegion *jmpi_target =
          builder.createSrcRegRegion(ret_reg, builder.getRegionScalar());
      jmpi_target->setType(builder, Type_D);
      G4_INST *jmpi =
          builder.createJmp(nullptr, jmpi_target, InstOpt_NoCompact, false);

      // remove the ret
      bb->pop_back();
      // add the jmpi
      bb->push_back(add0);
      bb->push_back(add1);
      bb->push_back(jmpi);
    }
  }

  // there should be exactly one ret in a external function. We did not try
  // to restore the CallMask. We rely on single return of a function to make
  // sure the CallMask before and after calling this function is the same.
  vASSERT(num_ret == 1);
}

// Set a0 to tdr0 before sendc/sendsc
void Optimizer::setA0toTdrForSendc() {
  // check for the last inst of each BB, if it's sendc/sendsc, insert
  // "(W) mov(8) a0.0:uw tdr0.0:uw" right before it
  for (G4_BB *bb : kernel.fg) {
    if (bb->empty())
      continue;
    if (bb->back()->isSendConditional()) {
      // "(W) mov(8) a0.0:uw tdr0.0:uw"
      bb->insertBefore(
          --bb->end(),
          builder.createMov(g4::SIMD8,
                            builder.createDst(builder.phyregpool.getAddrReg(),
                                              0, 0, 1, Type_UW),
                            builder.createSrc(builder.phyregpool.getTDRReg(), 0,
                                              0, builder.getRegionScalar(),
                                              Type_UW),
                            InstOpt_WriteEnable, false));
    }
  }
}

// Check if there is WAR/WAW dependency between end inst and the preceding
// instruction
bool Optimizer::chkFwdOutputHazard(INST_LIST_ITER &startIter,
                                   INST_LIST_ITER &endIter) {
  G4_INST *startInst = *startIter;

  INST_LIST_ITER forwardIter = startIter;
  forwardIter++;
  while (forwardIter != endIter) {
    if ((*forwardIter)->isWAWdep(startInst) ||
        (*forwardIter)->isWARdep(startInst)) {
      break;
    }
    forwardIter++;
  }

  if (forwardIter != endIter) {
    return true;
  } else {
    return false;
  }
}

// check if startInst has any WAR/WAW conflicts with subsequent insts up till
// endIter (excluding endIter) precondition: startInst must be before endIter in
// the same BB this is used to sink an inst (or its sources) to the endIter
// location
bool Optimizer::chkFwdOutputHazard(G4_INST *startInst, INST_LIST_ITER endIter) {
  INST_LIST_ITER backIter = std::prev(endIter, 1);
  while (*backIter != startInst) {
    G4_INST *inst = *backIter;
    if (inst->isWARdep(startInst) || inst->isWAWdep(startInst)) {
      return true;
    }
    --backIter;
  }
  return false;
}

bool Optimizer::chkBwdOutputHazard(INST_LIST_ITER &startIter,
                                   INST_LIST_ITER &endIter) {
  G4_INST *endInst = *endIter;

  INST_LIST_ITER backwardIter = endIter;
  backwardIter--;
  while (backwardIter != startIter) {
    if (endInst->isWAWdep(*backwardIter) || endInst->isWARdep(*backwardIter)) {
      break;
    }
    backwardIter--;
  }

  if (backwardIter != startIter) {
    return true;
  } else {
    return false;
  }
}

bool Optimizer::chkBwdOutputHazard(G4_INST *startInst,
                                   INST_LIST_ITER &endIter) {
  G4_INST *endInst = *endIter;

  INST_LIST_ITER backwardIter = endIter;
  backwardIter--;
  while (*backwardIter != startInst) {
    if (endInst->isWAWdep(*backwardIter) ||
        //    Makes sure there is not WAR conflict between this instruction and
        //    instruction preceding it:
        //    ... grf1(use preceding inst)
        //    grf1 <---- def this inst
        endInst->isWARdep(*backwardIter)) {
      break;
    }
    backwardIter--;
  }

  if (*backwardIter != startInst) {
    return true;
  } else {
    return false;
  }
}

/*
Skips WAW check for the skipInst
*/
bool Optimizer::chkBwdOutputHazard(G4_INST *startInst, INST_LIST_ITER &endIter,
                                   G4_INST *skipInst) {
  G4_INST *endInst = *endIter;

  INST_LIST_ITER backwardIter = endIter;
  backwardIter--;
  while (*backwardIter != startInst) {
    if (skipInst == *backwardIter) {
      --backwardIter;
      continue;
    }

    // Makes sure there is not WAR conflict between this instruction and
    // instruction preceding it:
    // ... grf1(use preceding inst)
    // grf1 <---- def this inst
    if (endInst->isWARdep(*backwardIter) || endInst->isWAWdep(*backwardIter)) {
      break;
    }
    --backwardIter;
  }

  if (*backwardIter != startInst) {
    return true;
  } else {
    return false;
  }
}

bool Optimizer::chkBwdWARdep(G4_INST *startInst, INST_LIST_ITER endIter) {
  while (*endIter != startInst) {
    G4_INST *inst = *endIter;
    if (inst->isWARdep(startInst)) {
      return true;
    }
    --endIter;
  }
  return false;
}

// Check if there is WAW dependency between startInst and subsequent insts till
// endIter
bool Optimizer::chkBwdWAWdep(G4_INST *startInst, INST_LIST_ITER endIter) {
  INST_LIST_ITER backIter = std::prev(endIter, 1);
  while (*backIter != startInst) {
    G4_INST *inst = *backIter;
    if (inst->isWAWdep(startInst)) {
      return true;
    }
    --backIter;
  }
  return false;
}

// This function performs the following renaming to enable further optimization
// opportunities:
//
// op   v3, v1, v2
// mov  v4, v3
// mov  v5, v3
// mov  v6, v3
// ======>
// op   v3, v1, v2
// mov  v4, v3
// mov  v5, v4
// mov  v6, v4
void Optimizer::renameRegister() {
  const int MAX_REG_RENAME_DIST = 250;
  const int MAX_REG_RENAME_SIZE = 2;

  for (G4_BB *bb : fg) {
    bb->resetLocalIds();
    std::unordered_set<G4_INST *> Seen;

    INST_LIST_ITER ii = bb->begin(), iend(bb->end());
    while (ii != iend) {
      G4_INST *inst = *ii;

      if (!inst->isRawMov() || inst->getPredicate() || Seen.count(inst) > 0 ||
          inst->def_size() != 1 ||
          !inst->canHoist(!bb->isAllLaneActive(), fg.builder->getOptions())) {
        ii++;
        continue;
      }

      G4_Operand *src = inst->getSrc(0);
      G4_DstRegRegion *dst = inst->getDst();

      G4_Declare *srcDcl =
          src->isRegRegion() ? GetTopDclFromRegRegion(src) : nullptr;
      G4_Declare *dstDcl = GetTopDclFromRegRegion(dst);

      if (!srcDcl || !dstDcl) {
        ++ii;
        continue;
      }

      // If this move is between two different register files, then
      // do not do register renaming.
      if (srcDcl && dstDcl && srcDcl->getRegFile() != dstDcl->getRegFile()) {
        ++ii;
        continue;
      }

      G4_INST *defInst = inst->def_front().first;
      G4_Declare *defDstDcl = GetTopDclFromRegRegion(defInst->getDst());
      if ((dstDcl && dstDcl->getAddressed()) ||
          (defDstDcl && defDstDcl->getAddressed())) {
        ii++;
        continue;
      }

      G4_DstRegRegion *defDstRegion = defInst->getDst();
      if (Seen.count(defInst) > 0 ||
          src->compareOperand(defDstRegion, builder) != Rel_eq) {
        ii++;
        continue;
      }

      unsigned int instMaskOption = inst->getMaskOption();
      bool canRename = true;

      if (defInst->use_size() == 1) {
        ii++;
        continue;
      }

      int32_t sizeRatio = dstDcl->getByteSize() / srcDcl->getByteSize();

      G4_INST *lastUse = defInst->use_front().first;
      for (auto iter = defInst->use_begin(), E = defInst->use_end(); iter != E;
           ++iter) {
        G4_INST *useInst = (*iter).first;

        if (useInst == inst || ((useInst->getLocalId() - inst->getLocalId()) >
                                    MAX_REG_RENAME_DIST &&
                                sizeRatio > MAX_REG_RENAME_SIZE)) {
          continue;
        }

        /*
            it incorrectly renames in this case, because it doesn't consider
            defInst mask.
            BEFORE:
            <TR><TD ALIGN="LEFT"><FONT color="black">0:mov (1) V44(0,0)[1]:d
           V46(0,0)[0;1,0]:d [Align1, NoMask] %11</FONT></TD></TR> <TR><TD
           ALIGN="LEFT"><FONT color="black">0:mov (8) V48(0,0)[1]:d
           V44(0,0)[0;1,0]:d [Align1, Q1] %12</FONT></TD></TR> <TR><TD
           ALIGN="LEFT"><FONT color="black">0:mov (8) V56(0,0)[1]:d
           V44(0,0)[0;1,0]:d [Align1, Q1] %22</FONT></TD></TR>

            AFTER:
            <TR><TD ALIGN="LEFT"><FONT color="black">0:mov (1) V44(0,0)[1]:d
           V46(0,0)[0;1,0]:d [Align1, NoMask] %11</FONT></TD></TR> <TR><TD
           ALIGN="LEFT"><FONT color="black">0:mov (8) V48(0,0)[1]:d
           V44(0,0)[0;1,0]:d [Align1, Q1] %12</FONT></TD></TR> <TR><TD
           ALIGN="LEFT"><FONT color="black">0:mov (8) V56(0,0)[1]:d
           V48(0,0)[0;1,0]:d [Align1, Q1] %22</FONT></TD></TR>

            Fix: BB in SIMD control flow && (inst not NoMask) !(instMask ==
           defFask == useMask)

            Disallow replication?
        */
        if (useInst->getLocalId() < inst->getLocalId() ||
            !useInst->isRawMov() ||
            inst->getExecSize() != useInst->getExecSize() ||
            (useInst->getSrc(0))->compareOperand(defDstRegion, builder) !=
                Rel_eq ||
            useInst->def_size() > 1 ||
            (!(inst->isWriteEnableInst()) &&
             useInst->getMaskOption() != instMaskOption) ||
            // fix described above
            (!bb->isAllLaneActive() && !inst->isWriteEnableInst() &&
             !(inst->getExecSize() == defInst->getExecSize() &&
               inst->getExecSize() == useInst->getExecSize()))) {
          canRename = false;
          break;
        }

        if (useInst->getLocalId() > lastUse->getLocalId()) {
          lastUse = useInst;
        }
      }

      for (auto iter = defInst->use_begin(), E = defInst->use_end(); iter != E;
           ++iter) {
        G4_INST *useInst = (*iter).first;
        Seen.insert(useInst);
      }

      if (!canRename) {
        ii++;
        continue;
      }

      INST_LIST_ITER forwardIter = ii;
      forwardIter++;
      while (canRename && *forwardIter != lastUse &&
             (((*forwardIter)->getLocalId() - inst->getLocalId()) <=
                  MAX_REG_RENAME_DIST ||
              sizeRatio <= MAX_REG_RENAME_SIZE)) {
        if ((*forwardIter)->isWAWdep(inst)) {
          canRename = false;
          break;
        }
        forwardIter++;
      }

      if (!canRename) {
        ii++;
        continue;
      }

      for (auto useIter = defInst->use_begin(); useIter != defInst->use_end();
           /*empty*/) {
        G4_INST *useInst = (*useIter).first;

        if (useInst == inst || ((useInst->getLocalId() - inst->getLocalId()) >
                                    MAX_REG_RENAME_DIST &&
                                sizeRatio > MAX_REG_RENAME_SIZE)) {
          useIter++;
          continue;
        }

        G4_Operand *useSrc = useInst->getSrc(0);
        unsigned char execSize = useInst->getExecSize();
        unsigned short dstHS = dst->getHorzStride();
        const RegionDesc *newSrcRd;

        if (useSrc->asSrcRegRegion()->isScalar()) {
          newSrcRd = builder.getRegionScalar();
        } else {
          unsigned tExecSize = (execSize > 8) ? 8 : execSize;
          if (RegionDesc::isLegal(tExecSize * dstHS, execSize, dstHS)) {
            newSrcRd = builder.createRegionDesc((uint16_t)tExecSize * dstHS,
                                                execSize, dstHS);
          } else {
            // Skip this use. TODO: normalize this region.
            ++useIter;
            continue;
          }
        }

        G4_SrcRegRegion *newSrcOpnd = builder.createSrcRegRegion(
            Mod_src_undef, dst->getRegAccess(), dst->getBase(),
            dst->getRegOff(), dst->getSubRegOff(), newSrcRd, useSrc->getType());
        if (dst->getRegAccess() != Direct) {
          newSrcOpnd->asSrcRegRegion()->setImmAddrOff(dst->getAddrImm());
        }
        useInst->setSrc(newSrcOpnd, 0);

        // Maintain def-use for this change:
        // - remove this use from defInst
        // - add a new use to inst
        useIter = defInst->eraseUse(useIter);
        inst->addDefUse(useInst, Opnd_src0);
      }

      ii++;
    }
  }
}

//
// recompute bounds for declares in the given unordered_set
// this only affects DstRegRegion and SrcRegRegion
// If the operand is global, we have to update the global operand table as well
// as the bounds may have changed
//
void Optimizer::recomputeBound(std::unordered_set<G4_Declare *> &declares) {

  for (auto bb : fg) {
    for (auto ii = bb->begin(), iiEnd = bb->end(); ii != iiEnd; ++ii) {
      G4_INST *inst = *ii;
      if (inst->getDst() != NULL) {
        G4_DstRegRegion *dst = inst->getDst();
        if (dst->getTopDcl() != NULL &&
            declares.find(dst->getTopDcl()) != declares.end()) {
          bool isGlobal = builder.kernel.fg.globalOpndHT.isOpndGlobal(dst);
          dst->computeLeftBound(builder);
          inst->computeRightBound(dst);
          if (isGlobal) {
            builder.kernel.fg.globalOpndHT.addGlobalOpnd(dst);
          }
        }
      }
      for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
        if (inst->getSrc(i) != NULL && inst->getSrc(i)->isSrcRegRegion()) {
          G4_SrcRegRegion *src = inst->getSrc(i)->asSrcRegRegion();
          if (src->getTopDcl() != NULL &&
              declares.find(src->getTopDcl()) != declares.end()) {
            bool isGlobal = builder.kernel.fg.globalOpndHT.isOpndGlobal(src);
            src->computeLeftBound(builder);
            inst->computeRightBound(src);
            if (isGlobal) {
              builder.kernel.fg.globalOpndHT.addGlobalOpnd(src);
            }
          }
        }
      }
    }
  }
}

//
// Given a sequence of simd1 instructions (max 4), try to merge them into a
// single instruction e.g., mul (1) r0.4<1>:f r0.0<0;1,0>:f r6.5<0;1,0>:f
// {NoMask} mul (1) r0.5<1>:f r0.1<0;1,0>:f r6.5<0;1,0>:f {NoMask} mul (1)
// r0.6<1>:f r0.2<0;1,0>:f r6.5<0;1,0>:f {NoMask} mul (1) r0.7<1>:f
// r0.3<0;1,0>:f r6.5<0;1,0>:f {NoMask} becomes mul (4) r0.4<1>:f r0.0<1;1,0>:f
// r6.5<0;1,0>:f {NoMask} A bunch of conditions have to be satisified; check
// BUNDLE_INFO for more details. This is only performed for 3D input as CM is
// very unlikely to benefit from this (put another way, if this succeeds for CM
// our FE is doing something wrong)
//
void Optimizer::mergeScalarInst() {

  int bundleSizeLimit = BUNDLE_INFO::maxBundleSize;
  if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D || builder.noInt64()) {
    bundleSizeLimit = 4;
  }

  // set of declares that have been changed to alias to another declare
  std::unordered_set<G4_Declare *> modifiedDcl;
  std::vector<G4_Declare *> newInputs;

  // stats
  int numBundles = 0;
  int numDeletedInst = 0;

  for (G4_BB *bb : fg) {
    std::vector<BUNDLE_INFO> bundles;
    INST_LIST_ITER ii = bb->begin(), iiEnd = bb->end();
    while (ii != iiEnd) {
      G4_INST *inst = *ii;
      auto nextIter = ii;
      ++nextIter;
      if (nextIter != iiEnd && BUNDLE_INFO::isMergeCandidate(
                                   inst, builder, !bb->isAllLaneActive())) {
        BUNDLE_INFO bundle(bb, ii, bundleSizeLimit);
        bundle.findInstructionToMerge(nextIter, builder);
        if (bundle.size > 1)
          bundles.emplace_back(bundle);
        ii = nextIter;
      } else {
        ++ii;
      }
    }

    for (auto &bundle : bundles) {
      bool success = bundle.doMerge(builder, modifiedDcl, newInputs);
      if (success) {
        numBundles++;
        numDeletedInst += bundle.size - 1;
      }
    }
  }

  // we have to reset the bound for all operands whose declares have been
  // modified
  recomputeBound(modifiedDcl);

  VISA_DEBUG({
    std::cout << "             === Merge Scalar Optimization ===\n";
    std::cout << "Number of optimized bundles:\t" << numBundles << "\n";
    std::cout << "Number of instructions saved:\t" << numDeletedInst << "\n";
  });
}

static bool isMad(G4_INST *I) {
  // Disable int mac for PVC
  auto dst = I->getDst();
  return (I->opcode() == G4_pseudo_mad &&
          !(I->getBuilder().waDisableIntMac() && dst &&
            I->isIntegerPipeType(dst->getType())));
}

static inline bool isWBTypeAndNotNull(G4_Operand *opnd) {
  // Requires opnd to be not null.
  return opnd && (IS_BTYPE(opnd->getType()) || IS_WTYPE(opnd->getType()));
}

namespace {

/// Class to describe a mad sequence that can be turned into a sequence of MAC
/// instructions.
class MadSequenceInfo {
public:
  // IR builder object.
  IR_Builder &builder;

  // The basic block being examined.
  G4_BB *bb;

  enum MadSeqKind { MK_unknown, MK_isSafe, MK_isNotSafe };

private:
  // Flag indicates if ACC transformation is safe.
  MadSeqKind kind;

  // The single definition that defines the first mad's src2. If there are
  // multiple defintions, it is nullptr.
  G4_INST *src2Def;

  // The sequence of mad instruction to be examined.
  std::vector<G4_INST *> madSequence;

  // The use chain of the last mad. This use chain ended with an instruction
  // that has *B/*W type, and the chain length is limited by a predefined
  // constant.
  std::vector<G4_INST *> lastMadUserChain;

public:
  MadSequenceInfo(IR_Builder &builder, G4_BB *bb)
      : builder(builder), bb(bb), kind(MK_unknown), src2Def(nullptr) {}

  bool isSafe() const { return kind == MK_isSafe; }
  bool isNotSafe() const { return kind == MK_isNotSafe; }
  void setNotSafe() { kind = MK_isNotSafe; }
  void setSafe() { kind = MK_isSafe; }

  G4_INST *getSrc2Def() { return src2Def; }
  G4_INST *getFirstMad() const { return madSequence.front(); }
  G4_INST *getLastMad() const { return madSequence.back(); }
  void appendMad(INST_LIST_ITER begin, INST_LIST_ITER end) {
    madSequence.insert(madSequence.end(), begin, end);
  }
  typedef std::vector<G4_INST *>::iterator mad_iter;
  mad_iter mad_begin() { return madSequence.begin(); }
  mad_iter mad_end() { return madSequence.end(); }

  void appendUser(G4_INST *inst) { lastMadUserChain.push_back(inst); }
  G4_INST *getLastUser() { return lastMadUserChain.back(); }

  void reset() {
    kind = MK_unknown;
    src2Def = nullptr;
    madSequence.clear();
    lastMadUserChain.clear();
  }

  // Collect all candidate instructions and perform minimal checks.
  INST_LIST_ITER populateCandidates(INST_LIST_ITER iter);

  // Make changes to all the candidates collected. This is the only
  // function that makes changes to the IR.
  void processCandidates();

private:
  void populateUserChain(G4_INST *defInst, int level);
  void populateSrc2Def();

  // Check whether this mad sequence can be turned into a MAC sequence.
  bool checkMadSequence();

  // Check whether the user chain blocks this transformation or not.
  bool checkUserChain();

  // Check if other instructions between defInst and useInst are also updating
  // ACC registers, which may block this transformation.
  bool checkACCDependency(G4_INST *defInst, G4_INST *useInst);

  // The common type for accumulator operands.
  G4_Type getCommonACCType() {
    G4_Type T = Type_UNDEF;

    // If there is no user chain to check. Use the last mad's destionation
    // operand type as the common type. Otherwise, use the last user's
    // destionation type.
    if (lastMadUserChain.empty())
      T = getLastMad()->getDst()->getType();
    else
      T = getLastUser()->getDst()->getType();

    vISA_ASSERT((IS_FTYPE(T) || IS_HFTYPE(T) || IS_INT(T)),
                "Only F/HF/W/B types are expected here");
    return (IS_FTYPE(T) || IS_HFTYPE(T))
               ? T
               : (IS_SIGNED_INT(T) ? Type_W : Type_UW);
  }
};

class AccRestriction {
  unsigned encoding;

public:
  // Accumulator Restriction Kind:
  enum Accumulator_RK {
    ARK_NoRestriction = 0x01,   // No restrictions.
    ARK_NoAccess = 0x02,        // No accumulator access, implicit or explicit.
    ARK_NoSourceOperand = 0x04, // Source operands cannot be accumulators.
    ARK_NoModifier =
        0x08, // Source modifier is not allowed if source is an accumulator.
    ARK_NoExplicitSource = 0x010, // Accumulator is an implicit source and thus
                                  // cannot be an explicit source operand.
    ARK_NoDst =
        0x20, // Accumulator cannot be destination, implicit or explicit.
    ARK_AccWrEnRequired =
        0x40, // AccWrEn is required. The accumulator is an implicit
              // destination and thus cannot be an explicit destination operand.
    ARK_NoIntegerSource =
        0x80, // Integer source operands cannot be accumulators.
    ARK_NoExplicitSrcAllowAccWrEn =
        0x100, // No explicit accumulator access because this is a three-source
               // instruction. AccWrEn is allowed for implicitly updating the
               // accumulator.
    ARK_NoBothSrcAndDst = 0x200 // An accumulator can be a source or destination
                                // operand but not both.
  };

  AccRestriction(unsigned val) : encoding(val) {}

  bool useAccAsSrc(G4_SrcRegRegion *opnd, bool isExplicit = true,
                   bool isAlreadyDst = false) const {
    if (!opnd)
      return false;

    if (encoding & ARK_NoAccess)
      return false;

    if (encoding & ARK_NoRestriction)
      return true;

    if (encoding & ARK_NoSourceOperand)
      return false;

    if (encoding & ARK_NoIntegerSource)
      return !IS_TYPE_INT(opnd->getType());

    if (encoding & ARK_NoExplicitSource)
      return !isExplicit;

    if (encoding & ARK_NoExplicitSrcAllowAccWrEn)
      return false;

    if (encoding & ARK_NoBothSrcAndDst)
      return !isAlreadyDst;

    if (encoding & ARK_NoModifier)
      return opnd->getModifier() == Mod_src_undef;

    return true;
  }

  bool useAccAsDst(G4_DstRegRegion *opnd, bool isExplicit = true,
                   bool isAlreadySrc = false) const {
    if (!opnd)
      return false;

    if (encoding & ARK_NoAccess)
      return false;

    if (encoding & ARK_NoRestriction)
      return true;

    if (encoding & ARK_NoDst)
      return false;

    if (encoding & ARK_AccWrEnRequired)
      return !isExplicit;

    if (encoding & ARK_NoBothSrcAndDst)
      return !isAlreadySrc;

    return true;
  }

  static AccRestriction getRestrictionKind(G4_INST *inst);
};

} // namespace

AccRestriction AccRestriction::getRestrictionKind(G4_INST *inst) {
  switch (inst->opcode()) {
  default:
    break;
  case G4_add:
  case G4_asr:
  case G4_avg:
  case G4_csel:
  case G4_frc:
  case G4_sel:
  case G4_shr:
  case G4_smov:
    return ARK_NoRestriction;
  case G4_addc:
  case G4_subb:
    return ARK_AccWrEnRequired;
  case G4_and:
  case G4_not:
  case G4_or:
  case G4_xor:
    return ARK_NoModifier;
  case G4_cmp:
  case G4_cmpn:
  case G4_lzd:
    return ARK_NoRestriction;
  case G4_dp2:
  case G4_dp3:
  case G4_dp4:
  case G4_dph:
  case G4_line:
  case G4_movi:
  case G4_pln:
  case G4_sad2:
  case G4_sada2:
    return ARK_NoSourceOperand;
  case G4_lrp:
  case G4_mac:
    return ARK_NoExplicitSource;
  case G4_madm:
    return ARK_NoExplicitSrcAllowAccWrEn;
  case G4_mach:
    return ARK_NoExplicitSource | ARK_AccWrEnRequired;
  case G4_mov:
    return ARK_NoBothSrcAndDst;
  case G4_mul:
    return ARK_NoIntegerSource;
  case G4_rndd:
  case G4_rnde:
  case G4_rndu:
  case G4_rndz:
    return ARK_NoRestriction;
  case G4_shl:
    return ARK_NoDst;
  }

  return ARK_NoAccess;
}

/// Check this pseudo-mad's dst operand. Returns false if there is anything
/// blocking acc's usage.
static bool checkMadDst(G4_INST *inst, IR_Builder &builder) {
  G4_DstRegRegion *dst = inst->getDst();
  if (!dst || builder.kernel.fg.globalOpndHT.isOpndGlobal(dst))
    return false;

  if (dst->getRegAccess() != Direct)
    return false;

  // Only acc0 is available for w/uw destination.
  // FIXME: This acc type size is only for simd 16.
  unsigned Sz = TypeSize(Type_W);
  Sz *= dst->getHorzStride() * inst->getExecSize();
  return Sz <= builder.numEltPerGRF<Type_UB>();
}

// Check whether this mad sequence can be turned into a MAC sequence.
bool MadSequenceInfo::checkMadSequence() {
  unsigned int maskOffset = getFirstMad()->getMaskOffset();

  // First check each individual mad.
  for (auto inst : madSequence) {
    vISA_ASSERT(isMad(inst), "not a mad");

    // Only for simd 16. TODO: support simd8.
    if (inst->getExecSize() != g4::SIMD16)
      return false;

    if (inst->getMaskOffset() != maskOffset)
      return false;

    // Do not handle predicate yet.
    if (inst->getPredicate() != nullptr)
      return false;

    // Do not handle cond modifier yet.
    if (inst->getCondMod() != nullptr)
      return false;

    if (!checkMadDst(inst, builder))
      return false;

    G4_Operand *src0 = inst->getSrc(0);
    G4_Operand *src1 = inst->getSrc(1);
    G4_Operand *src2 = inst->getSrc(2);

    if (!src0 || !src1 || !src2)
      return false;

    if (builder.noDFTypeMac()) {
      if (IS_DFTYPE(src0->getType()) || IS_DFTYPE(src1->getType()) ||
          IS_DFTYPE(src2->getType()) || IS_DFTYPE(inst->getDst()->getType()))
        return false;
    }

    if (IS_FTYPE(src0->getType()) && IS_FTYPE(src1->getType()) &&
        IS_FTYPE(src2->getType())) {
      // ok
    } else if ((!IS_BTYPE(src0->getType()) && !IS_WTYPE(src0->getType())) ||
               (!IS_BTYPE(src1->getType()) && !IS_WTYPE(src1->getType()))) {
      // Only when src0 and src1 are of Byte/Word types.
      return false;
    } else if (!IS_BTYPE(src2->getType()) && !IS_WTYPE(src2->getType()) &&
               !IS_DTYPE(src2->getType())) {
      // Only when src2 is of Byte/Word/DWord types.
      return false;
    }

    if (!builder.hasByteALU()) {
      if (IS_BTYPE(src0->getType()) || IS_BTYPE(src1->getType())) {
        return false;
      }
    }

    if (builder.avoidAccDstWithIndirectSource()) {
      if (src0->isSrcRegRegion() && src0->asSrcRegRegion()->isIndirect()) {
        return false;
      }
      if (src1->isSrcRegRegion() && src1->asSrcRegRegion()->isIndirect()) {
        return false;
      }
    }

    // If there is a modifier for src2, or src2 is accessed somewhere
    // indirectly then we will not generate a MAC.
    if (!src2->isSrcRegRegion())
      return false;

    if (src2->asSrcRegRegion()->getModifier() != Mod_src_undef ||
        src2->asSrcRegRegion()->getRegAccess() != Direct ||
        (src2->getTopDcl() && src2->getTopDcl()->getAddressed()))
      return false;
  }

  // Now check instructions in pairs.
  G4_INST *defInst = getSrc2Def();
  G4_INST *lastMad = getLastMad();
  for (auto I = mad_begin(); defInst != lastMad; ++I) {
    G4_INST *useInst = *I;
    G4_Operand *dst = defInst->getDst();
    G4_Operand *src2 = useInst->getSrc(2);
    vISA_ASSERT(dst && dst->isDstRegRegion(), "invalid dst");
    vISA_ASSERT(src2 && src2->isSrcRegRegion(), "invalid src2");
    if (dst->compareOperand(src2, builder) != Rel_eq)
      return false;

    // Move the next pair.
    defInst = useInst;
  }

  return true;
}

bool MadSequenceInfo::checkACCDependency(G4_INST *defInst, G4_INST *useInst) {
  auto iter = std::find(bb->begin(), bb->end(), defInst);
  vISA_ASSERT(iter != bb->end(), "no instruction found?");

  for (++iter; (*iter) != useInst; ++iter) {
    if ((*iter)->defAcc() || (*iter)->useAcc() ||
        (*iter)->mayExpandToAccMacro())
      return false;
  }
  return true;
}

// Check whether this user chain is safe to use ACC.
bool MadSequenceInfo::checkUserChain() {
  // skip if there is no user to be analyzed.
  if (lastMadUserChain.empty())
    return true;

  G4_INST *defInst = getLastMad();
  G4_INST *useInst = defInst->use_back().first;

  while (true) {
    // TODO: enable simd8.
    if (useInst->getExecSize() != g4::SIMD16)
      return false;

    // Only when used as a source operand.
    Gen4_Operand_Number opndNum = defInst->use_back().second;
    if (!G4_INST::isSrcNum(opndNum))
      return false;

    G4_Operand *useOpnd = useInst->getSrc(G4_INST::getSrcNum(opndNum));
    if (!useOpnd || !useOpnd->isSrcRegRegion())
      return false;

    if (useOpnd->asSrcRegRegion()->isIndirect())
      return false;

    // check other source type.
    for (int i = 0, e = useInst->getNumSrc(); i < e; ++i) {
      G4_Operand *otherSrc = useInst->getSrc(i);
      if (otherSrc == useOpnd)
        continue;

      if (!isWBTypeAndNotNull(otherSrc))
        return false;
    }

    bool isLastUser = (useInst == getLastUser());

    // The last user does not use ACC as its dst.
    AccRestriction AR = AccRestriction::getRestrictionKind(useInst);
    if (!AR.useAccAsSrc(useOpnd->asSrcRegRegion(), true, !isLastUser))
      return false;

    // Now check between defInst and useInst, no ACC will be written by
    // other instructions.
    if (!checkACCDependency(defInst, useInst))
      return false;

    if (isLastUser)
      // No extra check for the last user.
      break;

    // This is not the last user. We check its dst too.
    G4_Operand *useDst = useInst->getDst();
    if (!useDst)
      return false;

    // check type, no support for *Q types yet.
    if (!IS_DTYPE(useDst->getType()))
      return false;

    // For each inner user, need to use ACC as its explicit dst.
    if (!AR.useAccAsDst(useDst->asDstRegRegion(), true, true))
      return false;

    if (defInst->getDst()->compareOperand(useOpnd, builder) != Rel_eq)
      return false;

    // move to next pair.
    defInst = useInst;
    useInst = defInst->use_back().first;
  }

  // nothing wrong.
  return true;
}

void MadSequenceInfo::populateSrc2Def() {
  G4_INST *firstMad = getFirstMad();
  vISA_ASSERT(firstMad && isMad(firstMad), "invalid mad");

  src2Def = firstMad->getSingleDef(Opnd_src2, true);
  if (src2Def == nullptr)
    // Cannot find a single definition.
    return setNotSafe();

  // Check it right here.
  // Only support splats or simd16 initialization.
  if (src2Def->getExecSize() != g4::SIMD16 &&
      src2Def->getExecSize() != g4::SIMD1) {
    return setNotSafe();
  }

  G4_Operand *Dst = src2Def->getDst();
  if (!Dst || builder.kernel.fg.globalOpndHT.isOpndGlobal(Dst))
    return setNotSafe();

  if (Dst->asDstRegRegion()->getRegAccess() != Direct)
    return setNotSafe();

  if (src2Def->getPredicate() || src2Def->getSaturate() ||
      !src2Def->hasOneUse())
    return setNotSafe();

  if (!src2Def->canDstBeAcc())
    return setNotSafe();

  if (IS_DTYPE(src2Def->getExecType())) {
    // since we use <1>:w region for our acc temp, due to alignment requirements
    // we can't allow dword source types
    return setNotSafe();
  }

  if (!builder.hasByteALU()) {
    // do not allow acc if src2Dest inst has byte source
    for (int i = 0; i < src2Def->getNumSrc(); ++i) {
      if (IS_BTYPE(src2Def->getSrc(i)->getType())) {
        return setNotSafe();
      }
    }
  }

  if (builder.avoidAccDstWithIndirectSource()) {
    for (int i = 0; i < src2Def->getNumSrc(); ++i) {
      if (src2Def->getSrc(i)->isSrcRegRegion() &&
          src2Def->getSrc(i)->asSrcRegRegion()->isIndirect()) {
        return setNotSafe();
      }
    }
  }

  // Check if there is any ACC dependency.
  if (!checkACCDependency(src2Def, firstMad))
    return setNotSafe();

  // Check restrictions on compression to ensure that changing the destination
  // type will not change the source region meaning due to instruction
  // compression.
  //
  // If both instructions are compressed or both non-compressed then it is
  // safe. Otherwise, check whether source regions are compression invariants.
  if (src2Def->isComprInst() ^ firstMad->isComprInst()) {
    auto checkCompression = [](G4_INST *inst) {
      for (int i = 0; i < inst->getNumSrc(); ++i) {
        G4_Operand *opnd = inst->getSrc(i);
        if (!opnd || !opnd->isSrcRegRegion())
          continue;
        if (!inst->isComprInvariantSrcRegion(opnd->asSrcRegRegion(), i))
          return false;
        if (IS_DTYPE(opnd->getType()))
          return false;
      }
      return true;
    };

    if (src2Def->isComprInst()) {
      if (!checkCompression(src2Def))
        return setNotSafe();
    } else {
      if (!checkCompression(firstMad))
        return setNotSafe();
    }
  }

  AccRestriction AR = AccRestriction::getRestrictionKind(src2Def);
  if (!AR.useAccAsDst(Dst->asDstRegRegion()))
    return setNotSafe();
}

void MadSequenceInfo::populateUserChain(G4_INST *defInst, int level) {
  // Failed.
  if (level <= 0)
    return setNotSafe();

  // Only for a single use.
  if (!defInst->hasOneUse())
    return setNotSafe();

  // Only when used as a source operand.
  Gen4_Operand_Number opndNum = defInst->use_back().second;
  if (!G4_INST::isSrcNum(opndNum))
    return setNotSafe();

  G4_INST *useInst = defInst->use_back().first;
  auto useDst = useInst->getDst();

  if (useDst == nullptr)
    return setNotSafe();

  appendUser(useInst);

  // If this user has *W/*B types then candidate found and stop the search.
  if (IS_BTYPE(useDst->getType()) || IS_WTYPE(useDst->getType()))
    return;

  // Search to the next level.
  return populateUserChain(useInst, level - 1);
}

// Currently, we assume that MAD instructions are back-to-back. This avoids
// dependency checking among mad and non-mad instructions.
//
// TODO: hoist or sink instructions.
//
INST_LIST_ITER MadSequenceInfo::populateCandidates(INST_LIST_ITER iter) {
  // Find the first pseudo-mad instruction.
  iter = std::find_if(iter, bb->end(), isMad);

  // No mad found
  if (iter == bb->end())
    return iter;

  // Find the first non-mad instruction following this sequence.
  auto end = std::find_if_not(iter, bb->end(), isMad);

  vISA_ASSERT(iter != end, "out of sync");
  appendMad(iter, end);

  // Checking the first mad's src2.
  populateSrc2Def();

  // If the mad sequence has *W/*B types then it is safe to use ACC regardless
  // of the destionation operand type in its use.
  // ..
  // mac (16) acc0.0<1>:w r10.7<0;1,0>:w r62.16<16;16,1>:ub {Align1, H1}
  // mac (16) acc0.0<1>:w r11.6<0;1,0>:w r63.0<16;16,1>:ub {Align1, H1}
  // mac (16) r24.0<1>:w r11.7<0;1,0>:w r63.16<16;16,1>:ub {Align1, H1}
  // add (16) r14.0<1>:d r14.0<8;8,1>:d r24.0<8;8,1>:w {Align1, H1}
  //
  // could be generated.
  G4_Type MadDstType = getLastMad()->getDst()->getType();
  if (IS_DTYPE(MadDstType)) {
    // Populate the user chain up to some predetermined level.
    const int level = 4;
    populateUserChain(getLastMad(), level);
  }

  // We have gathered all candidates for this optimization. Now we make
  // comprehensive checks on the mad sequence and the user chain.
  if (isNotSafe())
    return end;

  if (!checkMadSequence())
    return end;

  if (!checkUserChain())
    return end;

  // everything is OK, preceed to do transformation.
  setSafe();
  return end;
}

// Makes changes to the mad sequence and its users.
void MadSequenceInfo::processCandidates() {
  vISA_ASSERT(isSafe(), "not safe for ACC");
  vISA_ASSERT(getSrc2Def(), "null src");
  vISA_ASSERT(!madSequence.empty(), "no mad");

  // In this function we replace all src2 to implicit ACC registers and
  // update operands in its use chain.
  G4_Type AdjustedType = getCommonACCType();

  // Fix src2Def
  G4_INST *src2Def = getSrc2Def();
  {
    // change dst of the last MAD
    G4_DstRegRegion *accDstOpnd = builder.createDst(
        builder.phyregpool.getAcc0Reg(), 0, 0, 1, AdjustedType);
    src2Def->setDest(accDstOpnd);

    // Convert splat.
    if (src2Def->getExecSize() == g4::SIMD1) {
      src2Def->setExecSize(getFirstMad()->getExecSize());
    }
  }

  // update use-chain
  if (!lastMadUserChain.empty()) {
    G4_INST *defInst = getLastMad();
    G4_INST *useInst = defInst->use_back().first;
    Gen4_Operand_Number opndNum = defInst->use_back().second;
    vISA_ASSERT(defInst->hasOneUse(), "bad candidate");

    while (true) {
      const RegionDesc *rd = builder.getRegionStride1();
      auto mod = useInst->getOperand(opndNum)->asSrcRegRegion()->getModifier();
      G4_SrcRegRegion *accSrcOpnd = builder.createSrcRegRegion(
          mod, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, rd, AdjustedType);
      useInst->setSrc(accSrcOpnd, G4_INST::getSrcNum(opndNum));

      // The last use, only update source, and exit.
      if (useInst == getLastUser())
        break;

      // Also update the destination.
      G4_DstRegRegion *accDstOpnd = builder.createDst(
          builder.phyregpool.getAcc0Reg(), 0, 0, 1, AdjustedType);
      useInst->setDest(accDstOpnd);

      // move to the next pair.
      defInst = useInst;
      useInst = defInst->use_back().first;
      opndNum = defInst->use_back().second;
      vISA_ASSERT(defInst->hasOneUse(), "bad candidate");
    }
  }

  // update mad sequence
  for (auto I = mad_begin(), E = mad_end(); I != E; ++I) {
    G4_INST *inst = *I;
    vISA_ASSERT(isMad(inst), "not a mad");

    const RegionDesc *rd = builder.getRegionStride1();
    G4_SrcRegRegion *accSrcOpnd = builder.createSrc(
        builder.phyregpool.getAcc0Reg(), 0, 0, rd, AdjustedType);

    inst->setImplAccSrc(accSrcOpnd);
    inst->setSrc(nullptr, 2);
    // For the last mad, if it has *B/*W type, then no user will be modified
    // and do not change its destination operand. Otherwise, use acc as the
    // destination.
    if (getLastMad() != inst || !lastMadUserChain.empty()) {
      G4_DstRegRegion *accDstOpnd = builder.createDst(
          builder.phyregpool.getAcc0Reg(), 0, 0, 1, AdjustedType);
      inst->setDest(accDstOpnd);
    }
    inst->setOpcode(G4_mac);
    inst->fixMACSrc2DefUse();
  }
}

// Do any kind of proprocessing in this basic block to help MAC transformation.
// Returns false if we can easily detect this optimization is not possible.
// Otherwise, returns true.
static bool preprocessMadInBlock(IR_Builder &builder, G4_BB *bb) {
  bool hasMad = false;
  for (auto inst : *bb) {
    if (isMad(inst)) {
      hasMad = true;
      HWConformity::tryEliminateMadSrcModifier(builder, inst);
    }
  }

  // nothing to do if there is no mad.
  return hasMad;
}

// clang-format off
//
// mul (16) V48(0,0)<1>:d r0.1<0;1,0>:w V42_in(7,2)<16;16,1>:ub {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r1.0<0;1,0>:w V42_in(7,1)<16;16,1>:ub V48(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.2<0;1,0>:w V42_in(7,3)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.3<0;1,0>:w V42_in(8,1)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.4<0;1,0>:w V42_in(8,2)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.5<0;1,0>:w V42_in(8,3)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.6<0;1,0>:w V42_in(9,1)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.7<0;1,0>:w V42_in(9,2)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// psuedo_mad (16) V51_tempConvolve(0,0)<1>:d r0.8<0;1,0>:w V42_in(9,3)<16;16,1>:ub V51_tempConvolve(0,0)<16;16,1>:d {Align1, H1}
// add (16) V51_tempConvolve(0,0)<1>:d V51_tempConvolve(0,0)<16;16,1>:d 0x4000:w {Align1, H1}
// shr.sat (16) V52(0,0)<1>:ub V51_tempConvolve(0,0)<16;16,1>:d 0xf:w {Align1, H1}
//
// clang-format on
void Optimizer::lowerMadSequence() {

  // Only enable CM for now.
  if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) != VISA_CM)
    return;

  if (!builder.hasMacMacl())
    return;

  for (G4_BB *bb : fg) {
    // Preprocess this basic block. If no mad sequence found then skip to
    // the next basic block right away.
    if (!preprocessMadInBlock(builder, bb))
      continue;

    // Object to gather information for ACC optimization.
    MadSequenceInfo madInfo(builder, bb);

    auto iter = bb->begin();
    while (iter != bb->end()) {
      // Returns an iterator to the next non-mad instruction after the mad
      // sequence. It is safe to insert/delete instructions before it.
      iter = madInfo.populateCandidates(iter);

      // Perform transformation. The resulted IR may still need to be
      // fixed by HWConformity, e.g. the dst may still have *B type.
      if (madInfo.isSafe())
        madInfo.processCandidates();

      // Cleanup immediate results, whether change has been made or not.
      madInfo.reset();
    }
  }
}

void Optimizer::ifCvt() { runIfCvt(fg); }


namespace {

enum SplitBounds : unsigned {
  LoLBound = 0,
  LoRBound = 63,
  HiLBound = 64,
  HiRBound = 127
};

static bool isCandidateDecl(G4_Declare *Dcl, const IR_Builder &builder) {
  G4_Declare *RootDcl = Dcl->getRootDeclare();
  if (RootDcl->getRegFile() != G4_GRF)
    return false;

  // Only split 4GRF variables. We should be able to split > 4GRF variables,
  // but this should have been done in FE.
  if (RootDcl->getByteSize() != 4 * builder.numEltPerGRF<Type_UB>())
    return false;

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

  if (builder.isPreDefArg(RootDcl) || builder.isPreDefRet(RootDcl)) {
    return false;
  }

  if (Dcl->isOutput())
    return false;

  // ToDo: add more special declares to exclude list

  return true;
}

// Associated declarations for splitting.
struct DclMapInfo {
  // The low part of the splitted variable.
  G4_Declare *DclLow;

  // The high part of the splitted variable.
  G4_Declare *DclHigh;

  // Aliases of the low part. Created if needed for different types.
  std::vector<G4_Declare *> AliasLow;

  // Aliases of the high part. Created if needed for different types.
  std::vector<G4_Declare *> AliasHigh;

  DclMapInfo(G4_Declare *Lo, G4_Declare *Hi) : DclLow(Lo), DclHigh(Hi) {}

  // Return an appropriate declaration/alias for low or high part.
  G4_Declare *getDcl(IR_Builder &Builder, G4_Type Ty, bool IsLow) {
    return IsLow ? getDcl(Builder, Ty, DclLow, AliasLow)
                 : getDcl(Builder, Ty, DclHigh, AliasHigh);
  }

private:
  G4_Declare *getDcl(IR_Builder &Builder, G4_Type Ty, G4_Declare *RootDcl,
                     std::vector<G4_Declare *> &Aliases) {
    if (Ty == RootDcl->getElemType())
      return RootDcl;

    for (auto AL : Aliases) {
      if (Ty == AL->getElemType())
        return AL;
    }

    // Create such an alias if it does not exist yet.
    unsigned NElts = RootDcl->getByteSize() / TypeSize(Ty);
    auto Alias = Builder.createTempVar(
        NElts, Ty, Any,
        (std::string(RootDcl->getName()) + "_" + TypeSymbol(Ty)).c_str(),
        false);
    Alias->setAliasDeclare(RootDcl, 0);
    Aliases.push_back(Alias);
    return Alias;
  }
};

} // namespace

//
// We split any 4GRF variables (they typically result from simd16 64-bit vars)
// into two half if
// -- they are not address taken or used in send
// -- none of the operands cross from the 2nd to the 3rd GRF
// This is intended to give RA more freedom as the split variables do
// not have to be allocated contiguously.
// Note that this invalidates existing def-use chains
//
void Optimizer::split4GRFVars() {
  std::unordered_set<G4_Declare *> varToSplit;
  std::vector<G4_Declare *> varToSplitOrdering;
  // map each split candidate to their replacement split variables
  std::unordered_map<const G4_Declare *, DclMapInfo *> DclMap;

  if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) != VISA_3D) {
    return;
  }

  if (builder.getOption(vISA_Debug)) {
    return;
  }

  // Only for simd16 and simd32.
  if (kernel.getSimdSize() == g4::SIMD8) {
    return;
  }

  // first scan the decl list
  for (auto dcl : kernel.Declares) {
    if (dcl->getAliasDeclare() == nullptr) {
      if (isCandidateDecl(dcl, builder)) {
        if (varToSplit.find(dcl) == varToSplit.end()) {
          varToSplitOrdering.push_back(dcl);
        }

        varToSplit.emplace(dcl);
      }
    } else {
      // strictly speaking this condition is not necesary, but having
      // no aliases that could point into a middle of the split candidate
      // makes replacing the split var much easier. By construction the root
      // must appear before its alias decls
      uint32_t offset = 0;
      G4_Declare *rootDcl = dcl->getRootDeclare(offset);
      if (offset != 0 && isCandidateDecl(rootDcl, builder)) {
        varToSplit.erase(rootDcl);
      }
    }
  }

  if (varToSplit.empty()) {
    // early exit if there are no split candidate
    return;
  }

  // first pass is to make sure the validity of all split candidates
  for (auto bb : kernel.fg) {
    for (auto inst : *bb) {
      auto removeCandidate = [&varToSplit](G4_Declare *dcl) {
        if (dcl) {
          dcl = dcl->getRootDeclare();
          varToSplit.erase(dcl);
        }
      };

      if (inst->isSend()) {
        removeCandidate(inst->getDst()->getTopDcl());
        removeCandidate(inst->getSrc(0)->getTopDcl());
        if (inst->isSplitSend()) {
          removeCandidate(inst->getSrc(1)->getTopDcl());
        }
      } else {
        auto cross2GRF = [this](G4_Operand *opnd) {
          uint32_t lb = opnd->getLeftBound();
          uint32_t rb = opnd->getRightBound();
          return (lb < 2u * kernel.numEltPerGRF<Type_UB>()) &&
                 (rb >= 2u * kernel.numEltPerGRF<Type_UB>());
        };
        // check and remove decls with operands that cross 2GRF boundary
        if (inst->getDst()) {
          G4_Declare *dstDcl = inst->getDst()->getTopDcl();
          if (dstDcl && cross2GRF(inst->getDst())) {
            removeCandidate(dstDcl);
          }
        }
        for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
          G4_Operand *src = inst->getSrc(i);
          if (src && src->getTopDcl() && cross2GRF(src)) {
            removeCandidate(src->getTopDcl());
          }
        }
      }
    }
  }

  if (varToSplit.empty()) {
    // early exit if there are no split candidate
    return;
  }

  // create Lo/Hi for each variable being split
  for (auto splitDcl : varToSplitOrdering) {
    // varToSplitOrdering may have extra elements since we never delete any
    // inserted dcl from it.
    if (varToSplit.find(splitDcl) == varToSplit.end())
      continue;
    G4_Type Ty = splitDcl->getElemType();
    unsigned NElts = splitDcl->getTotalElems();
    std::string varName(splitDcl->getName());
    auto DclLow = builder.createTempVar(NElts / 2, Ty, builder.getGRFAlign(),
                                        (varName + "Lo").c_str(), false);
    auto DclHi = builder.createTempVar(NElts / 2, Ty, builder.getGRFAlign(),
                                       (varName + "Hi").c_str(), false);
    DclMap[splitDcl] = new DclMapInfo(DclLow, DclHi);
    // std::cerr << "split " << splitDcl->getName() << " into (" <<
    //    DclLow->getName() << ", " << DclHi->getName() << ")\n";
  }

  // second pass actually does the replacement
  for (auto bb : kernel.fg) {
    for (auto inst : *bb) {
      auto dst = inst->getDst();
      if (dst && dst->getTopDcl()) {
        G4_Declare *dstRootDcl = dst->getTopDcl()->getRootDeclare();
        if (DclMap.count(dstRootDcl)) {
          bool isLow =
              dst->getLeftBound() < 2u * kernel.numEltPerGRF<Type_UB>();
          auto NewDcl =
              DclMap[dstRootDcl]->getDcl(builder, dst->getType(), isLow);
          auto NewDst = builder.createDst(
              NewDcl->getRegVar(), dst->getRegOff() - (isLow ? 0 : 2),
              dst->getSubRegOff(), dst->getHorzStride(), dst->getType(),
              dst->getAccRegSel());
          inst->setDest(NewDst);
        }
      }

      for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
        G4_Operand *src = inst->getSrc(i);
        if (src && src->getTopDcl()) {
          G4_SrcRegRegion *srcRegion = src->asSrcRegRegion();
          G4_Declare *srcRootDcl = src->getTopDcl()->getRootDeclare();
          if (DclMap.count(srcRootDcl)) {
            bool isLow =
                src->getLeftBound() < 2u * kernel.numEltPerGRF<Type_UB>();
            auto NewSrcDcl =
                DclMap[srcRootDcl]->getDcl(builder, src->getType(), isLow);
            auto NewSrc = builder.createSrcRegRegion(
                srcRegion->getModifier(), srcRegion->getRegAccess(),
                NewSrcDcl->getRegVar(),
                srcRegion->getRegOff() - (isLow ? 0 : 2),
                srcRegion->getSubRegOff(), srcRegion->getRegion(),
                src->getType(), src->getAccRegSel());
            inst->setSrc(NewSrc, i);
          }
        }
      }
    }
  }

  for (const auto &DI : DclMap) {
    delete DI.second;
  }
}

//
// A platform may not support 64b types (FP64, INT64, or neither).
// While HW conformity should have legalized away use of such types, they may
// get re-introduced again later due to copy moves inserted by spill code
// generation, rematerialization etc. Instead of checking whether 64b type is
// used at each createMov(), we add a catch-all pass here. Since this is called
// post-RA the change we can make are very limited, for now just handle copy
// moves. We make this a separate pass instead of part of changeMoveType() as
// the latter is considered an optimization.
//
void Optimizer::legalizeType() {
  if (builder.noFP64() || builder.noInt64()) {
    for (auto bb : kernel.fg) {
      for (auto inst : *bb) {
        auto uses64bType = [](G4_INST *inst) {
          bool useFP64 = false;
          bool useInt64 = false;
          {
            auto dstTy =
                inst->getDst() ? inst->getDst()->getType() : Type_UNDEF;
            if (dstTy == Type_DF) {
              useFP64 = true;
            } else if (dstTy == Type_Q || dstTy == Type_UQ) {
              useInt64 = true;
            }
          }
          for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
            auto srcTy =
                inst->getSrc(i) ? inst->getSrc(i)->getType() : Type_UNDEF;
            if (srcTy == Type_DF) {
              useFP64 = true;
            } else if (srcTy == Type_Q || srcTy == Type_UQ) {
              useInt64 = true;
            }
          }
          return std::make_tuple(useFP64, useInt64);
        };
        // ToDo: handle more cases (e.g., immSrc, use UD for copy moves)
        if (inst->isRawMov() && inst->getSrc(0)->isSrcRegRegion()) {
          bool hasFP64 = false, hasInt64 = false;
          std::tie(hasFP64, hasInt64) = uses64bType(inst);
          if (hasFP64 && hasInt64) {
            vISA_ASSERT(
                false,
                "can't handle inst with both FP64 and INT64 at this point");
            return;
          }
          if (hasFP64 && builder.noFP64()) {
            vISA_ASSERT(!builder.noInt64(), "can't change DF to UQ");
            inst->getDst()->setType(builder, Type_UQ);
            inst->getSrc(0)->asSrcRegRegion()->setType(builder, Type_UQ);
          }
          if (hasInt64 && builder.noInt64() && !builder.noFP64()) {
            inst->getDst()->setType(builder, Type_DF);
            inst->getSrc(0)->asSrcRegRegion()->setType(builder, Type_DF);
          }
        }
      }
    }
  }
}

//
// Categorize move instructions to help with performance analysis
//
void Optimizer::analyzeMove() {

#define MOVE_TYPE(DO)                                                          \
  DO(Total)                                                                    \
  DO(SatOrMod)                                                                 \
  DO(Imm32)                                                                    \
  DO(Imm64)                                                                    \
  DO(FPConvert)                                                                \
  DO(Trunc)                                                                    \
  DO(Extend)                                                                   \
  DO(Broadcast)                                                                \
  DO(UNPACK)                                                                   \
  DO(PACK)                                                                     \
  DO(Copy)                                                                     \
  DO(Misc)                                                                     \
  DO(LAST)

  enum MovTypes { MOVE_TYPE(MAKE_ENUM) };

  static const char *moveNames[] = {MOVE_TYPE(STRINGIFY)};

  std::array<int, MovTypes::LAST> moveCount = {0};

  for (auto bb : kernel.fg) {
    for (auto inst : *bb) {
      if (!inst->isMov()) {
        continue;
      }
      moveCount[MovTypes::Total]++;

      if (inst->getSaturate()) {
        moveCount[MovTypes::SatOrMod]++;
        continue;
      }
      auto dstTy = inst->getDst()->getType();
      auto srcTy = inst->getSrc(0)->getType();
      if (inst->getSrc(0)->isImm()) {
        moveCount[TypeSize(srcTy) == 8 ? MovTypes::Imm64 : MovTypes::Imm32]++;
      } else if (inst->getSrc(0)->isSrcRegRegion()) {
        auto srcRR = inst->getSrc(0)->asSrcRegRegion();
        if (srcRR->getModifier() != Mod_src_undef) {
          moveCount[SatOrMod]++;
          continue;
        }
        bool signChange = false;
        if (dstTy != srcTy) {
          if (IS_FTYPE(srcTy) || IS_FTYPE(dstTy)) {
            // distinguish inttofp and fpconvert?
            moveCount[MovTypes::FPConvert]++;
          } else if (TypeSize(dstTy) > TypeSize(srcTy)) {
            moveCount[MovTypes::Extend]++;
          } else if (TypeSize(srcTy) > TypeSize(dstTy)) {
            moveCount[MovTypes::Trunc]++;
          } else {
            signChange = true;
          }
        }
        if (dstTy == srcTy || signChange) {
          if (srcRR->isScalar()) {
            moveCount[inst->getExecSize() > g4::SIMD1 ? MovTypes::Broadcast
                                                      : MovTypes::Copy]++;
          } else if (srcRR->getRegion()->isContiguous(inst->getExecSize())) {
            moveCount[inst->getDst()->getHorzStride() == 1
                          ? MovTypes::Copy
                          : MovTypes::UNPACK]++;
          } else {
            bool singleStride =
                srcRR->getRegion()->isSingleStride(inst->getExecSize());
            if (singleStride && inst->getDst()->getHorzStride() == 1) {
              moveCount[MovTypes::PACK]++;
            } else {
              // give up
              moveCount[MovTypes::Misc]++;
            }
          }
        }
      } else {
        moveCount[MovTypes::Misc]++;
      }
    }
  }

  std::cerr << "Move classification:\n";
  for (int i = 0; i < MovTypes::LAST; ++i) {
    if (moveCount[i] > 0) {
      std::cerr << "\t" << moveNames[i] << ":\t" << moveCount[i] << "\n";
    }
  }

#undef MOVE_TYPE
}

void Optimizer::staticProfiling() {
  // NOTE: local data flow analysis can not be called because regVar info
  // missed.
  StaticProfiling s(builder, kernel);
  s.run();

  // Do static cycle profiling only for platforms have 3 or more ALU pipelines.
  // Do static cycle profling only when shader dump is enabled.
  if (builder.hasThreeALUPipes() &&
      builder.getOptions()->getOption(vISA_outputToFile) &&
      builder.getOptions()->getOption(vISA_staticBBProfiling)) {
    StaticCycleProfiling sc(kernel);
    sc.run();
  }
}

static void markBreakpoint(G4_BB *bb, INST_LIST_ITER it, IR_Builder *builder) {
  G4_INST *inst = *it;
  vISA_ASSERT(inst->isIntrinsic() &&
                  inst->asIntrinsicInst()->getIntrinsicId() ==
                      Intrinsic::Breakpoint,
              "expect breakpoint intrinsic");
  auto nextIt = ++it;
  // if we encounter a breakpoint, mark the instruction after the
  // breakpoint intrinsic with breakpoint instruction option
  if (nextIt != bb->end()) {
    // intrinsic is not at the end of bb
    G4_INST *nextInst = *(nextIt);
    nextInst->setOptionOn(InstOpt_BreakPoint);
  } else {
    // intrinsic is at the end of bb
    // create a dummy mov with breakpoint option set
    auto nullDst = builder->createNullDst(Type_UD);
    auto nullSrc = builder->createNullSrc(Type_UD);

    G4_INST *dummyMov = builder->createMov(g4::SIMD1, nullDst, nullSrc,
                                           InstOpt_BreakPoint, false);
    bb->push_back(dummyMov);
  }
}

//
// remove Intrinsics
//
void Optimizer::removeIntrinsics() {
  for (auto bb : kernel.fg) {
    for (auto I = bb->begin(); I != bb->end(); ++I) {
      G4_INST *inst = *I;
      if (!inst->isIntrinsic())
        continue;
      if (inst->asIntrinsicInst()->getIntrinsicId() == Intrinsic::Breakpoint) {
        markBreakpoint(bb, I, fg.builder);
      }
    }

    std::vector<Intrinsic> intrinIdVec = {
      Intrinsic::MemFence,
      Intrinsic::FlagSpill,
      Intrinsic::Breakpoint
    };
    bb->removeIntrinsics(intrinIdVec);
  }
}

//
// for some platforms int has half throughout compared to float,
// so for copy moves we should change their type
// from D/UD to F or W/UW to HF when possible
//
void Optimizer::changeMoveType() {
  if (!builder.favorFloatMov() && !builder.balanceIntFloatMoves()) {
    return;
  }

  if (builder.avoidSrc1Src2Overlap()) {
    return;
  }

  auto changeType = [this](G4_INST *movInst, G4_Type newTy) {
    movInst->getDst()->setType(builder, newTy);
    auto src0 = movInst->getSrc(0);
    if (src0->isImm()) {
      uint32_t mask = TypeSize(newTy) == 4 ? 0xFFFFFFFF : 0xFFFF;
      movInst->setSrc(
          fg.builder->createImm(src0->asImm()->getImm() & mask, newTy), 0);
      if (newTy == Type_F) {
        uint32_t value = src0->asImm()->getImm() & mask;
        std::stringstream ss;
        ss << "(";
        ss << "0x" << std::setfill('0') << std::hex << std::setw(8) << value;
        ss << ":f)";
        movInst->addComment(ss.str());
      }
    } else {
      movInst->getSrc(0)->asSrcRegRegion()->setType(builder, newTy);
    }
  };

  auto isCandidateMov = [this](G4_INST *inst) {
    if (inst->opcode() != G4_mov || inst->getSaturate() || inst->getCondMod()) {
      return false;
    }
    auto src0 = inst->getSrc(0);
    G4_Type dstTy = inst->getDst()->getType();
    G4_Type src0Ty = src0->getType();
    if (!inst->getDst()->isGreg()) {
      // don't apply it on ARFs (both dst and src)
      return false;
    }
    // Used only for splitting QW->2xUD
    if (TypeSize(dstTy) == 8) {
      if (dstTy != src0Ty) {
        // allow UD->(Q|UQ) as we zext, but not D->Q
        if (!(IS_TYPE_INT(dstTy) && src0Ty == Type_UD)) {
          return false;
        }
      }
      // we can split: scalar, contigous, stride2  w/out SrcMod
      if (src0->isSrcRegRegion() && src0->isGreg()) {
        auto srcReg = src0->asSrcRegRegion();
        bool modifier = srcReg->hasModifier();
        uint16_t stride = 0;
        bool singleStrideMax2 =
            srcReg->getRegion()->isSingleStride(inst->getExecSize(), stride) &&
            (stride <= 2);

        return !modifier && singleStrideMax2;
      } else // or immediates
        return src0->isImm();
    }
    if (dstTy != src0Ty) {
      // allow D <-> UD and W <-> UW moves
      if (!(IS_TYPE_INT(dstTy) && IS_TYPE_INT(src0Ty) &&
            TypeSize(dstTy) == TypeSize(src0Ty))) {
        return false;
      }
    }
    auto isLegalType = [](G4_Type ty) {
      return TypeSize(ty) == 2 || TypeSize(ty) == 4;
    };
    if (!isLegalType(dstTy) || !isLegalType(src0Ty)) {
      return false;
    }

    if (src0->isRelocImm()) {
      return false;
    }

    if (src0->isSrcRegRegion() && src0->isGreg()) {
      auto src0R = src0->asSrcRegRegion();
      bool hasNoModifier = src0R->getModifier() == Mod_src_undef;
      bool hasSimpleRegion =
          src0R->isScalar() ||
          (src0R->getRegion()->isContiguous(inst->getExecSize()) &&
           inst->getDst()->getHorzStride() == 1);
      bool dstSrcAligned =
          src0R->getLinearizedStart() % kernel.numEltPerGRF<Type_UB>() ==
          inst->getDst()->getLinearizedStart() % kernel.numEltPerGRF<Type_UB>();
      return hasNoModifier && hasSimpleRegion && dstSrcAligned;
    } else if (src0->isImm()) {
      // allow sext and zext imm moves
      // float imm can always be converted to int imm
      int64_t immVal = src0->asImm()->getImm();
      bool isIntImmMove = IS_TYPE_INT(dstTy) && IS_TYPE_INT(src0Ty) &&
                          G4_Imm::isInTypeRange(immVal, dstTy);
      return isIntImmMove || IS_FTYPE(dstTy) || IS_HFTYPE(dstTy);
    }
    return false;
  };
  auto splitMov64Imm = [this](INST_LIST_ITER curInst, G4_BB *BB) {
    auto firstMovInst = *curInst;
    auto src0 = firstMovInst->getSrc(0);
    auto dst = firstMovInst->getDst();
    auto srcType = src0->getType();
    auto dstType = dst->getType();

    // Saturate, CondMod, SrcMod, regioning are covered when adding to input
    // list, so no need for check now
    bool isSrcReg = src0->isSrcRegRegion();

    bool isSrcImm = src0->isImm();
    bool is64to64 = isSrcReg && (srcType == dstType) &&
                    (IS_QTYPE(dstType) || dstType == Type_DF);
    bool isU32to64 = isSrcReg && (srcType == Type_UD) &&
                     IS_QTYPE(dstType); // can zero extend it

    if (!(isSrcImm || isU32to64 || is64to64))
      return;

    // common for each variant
    auto newTy = Type_UD;
    unsigned char execSize = firstMovInst->getExecSize();
    unsigned char secondMovExecSize = firstMovInst->getExecSize();

    dst =
        builder.createDst(dst->getBase(), dst->getRegOff(),
                          2 * dst->getSubRegOff(), dst->getHorzStride(), newTy);

    G4_Operand *firstMovSrc0 = src0;
    G4_Operand *secondMovSrc0 = nullptr;

    bool canDoubleExecSize = false;
    if (isSrcImm) {
      uint64_t original = src0->asImm()->getImm();
      uint64_t lopart = original & 0xFFFFFFFF;
      uint64_t hipart = (original >> 32);

      // original mov takes low part
      firstMovSrc0 = fg.builder->createImm(lopart, newTy);

      // second mov, with high part and offset
      secondMovSrc0 = fg.builder->createImm(hipart, newTy);

      /*
          from :
          (W)      mov (8|M0)               r2.0<1>:df    0x0:df

          make:
          (W)      mov (16|M0)              r2.0<1>:ud    0x0:ud
      */
      if (lopart == hipart)
        canDoubleExecSize = true;
    } else if (isU32to64) {
      // original move src0 stays the same (will have different dst)
      // second mov zero extends type
      // TODO(?):  mov r1:uq 0:ud
      secondMovSrc0 = fg.builder->createImm(0, newTy);
    } else if (is64to64) {
      auto src0ASR = src0->asSrcRegRegion();
      auto prevReg = src0ASR->getRegion();

      src0ASR = builder.createSrcRegRegion(
          src0ASR->getModifier(), src0ASR->getRegAccess(), src0ASR->getBase(),
          src0ASR->getRegOff(), src0ASR->getSubRegOff() * 2,
          src0ASR->getRegion(), newTy);

      if (prevReg->vertStride <= 1) {
        // from:
        //       mov (4|M0)               r14.0<1>:q    r24.0<1;1,0>:q
        //       mov (1|M0)               r94.2<1>:q    r14.2<0;1,0>:q
        // to:
        //       mov (8|M0)               r14.0<1>:ud   r24.0<1;1,0>:ud
        //       mov (2|M0)               r94.4<1>:ud   r14.4<1;1,0>:ud
        canDoubleExecSize = true;

        // convert both <0;1,0> and <1;1,0>
        src0ASR->setRegion(builder, fg.builder->getRegionStride1());

        // just create copy of src region to second mov
        secondMovSrc0 = fg.builder->createSubSrcOperand(
            src0ASR, 0, 2 * execSize, 1, prevReg->width);
      } else {
        /* some weird stuff like
               mov (2|M0)               r14.0<1>:q    r24.1<2;1,0>:q

        we should split into 2 (can't double exec).
               mov (2|M0)               r14.0<1>:ud   r24.2<2;1,0>:ud
               mov (2|M0)               r14.1<1>:ud   r24.3<2;1,0>:ud
        */

        // calculate offset on original regioning at lower type
        secondMovSrc0 = fg.builder->createSubSrcOperand(
            src0ASR, 1, execSize, prevReg->vertStride, prevReg->width);

        // change to stride2 now
        auto newReg =
            fg.builder->createRegionDesc(execSize, prevReg->vertStride * 2,
                                         prevReg->width, prevReg->horzStride);

        src0ASR->setRegion(builder, newReg);
        secondMovSrc0->asSrcRegRegion()->setRegion(builder, newReg);
      }
    }
    firstMovInst->setSrc(firstMovSrc0, 0);

    // common offset for all paths
    G4_DstRegRegion *secondMovDst;

    if (canDoubleExecSize) {
      secondMovExecSize *= 2;
      secondMovDst = fg.builder->createSubDstOperand(dst, 0, secondMovExecSize);
    } else {
      secondMovDst = fg.builder->createSubDstOperand(dst, 1, secondMovExecSize);

      // set HzStride for both dst if it matters
      if (execSize > 1) {
        dst->setHorzStride(2);
        secondMovDst->setHorzStride(2);
      }
    }

    G4_Predicate *pred =
        firstMovInst->getPredicate()
            ? builder.duplicateOperand(firstMovInst->getPredicate())
            : nullptr;

    // Create second mov, with different only src/dst, rest the same
    G4_INST *secondMovInst = builder.createInternalInst(
        pred, G4_mov, nullptr, g4::NOSAT, G4_ExecSize(secondMovExecSize),
        secondMovDst, secondMovSrc0, nullptr, firstMovInst->getOption());

    BB->insertBefore(curInst, secondMovInst);

    // we can't alter execSize of first mov, so newMov will take it's place, and
    // remove original
    // TODO: we don't estimate cost of this doubledExec correctly need to fix
    if (canDoubleExecSize) {
      BB->erase(curInst);
    }

    /*
    TODO: currently we do this
    (W)      mov (1|M0)               r66.0<1>:df   0x37F0000000000000:df
    (W)      mov (1|M0)               r66.1<1>:df   0x47F0000000000000:df
    (W)      mov (1|M0)               r66.2<1>:df   0x7FF0000000000000:df
    ->
    (W)      mov (1|M0)               r66.1<1>:ud   0x37F00000:ud
    (W)      mov (1|M0)               r66.0<1>:ud   0x0:ud
    (W)      mov (1|M0)               r66.3<1>:ud   0x47F00000:ud
    (W)      mov (1|M0)               r66.2<1>:ud   0x0:ud
    (W)      mov (1|M0)               r66.5<1>:ud   0x7FF00000:ud
    (W)      mov (1|M0)               r66.4<1>:ud   0x0:ud

    but we could do this ?
    ->
    (W)      mov (1|M0)               r66.1<1>:ud   0x37F00000:ud
    (W)      mov (1|M0)               r66.3<1>:ud   0x47F00000:ud
    (W)      mov (1|M0)               r66.5<1>:ud   0x7FF00000:ud
    (W)      mov (2|M0)               r66.0<2>:ud   0x0:ud
    (W)      mov (1|M0)               r66.4<1>:ud   0x0:ud
    */
  };

  /*
  0 - don't convert.
  1 - per BB balance. <default>
  2 - all suitable 64bit mov (experimental)
  */
  unsigned SplitMov64Mode =
      fg.builder->getOptions()->getuInt32Option(vISA_SplitMov64);

  if (builder.balanceIntFloatMoves()) {
    auto dstOrAnySrcIs2GRF = [this](G4_INST *inst) {
      auto dst = inst->getDst();
      bool dstIs2GRF = dst && !dst->isNullReg() && dst->isCrossGRFDst(builder);
      if (dstIs2GRF)
        return true;

      for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) {
        auto curSrc = inst->getSrc(i);
        if (inst->getSrc(i) == nullptr)
          continue;
        if (curSrc->isGreg() && curSrc->asSrcRegRegion()->crossGRF(builder))
          return true;
      }
      return false;
    };

    // attempt to balance the number of float v. int instructions in each BB
    // by changing the types of int or float copy moves
    for (auto bb : fg) {
      // candidate int and float moves
      std::vector<G4_INST *> intMovs, floatMovs;
      std::vector<INST_LIST_ITER> QWInstructions;
      // int/math/send share one decoder, float and 64b share the other decoder
      int numIntCost = 0, numFloatCost = 0;
      for (auto I = bb->begin(); I != bb->end(); /*empty*/) {
        auto CurI = I++;
        G4_INST *inst = *CurI;
        if (inst->getDst() && !inst->isDpas()) {
          auto execSize = inst->getExecSize();
          G4_Type dstTy = inst->getDst()->getType();
          uint32_t dstTySize = TypeSize(dstTy);

          uint32_t affectedGRFsCost = dstOrAnySrcIs2GRF(inst) ? 2 : 1;

          // Assumption:
          // FPU0 : FLT16/FLT32/FLT64/INT64
          // FPU1 : INT16 / INT32 / EM
          if (inst->isMath()) {
            // native simd1 for :DF, simd2 for :F
            numIntCost += (dstTySize == 8) ? execSize : execSize / 2;
          } else if (inst->isSend()) {
            numIntCost++;
          } else if (dstTySize == 8) {
            numFloatCost += affectedGRFsCost;
            if (isCandidateMov(inst)) {
              QWInstructions.push_back(CurI);
            }
          } else {
            if (IS_TYPE_INT(dstTy)) {
              numIntCost += affectedGRFsCost;
              if (isCandidateMov(inst)) {
                intMovs.push_back(inst);
              }
            } else if (IS_TYPE_FLOAT_ALL(dstTy)) {
              numFloatCost += affectedGRFsCost;
              if (isCandidateMov(inst)) {
                floatMovs.push_back(inst);
              }
            }
          }
        }
      }
      // std::cout << "num int cost/mov: " << numIntCost << "/" <<
      // intMovs.size() << " "
      //           << "num float cost/mov: " << numFloatCost << "/" <<
      //           floatMovs.size() << " "
      //           << "QW movs: " << QWInstructions.size() << "\n";
      int diff = std::abs(numIntCost - numFloatCost) / 2;

      auto changeMovsFromVector = [&](std::vector<G4_INST *> &table,
                                      G4_Type newType32, G4_Type newType16) {
        for (int i = 0, numInt = table.size(); diff > 0 && i < numInt; ++i) {
          auto inst = table[i];
          auto typeSize = inst->getDst()->getTypeSize();
          G4_Type floatTy = typeSize == 4 ? newType32 : newType16;

          changeType(inst, floatTy);

          auto estimatedClockCount = dstOrAnySrcIs2GRF(inst) ? 2 : 1;
          diff -= estimatedClockCount;
        }
      };

      bool forceSplitAllMov64 = (SplitMov64Mode == 2);

      if (numIntCost > numFloatCost && !forceSplitAllMov64) {
        // change int move to float move
        changeMovsFromVector(intMovs, Type_F, Type_HF);
      } else {
        // change float move to int move
        changeMovsFromVector(floatMovs, Type_UD, Type_UW);

        // if there's still unbalance
        // split `mov <imm64>` (or `mov 64to64` or mov `u32to64`) into 2x `mov
        // <imm32>`
        // TODO: or maybe split "and", "or" as well

        // Above changeMovsFromVector() had always same added and decreased
        // values so it operated on halfDiff but now we might have different
        // values so let's operate on full diff, not half
        diff = diff * 2;

        int rep = 0;
        if (!SplitMov64Mode)
          diff = 0;

        for (int i = 0, numInt = QWInstructions.size();
             ((diff > 0) || forceSplitAllMov64) && i < numInt; ++i) {
          auto inst = *QWInstructions[i];
          auto execSize = inst->getExecSize();
          auto estimatedSrcCost =
              dstOrAnySrcIs2GRF(inst) ? 2 : 1; // cost of mov before change

          auto dstTypeSize = TypeSize(Type_UD);
          auto estimatedDstCost = (execSize * dstTypeSize * /*HzStride*/ 2) > 32
                                      ? 2
                                      : 1; // cost of new mov

          // it might be that we remove 1 cycle mov (1) :df, and add 2x 1cycle
          // mov(1) :ud => 3 cycles diff.
          auto new_diff = diff - (2 * estimatedDstCost + estimatedSrcCost);

          if (abs(new_diff) >= abs(diff) && !forceSplitAllMov64) {
            break;
          }

          splitMov64Imm(QWInstructions[i], bb);

          diff = new_diff;
          rep++;
        }
        // std::cout << "diff before " << diff_prev << " after " << diff <<"
        // reps done " << rep << "\n";
      }
    }
    return;
  }

  for (auto bb : fg) {
    for (auto inst : *bb) {
      if (inst->opcode() != G4_mov) {
        continue;
      }
      // copy move means dst and src has identical bits (implies same type
      // width), and there are no sat/conditional modifier as well as src
      // modifier ToDo: we should probably change isRawMov() to include mov UD D
      auto src0 = inst->getSrc(0);

      // FIXME: This is a quick WA to bypass RelocImm, so that it won't create a
      // new src0 and overwrite the original RelocImm While this optimization
      // should still be able to apply to RelocImm. Once we turn on this
      // optimization for RelocImm, we should update assert in
      // VISAKernelImpl::GetGenRelocEntryBuffer to allow float type
      if (src0->isRelocImm())
        continue;

      G4_Type dstTy = inst->getDst()->getType();
      G4_Type src0Ty = src0->getType();
      bool hasNoModifier =
          !inst->getSaturate() && !inst->getCondMod() &&
          (src0->isImm() ||
           (src0->isSrcRegRegion() &&
            src0->asSrcRegRegion()->getModifier() == Mod_src_undef));

      // it may be unsafe to change the move type for acc as it has higher
      // precision
      if (inst->getDst()->isGreg() && hasNoModifier) {
        if (src0->isGreg()) {
          bool isIntCopyMove = IS_TYPE_INT(dstTy) && IS_TYPE_INT(src0Ty) &&
                               TypeSize(dstTy) == TypeSize(src0Ty);
          if (isIntCopyMove) {
            if (dstTy == Type_D || dstTy == Type_UD) {
              changeType(inst, Type_F);
            } else if (dstTy == Type_W || dstTy == Type_UW) {
              changeType(inst, Type_HF);
            }
          }
        } else if (src0->isImm()) {
          // allow sext and zext imm moves
          int64_t immVal = src0->asImm()->getImm();
          bool isIntImmMove = IS_TYPE_INT(dstTy) && IS_TYPE_INT(src0Ty) &&
                              G4_Imm::isInTypeRange(immVal, dstTy);
          if (isIntImmMove) {
            if (dstTy == Type_D || dstTy == Type_UD) {
              changeType(inst, Type_F);
            } else if (dstTy == Type_W || dstTy == Type_UW) {
              changeType(inst, Type_HF);
            }
          }
        }
      }
    }
  }
}

static bool isDeadInst(FlowGraph &fg, G4_INST *Inst) {
  if ((Inst->isMov() && !Inst->isRelocationMov() &&
       !Inst->getDst()->isNullReg()) ||
      Inst->isLogic() || Inst->isCompare() || Inst->isArithmetic() ||
      Inst->isVector()) {

    // Check side-effects.
    // - no global
    // - no indirect
    // - not physically assigned (including ARF)
    auto checkOpnd = [&](G4_Operand *Opnd) {
      if (Opnd == nullptr || Opnd->isNullReg())
        return true;
      if (fg.globalOpndHT.isOpndGlobal(Opnd))
        return false;
      if (Opnd->isDstRegRegion() && Opnd->asDstRegRegion()->isIndirect())
        return false;
      if (G4_VarBase *Base = Opnd->getBase()) {
        if (!Base->isRegVar())
          return false;
        if (Base->asRegVar()->isPhyRegAssigned())
          return false;
      }
      if (G4_Declare *Dcl = Opnd->getTopDcl()) {
        if (Dcl->isPreDefinedVar()) {
          // This can be improved by checking each preDefinedVar
          return false;
        }
        if (Dcl->isOutput() || Dcl->isPayloadLiveOut())
          return false;
      }
      return true;
    };

    // Should have no use.
    if (Inst->use_size() > 0)
      return false;

    // Skip instructions with special attributes.
    if (Inst->isYieldInst() || Inst->isBreakPointInst())
      return false;

    // Check defs. Assuming acc operands are all locally defined
    // and def-use are correctly maintained.
    if (!checkOpnd(Inst->getDst()) || !checkOpnd(Inst->getCondMod()))
      return false;

    // At this point, this instruction is dead.
    return true;
  }

  // By default it is not dead.
  return false;
}

// DCE() is disabled if the kernel has non-LSC messages because of below issue:
// Some cases have inaccurate kills, thus it is unsafe to turn it on by default.
// For example,
//    1. mov (1) r10.2:ud  r 20.0:ud
//    2. send (1) r10:ud  ...  // a32 dword read
//    3.   ... r10.2 ...
// In this case, send's footprint is the entire r10 (0-7 dw), thus it kill 1).
// In fact, send only modifies r10.0:ud (a single dw), thus it actually does not
// kill 1).  If dce is on, it willl use the false kill info to remove 1), as
// result, the code would be wrong.
//
//
void Optimizer::dce() {
  // Do not do DCE if there is any legacy message.
  for (auto bb : fg) {
    for (auto I = bb->rbegin(), E = bb->rend(); I != E; ++I) {
      G4_INST *Inst = *I;
      if (Inst->isSend() && Inst->getMsgDesc()->isHDC()) {
        return;
      }
    }
  }

  // make sure dataflow is up to date
  kernel.fg.resetLocalDataFlowData();
  kernel.fg.localDataFlowAnalysis();

  for (auto bb : fg) {
    for (auto I = bb->rbegin(), E = bb->rend(); I != E; ++I) {
      G4_INST *Inst = *I;
      if (isDeadInst(fg, Inst)) {
        Inst->removeAllDefs();
        Inst->markDead();
      }
    }
    bb->erase(std::remove_if(bb->begin(), bb->end(),
                             [](G4_INST *Inst) { return Inst->isDead(); }),
              bb->end());
  }
}

// Barrier is translated into signal and wait instructions. Both are scheduling
// barriers resulting in no any other instruction could be scheduled in-between.
// However, signal will take a while to go through among threads, so we could
// treat wait as a scheduling barrier for mayLoad/mayStore instructions only to
// improve performance. This pass tries to sink barrier wait until non-scratch
// send is found or when there's a possible flag overlap for nbarrier cases.
void Optimizer::sinkBarrierWait() {
  // Skip the optimization when barrier WA is required.
  if (builder.needBarrierWA())
    return;

  // TODO: Check whether there's really a flag overlap between the two
  // instructions. Given named barrier with flag src0 probably is rarely used,
  // currently simply treat the case, wait's src0 is flag and the current inst
  // writes flag, as an overlap.
  auto hasFlagOverlap = [](const G4_INST *i1, const G4_INST *i2) -> bool {
    vASSERT(i1 && i1->opcode() == G4_wait);
    return i1->getSrc(0)->isFlag() && i2->writesFlag();
  };

  for (auto bb : fg) {
    INST_LIST waits;
    for (auto it = bb->begin(), ie = bb->end(); it != ie;) {
      G4_INST *inst = *it;
      // Move any barrier wait to the temporary list.
      if (inst->opcode() == G4_wait) {
        auto next = std::next(it);
        waits.splice(waits.end(), bb->getInstList(), it);
        it = next;
        continue;
      }

      // Move all barrier waits from the temporary list back to inst list right
      // before an interesting position like a non-scratch send or
      // a control-flow instruction.
      // TODO: Check if we can relax or need more restrictions. For example,
      // private memory access probably could also be skipped.
      if ((inst->isSend() && !inst->getMsgDesc()->isScratch()) ||
          inst->isCFInst())
        bb->splice(it, waits);

      // When there's any wait that has a flag overlap with the current inst,
      // move the range [waits.begin(), last overlapping wait iterator] back to
      // the inst list so that the waits are not reordered.
      auto rwit = std::find_if(waits.rbegin(), waits.rend(),
          [=](const G4_INST *i) { return hasFlagOverlap(i, inst); });
      if (rwit != waits.rend()) {
        G4_INST *prev = nullptr, *last = *rwit;
        auto wit = waits.begin();
        while (prev != last) {
          prev = *wit;
          auto next = std::next(wit);
          bb->splice(it, waits, wit);
          wit = next;
        };
      }

      ++it;
    }
    // Every BB should end with a EOT or a CF inst like goto/jmpi/ret.
    vASSERT(waits.empty());
  }
}