File: GenXCoalescing.cpp

package info (click to toggle)
intel-graphics-compiler 1.0.12504.6-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 83,912 kB
  • sloc: cpp: 910,147; lisp: 202,655; ansic: 15,197; python: 4,025; yacc: 2,241; lex: 1,570; pascal: 244; sh: 104; makefile: 25
file content (2114 lines) | stat: -rw-r--r-- 87,972 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
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2021 Intel Corporation

SPDX-License-Identifier: MIT

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

//
/// GenXCoalescing
/// --------------
///
/// The LLVM target independent code generator, used by most backends, has a
/// coalescing pass that runs after de-SSA of the machine IR and two-address
/// handling, and attempts to remove the added copies by coalescing values. It
/// also attempts to coalesce a value with a hardreg that it is copied to/from.
///
/// This GenX coalescing and copy insertion pass is a bit different, in that
/// it runs on LLVM IR, which must remain in SSA, and it attempts to coalesce
/// values to try and avoid adding the copy in the first place. In any phi node
/// or two address op where it fails to coalesce, it inserts a copy (and
/// coalesces the result of the copy into the result of the phi node or
/// two address op).
///
/// There are three different kinds of coalescing. Copy coalescing is done first,
/// then the other two are done together.
///
/// 1. Copy coalescing.
///
///    Generally there are no copy instructions in SSA, but we
///    can treat a bitcast as a copy (the operand and result can live in the
///    same register aliased in different registers), and an extractvalue is
///    treated as a copy to be coalesced, and the "inserted value" operand
///    and the corresponding element(s) of the result in an insertvalue are
///    treated as a copy to be coalesced.
///
///    Copy coalescing represents two values that are known to be identical
///    occupying the same register at the same time, thus it is possible even
///    if the two values interfere (are live at the same point). Because we
///    handle copy coalescing before any other kind of coalescing, it usually
///    succeeds.
///
///    This only works because we do copy coalescing first, so we know that
///    neither value that we want to copy coalesce has already undergone normal
///    or phi coalescing.
///
///    However there is a case when copy coalescing between two live ranges
///    LR1 and LR2 (each of which is possibly already copy coalesced) cannot be
///    allowed: when LR2 loops round and has a phi use in the same basic block
///    as a phi definition in LR1, where the phi use of LR2 is after the phi
///    definition of LR1. This can happen because LLVM IR does not attach any
///    meaning to the order of phi nodes, but the GenX backend does with its
///    instruction numbering.
///
///    This constraint on copy coalescing is embodied in the concept of
///    "copy-interference". The two live ranges LR1 and LR2 copy-interfere,
///    meaning they cannot be copy coalesced, if LR1 has a phi definition,
///    one of whose numbers is within LR2's live range.
///
/// 2. Normal coalescing
///
///    This arises where we have a two-address operation, that is, it has an
///    operand that needs to be in the same register as the result, because the
///    instruction represents a partial write operation. The main example of
///    this is wrregion, but there are also some shared function intrinsics
///    that need this.
///
///    Here, we gather all the possible coalesces (including the phi ones),
///    together with an estimate of the cost of failing to coalesce (due to
///    needing to insert a copy), and then sort them in cost order and process
///    them.
///
///    This kind of coalescing is possible only if the two live ranges do not
///    interfere. If coalescing fails, we need to insert a copy just before
///    the instruction, creating a new value with a very short live range
///    that can trivially be coalesced with the result of the original
///    instruction.
///
///    Some subkinds of normal coalescing are:
///
///    2a. call arg pre-copy
///
///        A call arg needs to be coalesced with or copied to the corresponding
///        function arg.
///
///        Unlike most other kinds of coalescing, if coalescing fails, the copy
///        insertion is delayed until later, so we can ensure that the copies
///        are in the same order as the args, as the live ranges were computed
///        on that basis.
///
///        Normally, call arg pre-copy coalescing occurs, like other normal
///        coalescing, if the two live ranges do not interfere. If this fails,
///        we can still do *call arg special coalescing* (CASC) of call arg A
///        and function arg B as long as both of the following are true:
///
///         i. B has not been normal coalesced into anything (which would be
///            in the subroutine or some other subroutine it calls), except
///            that B is allowed to be call arg pre-copy coalesced;
///
///        ii. For any other call site where the corresponding call arg is not
///            A, A does not interfere with it.
///
///        Call arg special coalescing allows call arg A and function arg B to
///        be in the same register, even if A is used after the call, as long
///        as that register is not already being used for a different value
///        in the subroutine, and as long as a different value for the call
///        arg is not used at a different call site where A is live.
///
///        **Note**: Call arg special coalescing is disabled, because it broke
///        a test and I never got round to investigating why. I don't even know
///        if it would be beneficial any more, given more recent changes to
///        liveness and coalescing.
///
///    2b. ret value pre-copy
///
///        At a ReturnInst, the return value operand needs to be coalesced with
///        or copied to the unified return value for the function. This is
///        handled mostly the same as a normal coalesce.
///
///    2c. ret value post-copy
///
///        After a CallInst for a subroutine call, the unified return value
///        needs to be coalesced with or copied to the result of the call. On
///        failure, the copy insertion is delayed until later.
///
/// 3. Phi coalescing
///
///    This is how we "de-SSA" the code. A phi incoming wants to coalesce with
///    the result of the phi node.
///
///    Again, this kind of coalescing is possible only if the two live ranges
///    do not interfere. (A phi incoming can never interfere with its phi
///    result, but earlier coalescing could make them now interfere.) If
///    coalescing fails, we need to insert a copy at the end of the incoming
///    predecessor basic block. In fact we defer the copy insertion from failed
///    phi coalescing to the end, because we need to make sure the inserted
///    copies are in the same order as the phi nodes, as that is the basis on
///    which the live ranges were constructed.
///
///    After phi coalescing, the LLVM IR is still in SSA form, but the phi
///    coalescing, and the copies inserted where phi coalescing failed, mean
///    that it is trivial to transform into non-SSA vISA code: generate code for
///    the phi copies, and ignore the phi nodes themselves because they are
///    completely coalesced.
///
/// Kernel argument copying
/// ^^^^^^^^^^^^^^^^^^^^^^^
///
/// The kernel argument offsets (i.e. where kernel arguments appear in the GRF
/// on entry to the kernel) are set in a very early pass just after Clang
/// codegen. This sets offsets and packs holes in a way that is specific to the
/// language being compiled and its contract with its runtime.
///
/// However, when we get here, we may find that a live range that contains a
/// kernel argument has an alignment requirement that the offset from
/// earlier does not comply with.
///
/// So an extra function of this pass, after doing the coalescing, is to spot
/// this case, where a kernel argument has an offset that is not aligned enough,
/// and insert an extra copy at the start of the function.
///
//===----------------------------------------------------------------------===//

#include "FunctionGroup.h"
#include "GenX.h"
#include "GenXBaling.h"
#include "GenXGotoJoin.h"
#include "GenXIntrinsics.h"
#include "GenXLiveness.h"
#include "GenXModule.h"
#include "GenXNumbering.h"
#include "GenXSubtarget.h"
#include "GenXTargetMachine.h"
#include "GenXUtil.h"
#include "GenXVisitor.h"

#include "vc/Support/GenXDiagnostic.h"
#include "vc/Utils/GenX/GlobalVariable.h"
#include "vc/Utils/GenX/KernelInfo.h"
#include "vc/Utils/GenX/RegCategory.h"

#include "Probe/Assertion.h"
#include "llvmWrapper/IR/InstrTypes.h"
#include "llvmWrapper/IR/Instructions.h"

#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"

#include <algorithm>
#include <map>
#include <vector>

#define DEBUG_TYPE "GENX_COALESCING"

using namespace llvm;
using namespace genx;

static cl::opt<unsigned> GenXShowCoalesceFailThreshold("genx-show-coalesce-fail-threshold", cl::init(UINT_MAX), cl::Hidden,
                                      cl::desc("GenX size threshold (bytes) for showing coalesce fails."));
static cl::opt<bool> GenXCoalescingLessCopies(
    "genx-coalescing-less-copies", cl::init(true), cl::Hidden,
    cl::desc(
        "GenX Coalescing will try to emit less copies on coalescing failures"));

STATISTIC(NumCoalescingCandidates, "Number of coalescing candidates");
STATISTIC(NumInsertedCopies, "Number of inserted copies");

namespace {

  // Candidate : description of a coalescing candidate
  struct Candidate {
    genx::SimpleValue Dest;
    Use *UseInDest;
    unsigned SourceIndex;
    unsigned Priority;
    Candidate(SimpleValue Dest, Use *UseInDest, unsigned SourceIndex,
              unsigned Priority)
        : Dest(Dest), UseInDest(UseInDest), SourceIndex(SourceIndex),
          Priority(Priority) {}
    bool operator<(const Candidate &C2) const { return Priority > C2.Priority; }
  };

  struct PhiCopy {
    PHINode *Phi;
    unsigned IncomingIdx;
    PhiCopy(PHINode *Phi, unsigned IncomingIdx)
        : Phi(Phi), IncomingIdx(IncomingIdx) {}
  };

  enum CopyType { PHICOPY, PHICOPY_BRANCHING_JP, TWOADDRCOPY };

  struct CopyData {
    SimpleValue Dest;
    SimpleValue Source;
    Use *UseInDest;
    Instruction *InsertPoint;
    CopyType CopyT;
    unsigned DestPos;
    unsigned Serial;
    CopyData(SimpleValue Dest, SimpleValue Source, Use *UseInDest,
             Instruction *InsertPoint, CopyType CopyT, unsigned DestPos,
             unsigned Serial)
        : Dest(Dest), Source(Source), UseInDest(UseInDest),
          InsertPoint(InsertPoint), CopyT(CopyT), DestPos(DestPos),
          Serial(Serial) {}
    bool operator<(const CopyData &CD2) const {
      if (DestPos != CD2.DestPos)
        return DestPos < CD2.DestPos;
      return Serial < CD2.Serial;
    }
  };

  // Copies for values for live range
  struct CopiesForLRData {
    MapVector<SimpleValue, std::set<CopyData>> CopiesPerValue;
    void insertData(Value *SourceVal, CopyData &CD) {
      SimpleValue SourceSV(SourceVal, CD.Source.getIndex());
      CopiesPerValue[SourceSV].insert(CD);
    }
  };

  // Copies for all live ranges
  // Note that SourceVal can differ from CD.Source due to
  // CopyCoalescing (bitcasts between different types one register).
  struct SortedCopies {
    MapVector<LiveRange *, CopiesForLRData> CopiesPerLR;
    void insertData(LiveRange *LR, Value *SourceVal, CopyData &CD) {
      CopiesPerLR[LR].insertData(SourceVal, CD);
    }
  };

  // GenX coalescing pass
  class GenXCoalescing : public FGPassImplInterface,
                         public IDMixin<GenXCoalescing>,
                         public GenXVisitor<GenXCoalescing> {
  private:
    const DataLayout *DL = nullptr;
    const GenXSubtarget *ST = nullptr;
    GenXBaling *Baling = nullptr;
    GenXLiveness *Liveness = nullptr;
    GenXNumbering *Numbering = nullptr;
    DominatorTreeGroupWrapperPass *DTWrapper = nullptr;
    LoopInfoGroupWrapperPass *LIWrapper = nullptr;

    std::vector<Candidate> CopyCandidates;
    std::vector<Candidate> NormalCandidates;
    std::vector<CallInst*> Callables;
    std::vector<CopyData> ToCopy;
    std::map<SimpleValue, Value*> CallToRetVal;
    std::unordered_map<Instruction *, Value *> CopyCoalesced;

  public:
    explicit GenXCoalescing() {}
    static StringRef getPassName() {
      return "GenX coalescing and copy insertion";
    }
    static void getAnalysisUsage(AnalysisUsage &AU) {
      AU.addRequired<GenXLiveness>();
      AU.addRequired<GenXGroupBaling>();
      AU.addRequired<GenXNumbering>();
      AU.addRequired<DominatorTreeGroupWrapperPassWrapper>();
      AU.addRequired<LoopInfoGroupWrapperPass>();
      AU.addRequired<TargetPassConfig>();
      AU.addPreserved<DominatorTreeGroupWrapperPass>();
      AU.addPreserved<LoopInfoGroupWrapperPass>();
      AU.addPreserved<GenXGroupBaling>();
      AU.addPreserved<GenXLiveness>();
      AU.addPreserved<GenXModule>();
      AU.addPreserved<GenXNumbering>();
      AU.addPreserved<FunctionGroupAnalysis>();
      AU.setPreservesCFG();
    }
    bool runOnFunctionGroup(FunctionGroup &FG) override;

    void visitPHINode(PHINode &Phi);
    void visitCallInst(CallInst &CI);
    void visitGenXIntrinsicInst(GenXIntrinsicInst &II);
    void visitCastInst(CastInst &CI);
    void visitExtractValueInst(ExtractValueInst &EVI);
    void visitInsertValueInst(InsertValueInst &IVI);
  private:
    unsigned getPriority(Type *Ty, BasicBlock *BB) const;
    unsigned getPriority(SimpleValue Val) const;
    // Various permutations of the function to record a coalescing candidate.
    void recordCopyCandidate(SimpleValue Dest, unsigned OperandIndex,
                             unsigned SourceIndex = 0) {
      IGC_ASSERT(isa<User>(Dest.getValue()));
      recordCandidate(Dest, &cast<User>(Dest.getValue())->getOperandUse(OperandIndex),
                      SourceIndex, getPriority(Dest), CopyCandidates);
    }
    void recordNormalCandidate(SimpleValue Dest, unsigned OperandIndex,
                               unsigned SourceIndex = 0) {
      IGC_ASSERT(isa<User>(Dest.getValue()));
      recordCandidate(Dest, &cast<User>(Dest.getValue())->getOperandUse(OperandIndex),
                      SourceIndex, getPriority(Dest), NormalCandidates);
    }
    void recordCallArgCandidate(SimpleValue Dest, Use *UseInDest, unsigned SourceIndex,
                                unsigned Priority) {
      recordCandidate(Dest, UseInDest, SourceIndex, Priority, NormalCandidates);
    }
    void recordUnifiedRetCandidate(SimpleValue Dest, unsigned SourceIndex) {
      recordCandidate(Dest, nullptr, SourceIndex, getPriority(Dest), NormalCandidates);
    }
    void recordPhiCandidate(PHINode &Phi, unsigned IncomingIndex, unsigned Priority) {
      recordCandidate(&Phi, &Phi.getOperandUse(IncomingIndex), 0, Priority,
                      NormalCandidates);
    }
    void recordCandidate(SimpleValue Dest, Use *UseInDest, unsigned SourceIndex,
                         unsigned Priority, std::vector<Candidate> &Candidates);
    void recordCallCandidates(FunctionGroup *FG);
    void recordCallArgCandidates(Value *Dest, unsigned ArgNum,
                                 ArrayRef<Instruction *> Insts);
    // Functions for processing coalecing candidates.
    void processCopyCandidate(const Candidate &Cand) {
      processCandidate(Cand, true /*IsCopy*/);
    }
    void processCandidate(const Candidate &Cand, bool IsCopy = false);
    void processPhiNodes(FunctionGroup *FG);
    void analysePhiCopies(PHINode *Phi, std::vector<PhiCopy> &ToProcess);
    void processPhiCopy(PHINode *Phi, unsigned Inc,
                        std::vector<PHINode *> &Phis);
    void processPhiBranchingJoinLabelCopy(PHINode *Phi, unsigned Inc,
                                          std::vector<PHINode *> &Phis);
    PHINode *copyNonCoalescedPhi(PHINode *PhiPred, PHINode *PhiSucc);
    void processCalls(FunctionGroup *FG);
    void processKernelArgs(FunctionGroup *FG);
    void coalesceOutputArgs(FunctionGroup *FG);
    void coalesceCallables();
    void coalesceGlobalLoads(FunctionGroup *FG);
    Instruction *insertCopy(SimpleValue Input, LiveRange *LR,
                            Instruction *InsertBefore, StringRef Name,
                            unsigned Number);
    Instruction *insertIntoStruct(Type *Ty, unsigned FlattenedIndex,
                                  Value *OldStruct, Instruction *NewVal,
                                  Instruction *InsertBefore);
    void showCoalesceFail(SimpleValue V, const DebugLoc &DL, const char *Intro,
                          LiveRange *DestLR, LiveRange *SourceLR);
    // Functions for creating copies
    void applyCopies();
    Instruction *createCopy(const CopyData &CD);
    void replaceAllUsesWith(Instruction *OldInst, Instruction *NewInst);
    // Functions for opimized copies generation
    SortedCopies getSortedCopyData();
    void applyCopiesOptimized();
    void applyCopiesForValue(const std::set<CopyData> &CDSet);
    template <typename Iter>
    Iter mergeCopiesTillFailed(SimpleValue CopySV, Iter BeginIt, Iter EndIt);
    // Helpers
    DominatorTree *getDomTree(Function *F) const {
      return DTWrapper->getDomTree(F);
    }
    LoopInfo *getLoopInfo(Function *F) const {
      return LIWrapper->getLoopInfo(F);
    }
  };

} // end anonymous namespace

namespace llvm {
void initializeGenXCoalescingWrapperPass(PassRegistry &);
using GenXCoalescingWrapper = FunctionGroupWrapperPass<GenXCoalescing>;
}
INITIALIZE_PASS_BEGIN(GenXCoalescingWrapper, "GenXCoalescingWrapper",
                      "GenXCoalescingWrapper", false, false)
INITIALIZE_PASS_DEPENDENCY(GenXGroupBalingWrapper)
INITIALIZE_PASS_DEPENDENCY(GenXLivenessWrapper)
INITIALIZE_PASS_DEPENDENCY(GenXNumberingWrapper)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeGroupWrapperPassWrapper);
INITIALIZE_PASS_DEPENDENCY(LoopInfoGroupWrapperPassWrapper);
INITIALIZE_PASS_END(GenXCoalescingWrapper, "GenXCoalescingWrapper",
                    "GenXCoalescingWrapper", false, false)

ModulePass *llvm::createGenXCoalescingWrapperPass() {
  initializeGenXCoalescingWrapperPass(*PassRegistry::getPassRegistry());
  return new GenXCoalescingWrapper();
}

/***********************************************************************
 * runOnFunctionGroup : run the coalescing pass for this FunctionGroup
 */
bool GenXCoalescing::runOnFunctionGroup(FunctionGroup &FG)
{
  DL = &FG.getModule()->getDataLayout();
  // Get analyses that we use and/or modify.
  ST = &getAnalysis<TargetPassConfig>()
            .getTM<GenXTargetMachine>()
            .getGenXSubtarget();
  Baling = &getAnalysis<GenXGroupBaling>();
  Liveness = &getAnalysis<GenXLiveness>();
  Numbering = &getAnalysis<GenXNumbering>();
  DTWrapper = &getAnalysis<DominatorTreeGroupWrapperPass>();
  LIWrapper = &getAnalysis<LoopInfoGroupWrapperPass>();

  // Coalesce all global loads prior to normal coalescing.
  coalesceGlobalLoads(&FG);

  // Record all the coalescing candidates except the call arg and return
  // value pre-copy ones.
  visit(FG);

  // Process the copy coalescing candidates.
  for (unsigned i = 0; i != CopyCandidates.size(); ++i)
    processCopyCandidate(CopyCandidates[i]);

  // Record the call arg and return value pre-copy candidates.
  recordCallCandidates(&FG);

  // Sort the array of normal coalescing candidates (including phi ones) then
  // process them. Preserve original ordering for equal priority candidates
  // to get consistent results across different runs.
  std::stable_sort(NormalCandidates.begin(), NormalCandidates.end());
  for (unsigned i = 0; i != NormalCandidates.size(); ++i)
    processCandidate(NormalCandidates[i]);

  // Now scan all phi nodes again, inserting copies where necessary. Doing
  // them in one go here ensures that the copies appear in the predecessor
  // blocks in the same order as the phi nodes, which is the basis on which
  // we computed live ranges.
  processPhiNodes(&FG);

  // Scan all the calls, inserting copies where necessary for call arg
  // pre-copies and return value pre- and post-copies. Doing them in one go
  // here ensures that the copies appear in the order that live range
  // computation assumed they would appear. Also, for call arg and return
  // value pre-copies, a single coalesce candidate is shared across multiple
  // calls/returns using the same LR, so we need this separate scan to find
  // the calls/returns.
  processCalls(&FG);

  // Add a copy for each kernel arg that is not aligned enough.
  processKernelArgs(&FG);
  coalesceCallables();
  coalesceOutputArgs(&FG);

  applyCopies();

  CopyCandidates.clear();
  NormalCandidates.clear();
  Callables.clear();
  CallToRetVal.clear();
  ToCopy.clear();
  CopyCoalesced.clear();
  return true;
}

/***********************************************************************
 * visitPHINode : for each incoming, record a phi candidate, unless it is a
 * registerless value (EM/RM).
 * If the incoming block is a branching join label block, then we
 * cannot insert any phi copies there, so give the coalescing
 * candidate a high priority to ensure it gets coalesced first.
 */
void GenXCoalescing::visitPHINode(PHINode &Phi) {
  if (!vc::isRealOrNoneCategory(Liveness->getLiveRange(&Phi)->getCategory()))
    return;
  for (unsigned i = 0; i < Phi.getNumIncomingValues(); ++i) {
    auto IncomingBlock = Phi.getIncomingBlock(i);
    unsigned Priority = GotoJoin::isBranchingJoinLabelBlock(IncomingBlock) ?
                        UINT_MAX : getPriority(Phi.getType(), IncomingBlock);
    recordPhiCandidate(Phi, i, Priority);
  }
}

/***********************************************************************
 * visitCallInst : process inlime asm and direct non-intrinsic calls
 */
void GenXCoalescing::visitCallInst(CallInst &CI) {
  if (CI.isInlineAsm()) {
    InlineAsm *IA = cast<InlineAsm>(IGCLLVM::getCalledValue(CI));
    // Do not process if no constraints provided or it's baled
    // (the coalescing actually needs to be done at the wrregion).
    if (IA->getConstraintString().empty() || Baling->isBaled(&CI))
      return;
    unsigned NumOutputs = genx::getInlineAsmNumOutputs(&CI);
    auto ConstraintsInfo = genx::getGenXInlineAsmInfo(&CI);
    // we need to coalesce if there is a '+' modifier
    // because those operands are tied and have to be in the same
    // registers
    for (unsigned ArgNo = 0; ArgNo < ConstraintsInfo.size(); ArgNo++) {
      auto &Info = ConstraintsInfo[ArgNo];
      if (!Info.isOutput() || !Info.hasMatchingInput())
        continue;
      unsigned ActualIdx = Info.getMatchingInput() - NumOutputs;
      auto OpInst = dyn_cast<Instruction>(CI.getOperand(ActualIdx));
      if (!OpInst || Baling->isBaled(OpInst))
        continue;
      SimpleValue SV (&CI, isa<StructType>(CI.getType()) ? ArgNo : 0);
      recordNormalCandidate(SV, ActualIdx);
    }
    return;
  }
  if (IGCLLVM::isIndirectCall(CI))
    return;
  // This is a non-intrinsic call. If it returns a value, mark
  // (elements of) the return value for coalescing with the
  // unified return value.
  if (!CI.getType()->isVoidTy()) {
    for (unsigned i = 0, e = IndexFlattener::getNumElements(CI.getType());
         i != e; ++i)
      recordUnifiedRetCandidate(SimpleValue(&CI, i), i);
    return;
  }
  // handle callable kernel
  Function *Callee = CI.getCalledFunction();
  if (!Callee->hasFnAttribute("CMCallable"))
    return;
  if (CI.getFunction()->hasFnAttribute("CMCallable")) {
    vc::diagnose(CI.getContext(), "GenXCoalescing",
                 "Callable function must not call", &CI);
  }
  Callables.push_back(&CI);
}

/***********************************************************************
 * visitGenXIntrinsicInst : process an intrinsic with a two address operand
 * (including the case of operand 0 in wrregion). That operand has to be in
 * the same register as the result.
 * NOTE: *.predef.reg intrinsics should not participate in coalescing
 * since they don't have any LR
 */
void GenXCoalescing::visitGenXIntrinsicInst(GenXIntrinsicInst &II) {
  if (GenXIntrinsic::isReadWritePredefReg(&II))
    return;
  auto OperandNum = getTwoAddressOperandNum(&II);
  if (!OperandNum)
    return;
  if (Baling->isBaled(&II) ||
      GenXIntrinsic::isReadWritePredefReg(II.getOperand(0))) {
    // The intrinsic is baled into a wrregion. The two address
    // operand must also have a rdregion baled in whose input is
    // the "old value" input of the wrregion, and the coalescing
    // actually needs to be done at the wrregion.  That is handled
    // when this pass reaches the wrregion, so we do not want to do
    // anything here.
    return;
  }
  // Normal unbaled twoaddr operand.
  recordNormalCandidate(&II, *OperandNum);
}

/***********************************************************************
 * visitCastInst : the source and destination of a no-op cast can copy coalesce,
 * but only if it is not the case that the source is a phi and
 * the destination has a use in a phi node in the same block and
 * after the source's phi. If the above is the case, then we try
 * and normal coalesce instead, which fails, leading to a copy
 * being generated.
 * Ignore bitcasts of volatile globals as they normally
 * participate in load/store only, so no coalescing is possible anyway.
 */
void GenXCoalescing::visitCastInst(CastInst &CI) {
  if (!genx::isNoopCast(&CI))
    return;
  IGC_ASSERT_MESSAGE(!isa<StructType>(CI.getDestTy()), "not expecting cast to struct");
  IGC_ASSERT_MESSAGE(!isa<StructType>(CI.getSrcTy()), "not expecting cast from struct");
  if (GenXLiveness::wrapsAround(CI.getOperand(0), &CI))
    recordNormalCandidate(&CI, 0);
  else {
    if (!Liveness->getLiveRangeOrNull(&CI))
      return;
    if (GenXIntrinsic::isReadWritePredefReg(CI.getOperand(0)))
      return;
    if (auto * GV = dyn_cast<GlobalVariable>(CI.getOperandUse(0));
        GV && GV->hasAttribute(VCModuleMD::VCVolatile))
      return;
    recordCopyCandidate(&CI, 0);
  }
}

/***********************************************************************
 * visitExtractValueInst : copy coalesce the element being extracted, as long as
 * both source and destination have live ranges. The two cases where
 * they don't are:
 *  1. the source live range got removed in the code below that
 *     handles undef elements in an insertvalue chain;
 *  2. this is the extract of the !any(EM) result of a goto/join,
 *     which does not have a live range because it is baled in to the
 *     branch.
 */
void GenXCoalescing::visitExtractValueInst(ExtractValueInst &EVI) {
  if (!Liveness->getLiveRangeOrNull(&EVI))
    return;
  unsigned StartIndex = IndexFlattener::flatten(
      cast<StructType>(EVI.getAggregateOperand()->getType()), EVI.getIndices());
  unsigned NumElements = IndexFlattener::getNumElements(EVI.getType());
  for (unsigned i = 0; i < NumElements; ++i)
    if (Liveness->getLiveRangeOrNull(
            SimpleValue(EVI.getAggregateOperand(), StartIndex + i)))
      recordCopyCandidate(SimpleValue(&EVI, i), 0, StartIndex + i);
}


/***********************************************************************
 * visitInsertValueInst :
 * First, if the struct value input is undef, scan the possible chain
 * of insertvalues and remove the live range for any SimpleValue that
 * is undef. We need to do this to stop a register being allocated
 * later for a coalesced SimpleValue from a chain of insertvalues
 * for a return where that element is never set.
 */
void GenXCoalescing::visitInsertValueInst(InsertValueInst &IVI) {
  auto ST = cast<StructType>(IVI.getType());
  unsigned NumElements = IndexFlattener::getNumElements(ST);
  if (isa<UndefValue>(IVI.getAggregateOperand())) {
    SmallBitVector IsDefined(NumElements);
    // For each insertvalue in the chain:
    for (auto ThisIVI = &IVI; ThisIVI;) {
      // For the element set by this one, set it as defined (unless the
      // input is undef).
      unsigned StartIdx = IndexFlattener::flatten(ST, ThisIVI->getIndices());
      unsigned EndIdx =
          StartIdx + IndexFlattener::getNumElements(
                         ThisIVI->getInsertedValueOperand()->getType());
      if (!isa<UndefValue>(ThisIVI->getInsertedValueOperand()))
        IsDefined.set(StartIdx, EndIdx);
      // For any element that is still undef, remove its live range.
      for (unsigned i = 0; i != NumElements; ++i)
        if (!IsDefined[i])
          Liveness->removeValue(SimpleValue(ThisIVI, i));
      if (!ThisIVI->hasOneUse())
        break;
      ThisIVI = dyn_cast<InsertValueInst>(ThisIVI->use_begin()->getUser());
    }
  }
  // Copy coalesce the element being inserted and the other elements,
  // as long as the appropriate live ranges did not get removed above.
  unsigned StartIdx = IndexFlattener::flatten(ST, IVI.getIndices());
  unsigned EndIdx = StartIdx + IndexFlattener::getNumElements(
                                   IVI.getInsertedValueOperand()->getType());
  for (unsigned i = 0; i != NumElements; ++i) {
    if (!Liveness->getLiveRangeOrNull(SimpleValue(&IVI, i)))
      continue;
    if ((StartIdx <= i) && (i < EndIdx)) {
      if (Liveness->getLiveRangeOrNull(SimpleValue(IVI.getInsertedValueOperand(), i - StartIdx)))
        recordCopyCandidate(SimpleValue(&IVI, i), 1, i - StartIdx);
    } else {
      if (Liveness->getLiveRangeOrNull(
              SimpleValue(IVI.getAggregateOperand(), i)))
        recordCopyCandidate(SimpleValue(&IVI, i), 0, i);
    }
  }
}

/***********************************************************************
 * recordCallCandidates : record the call arg pre-copy and ret value
 *                        pre-copy candidates
 *
 * This is done here, after copy coalescing has been done, so we can
 * more accurately estimate the cost of not coalescing a candidate by
 * summing the cost from each call site / return instruction that uses
 * the same (copy coalesced) value.
 */
void GenXCoalescing::recordCallCandidates(FunctionGroup *FG)
{
  // For each subroutine...
  for (auto fgi = FG->begin() + 1, fge = FG->end(); fgi != fge; ++fgi) {
    Function *F = *fgi;
    // Gather the call sites.
    SmallVector<Instruction *, 8> CallSites;
    for (auto *U: F->users())
      if (auto *CI = checkFunctionCall(U, F))
        CallSites.push_back(CI);
    // For each arg...
    unsigned ArgIdx = 0;
    for (auto ai = F->arg_begin(), ae = F->arg_end();
        ai != ae; ++ai, ++ArgIdx) {
      Argument *Arg = &*ai;
      if (Arg->use_empty())
        continue; // Ignore unused arg.
      // Record a coalesce candidate for each unique input LR for each
      // struct element in the arg.
      recordCallArgCandidates(Arg, ArgIdx, CallSites);
    }
    // Now scan for return value pre-copies.
    if (F->getReturnType()->isVoidTy())
      continue;
    // Gather the return insts by looking at the terminator of each BB.
    SmallVector<Instruction *, 8> RetInsts;
    for (auto fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
      auto RetInst = dyn_cast<ReturnInst>(fi->getTerminator());
      if (RetInst)
        RetInsts.push_back(RetInst);
    }
    // Record a coalesce candidate for each unique input LR for each
    // struct element in the return value.
    recordCallArgCandidates(Liveness->getUnifiedRet(F), 0, RetInsts);
  }
}

/***********************************************************************
 * recordCallArgCandidates : common code for adding a candidate for each
 *    struct element of a call arg or a return value pre-copy
 *
 * Enter:   Dest = destination Value; the Argument for a call arg, or the
 *                 Function's unified return value for a ret pre-copy
 *          ArgNum = argument number for call arg, 0 for ret pre-copy
 *          Insts = array of call sites or return instructions
 *
 * For each struct element, this adds a coalesce candidate for each unique LR
 * used as a call arg or return value.
 */
namespace {
struct CallArg {
  Use *U;
  LiveRange *LR;
  CallArg(Use *U, LiveRange *LR) : U(U), LR(LR) {}
};
} // namespace
void GenXCoalescing::recordCallArgCandidates(Value *Dest, unsigned ArgNum,
    ArrayRef<Instruction *> Insts)
{
  for (unsigned StructIdx = 0,
      StructEnd = IndexFlattener::getNumElements(Dest->getType());
      StructIdx != StructEnd; ++StructIdx) {
    // For each unique LR used as this arg at any call site, sum the
    // cost and add a candidate.
    SmallVector<CallArg, 8> CallArgs;
    for (unsigned i = 0, ie = Insts.size(); i != ie; ++i) {
      Use *U = &Insts[i]->getOperandUse(ArgNum);
      CallArgs.emplace_back(
          U, Liveness->getLiveRangeOrNull(SimpleValue(*U, StructIdx)));
    }
    for (unsigned i = 0, ie = CallArgs.size(); i != ie; ++i) {
      LiveRange *LR = CallArgs[i].LR;
      if (!LR)
        continue; // Already done this one (or it was an undef).
      Use *U = CallArgs[i].U;
      unsigned Priority = 0;
      for (unsigned j = i, je = CallArgs.size(); j != je; ++j) {
        if (LR != CallArgs[j].LR)
          continue;
        Priority += getPriority(IndexFlattener::getElementType(
              (*U)->getType(), StructIdx), Insts[j]->getParent());
        CallArgs[j].LR = nullptr; // Blank out so we can see we have done this one.
      }
      recordCallArgCandidate(SimpleValue(Dest, StructIdx),
          U, StructIdx, Priority);
    }
  }
}

/***********************************************************************
 * getPriority : get priority of coalescing candidate
 *
 * Enter:   Ty = type that would need to be copied if coalescing failed,
 *               so we can estimate the copy cost.
 *          BB = basic block where copy would be inserted, so we can use
 *               loop depth to adjust the cost.
 *
 * Return:  priority (estimate of cost of inserting a copy)
 */
unsigned GenXCoalescing::getPriority(Type *Ty, BasicBlock *BB) const
{
  IGC_ASSERT(Ty);
  IGC_ASSERT(BB);
  // Multiplier of priority when copy located in loop.
  constexpr unsigned LoopScale = 4;

  // Estimate number of moves required for this type.
  unsigned VecWidth = vc::getTypeSize(Ty, DL).inBytesCeil();
  unsigned Priority = VecWidth / ST->getGRFByteSize() +
    countPopulation(VecWidth % ST->getGRFByteSize());
  // Scale by loop depth.
  Priority *= std::pow(LoopScale,
      getLoopInfo(BB->getParent())->getLoopDepth(BB));
  return Priority;
}

unsigned GenXCoalescing::getPriority(SimpleValue SV) const
{
  IGC_ASSERT(isa<Instruction>(SV.getValue()));
  auto *BB = cast<Instruction>(SV.getValue())->getParent();
  auto *Type = IndexFlattener::getElementType(SV.getValue()->getType(), SV.getIndex());
  return getPriority(Type, BB);
}

/***********************************************************************
 * recordCandidate : record a candidate for coalescing
 *
 * Enter:   Dest = destination of copy
 *          UseInDest = pointer to the use of the source in Dest
 *          SourceIndex = flattened index of element in source struct
 *          Priority = priority of coalescing this candidate
 *          Candidates = vector of candidates to push to
 *
 * For call arg coalescing, Dest is the subroutine's Argument, and
 * UseInDest/SourceIndex are the use in one of the possibly many call sites
 * using the same source value.
 *
 * For ret value pre-copy coalescing (before the return inst), Dest is the the
 * unified return value, and UseInDest/SourceIndex are the use in one of the
 * possibly many return instructions using the same source value.
 *
 * For ret value post-copy coalescing (after the call inst), Dest is the
 * CallInst, and UseInDest and SourceIndex are 0.
 */
void GenXCoalescing::recordCandidate(SimpleValue Dest, Use *UseInDest,
    unsigned SourceIndex, unsigned Priority, std::vector<Candidate> &Candidates)
{
  LLVM_DEBUG(dbgs() << "Trying to record cand " << *(Dest.getValue()) << "\n");
  if (UseInDest && (isa<UndefValue>(*UseInDest) || isa<Constant>(*UseInDest)))
    return;
  LLVM_DEBUG(dbgs() << "Recording cand " << *(Dest.getValue()) << "\n");
  Candidates.emplace_back(Dest, UseInDest, SourceIndex, Priority);
  ++NumCoalescingCandidates;
}

/***********************************************************************
 * processCandidate : process a coalescing candidate
 *
 * This attempts to coalesce the candidate. On failure, it inserts a copy
 * if necessary:
 *
 *  - a copy candidate never fails to coalesce;
 *  - a two address candidate needs a copy and it is inserted here;
 *  - a phi candidate needs a copy, but it is not inserted here. Instead it
 *    is inserted later so we can ensure that multiple copies inserted at
 *    the end of an incoming block are in phi node order, which was the
 *    assumption made by the live range calculation.
 *
 * See the comment at the top of recordCandidate for the special values of
 * fields in Candidate for a call arg coalesce and a ret value coalesce.
 */
void GenXCoalescing::processCandidate(const Candidate &Cand, bool IsCopy)
{
  SimpleValue Dest = Cand.Dest;
  SimpleValue Source;
  if (!Cand.UseInDest) {
    auto *Callee = cast<CallInst>(Dest.getValue())->getCalledFunction();
    // Do not process calls to external functions
    if (Callee->isDeclaration())
      return;

    // This is a return value post-copy coalesce candidate. The actual source
    // is the unified return value.
    Source = SimpleValue(Liveness->getUnifiedRet(Callee), Cand.SourceIndex);
  } else
    Source = SimpleValue(*Cand.UseInDest, Cand.SourceIndex);
  LLVM_DEBUG(dbgs() << "Trying coalesce from ";
      Source.printName(dbgs());
      dbgs() << " to ";
      Dest.printName(dbgs());
      dbgs() << " priority " << Cand.Priority;
      if (isa<Argument>(Dest.getValue()))
        dbgs() << " (call arg)";
      else if (Liveness->isUnifiedRet(Dest.getValue()))
        dbgs() << " (ret pre-copy)";
      else if (!Cand.UseInDest)
        dbgs() << " (ret post-copy)";
      dbgs() << "\n");
  LiveRange *DestLR = Liveness->getLiveRange(Dest);
  LiveRange *SourceLR = 0;
  // Source should not be a constant (but could be undef) because
  // GenXLowering ensured that all our two address operands and phi incomings
  // are not constant.
  IGC_ASSERT(!Cand.UseInDest || !isa<Constant>(Source.getValue()) || isa<UndefValue>(Source.getValue()));
  SourceLR = Liveness->getLiveRange(Source);
  IGC_ASSERT(DestLR);
  if (SourceLR == DestLR)
    return; // already coalesced
  if (SourceLR && SourceLR->Category == DestLR->Category) {
    if (IsCopy) {
      // For a copy candidate, we can coalesce if the source and destination do
      // not copy-interfere, i.e. we do not have a situation where DestLR
      // wraps round a loop into a phi use in the same basic block as the phi
      // def of SourceLR but after it.
      if (!Liveness->copyInterfere(SourceLR, DestLR)) {
        Liveness->coalesce(DestLR, SourceLR, /*DisallowCASC=*/ false);
        if (auto *CI = dyn_cast<CastInst>(Dest.getValue());
            CI && genx::isNoopCast(CI)) {
          CopyCoalesced[CI] = Source.getValue();
        }
        return;
      }
    } else {
      // For a normal candidate, we can coalesce if the source and destination
      // do not interfere, i.e. there is no point in the program where both
      // LRs are live.
      if (!Liveness->twoAddrInterfere(DestLR, SourceLR)) {
        // In the coalesce, disallow future call arg special coalescing if this
        // is not a call arg coalesce.
        Liveness->coalesce(DestLR, SourceLR,
            /*DisallowCASC=*/ !isa<Argument>(Dest.getValue()));
        return;
      }
    }
  }
#if 0
  // Disable call arg special coalescing for now, as it seems to break the FRC_MC example.

  if (isa<Argument>(Dest.getValue())
      && SourceLR->Category == DestLR->Category) {
    // This is an attempt at call arg coalescing. The two LRs interfere, but
    // we can still try for "call arg special coalescing" (CASC). See the
    // comment at the top of the file.
    if (!DestLR->DisallowCASC) {
      // CASC not disallowed. (It would have been disallowed if DestLR had
      // already participated in normal coalescing other than CASC.)
      // For any call site where SourceLR is not the corresponding call arg,
      // check that A is not live.
      auto ThisCallSite = cast<CallInst>(Cand->UseInDest->getUser());
      auto Callee = ThisCallSite->getCalledFunction();
      bool FailedCASC = false;
      for (auto ui = Callee->use_begin(), ue = Callee->use_end();
          ui != ue; ++ui) {
        auto CallSite = cast<CallInst>(ui->getUser());
        if (CallSite == ThisCallSite)
          continue;
        auto OtherArg = SimpleValue(CallSite->getArgOperand(cast<Argument>(
                Dest.getValue())->getArgNo()), Dest.getIndex());
        auto OtherLR = Liveness->getLiveRange(OtherArg);
        // Check whether OtherArg is the same as SourceLR. This check covers
        // several cases:
        // 1. OtherArg == SourceLR: the other arg is already coalesced with
        //    our arg, so it would be OK to do CASC.
        // 2. OtherArg is DestLR, meaning that the other call arg has already
        //    been coalesced with the func arg. We cannot do CASC if SourceLR
        //    and OtherArg interfere, which they do because we already know
        //    that DestLR interferes with SourceLR.
        // 3. OtherArg is something else, meaning that some other value will
        //    be copied to the func arg here. We cannot do CASC if SourceLR
        //    and OtherArg interfere.
        if (OtherLR == SourceLR)
          continue;
        if (Liveness->interfere(OtherLR, SourceLR)) {
          FailedCASC = true;
          break;
        }
      }
      if (!FailedCASC) {
        // Can coalesce. Do not disallow future CASC.
        Liveness->coalesce(DestLR, SourceLR, /*DisallowCASC=*/ false);
        return;
      }
    }
  }
#endif

  // Coalescing failed.
  LLVM_DEBUG(
    if (SourceLR) {
      dbgs() << "Live ranges \"";
      DestLR->print(dbgs());
      dbgs() << "\" and \"";
      SourceLR->print(dbgs());
      dbgs() << "\"" << (IsCopy ? " copy" : "") << " interfere, not coalescing\n";
    } else {
      dbgs() << "Need copy of constant \"";
      Source.print(dbgs());
      dbgs() << "\" to \"";
      Dest.printName(dbgs());
      dbgs() << "\"\n";
    }
  );
  if (isa<PHINode>(Dest.getValue()))
    return; // Candidate is phi; copy insertion done later.
  if (isa<Argument>(Dest.getValue()))
    return; // Call arg pre-copy, defer copy insertion
  if (Liveness->isUnifiedRet(Dest.getValue()))
    return; // Return value pre-copy, defer copy insertion
  if (!Cand.UseInDest)
    return; // Return value post-copy, defer copy insertion
  // Ignore SIMD CF
  auto DestCategory = Liveness->getLiveRange(Cand.Dest)->getCategory();
  if (!vc::isRealOrNoneCategory(DestCategory))
    return;
  if (auto *CI = dyn_cast<CastInst>(Dest.getValue());
      CI && genx::isNoopCast(CI)) {
    // A bitcast is normally copy coalesced, which means it cannot fail to
    // coalesce. However, if the source is a phi node and the destination
    // wraps round the loop and is used in another phi node in the same
    // block that is later than the first phi node, then we instead
    // try to normal coalesce, which fails because they interfere.
    // This happens with a bitcast inserted in GenXLiveRanges to resolve
    // an overlapping circular phi, but can happen in other cases too.
    unsigned TySz = vc::getTypeSize(Dest.getValue()->getType(), DL).inBytes();
    if (isPowerOf2_32(TySz) && TySz <= ST->getGRFByteSize()) {
      // This is a bitcast with a legal size for a single copy. We do not
      // insert a copy, because GenXCisaBuilder will generate one.
      // (GenXLegalization does not legalize a bitcast, so it can be
      // illegal size here. We do that on the basis that a bitcast is
      // normally copy coalesced.)
      return;
    }
    // Otherwise, it is a bitcast of size more than 1 GRF or non-power-of-two,
    // so we insert a copy.
  }

  // Store info for two address op copy
  Instruction *DestInst = cast<Instruction>(Dest.getValue());
  ToCopy.emplace_back(Dest, Source, Cand.UseInDest, DestInst, TWOADDRCOPY,
                      Numbering->getNumber(DestInst), ToCopy.size());
}

/***********************************************************************
 * processPhiNodes : add copies for uncoalesced phi node incomings
 */
void GenXCoalescing::processPhiNodes(FunctionGroup *FG)
{
  std::vector<PhiCopy> PhiCopies;

  for (auto fgi = FG->begin(), fge = FG->end(); fgi != fge; ++fgi) {
    Function *F = *fgi;
    for (Function::iterator fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
      BasicBlock *BB = &*fi;
      for (BasicBlock::iterator bi = BB->begin(), be = BB->end(); bi != be; ++bi) {
        // Scan the phi nodes at the start of this BB, if any.
        PHINode *Phi = dyn_cast<PHINode>(&*bi);
        if (!Phi)
          break;

        // Collect copies to process
        analysePhiCopies(Phi, PhiCopies);
      }
    }
  }

  // Perform copy of uncoalesced phi node incomings.
  // New phis can be created during this, store them.
  std::vector<PHINode *> NewPhis;
  for (auto Elem : PhiCopies) {
    processPhiCopy(Elem.Phi, Elem.IncomingIdx, NewPhis);
  }
  // Phi copies are resolved. Clean the list.
  PhiCopies.clear();

  // Process newly created phis. This loop is executed
  // when coalescing failed to resolve issues with phis
  // in branching join label blocks. Such situation is
  // very rare because coalescing tries to solve it
  // with the highest priority.
  while (!NewPhis.empty()) {
    // Collect phi copy candidates
    for (auto *Phi : NewPhis) {
      analysePhiCopies(Phi, PhiCopies);
    }
    // Phi copies are collected, clean current Phis worklist
    NewPhis.clear();

    // Perform copy of uncoalesced phi node incomings.
    for (auto Elem : PhiCopies) {
      processPhiCopy(Elem.Phi, Elem.IncomingIdx, NewPhis);
    }
    // Phi copies are resolved. Clean the list.
    PhiCopies.clear();
  }
}

/***********************************************************************
 * analysePhiCopies : for one phi node, collect copies for uncoalesced incomings
 */
void GenXCoalescing::analysePhiCopies(PHINode *Phi,
                                      std::vector<PhiCopy> &ToProcess) {
  // Scan each incoming to see if it was successfully coalesced.
  LiveRange *DestLR = Liveness->getLiveRange(Phi);
  if (!vc::isRealOrNoneCategory(DestLR->getCategory()))
    return; // Ignore phi node of EM/RM value.
  for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
    Value *Incoming = Phi->getIncomingValue(i);
    // Incoming should not be a constant (but could be undef) because
    // GenXPostLegalization and GenXCategory called loadNonSimpleConstants
    // to load the non-simple constant incomings, then GenXCategory also
    // called GenXConstants::loadConstant for each remaining (simple)
    // constant.
    if (isa<UndefValue>(Incoming))
      continue; // undef, no copy needed
    IGC_ASSERT(!isa<Constant>(Incoming));
    if (Liveness->getLiveRange(Incoming) == DestLR)
      continue; // coalesced, no copy needed
    // A phi copy is needed
    auto IncomingBlock = Phi->getIncomingBlock(i);
    LLVM_DEBUG(dbgs() << "Need phi copy " << Incoming->getName() << " -> "
                      << Phi->getName() << " in " << IncomingBlock->getName()
                      << "\n");
    ToProcess.emplace_back(Phi, i);
  }
}

/***********************************************************************
 * processPhiCopy : for one phi node incoming, add copy
 */
void GenXCoalescing::processPhiCopy(PHINode *Phi, unsigned Inc,
                                    std::vector<PHINode *> &Phis) {
  LiveRange *DestLR = Liveness->getLiveRange(Phi);
  Value *Incoming = Phi->getIncomingValue(Inc);
  auto *IncomingBlock = Phi->getIncomingBlock(Inc);
  // Should be checked in analysePhiCopies
  IGC_ASSERT_MESSAGE(vc::isRealOrNoneCategory(DestLR->getCategory()),
                     "Should be checked earlier!");
  IGC_ASSERT_MESSAGE(!isa<UndefValue>(Incoming), "Should be checked earlier!");
  IGC_ASSERT_MESSAGE(!isa<Constant>(Incoming), "Should be checked earlier!");
  // Check it again: something could change
  if (Liveness->getLiveRange(Incoming) == DestLR) {
    LLVM_DEBUG(dbgs() << "Already coalesced " << Incoming->getName() << " -> "
                      << Phi->getName() << " in " << IncomingBlock->getName()
                      << "\n");
    return;
  }

  LLVM_DEBUG(dbgs() << "Copying " << Incoming->getName() << " -> "
                    << Phi->getName() << " in " << IncomingBlock->getName()
                    << "\n");

  // Handle branching join label block separately
  if (GotoJoin::isBranchingJoinLabelBlock(IncomingBlock)) {
    processPhiBranchingJoinLabelCopy(Phi, Inc, Phis);
    return;
  }

  DominatorTree *DomTree = getDomTree(IncomingBlock->getParent());
  Instruction *InsertPoint = IncomingBlock->getTerminator();
  InsertPoint = GotoJoin::getLegalInsertionPoint(InsertPoint, DomTree);

  if (auto *I = dyn_cast<Instruction>(Incoming)) {
    // This should not happen for good BBs (not join blocks)
    // if DFG is correct.
    IGC_ASSERT_MESSAGE(DomTree->dominates(I->getParent(), InsertPoint->getParent()),
      "Dominance corrupted!");
  }

  // Store info for copy
  ToCopy.emplace_back(SimpleValue(Phi), SimpleValue(Incoming),
                      &Phi->getOperandUse(Inc), InsertPoint, PHICOPY,
                      Numbering->getNumber(InsertPoint), ToCopy.size());
}

/***********************************************************************
 * processPhiBranchingJoinLabelCopy : for one phi node incoming, add copy
 * for branching join label incoming BB case
 */
void GenXCoalescing::processPhiBranchingJoinLabelCopy(
    PHINode *Phi, unsigned Inc, std::vector<PHINode *> &Phis) {
  LiveRange *DestLR = Liveness->getLiveRange(Phi);
  Value *Incoming = Phi->getIncomingValue(Inc);
  auto *IncomingBlock = Phi->getIncomingBlock(Inc);
  // Should be checked in analysePhiCopies
  IGC_ASSERT_MESSAGE(vc::isRealOrNoneCategory(DestLR->getCategory()),
                     "Should be checked earlier!");
  IGC_ASSERT_MESSAGE(!isa<UndefValue>(Incoming), "Should be checked earlier!");
  IGC_ASSERT_MESSAGE(!isa<Constant>(Incoming), "Should be checked earlier!");
  // Should be checked in processPhiCopy
  IGC_ASSERT_MESSAGE(Liveness->getLiveRange(Incoming) != DestLR,
    "Should be checked earlier!");
  IGC_ASSERT_MESSAGE(GotoJoin::isBranchingJoinLabelBlock(IncomingBlock),
    "Should be checked earlier!");

  LLVM_DEBUG(dbgs() << "Handling branching join label block case\n");

  DominatorTree *DomTree = getDomTree(IncomingBlock->getParent());
  Instruction *InsertPoint = IncomingBlock->getTerminator();
  InsertPoint = GotoJoin::getLegalInsertionPoint(InsertPoint, DomTree);

  if (auto *PhiPred = dyn_cast<PHINode>(Incoming)) {
    // In case when pred is Phi, it is possible to meet Phi in
    // branching join blocks since such Phi does not brake
    // SIMD CF Conformance. If such situation happens, we cannot
    // perform copy of a phi value copy, we need to perform copy
    // on all its incoming values. To do that, copy Phi and add
    // it to Phis worklist.
    //
    // This situation is detected via corrupted dominance.
    if (!DomTree->dominates(PhiPred->getParent(), InsertPoint->getParent())) {
      auto *PhiCopy = copyNonCoalescedPhi(PhiPred, Phi);
      IGC_ASSERT_MESSAGE(PhiCopy, "Invalid phi copy!");
      Phis.push_back(PhiCopy);
      return;
    }
  }

  if (auto *I = dyn_cast<Instruction>(Incoming)) {
    // This should not happen for good BBs (not join blocks)
    // if DFG is correct.
    //
    // For join block, def must be somewhere before it
    // because of SIMD CF Conformance. Case for Phi is
    // described and handled above.
    IGC_ASSERT_MESSAGE(DomTree->dominates(I->getParent(), InsertPoint->getParent()),
      "Dominance corrupted!");
  }

  // Store info for copy
  ToCopy.emplace_back(SimpleValue(Phi), SimpleValue(Incoming),
                      &Phi->getOperandUse(Inc), InsertPoint,
                      PHICOPY_BRANCHING_JP, Numbering->getNumber(InsertPoint),
                      ToCopy.size());
}

/***********************************************************************
 * copyNonCoalescedPhi : copy PhiPred and coalesce copy's LR with
 * PhiSucc's LR
 */
PHINode *GenXCoalescing::copyNonCoalescedPhi(PHINode *PhiPred,
                                             PHINode *PhiSucc) {
  // Perform copy
  auto *PhiCopy = cast<PHINode>(PhiPred->clone());
  PhiCopy->insertBefore(PhiPred->getNextNode());
  PhiCopy->setName(PhiPred->getName() + ".copy");
  Numbering->setNumber(PhiCopy, Numbering->getNumber(PhiPred));

  // Handle LRs
  Liveness->buildLiveRange(PhiCopy);
  LiveRange *DestLR = Liveness->getLiveRange(PhiSucc);
  LiveRange *NewLR = Liveness->getLiveRange(PhiCopy);
  Liveness->coalesce(DestLR, NewLR, false);

  // Update incoming values
  for (unsigned i = 0, e = PhiSucc->getNumIncomingValues(); i != e; ++i) {
    Value *IncValue = PhiSucc->getIncomingValue(i);
    if (IncValue == PhiPred)
      PhiSucc->setIncomingValue(i, PhiCopy);
  }

  return PhiCopy;
}

/***********************************************************************
 * processCalls : insert copies where necessary for call args and ret values
 *
 * This scans all the calls, inserting copies where necessary for call arg
 * pre-copies and return value pre- and post-copies.
 *
 * We need to do them in one go here because
 * 1. a call arg or return value pre-copy coalescing candidate covers
 *    possibly multiple sites where the same LR input is used, without giving
 *    any way of getting back to them all;
 * 2. we want the inserted copies to be in the order that live range
 *    computation assumed they would appear.
 */
void GenXCoalescing::processCalls(FunctionGroup *FG)
{
  // For each subroutine...
  for (auto fgi = FG->begin() + 1, fge = FG->end(); fgi != fge; ++fgi) {
    Function *F = *fgi;
    // For each call site...
    for (auto *U: F->users()) {
      if (auto *CI = genx::checkFunctionCall(U, F)) {
        // For each func arg...
        unsigned ArgIdx = 0;
        for (auto ai = F->arg_begin(), ae = F->arg_end(); ai != ae;
             ++ai, ++ArgIdx) {
          Argument *Arg = &*ai;
          if (Arg->use_empty()) {
            // Arg is unused inside the subroutine. Do not try and process
            // further, as its live range probably does not have a category.
            continue;
          }
          Value *CallArg = CI->getOperand(ArgIdx);
          if (isa<UndefValue>(CallArg)) {
            // Call arg undefined. No coalescing needed.
            continue;
          }
          // For each SimpleValue in the func arg...
          for (unsigned StructIdx = 0,
                        se = IndexFlattener::getNumElements(Arg->getType());
               StructIdx != se; ++StructIdx) {
            auto FuncArgSV = SimpleValue(Arg, StructIdx);
            auto CallArgSV = SimpleValue(CallArg, StructIdx);
            // See if they are coalesced.
            auto DestLR = Liveness->getLiveRange(FuncArgSV);
            auto SourceLR = Liveness->getLiveRangeOrNull(CallArgSV);
            if (!SourceLR)
              // This probably means that source is undef at this index,
              // so no need to insert copies
              continue;
            if (!DestLR || DestLR == SourceLR || F == CI->getFunction())
              continue;
            if (!vc::isRealOrNoneCategory(DestLR->getCategory()))
              continue; // Called function arg is EM.
            // Need to insert a copy. Give it the number of the arg's pre-copy
            // slot.
            LLVM_DEBUG(showCoalesceFail(CallArgSV, CI->getDebugLoc(),
                                        "call arg", DestLR, SourceLR));
            unsigned Num =
                Numbering->getArgPreCopyNumber(CI, ArgIdx, StructIdx);
            Instruction *NewCopy =
                insertCopy(CallArgSV, DestLR, CI, "callarg.precopy", Num);
            NewCopy = insertIntoStruct(Arg->getType(), StructIdx,
                                       CI->getOperand(ArgIdx), NewCopy, CI);
            // Replace operand in call.
            IGC_ASSERT(CI->getOperand(ArgIdx)->getType() == NewCopy->getType());
            CI->setOperand(ArgIdx, NewCopy);
            // No need to extend the live range like we do in the two address op
            // case in processCandidate(). The live range of a func arg already
            // starts at each point where a copy might need to be inserted.
          }
        }
        // Now check the return value post-copy.
        //
        // The code to handle a coalesce failure in a return value post-copy
        // is different to all other cases of coalesce failure, which are
        // pre-copy. We need to ensure that the post-copied value is in the
        // original live range for the original value (the return value),
        // and all the original value's users are changed to use the post-copied
        // value instead. The original value (the return value) gets moved out
        // of its live range and put into that of the unified return value.
        //
        // If the return value is a struct, all the above happens for each
        // struct element, with the extra complication of more new values to
        // handle because of the extractvalue and insertvalue instructions we
        // need to insert.
        //
        // First remember all uses of the return value, because we want to
        // replace them after adding new ones below. Remember if they are
        // all extractvalue with a non-struct result (which should usually be
        // the case because GenXLowering removes most structs).
        SmallVector<Use *, 8> CIUses;
        bool AllUsesAreExtract = isa<StructType>(CI->getType());
        for (auto ui = CI->use_begin(), ue = CI->use_end(); ui != ue; ++ui) {
          auto EV = dyn_cast<ExtractValueInst>(ui->getUser());
          if (!EV || isa<StructType>(EV->getType()))
            AllUsesAreExtract = false;
          CIUses.push_back(&*ui);
        }
        Instruction *InsertBefore = CI->getNextNode();
        Value *StructValue = CI;
        SmallVector<LiveRange *, 8> PreviousElements;
        // For each SimpleValue in the return value...
        for (unsigned StructIdx = 0,
                      se = IndexFlattener::getNumElements(CI->getType());
             StructIdx != se; ++StructIdx) {
          auto UnifiedSV = SimpleValue(Liveness->getUnifiedRet(F), StructIdx);
          auto SV = SimpleValue(CI, StructIdx);
          // See if (the element in) the returned value is dead, or successfully
          // coalesced with (the element in) the unified return value.
          auto DestLR = Liveness->getLiveRangeOrNull(SV);
          PreviousElements.push_back(DestLR);
          if (!DestLR)
            continue; // dead
          auto SourceLR = Liveness->getLiveRange(UnifiedSV);
          if (DestLR == SourceLR)
            continue; // coalesced
          IGC_ASSERT(SourceLR);
          if (!vc::isRealOrNoneCategory(SourceLR->getCategory()))
            continue; // Unified return value is EM, ignore.
          // Remove (the element of) CI, the actual return value, from its
          // own live range, and add it instead to the unified return value.
          // insertCopy() will add the new value to DestLR (what
          // was the LR for the element of CI).
          Liveness->removeValueNoDelete(SV);
          Liveness->setLiveRange(SV, SourceLR);
          // Need to insert a copy. Give it the number of the post-copy slot.
          LLVM_DEBUG(showCoalesceFail(SimpleValue(CI, StructIdx),
                                      CI->getDebugLoc(), "ret postcopy", DestLR,
                                      SourceLR));
          unsigned Num = Numbering->getRetPostCopyNumber(CI, StructIdx);
          SimpleValue Source(CI, StructIdx);
          Instruction *NewCopy =
              insertCopy(Source, DestLR, InsertBefore, "retval.postcopy", Num);
          CallToRetVal[Source] = NewCopy;
          IGC_ASSERT(NewCopy);
          if (AllUsesAreExtract) {
            // For a struct ret value where all the uses are non-struct
            // extractvalue, replace uses of the extractvalues with NewCopy.
            // Doing this, rather than calling insertIntoStruct() and letting
            // the existing extractvalue extract it again, does not improve the
            // code generated by the compiler (insertvalue/extractvalue do not
            // generate any code), but it does make the IR simpler and easier
            // to understand in a dump.
            for (unsigned i = 0, e = CIUses.size(); i != e; ++i) {
              if (!CIUses[i])
                continue;
              auto EV = cast<ExtractValueInst>(CIUses[i]->getUser());
              if (StructIdx ==
                  IndexFlattener::flatten(cast<StructType>(CI->getType()),
                                          EV->getIndices())) {
                NewCopy->takeName(EV);
                replaceAllUsesWith(EV, NewCopy);
                if (EV == InsertBefore)
                  InsertBefore = InsertBefore->getNextNode();
                Liveness->removeValue(SimpleValue(EV));
                EV->eraseFromParent();
                CIUses[i] = 0;
              }
            }
          } else {
            // If this is a struct return value, we also need to insertvalue,
            // creating a new struct value.
            StructValue = insertIntoStruct(CI->getType(), StructIdx,
                                           StructValue, NewCopy, InsertBefore);
            // Also, for this and previously seen elements that are not dead,
            // add that element of StructValue (the new insertvalue) to the live
            // range.
            if (StructValue != NewCopy) {
              for (unsigned k = 0, ke = PreviousElements.size(); k != ke; ++k) {
                if (PreviousElements[k])
                  Liveness->setLiveRange(SimpleValue(StructValue, k),
                                         PreviousElements[k]);
              }
            }
          }
        }
        if (!AllUsesAreExtract) {
          // Replace uses of the whole return value that existed before we added
          // more uses above.
          for (unsigned i = 0, e = CIUses.size(); i != e; ++i) {
            IGC_ASSERT(CIUses[i]->get()->getType() == StructValue->getType());
            *CIUses[i] = StructValue;
          }
        }
      }
    }
    if (F->getReturnType()->isVoidTy())
      continue; // no return value from this func
    // For each return inst in the func...
    for (auto fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
      auto RI = dyn_cast<ReturnInst>(fi->getTerminator());
      if (!RI)
        continue;
      Value *Input = RI->getOperand(0);
      // *.predef.reg intrinsics should not participate in coalescing
      // since they don't have any LR
      if (isa<UndefValue>(Input) || GenXIntrinsic::isReadWritePredefReg(Input))
        continue;
      Value *UnifiedRet = Liveness->getUnifiedRet(F);
      // For each struct element in the return value...
      for (unsigned StructIdx = 0,
          StructEnd = IndexFlattener::getNumElements(UnifiedRet->getType());
          StructIdx != StructEnd; ++StructIdx) {
        auto DestLR = Liveness->getLiveRange(SimpleValue(UnifiedRet, StructIdx));
        auto SourceLR = Liveness->getLiveRange(SimpleValue(Input, StructIdx));
        if (DestLR == SourceLR)
          continue; // coalesced
        // Need to insert a copy. Give it the number of the ret pre-copy slot.
        LLVM_DEBUG(showCoalesceFail(SimpleValue(Input, StructIdx),
                                    RI->getDebugLoc(), "ret precopy", DestLR,
                                    SourceLR));
        unsigned Num = Numbering->getNumber(RI) - StructEnd + StructIdx;
        Instruction *NewCopy = insertCopy(SimpleValue(Input, StructIdx),
            DestLR, RI, "retval.precopy", Num);
        NewCopy = insertIntoStruct(UnifiedRet->getType(), StructIdx,
            RI->getOperand(0), NewCopy, RI);
        // Replace operand in call.
        IGC_ASSERT(RI->getOperand(0)->getType() == NewCopy->getType());
        RI->setOperand(0, NewCopy);
        // No need to extend the live range like we do in the two address op
        // case in processCandidate(). The live range of the unified return
        // value already starts at each point where a copy might need to be
        // inserted.
      }
    }
  }
}

/***********************************************************************
 * processKernelArgs : add a copy for each kernel arg that is not aligned enough
 */
void GenXCoalescing::processKernelArgs(FunctionGroup *FG)
{
  auto F = FG->getHead();
  if (!vc::isKernel(F))
    return;
  Instruction *InsertBefore = F->front().getFirstNonPHIOrDbg();
  vc::KernelMetadata KM{F};
  unsigned Idx = 0;
  for (auto ai = F->arg_begin(), ae = F->arg_end(); ai != ae; ++ai) {
    if (KM.shouldSkipArg(Idx++))
      continue;
    auto Arg = &*ai;
    auto LR = Liveness->getLiveRange(Arg);
    if (!(LR->Offset & ((1U << LR->LogAlignment) - 1)))
      continue; // aligned enough
    // Insert a copy and give the original arg its own new live range. This
    // leaves the original live range still live from the start of the
    // function, and thus interfering with the new live range for the arg,
    // but that doesn't matter.
    SmallVector<Use *, 4> Uses;
    for (auto ui = Arg->use_begin(), ue = Arg->use_end(); ui != ue; ++ui)
      Uses.push_back(&*ui);
    unsigned Num = Numbering->getKernelArgCopyNumber(Arg);
    auto Copy = insertCopy(Arg, LR, InsertBefore, "argcopy", Num);
    Liveness->removeValueNoDelete(Arg);
    for (auto ui = Uses.begin(), ue = Uses.end(); ui != ue; ++ui)
      **ui = Copy;
    auto NewLR = Liveness->getOrCreateLiveRange(Arg);
    NewLR->setCategory(LR->getCategory());
    NewLR->push_back(Numbering->getNumber(F), Num);
    NewLR->Offset = LR->Offset;
    LR->Offset = 0;
  }
}

void GenXCoalescing::coalesceOutputArgs(FunctionGroup *FG) {
  auto *F = FG->getHead();
  if (!vc::isKernel(F))
    return;

  vc::KernelMetadata KM{F};

  SmallVector<Value*, 4> OutputArgs;
  for(unsigned i = 0; i < KM.getNumArgs(); ++i)
    if (KM.isOutputArg(i))
      OutputArgs.push_back(F->arg_begin() + i);

  if (OutputArgs.empty())
    return;

  auto GetNextGenXOutput = [](Instruction *StartFrom) -> CallInst* {
    while(StartFrom) {
      if (auto CI = dyn_cast<CallInst>(StartFrom))
        if (GenXIntrinsic::getGenXIntrinsicID(CI) ==
            GenXIntrinsic::genx_output_1)
          return CI;
      StartFrom = StartFrom->getNextNode();
    };
    return nullptr;
  };

  // Iterate over all basic blocks with genx.output.1 intrinsics and coalesce
  // corresponding output argument with intrinsic argument (assuming that their
  // number and ordering are exactly the same).
  for (auto &BB : *F) {
    CallInst *CI = GetNextGenXOutput(BB.getFirstNonPHI());
    if (!CI)
      continue;

    for (auto Arg : OutputArgs) {
      IGC_ASSERT_MESSAGE(CI, "No genx.output.1 intrinsic for output argument");

      // This is the final value stored into the output argument.
      // If this is coalesced into kernel argument, nothing to do.
      // Otherwise, insert a copy.
      Value *V = CI->getArgOperand(0);
      LiveRange *LR1 = Liveness->getLiveRangeOrNull(V);
      LiveRange *LR2 = Liveness->getLiveRange(Arg);

      auto coalesceInput = [=]() {
        // When LR1 is null, the input value should be Undef. Otherwise, it
        // should be loaded as a constant.
        if (LR1 == nullptr || LR1 == LR2)
          return false;

        if (!Liveness->interfere(LR1, LR2)) {
          Liveness->coalesce(LR1, LR2, false);
          return false;
        }

        // A copy is needed.
        return true;
      };

      if (coalesceInput()) {
        // Insert copy and add a short live range for copy-out.
        unsigned Num = Numbering->getNumber(CI);
        auto Copy = insertCopy(V, LR2, CI, "copyout", Num);
        CI->setArgOperand(0, Copy);
        LR2->push_back(Num, Num + 1);
        LR2->sortAndMerge();
      }
      CI = GetNextGenXOutput(CI->getNextNode());
    }
  }
}

void GenXCoalescing::coalesceCallables() {
  for (auto CI : Callables) {
    auto NI = CI->getNextNode();
    // if the next instruction is a CM-output intrinsic,
    // we don't really need that cm-output because CMCallable can serve as
    // the anchor for preventing DCE
    while (true) {
      if (NI && isa<CallInst>(NI)) {
        CallInst *OC = cast<CallInst>(NI);
        if (GenXIntrinsic::getGenXIntrinsicID(OC) == GenXIntrinsic::genx_output_1) {
          NI = NI->getNextNode();
          OC->eraseFromParent();
          continue;
        }
      }
      break;
    }

    auto Nxt = CI->getNextNode();
    auto Ret = Nxt;

    // 1. Possible next node is branch to return
    auto Br = dyn_cast<BranchInst>(Nxt);
    if (Br && Br->isUnconditional())
      Ret = &Br->getSuccessor(0)->front();

    // 2. Possible several next nodes are GenXIntrinsic::genx_output_1
    while (GenXIntrinsic::getGenXIntrinsicID(Ret) == GenXIntrinsic::genx_output_1)
      Ret = Ret->getNextNode();

    // Check if next node is correct return insn
    if (!Ret || !isa<ReturnInst>(Ret)) {
      // getRetVal could not determine what happens to this return value.
      DiagnosticSeverity DS_Type = ST->warnCallable() ? DS_Warning : DS_Error;
      vc::diagnose(CI->getContext(), "GenXCoalescing",
                   "Callable Call must be right before function return",
                   DS_Type, vc::WarningName::Generic, CI);
    }
    Function *F = CI->getParent()->getParent();
    IGC_ASSERT(vc::isKernel(F));
    vc::KernelMetadata KM{F};
    unsigned Idx = 0; // kernel argument index
    unsigned i = 0;   // call argument index
    for (auto I = F->arg_begin(), E = F->arg_end(); I != E; ++I) {
      if (!KM.isFastCompositeArg(Idx++))
        continue;

      // This is the final value stored into the output argument.
      // If this is coalesced into kernel argument, nothing to do.
      // Otherwise, insert a copy.
      Value *V = CI->getArgOperand(i);
      Value *Arg = &*I;
      LiveRange *LR1 = Liveness->getLiveRangeOrNull(V);
      LiveRange *LR2 = Liveness->getLiveRange(Arg);

      auto coalesceInput = [=]() {
        // When LR1 is null, the input value should be Undef. Otherwise, it
        // should be loaded as a constant.
        if (LR1 == nullptr || LR1 == LR2)
          return false;

        if (!Liveness->interfere(LR1, LR2)) {
          Liveness->coalesce(LR1, LR2, false);
          return false;
        }

        // A copy is needed.
        return true;
      };

      if (coalesceInput()) {
        // Insert copy and add a short live range for copy-out.
        unsigned Num = Numbering->getNumber(CI);
        auto Copy = insertCopy(V, LR2, CI, "copyout", Num);
        CI->setArgOperand(i, Copy);
        LR2->push_back(Num, Num + 1);
        LR2->sortAndMerge();
      }
      ++i;
    }
  }
}

void GenXCoalescing::coalesceGlobalLoads(FunctionGroup *FG) {
  for (auto &GV : FG->getModule()->globals()) {
    if (!GV.hasAttribute(genx::FunctionMD::GenXVolatile))
      continue;
    LiveRange *LR1 = Liveness->getLiveRangeOrNull(&GV);
    if (!LR1)
      continue;

    // Collect all loads.
    SetVector<Instruction *> LoadsInGroup;
    for (auto UI : GV.users()) {
      if (auto LI = dyn_cast<LoadInst>(UI)) {
        IGC_ASSERT(LI->getPointerOperand() == &GV);
        auto Fn = LI->getParent()->getParent();
        // Check this load is inside the group.
        if (std::find(FG->begin(), FG->end(), Fn) != FG->end())
          LoadsInGroup.insert(LI);
      }
      // Global variable is used in a constexpr.
      if (&GV != vc::getUnderlyingGlobalVariable(UI))
        continue;
      for (auto U : UI->users())
        if (auto LI = dyn_cast<LoadInst>(U)) {
          auto Fn = LI->getParent()->getParent();
          // Check this load is inside the group.
          if (std::find(FG->begin(), FG->end(), Fn) != FG->end())
            LoadsInGroup.insert(LI);
        }
    }

    // Do coalescing.
    for (auto LI : LoadsInGroup) {
      LiveRange *LR2 = Liveness->getLiveRange(LI);
      LR1 = Liveness->coalesce(LR1, LR2, false);
    }
  }
}

/***********************************************************************
 * insertCopy : insert a copy of a non-struct value
 *
 * Enter:   Input = value to copy
 *          LR = live range to add the new value to
 *          InsertBefore = insert copy before this inst
 *          Name = name to give the new value
 *          Number = number to give the new instruction(s)
 *
 * Return:  The new copy instruction
 *
 * This inserts multiple copies if the input value is a vector that is
 * bigger than two GRFs or a non power of two size.
 */
Instruction *GenXCoalescing::insertCopy(SimpleValue Input, LiveRange *LR,
    Instruction *InsertBefore, StringRef Name, unsigned Number)
{
  IGC_ASSERT(!isa<Constant>(Input.getValue()));
  if (auto ST = dyn_cast<StructType>(Input.getValue()->getType())) {
    // Input is a struct element. First extract it. This
    // extract is created coalesced by adding it to the live
    // range of the struct element. An extractvalue is always
    // coalesced and never generates code.
    auto Indices = IndexFlattener::unflatten(ST, Input.getIndex());
    Instruction *Extract = ExtractValueInst::Create(Input.getValue(), Indices,
        "twoaddr.extract", InsertBefore);
    auto SourceLR = Liveness->getLiveRange(Input);
    IGC_ASSERT(SourceLR);
    Liveness->setLiveRange(SimpleValue(Extract), SourceLR);
    Input = SimpleValue(Extract);
  }
  ++NumInsertedCopies;
  return Liveness->insertCopy(Input.getValue(), LR, InsertBefore, Name, Number,
                              ST);
}

/***********************************************************************
 * insertIntoStruct : create an insertvalue to insert a new value into a
 *                    struct
 *
 * Enter:   Ty = type of putative struct
 *          FlattenedIndex = flattened index within the struct
 *          OldStruct = old value of struct
 *          NewVal = new value to insert into it
 *          InsertBefore = where to insert new instruction before
 *
 * Return:  the new InsertValueInst
 *
 * If Ty is not a struct type, this just returns NewVal.
 */
Instruction *GenXCoalescing::insertIntoStruct(Type *Ty,
    unsigned FlattenedIndex, Value *OldStruct, Instruction *NewVal,
    Instruction *InsertBefore)
{
  auto ST = dyn_cast<StructType>(Ty);
  if (!ST)
    return NewVal;
  // We're copying into struct element. We need to add an insertvalue.
  auto Indices = IndexFlattener::unflatten(ST, FlattenedIndex);
  return InsertValueInst::Create(OldStruct, NewVal,
      Indices, "coalescefail.insert", InsertBefore);
}

/***********************************************************************
 * showCoalesceFail : output a message to say that coalescing has failed
 */
void GenXCoalescing::showCoalesceFail(SimpleValue V, const DebugLoc &DL,
                                      const char *Intro, LiveRange *DestLR,
                                      LiveRange *SourceLR) {
  if (isa<Constant>(V.getValue()))
    return;
  if (V.getType()->getPrimitiveSizeInBits() >=
      GenXShowCoalesceFailThreshold * 8U) {
    dbgs() << "GenX " << Intro << " coalesce failed on ";
    V.printName(dbgs());
    dbgs() << " size " << V.getType()->getPrimitiveSizeInBits() / 8U
           << " bytes at ";
    DL.print(dbgs());
    dbgs() << "\nDestLR: " << *DestLR << "\nSourceLR: " << *SourceLR << "\n";
  }
}

/***********************************************************************
 * applyCopies : insert copies according to collected data.
 *
 * Postponed insertion is possible during coalescing because all
 * liveranges already contains insertion points. The only possible
 * exception is Branching Join Blocks copy: the copy will be
 * created on joins falling path.
 */
void GenXCoalescing::applyCopies() {
  LLVM_DEBUG(dbgs() << "Applying copies\n");

  if (GenXCoalescingLessCopies) {
    LLVM_DEBUG(dbgs() << "Emitting optimized copies\n");

    applyCopiesOptimized();
  } else {
    LLVM_DEBUG(dbgs() << "Emitting all copies\n");

    // Just emit all copies
    for (auto &CD : ToCopy) {
      createCopy(CD);
    }
  }

  LLVM_DEBUG(dbgs() << "Finished applying copies\n");
}

/***********************************************************************
 * applyCopiesOptimized : insert copies according to collected data.
 * Try to use less number of copies if possible.
 *
 * There are several assumptions in current algorithm:
 *   - Possible bitcast sequences (bitcast->bitcast) are not handled.
 *     Assuming that they were resolved earlier as redundant. However,
 *     such sequences would not brake functionality, but can block
 *     possible redundant copy elimination.
 *   - The most suitable copy candidate is handled only. This is
 *     done to simplify algorithm complexity in the first place.
 *     Also, this is the most common case that can happen in single
 *     liverange.
 *   - The most suitable copy candidate is the one with smaller
 *     number. This comes from GenX blocks layout.
 *   - The most suitable copy candidate is the latest created copy.
 *     That is to prevent unnecessary liverange interference. This
 *     comes from the previous two bullets.
 *
 * These assumptions represent heuristic for the basic case when
 * redundant copies appear. It is possible that there are some
 * other cases to be optimized. However, the good thing here is
 * that current algorithm cannot make situation any worse compared to
 * non-optimized copy generator: the number of generated copies is
 * less or equal to one produced by non-optimized generator. Also,
 * this optimization doesn't affect any existing insertion points.
 *
 * The algorithm does the following steps:
 *   1. Sort CopyData (see sortCopyData for details)
 *      - It defines the traverse order.
 *   2. Create initial copy
 *   3. Try to apply it in other users
 *      - There are several checks: same LR, same value, dominance,
 *        interference. Same value check takes into account possible
 *        copy coalescing that could be applied on source
 *        value earlier.
 *   4. Repeat from 2 on failure.
 */
void GenXCoalescing::applyCopiesOptimized() {
  // Sort ToCopy array for simple traverse
  SortedCopies SortedCD = getSortedCopyData();

  // The loop hierarchy looks quite scary. However,
  // it is still simple linear traverse through all copies.

  // Traverse all LRs
  for (auto LRDataIt : SortedCD.CopiesPerLR) {
    // Traverse all copy values
    for (auto CDIt : LRDataIt.second.CopiesPerValue) {
      // Finally we got into current copy candidates.
      // Traverse all copy data.
      applyCopiesForValue(CDIt.second);
    }
  }
}

/***********************************************************************
 * applyCopiesForValue: apply copies for CDSet set of copies candidates.
 *
 * For more details, check applyCopiesOptimized description.
 */
void GenXCoalescing::applyCopiesForValue(const std::set<CopyData> &CDSet) {
  auto It = CDSet.begin(), EndIt = CDSet.end();
  while (It != EndIt) {
    // Create initial copy.
    SimpleValue DestSV = It->Dest;
    SimpleValue SourceSV = It->Source;
    Instruction *CurrCopy = createCopy(*It);
    unsigned Idx = It->Source.getIndex();

    // Unlink copy from LR and build its own one. This LR
    // is used to detect possible interference.
    auto CopySV = SimpleValue(CurrCopy, Idx);
    Liveness->removeValueNoDelete(CopySV);
    auto *CopyLR = Liveness->buildLiveRange(CopySV);
    auto *DestLR = Liveness->getLiveRange(DestSV);

    LLVM_DEBUG(dbgs() << "Created copy for LR: "; DestLR->print(dbgs());
               dbgs() << "\nValue that was copied: "; SourceSV.print(dbgs());
               dbgs() << "\nCopy inst: "; CopySV.print(dbgs()); dbgs() << "\n");

    // Try to apply this copy in other copy candidates.
    It = mergeCopiesTillFailed(CopySV, ++It, EndIt);

    LLVM_DEBUG(dbgs() << "Finished processing all candidates for that copy\n";
               dbgs() << "Final copy val LR: "; CopyLR->print(dbgs());
               dbgs() << "\n");

    // All possible copies were handled. Coalesce copy with its dst.
    DestLR = Liveness->coalesce(DestLR, CopyLR, false);

    LLVM_DEBUG(dbgs() << "Updated dest LR: "; DestLR->print(dbgs());
               dbgs() << "\n");
  }
}

/***********************************************************************
 * mergeCopiesTillFailed: merge all possible copy users until failure
 * is met.
 *
 * Returns iterator to the element where merge has stopped or EndIt
 * in case when all elements were handled.
 *
 * For more details, check applyCopiesOptimized description.
 */
template <typename Iter>
Iter GenXCoalescing::mergeCopiesTillFailed(SimpleValue CopySV, Iter BeginIt,
                                           Iter EndIt) {
  if (BeginIt == EndIt)
    return EndIt;

  auto *CopyLR = Liveness->buildLiveRange(CopySV);
  auto *DestLR = Liveness->getLiveRange(BeginIt->Dest);
  Instruction *CurrCopy = cast<Instruction>(CopySV.getValue());

  for (auto It = BeginIt; It != EndIt; ++It) {
    // Interference detection
    if (Liveness->interfere(DestLR, CopyLR)) {
      LLVM_DEBUG(dbgs() << "Interference detected\n");
      return It;
    }
    // Dominance detection
    if (!getDomTree(CurrCopy->getFunction())
             ->dominates(CurrCopy, cast<Instruction>(It->Dest.getValue()))) {
      LLVM_DEBUG(dbgs() << "Copy doesn't dominate user\n");
      return It;
    }

    // Copy may be redundant. Check interference after copy applied.
    LLVM_DEBUG(dbgs() << "Current copy value LR: "; CopyLR->print(dbgs());
               dbgs() << "\nChecking updated interference\n");
    Value *OldValue = It->UseInDest->get();
    BitCastInst *BCI = nullptr;
    if (It->Source.getValue()->getType() == CurrCopy->getType()) {
      *It->UseInDest = CurrCopy;
    } else {
      IGC_ASSERT_MESSAGE(It->Source.getIndex() == 0,
        "Must be non-aggregated type: should come from bitcast");
      IRBuilder<> Builder(CurrCopy->getNextNode());
      BCI = cast<BitCastInst>(Builder.CreateBitCast(
          CurrCopy, It->Source.getValue()->getType(), "red_copy_type_conv"));
      Numbering->setNumber(BCI, Numbering->getNumber(CurrCopy));
      *It->UseInDest = BCI;
      auto *BitcastLR = Liveness->buildLiveRange(SimpleValue(BCI, 0));
      CopyLR = Liveness->coalesce(CopyLR, BitcastLR, false);
    }

    Liveness->rebuildLiveRange(CopyLR);
    if (!Liveness->twoAddrInterfere(DestLR, CopyLR)) {
      LLVM_DEBUG(dbgs() << "Success. Moving to next candidate\n");
      continue;
    }

    // Undo copy elimination
    LLVM_DEBUG(dbgs() << "Interference detected\n");
    *It->UseInDest = OldValue;
    if (BCI) {
      Liveness->removeValue(BCI);
      BCI->eraseFromParent();
    }
    Liveness->rebuildLiveRange(CopyLR);
    return It;
  }

  return EndIt;
}

/***********************************************************************
 * getSortedCopyData : sort CopyData for optimizal traverse.
 *
 * The idea is to group CopyData in the following hierarchy:
 *   - Destination LR
 *     - Value to be copied
 *       - Copy data with the same Source Idx
 *         - Copy data sorted by instruction Num
 *
 * This is simply done by adding data into SortHelper. See
 * SortedCopies struct implementation for details.
 */
SortedCopies GenXCoalescing::getSortedCopyData() {
  SortedCopies SortHelper;

  std::for_each(ToCopy.begin(), ToCopy.end(), [&](auto &CD) {
    LiveRange *DestLR = Liveness->getLiveRange(CD.Dest);
    Value *SourceVal = CD.Source.getValue();
    // Apply copy coalesced value for source
    if (Instruction *CopyInst = dyn_cast<Instruction>(SourceVal)) {
      if (CopyCoalesced.count(CopyInst))
        SourceVal = CopyCoalesced[CopyInst];
    }
    SortHelper.insertData(DestLR, SourceVal, CD);
  });

  return SortHelper;
}

/***********************************************************************
 * createCopy : insert copy according to collected data.
 *
 * Only twoaddr and phi copies are handled now.
 */
Instruction *GenXCoalescing::createCopy(const CopyData &CD) {
  LiveRange *DestLR = Liveness->getLiveRange(CD.Dest);
  LiveRange *SourceLR = Liveness->getLiveRange(CD.Source);
  SimpleValue Source = CD.Source;
  if (auto It = CallToRetVal.find(Source); It != CallToRetVal.end())
    Source = SimpleValue{It->second};
  Instruction *NewCopy = nullptr;
  switch (CD.CopyT) {
  case PHICOPY:
  case PHICOPY_BRANCHING_JP: {
    PHINode *Phi = dyn_cast<PHINode>(CD.Dest.getValue());
    IGC_ASSERT_MESSAGE(Phi, "Expected PHI");
    unsigned Num =
        (CD.CopyT == PHICOPY)
            ? Numbering->getPhiNumber(
                  Phi, Phi->getIncomingBlock(CD.UseInDest->getOperandNo()))
            : Numbering->getNumber(CD.InsertPoint);
    LLVM_DEBUG(showCoalesceFail(CD.Dest, CD.InsertPoint->getDebugLoc(), "phi",
                                DestLR, SourceLR));
    NewCopy = insertCopy(Source, DestLR, CD.InsertPoint, "phicopy", Num);
    Phi->setIncomingValue(CD.UseInDest->getOperandNo(), NewCopy);
    break;
  }
  case TWOADDRCOPY: {
    // Insert the copy now for a two address op. Give it the number of the
    // pre-copy slot, which is one less than the number of the two address
    // instruction.
    Instruction *DestInst = cast<Instruction>(CD.Dest.getValue());
    LLVM_DEBUG(showCoalesceFail(CD.Dest, DestInst->getDebugLoc(), "two address",
                                DestLR, SourceLR));
    NewCopy = insertCopy(Source, DestLR, DestInst, "twoaddr",
                         Numbering->getNumber(DestInst) - 1);
    NewCopy =
        insertIntoStruct(CD.UseInDest->get()->getType(), CD.Dest.getIndex(),
                         *CD.UseInDest, NewCopy, DestInst);
    // Replace the use of the old source.
    IGC_ASSERT(CD.UseInDest->get()->getType() == NewCopy->getType());
    *CD.UseInDest = NewCopy;
    // No need to extend the live range, as the result of the two address op was
    // already marked as defined at the pre-copy slot.
    break;
  }
  default:
    IGC_ASSERT_EXIT_MESSAGE(0, "Unknown copy type!");
  }

  if (CD.CopyT == PHICOPY_BRANCHING_JP) {
    // Extend liverange: we skipped some basic blocks
    Liveness->rebuildLiveRange(DestLR);
  }

  IGC_ASSERT_MESSAGE(NewCopy, "Bad copy");

  return NewCopy;
}

/***********************************************************************
 * replaceAllUsesWith : replace all uses of OldInst with new instruction
 *   with regard to GenXCoalescing structs
 */
void GenXCoalescing::replaceAllUsesWith(Instruction *OldInst,
                                        Instruction *NewInst) {
  for (auto &&CD : ToCopy) {
    if (CD.InsertPoint == OldInst)
      CD.InsertPoint = cast<Instruction>(NewInst);
  }
  ToCopy.erase(std::remove_if(ToCopy.begin(), ToCopy.end(),
                              [&](CopyData const &CD) {
                                if (CD.Dest.getValue() == OldInst)
                                  return true;
                                if (CD.Source.getValue() == OldInst)
                                  return true;
                                return false;
                              }),
               ToCopy.end());
  OldInst->replaceAllUsesWith(NewInst);
}